From david at no.westcontrol.spam.com Tue Nov 26 05:41:24 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Tue, 26 Nov 2002 11:41:24 +0100 Subject: if : References: Message-ID: wrote in message news:artvr3$cbe$2 at wheel2.two14.net... > David Brown wrote: > > correctness. This particular "feature" is a huge source of bugs and > > frustration in C programming - mixing up "=" and "==" in conditions is > > probably the biggest single cause of C program bugs. Python, on the other > > Are you speaking from experience, or is this as well-founded as the > hysterical wails about how Python's use of indentation is just wrong? > It certainly isn't remotely near my own experience (which covers a bit > more than two decades, during much of which C was used more than > anything else). It is certainly a mistake I have made. C has a number of these "features", where you can very easily write valid C code that looks and reads like it should work ("=" and "==" look and read the same at first glance), yet fails. The one that gets me more often is missing a "break" in a switch statement. The more you write C, the less you make these sort of mistakes, so they are of a much bigger problem to newbies. But if you look at any of the coding standards designed for writing safety-critical or highly reliable code, they are full of rules about writing unnatural things like "if (1 == x)" or "if ((y) == x)" to force C compilers to generate error messages when you make these mistakes. From goodger at python.org Thu Nov 7 19:25:24 2002 From: goodger at python.org (David Goodger) Date: Fri, 08 Nov 2002 00:25:24 GMT Subject: ht2html and reStructured text In-Reply-To: References: Message-ID: Jim Tittsler wrote: >> Has anyone merged ht2html and reStructured text? Oliver Rutherfurd replied: > I've written an '.ht' writer for docutils which will convert > reStructuredText to an '.ht' file. It is not yet part of > docutils, but I hope it will be included in a future release. It definitely will be. I'm also interested in integrating them. > It can be found in the docutils sandbox here: > > http://docutils.sourceforge.net/sandbox/oliverr/ht/ We'd love to have you help out at Docutils. Lots of interesting work going on there now. I expect a new release as soon as I get some loose ends tied up. -- David Goodger Open-source projects: - Python Docutils: http://docutils.sourceforge.net/ (includes reStructuredText: http://docutils.sf.net/rst.html) - The Go Tools Project: http://gotools.sourceforge.net/ From jdhunter at ace.bsd.uchicago.edu Sun Nov 17 11:28:26 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 17 Nov 2002 10:28:26 -0600 Subject: Possibly a stupid question regarding Python Classes In-Reply-To: <3dd7c140$1_6@nopics.sjc> ("Adonis"'s message of "Sun, 17 Nov 2002 11:18:29 -0500") References: <3dd7c140$1_6@nopics.sjc> Message-ID: >>>>> "Adonis" == Adonis writes: Adonis> So in essence I want to override the Bar function, but as Adonis> well do what it would if it were instantiated. I know I Adonis> could instantiate Foo prior to printing Bar, but was Adonis> wondering if there was a way to keep it within the same Adonis> process. If I undersand your question correctly, you can do this by calling Foo.Bar with the self argument passed as the first parameter class Foo: def Bar(self): print 'Foo' class Fib(Foo): def Bar(self): Foo.Bar(self) print 'Bar' f = Fib() f.Bar() This comes up a lot in calling a parent classes initialization function class Bar: def __init__(self,x): self.x = x class Foo(Bar): def __init__(self, x, y): Bar.__init__(self, x) self.y = y f = Foo(1,2) print f.x, f.y John Hunter From tjreedy at udel.edu Mon Nov 18 22:11:28 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 18 Nov 2002 22:11:28 -0500 Subject: classifier systems re-coded in Python? References: Message-ID: <182dnaFhsdyUN0SgXTWcrg@comcast.com> "Kow K" wrote in message news:mailman.1037670692.6438.python-list at python.org... > Hi Pythoneers, > > I'm just wondering if anybody has re-coded David Goldberg's Pascal > implementation of John Holland's (learning) classifier system in Python. > > Any pointer will be appreciated. try: google('Holland learning classifier Python') TJR From Patrick.Carabin at MyRealBox.COM Wed Nov 13 03:30:48 2002 From: Patrick.Carabin at MyRealBox.COM (Patrick.Carabin at MyRealBox.COM) Date: 13 Nov 2002 00:30:48 -0800 Subject: How do I reply to an item in the list ? - testing only References: <44ee1dc2.0211120441.465eeb62@posting.google.com> Message-ID: <44ee1dc2.0211130030.4bb1657f@posting.google.com> this time i remove everything From rjones at ekit-inc.com Tue Nov 19 23:51:59 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Wed, 20 Nov 2002 15:51:59 +1100 Subject: Installation In-Reply-To: <2066386.1037763461@dbforums.com> References: <2066386.1037763461@dbforums.com> Message-ID: <200211201551.59887.rjones@ekit-inc.com> On Wed, 20 Nov 2002 2:37 pm, Tetsuo wrote: > A few days ago, Python simply stopped working. I tried reinstalling, and > it demanded that I log in as an admin, or it can't do some sys configs. > My mom tried to log in as an admin, and that was still not admin enough. > We concluded that the reason is the anivirus my mom installed. She > turned it off. No effect whatsoever. Same stupid message. > > What the heck? > > Win2K is the OS, Norton is the "anti" virus. > > I'm at the end of my wit. As ususal. You didn't tell us: 1. your version of python and how you installed it 2. what the "stupid message" is Richard From anton at vredegoor.doge.nl Tue Nov 12 09:08:28 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 12 Nov 2002 15:08:28 +0100 Subject: Optimisation problem References: Message-ID: On Tue, 12 Nov 2002 15:44:28 +0800, "Simon Wittber (Maptek)" wrote: >Does anyone have any idea how I can optimise this code? It is going to >be used in a very tight rendering loop. I would prefer to keep all the >code in Python, and avoid writing any external modules. > def __createMatrix(self): > self.matrix[0] = 1.0 - 2.0 * ( self.y * self.y + self.z >* self.z ) Create local variables so that they can be found in the local scope of the function: m,x,y,z = self.matrix,self.x,self.y,self.z This is faster and also saves typing. Creating local *functions* like sin = math.sin is also a bit faster. Furthermore testing the effects of speeding things up this way - using a speed test - is crucial. One is toggling with the handles of a very complex machinery and the results may be unpredictable. Regards, Anton From aleax at aleax.it Wed Nov 6 09:32:01 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 06 Nov 2002 14:32:01 GMT Subject: The Deitel book (was Re: Textbooks on Perl/Python) References: <87b0ada6.0211011453.1df4d216@posting.google.com> Message-ID: Chris Gonnerman wrote: ... > It's just a dang ugly book, in my opinion; and then on top of > that it's a hard read. Sure, it may be suitable for a Python > class at college, but my advice to the prospective victim (I > mean student) is to get Steve's book also and read it first. > Then you'll hardly have to look at the Dietel book most of the > course. Nolo contendere -- except that some students may prefer Magnus Hetland's "Practical Python" (aPress) instead of Steve's book. (I'm equally biased towards both, since I tech-reviewed both and both Magnus and Steve are my friends;-). Steve introduces many other technologies that an accomplished web programmer needs to understand something about, including networks, HTTP, HTML, relational databases, etc; and develops one large, powerful framework for programming asynchronous webpages that rely on a relational DB. Magnus develops ten not-quite-as-large rich, complete examples, in a wide variety of different fields. If you like fully-worked-out significant examples, either book should gladden your heart; if the web is what you most care about, then particularly if you don't feel quite secure about its various technologies Steve's book may be preferable -- if you care about a wider range of things (with some web programming, but not just that), Magnus' variety may be preferable. Steve has the advantage of being of English mother-tongue (he's British but has been living and working in the US for years, so no "jarring" Britishisms should give any problems even to native-US'ers), while Magnus, like me, has English has a second language (I don't notice that as producing any significant difference -- but then, I guess I wouldn't, not being of English mother tongue myself). Both books are BIG, in good part due to the fully worked out significant examples. As a personal taste, I prefer SMALL books, and I prefer toy examples rather than "fully worked out significant ones" (e.g., the kind of examples found in Eckel's or Lippmann's books are much more to my didactical tastes than those found in Stroustrup's...). For readers that share my tastes, it may be worth waiting for the next edition of Lutz and Ascher's "Learning Python", O'Reilly -- the current edition is very good but alas limited to Python 1.5.2, the next one will no doubt cover 2.2. You pays your money and you makes your choice...! Alex From bfordham at socialistsushi.com Sun Nov 3 12:48:47 2002 From: bfordham at socialistsushi.com (Bryan L. Fordham) Date: Sun, 03 Nov 2002 12:48:47 -0500 Subject: Foot in mouth disease References: <3dc52a19.3339913@news.cybermesa.com> Message-ID: <3DC5617F.4000801@socialistsushi.com> Aahz wrote >I'm afraid I was insufficiently clear: I'm looking for people who are >familiar with using refactoring tools with Java but still find Python >easier to refactor. > > A lot of it, of course, depends on you religion 8) I've worked at a company (now owned by verisign) for almost 2 years, and all the development produced in my department is in java. But, to me, it's much quicker for me to hack out quick scripts in python that produce java code than it is to try and do that in java. I've gotten a few people there to install python, and they all find it much easier to use than java. To me, refactoring is easier in python; my method is to hack out things at the commandline and then, when I get something working, dump it into a module. That works well for me and is much quicker than the write-compile-debug-repeat cycle one is forced into with java. As far as tools, I can't stand IDE's, but that's just me; I'm used to text editors and so I am quicker in those. I try and stay out of those "debates" as everyone stickes to their own opinion. My take is that you should use what works best for you. --B From hgg9140 at cola2.ca.boeing.com Wed Nov 13 09:29:31 2002 From: hgg9140 at cola2.ca.boeing.com (Harry George) Date: Wed, 13 Nov 2002 14:29:31 GMT Subject: perl2python References: <87y97xmy6o.fsf@flibuste.net> Message-ID: William writes: > hi, > > I want to convert a little perl script to python, is there a tools for > that ? or a little doc to learn the minimum of perl for python users ? When I was converting from perl to python, I found I wanted a way to do perl-ish idioms in python. That led to: http://www.seanet.com/~hgg9140/comp/pyperlish-1.2/doc/index.html Download available at: http://www.seanet.com/~hgg9140/comp/index.html I don't use it anymore, since my apps are now in native python idioms. > > This script is to convert XpressTag to HTML... maybe somebody else > is interested ? > > bye > > -- > William Dode - http://flibuste.net -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 294-8757 From mwh at python.net Tue Nov 19 12:25:28 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 19 Nov 2002 17:25:28 GMT Subject: pythonic way to optimize access to imported value? References: <3DD85526.6020606@something.invalid> <7h34radwzql.fsf@pc150.maths.bris.ac.uk> Message-ID: <7h34radv5jn.fsf@pc150.maths.bris.ac.uk> bokr at oz.net (Bengt Richter) writes: > On Tue, 19 Nov 2002 11:47:57 GMT, Michael Hudson wrote: > > >bokr at oz.net (Bengt Richter) writes: > > > >> IOW, IMO there ought to be a way to do a temporary global-side-effect-free > >> import and delete all traces of its having been done -- without restarting > >> the interpreter or invoking a second interpreter instance. > > > >I don't think this is so hard: > > > >def load_file(file, modname): > ^^^^- tch, tch ;-) It was fname at one point, but I thought that obscure... > > import new > > mod = new.module(modname) > > exec open(file).read() in mod.__dict__ > > return mod > > > > But as Jeff pointed out, if there are any imports in your imported file, > you have to encapsulate them too. So you need a temporary sandbox > import that captures all the import action into a private container/space. Hmm. Yes. > IIRC I saw some docs on sandboxing import. That's probably the trail > to follow. Yeah, just don't touch sys.modules in your __import__, I guess. I wonder if import new, __builtin__ mod = new.module(modname) d = __builtin__.__dict__.copy() d['__import__'] = my_hook mod.__dict__['__builtins__'] = d exec open(file).read() in mod.__dict__ return mod would be a good start? > Thanks for the reminders. BTW, is there a reason you preferred > > exec open(file).read() in mod.__dict__ > over > execfile(filepath, mod.__dict__) > above? Nope. Cheers, M. -- Exam invigilation - it doesn't come much harder than that, esp if the book you're reading turns out to be worse than expected. -- Dirk Bruere, sci.physics.research From max at alcyone.com Mon Nov 18 23:26:56 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 18 Nov 2002 20:26:56 -0800 Subject: static variables? References: Message-ID: <3DD9BD90.12223E70@alcyone.com> Josh wrote: > I am a python newbie, and I am sure there is an easy answer but, Is > there > any equivalent to C's static variables in Python? If not, how can you > have > variables inside a function, that 'remember' their values between > function > calls? Typically one would just have a global (module scope) variable with a leading underscore (a common convention meaning, "Don't touch me unless you're part of the implementation." _count = 0 def call(): global _count _count += 1 print "Count is %d" % _count In class, you can get the effect of "static variables" by defining variables in class scope, not local scope. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Pick the roses from the thorns / Wash with waters of the storms \__/ Chante Moore PyUID / http://www.alcyone.com/pyos/uid/ A module for generating "unique" IDs in Python. From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Wed Nov 27 15:39:17 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Wed, 27 Nov 2002 21:39:17 +0100 Subject: ANNOUNCE: Mod_python 3.0.1 References: Message-ID: <3de52d75$1@news.mt.net.mk> > The Apache Software Foundation and The Apache HTTP Server Project are > pleased to announce the release of mod_python 3.0.1. skipping through the online documentation, I noticed the PythonOutputFilter directive. If I understand corectly this and the AddOutputFilter Apache deirective will enable me to register different Python handlers for different file-extensions in the SAME directory, no. I'm asking this this was previously not possible with mod_python 2.x. -- ?????? There are three kind of lies: lies, damn lies and benchmarks. From mwh at python.net Mon Nov 4 08:48:51 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 4 Nov 2002 13:48:51 GMT Subject: What the heck has happened to PythonWin??? References: Message-ID: Mark Hammond writes: > Bob X wrote: > > "Mark Hammond" wrote in message > > news:ctiv9.10864$jE1.36952 at news-server.bigpond.net.au... > > > > > >>before. I *wish* I had time to play on Pythonwin, but it hasn't been > >>touched for ages (however, if you want an excellent spam detection tool > >>for Outlook 2000...) > > Something like this: http://p-nand-q.com/pynospam.htm > > or your own? > > Well, not mine . As Skip posted, the general project is > spambayes.sourceforge.net. I've put together a cute outlook addin. > The bayesian filter, Which, of course, isn't Bayesian... > plus Outlooks integration facilities is providing > an *incredibly* effective Spam filter with very tight integration and > incremental training capabilities. The bayesian nature means that it > doesn't use pre-determined heuristics, so tends to catch even the most > subtle spam. Cheers, M. -- ARTHUR: Yes. It was on display in the bottom of a locked filing cabinet stuck in a disused lavatory with a sign on the door saying "Beware of the Leopard". -- The Hitch-Hikers Guide to the Galaxy, Episode 1 From SBrunning at trisystems.co.uk Wed Nov 13 11:26:08 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Wed, 13 Nov 2002 16:26:08 -0000 Subject: Raw Newbie: What's the " > From: KEVIN ZEMBOWER [SMTP:KZEMBOWER at jhuccp.org] > I'm just now beginning my learning about python, and have to modify a > system written in python, the ezmlm-browse system, which allows ezmlm > mailing lists to be accessed via a web interface. > > I've found templates which look like this: > >
["%(type)s" not shown] > >
> >
%(markup_urls(html(body)))s
> > > Obviously, this is python code embedded in HTML, very similar to php in > HTML, with which I am more familiar. However, I can't find any references > to the " references to it in my Learning Python or Programming Python books. I > suspect that this is that I just don't know the proper terms to search > for. Where can I learn more about this aspect of python? > > The specific problem I'm working on involves the line '
width="640">'. I'd like to change the width to "100%", but the percent > sign must be interpreted as a special character. It causes strange errors. > I've tried escaping it with 'width="100\%"', but this doesn't seem to > work, either. Any help on this small problem? > > Thanks for your suggestions and help and patience with what I suspect is a > very newbie question. The " for many (though probably not all) of them. Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From nospam at bigfoot.com Thu Nov 28 08:21:31 2002 From: nospam at bigfoot.com (Gillou) Date: Thu, 28 Nov 2002 14:21:31 +0100 Subject: wxSocketServer in wxPython References: Message-ID: "moxie" a ?crit dans le message de news: b1078faa.0211271801.378f0cbe at posting.google.com... > I'm trying to use the wxSocketServer and wxSocketClient classes in > wxPython, but wxPython does not recognize these classes. > > wxSocketServer and wxSocketClient both are in the wxWindows > documentation, so I guess these classes are only available for C++ at > the moment. > > Any ideas? > > ~= moxie =~ Somewhere in the help of wxPython, there is a list of wxWindows features supported by wxPython. You'll notice that *most* GUI features are supported, but not *all* wxWindows features. --Gilles From costanza at web.de Tue Nov 12 05:26:45 2002 From: costanza at web.de (Pascal Costanza) Date: Tue, 12 Nov 2002 11:26:45 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCF83B2.2030008@web.de> Message-ID: <3DD0D765.3030907@web.de> Gareth McCaughan wrote: >>>You mean (funcall #'+ 1 1 1) and (funcall #'* 2 3). >> >> No, (funcall '+ 1 1 1) works as well (as defined by the ANSI specs). > > Yes, but identifying functions with the symbols that name them > at run time is generally reckoned bad Lisp style. You're right, but I wanted to avoid to explain the difference between ' and #'. These examples are only meant to give a first taste of Lisp. Pascal -- Pascal Costanza University of Bonn mailto:costanza at web.de Institute of Computer Science III http://www.pascalcostanza.de R?merstr. 164, D-53117 Bonn (Germany) From occitan at esperanto.org Tue Nov 5 16:10:04 2002 From: occitan at esperanto.org (Daniel Pfeiffer) Date: Tue, 5 Nov 2002 22:10:04 +0100 Subject: A vision for Parrot Message-ID: <20021105221004.339206f3.occitan@esperanto.org> Hi, this morning it struck me that it would be nice to have Parrot not only run Perl 6 and similar byte code, but that any of the common interpreted languages be compiled to this same byte code. Then no matter whether running a Perl 6, Python, Ruby, Tcl maybe even bash script the same interpreter library would be used. Then likely it would already be in memory speeding up start time. And this would also ease cross language module/library inclusion. Imagine instantiating some Python class from Perl! Apache would essentially have a mod_parrot. Maybe, if this can be tested very hard, we'd even have a Parrot kernel module for all Unices supporting that. Then exec() could perform compiled scripts right away, like machine code :-) coralament / best Gr?tens / liebe Gr??e / best regards / elkorajn salutojn Daniel Pfeiffer -- -- http://dapfy.bei.t-online.de/make.pl/ -- From gminick at hacker.pl Mon Nov 4 11:20:19 2002 From: gminick at hacker.pl (Wojtek Walczak) Date: Mon, 4 Nov 2002 16:20:19 +0000 (UTC) Subject: indirect **keyword calls References: Message-ID: Dnia Mon, 28 Oct 2002 00:59:11 -0800, Terry Hancock napisa?(a): > I've just recently come across a need for this idiom (isn't > this new in Python 2.x?): > def my_func(spam, ham=1, **eggs): > #... > pass There exist two ways of using dictionaries as arguments to functions. Here we go with examples: def first(**a): print "\n".join([ "%s==%s" % (k,v) for k,v in a.items()]) first(a="b",b="c",c="d") def second(a): print "\n".join([ "%s==%s" % (k,v) for k,v in a.items()]) second({"a":"b", "b":"c", "c":"d"}) If you want to read more about it, take a look at -- [ Wojtek gminick Walczak ][ http://gminick.linuxsecurity.pl/ ] [ gminick (at) hacker.pl ][ gminick (at) underground.org.pl ] From bloke at ii.net Tue Nov 5 11:37:09 2002 From: bloke at ii.net (Rob Hall) Date: Wed, 6 Nov 2002 00:37:09 +0800 Subject: pyqt table Message-ID: <3dc7f35b$0$11674@echo-01.iinet.net.au> I have created a qt table fine. I want to be able to colour the background of individual cells but I cant find a setBackground method fot QTableItem. How do I colour the background of a cell? Rob From cliechti at gmx.net Tue Nov 5 17:28:42 2002 From: cliechti at gmx.net (Chris Liechti) Date: 6 Nov 2002 00:28:42 +0200 Subject: calldll question References: <3DC847D5.60908@ihug.co.nz> <3DC85186.80209@ihug.co.nz> Message-ID: Matthew wrote in news:3DC85186.80209 at ihug.co.nz: > One question though, webpage states that calldll only > works on Py2.1. Is this true as I am running Py2.2.1 and so far calldll > appears to work without a hitch. binary extension on windows "pyd"s, which are in fact dlls, are compiled against a specific python version and will not work with other versions of python. however, you will almost certainly find a version for each newer python version. and in your case, you seem to have found the correct one already. chris -- Chris From rainer at cs.uu.nl Tue Nov 5 07:01:44 2002 From: rainer at cs.uu.nl (Rainer) Date: 5 Nov 2002 12:01:44 GMT Subject: urllib ?? References: <9782a2ed.0211040151.db070a3@posting.google.com> <3DC64C2A.7604FB4B@hotmail.com> <3DC688E4.BD46E2FB@hotmail.com> Message-ID: with the help of alan, we finally have the solution for this problem: 'Submit', 'Process query'), has to be set as a name/value pair.... this is it rainer In article <3DC688E4.BD46E2FB at hotmail.com>, alanmk at hotmail.com says... > >Rainer wrote: >> >> hi alan >> this is the problem, maybe i put it the wrong way. >> i DO NOT get the results from the server. the thing that is stored in >> 'results', is the 'query-webpage' with the values filled in, not the >> results page. > >OK, I think I see your peoblem now. > >You're submitting data to the server almost correctly, but the server is >just returning the input form to you, as if you had not filled out all >of the fields correctly. > >And I think that this is one of the things you are doing wrong: not >filling in the fields correctly. The problem lines are these > > d['.cgifields']='ContAllHits' > d['.cgifields']='SortByIde' > d['.cgifields']='StructAllHits' > d['.cgifields']='Map2Mismatch' > d['.cgifields']='Dbase3d' > >HTTP allows for multiple values for the same field in a POST request. >However, python dictionaries do NOT: python dicts can have only one >value for every key. Try the following at an interactive prompt > >>>>d = {} >>>>d['.cgifields']='ContAllHits' >>>>d >{'.cgifields': 'ContAllHits'} >>>>d['.cgifields']='SortByIde' >>>>d >{'.cgifields': 'SortByIde'} > >You're expecting it to maintain multiple values for the key >".cgifields", but it doesn't: the value gets overwritten each time, >meaning that you are submitting POST data that only includes the value >'.cgifields'='Dbase3d' (the last assignment in the list), and failing to >supply values for the (presumably necessary) 'ContAllHits', 'SortByIde', >'StructAllHits', 'Map2Mismatch'. > >The solution is to pass a list of tuples to "urlencode" instead of a >dictionary, like so > >#=----------------------------------------------------- > >def query2_polyphen(): > > d=[ > ('InputQuerySequence', '>GGG \012 sequence'), > ('Var1', 'C'), > ('InputQueryPosition', '282'), > ('Var2', 'Y'), > ('Dbase3d', 'pqs'), > ('SortByIde', '1'), > ('Map2Mismatch', '0'), > ('StructAllHits', '0'), > ('ContAllHits', '0'), > ('MinHitLen', '100'), > ('MinHitIde', '0.5'), > ('MaxHitGaps', '20'), > ('ContThresh', '6'), > ('.cgifields', 'ContAllHits'), > ('.cgifields', 'SortByIde'), > ('.cgifields', 'StructAllHits'), > ('.cgifields', 'Map2Mismatch'), > ('.cgifields', 'Dbase3d'), > ] > query=urllib.urlencode(d) > url = 'http://tux.embl-heidelberg.de/ramensky/polyphen.cgi' > results = urllib.urlopen(url,query).read() > open ('rainer.html','w').write(results) >#=----------------------------------------------------- > >However, I also notice, by manually submitting your form data using a >browser, that the data you are submitting give rise to an error. I don't >know enough about molecular biology to know what the error is, but I >suggest that you get your submitted data right manually before trying to >submit it automatically. > >Also, you might send an email to the provider of the polyphen service >asking them to somehow make it possible for automated submission scripts >to recognise when a query has failed, rather than simply sending the >form again. A return HTTP status value in the 4xx series might be >suitable, e.g. of the "404 - file not found" variety. > >HTH, > >alan kennedy >----------------------------------------------------- >check http headers here: http://xhaus.com/headers >email alan: http://xhaus.com/mailto/alan From aahz at pythoncraft.com Fri Nov 1 09:03:09 2002 From: aahz at pythoncraft.com (Aahz) Date: 1 Nov 2002 09:03:09 -0500 Subject: Global variable visibility References: Message-ID: In article , David LeBlanc wrote: > >Ah, the commands.Db idiom wasn't one I thought of. My "punt" was to create >an Initialize method in the commands.py file and call it with Db as a param: > >Db = None > >def Initialize(database) > global Db > Db = database > >commands.Db is obviously simpler and more obvious too. > >Not exactly sure what you mean by rebinding. Would (in commands.py) Db = >__main__.Db be a rebinding or another reference? It would be a rebinding, but what I was actually referring to was rebinding Db in main.py. The only strong argument against using commands.Db to set it is that someone looking at commands.py in isolation can't see how Db gets set. Here's a variation that's closer to what I usually do: class cfg: pass def Initialize(Db): cfg.Db = Db You could use a dict instead of a class, but I find the direct attribute access simpler. BTW, please do not top-post; it makes it difficult to see the context. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From wlfraed at ix.netcom.com Tue Nov 26 01:28:39 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 25 Nov 2002 22:28:39 -0800 Subject: some questions.... References: Message-ID: eugene kim fed this fish to the penguins on Tuesday 26 November 2002 12:40 am: > #!/usr/local/bin/python > > wow.. i thought python is easy to learn.. > but there are lot's of corks.. > namespace, scoping rule, exec, eval.. > all confuses me.. > > first.. about exec > class simple: > def __init__(self,value): > self.value = value > if value == 4 : > print c ## <--- ok > print C ## <--- error > > def __repr__(self): > return str(self.value) > > if __name__ == '__main__': > a = 3; > b = 4; > c = simple(a) You just created a "c" > d = simple(b) So this instance can find a "c" to print. There is NO "C" in existance at this point in the program > print c > print d > > exec "C = simple(a)" > print C NOW you have created a "C" > > > > another question about exec > aList = ['a', 'b'] > for aString in aList: > aString = myClass(aString) ## <--error Again, my first question is WHY are you assigning the result to a loop index? > exec "aString = myClass(aString)" ## <-- ok And what does myClass actually contain? -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From mail at andreas-penzel.de Fri Nov 15 09:56:33 2002 From: mail at andreas-penzel.de (Andreas Penzel) Date: Fri, 15 Nov 2002 15:56:33 +0100 Subject: eMail including attachment on Linux Message-ID: Hello NG! I am writing a Python program on Linux which should be able to send eMails including an attachment with sendmail. How to do that? Thanks for any help - Andreas From rmunn at pobox.com Sat Nov 30 13:04:06 2002 From: rmunn at pobox.com (Robin Munn) Date: Sat, 30 Nov 2002 18:04:06 GMT Subject: catch output of threads References: <87of88723i.fsf@flibuste.net> <87el946qjl.fsf@flibuste.net> Message-ID: William wrote: > martin at v.loewis.de (Martin v. L?wis) writes: > >> William writes: >> >> > Is it possible to catch the output from print of differents threads ? >> > In a single thread, i can change the value of sys.stdout... but with >> > differents thread i don't know ? >> >> You can still change the value of sys.stdout, even for multiple >> threads. The print statement internally uses sys.stdout itself. >> >> If multiple threads interleave print statements, you will get mixed >> output on your replaced sys.stdout, just as you would with the >> standard sys.stdout. > > It's why i cannot use this method... I specialy want to catch the output > to don't mix the ouput from all the threads. In that case, you probably want to use locking to guarantee that one thread's output won't get mixed with another. I don't know, off the top of my head, exactly what the locking interface is -- read the docs for the threading module. But what you'll want is something like: output_lock = Lock() # Some non-output code... output_lock.acquire() print "Here is some output" print "This will not be mixed" output_lock.release() That should be what you want -- as long as all your threads acquire the lock before they print, and release the lock when they're done, your threads' outputs will not be mixed. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From e8Kuula at hotmail.com Fri Nov 29 23:03:48 2002 From: e8Kuula at hotmail.com (Kristian Kuula) Date: Sat, 30 Nov 2002 06:03:48 +0200 Subject: Python + MySQL (Win32) Message-ID: HI! Little problen on connection, I get this: >>> import CompatMysqldb >>> conn = CompatMysqldb.mysqldb('test at 192.168.0.1 username password') Traceback (most recent call last): File "", line 1, in ? conn = CompatMysqldb.mysqldb('test at 192.168.0.1 username password') File "C:\PROGRA~1\Python\Lib\site-packages\CompatMysqldb.py", line 317, in mysqldb return Connection(dh[1], val[1], val[2], dh[0]) File "C:\PROGRA~1\Python\Lib\site-packages\CompatMysqldb.py", line 117, in __init__ self.__transactional = self.__conn.server_capabilities & CLIENT.TRANSACTIONS AttributeError: server_capabilities so what is wrong? :/ MySQL version: 3.23.53-max-nt MySQL-Python version: 0.9.2 (MySQL-python-0.9.2.win32-py2.2.exe) Python version: 2.2.1 From yaipa at aol.com Sun Nov 3 15:51:45 2002 From: yaipa at aol.com (yaipa) Date: 3 Nov 2002 12:51:45 -0800 Subject: python -u under cygwin telnet References: <954ef463.0211021945.7a1b5c05@posting.google.com> Message-ID: <8d148763.0211031251.1ed74d5@posting.google.com> I'm not doing exactly what you are, but I've had great success controlling serial ports in Solaris and Win2K using pySerial, http://pyserial.sourceforge.net/ Not so long ago I posted some working code titled "Working (basic) Eurotherm Temp Controller" on this alias. Good luck and keep us posted on your progress. I need to do the same thing you are in the next phase of my project. Cheers, -Yaipa.h avajrd at yahoo.com (Mike) wrote in message news:<954ef463.0211021945.7a1b5c05 at posting.google.com>... > Perhaps somebody here can enlighten me on this. > > I have a small program that interfaces with a serial port using the > uspp (univerisal serial port) package. This required the win32all > v148 as a pre-req. This program works as designed from cmd.exe. > > Python version is "Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 > bit (Intel)] on win32" > > I needed to have this program called from a cgi script using expect so > I installed the latest cygwin and configured inetd to run a service to > support telnetd. When I try to run the python interpreter > interactively from a telnet session, I do not get any prompts. > > When I run the program, it works, but no output is displayed until it > terminates. Using the -u switch overcomes this. > > The cygwin version of python works correctly interactively, but I > can't use this because uspp does not work in cygwin. > > I do not get this behaviour from a cygwin bash shell from the machine, > not using telnet. > > Does any of this make sense? I'm not really in a "pickle" (sorry for > the pun), but just trying to understand why. From jkraska at san.rr.com Thu Nov 21 00:01:10 2002 From: jkraska at san.rr.com (Courageous) Date: Thu, 21 Nov 2002 05:01:10 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <3DDBB8BD.6020806@web.de> <87ptt0otp1.fsf@theasylum.dyndns.org> <3DDC5A89.7080406@nyc.rr.com> Message-ID: >> Think all you like. Industry has spoken. Other languages = 10. Lisp = 0. >True, but they spoke before: COBOL, CICS, VSAM, ... Not, really. The absence of Lisp in the community is largely due to a _grass roots_ dislike of Lisp itself. C// From mhammond at skippinet.com.au Tue Nov 5 17:01:38 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 05 Nov 2002 22:01:38 GMT Subject: win32com / Dispatch In-Reply-To: <3dc6c2ad@news.uia.ac.be> References: <3dc6c2ad@news.uia.ac.be> Message-ID: <6dXx9.15577$5u4.50589@news-server.bigpond.net.au> Paul.Casteels at ua.ac.be wrote: > When I use win32com.client.Dispatch I get a CDispatch object with an > oleobj inside and I have direct access to all methods/attributes. > How can I obtain the same result when I get the IDispatch pointer from > an external application (as an argument from another COM method). > The type of this pointer is PyIDispatch but I am unable to invoke any > methods on it. Simply pass the PyIDispatch object to win32com.client.Dispatch() - it detects this case and creates a wrapper around it. Mark. From vinay_sajip at yahoo.co.uk Thu Nov 14 19:55:58 2002 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 14 Nov 2002 16:55:58 -0800 Subject: ANN: Logging Package v0.4.7 released Message-ID: <2e37dc1.0211141655.18262207@posting.google.com> A new version of the proposed Python standard logging package (as per PEP 282) has been released. What Does It Do? ================ The logging package offers the ability for any Python program to log events which occur during program execution. It's typically used to provide application diagnostics, warnings and error messages. In addition to capturing "what happened", "where it happened", "when it happened", "how important it is" and event specific data, you can configure, without changing the application source code, both the verbosity of logging and the routing of events to different destinations such as console, disk files, sockets, email addresses, Web servers, SOAP servers etc. etc. You can even change the configuration of a running program without stopping and restarting it! You can use the logging package in exception handlers, and it will include traceback information in the log. It's thread-safe, and very easy to use - just "import logging" and log away! Classes provided include: Logger - used to log messages for a particular area of an application. You can instantiate these wherever you want, there's no need to pass references to them around your application. You can log events based on importance levels of DEBUG (least important), INFO, WARN, ERROR, and CRITICAL (most important). You can define your own levels if the default levels don't meet your requirements. Handler - used to route events to particular destinations. Handlers included are: StreamHandler (for generalized streams, including console) FileHandler (for disk files - including log file rotation with size limits for log files) SocketHandler (for sending events to a TCP socket) DatagramHandler (for sending events to a UDP socket - faster, but less reliable than TCP) SMTPHandler (send events to arbitrary email addresses) HTTPHandler (send events to Web servers) SysLogHandler (send events to Unix syslog) MemoryHandler (batch up events and process them several at a time) NTEventLogHandler (send events to Windows NT event logs) There are also examples of XMLHandler and SOAPHandler in the distribution. Formatter - used to format events as text strings. Flexible "msg % arg_tuple" formatting is the basis for formatting, with flexible date/time formatting including ISO8601 and any strftime-based formats. Filter - used when filtering based on importance (DEBUG/INFO/WARN/ERROR/CRITICAL) is not sufficient. The distribution includes examples of filters based on class matching, regular expression matching, value matching, and logger matching. In the unlikely event that you're daunted by all the apparent complexity, fear not. The package offers a simple function-based interface to allow very simple, almost casual use of the underlying features. In addition to the core logging functionality, you get the ability to configure logging using a ConfigParser-based text file format, a Tkinter-based GUI configurator which creates configuration files for you, and a simple network-based event receiver which receives events on TCP, UDP, HTTP and SOAP ports. This is suitable for testing and might perhaps serve as a model for your own event receivers. Also included are over 20 test scripts which serve both as test harnesses and examples of how to use the logging package. You can get more information from http://www.red-dove.com/python_logging.html There are "download" and "recent changes" links at the top of that page. The new stuff includes some bug fixes, better support for class-based filtering and logging, more documentation of the configuration file format, an example hand-coded configuration file for those people who can't use the GUI configurator, an example Filter for regular-expression match-based filtering, and more! As always, your feedback is most welcome (especially bug reports, patches and suggestions for improvement). Enjoy! Cheers Vinay Sajip Red Dove Consultants Ltd. Changes since the last version: ================================= Made into a package with three modules: __init__ (the core code), handlers (all handlers other than FileHandler and its bases) and config (all the config stuff). Before doing this: Updated docstrings to include a short line, then a blank line, then more descriptive text. Renamed 'lvl' to 'level' in various functions. Changed FileHandler to use "a" and "w" instead of "a+" and "w+". Moved log file rotation functionality from FileHandler to a new class RotatingFileHandler. Improved docstring describing rollover. Updated makePickle to use 4-byte length and struct module, likewise logrecv.py. Also updated on-the-fly config reader to use 4-byte length/struct module. Altered ConfigParser test to look at 'readline' rather than 'read'. Added optional "defaults" argument to fileConfig, to be passed to ConfigParser. Renamed ALL to NOTSET to avoid confusion. Commented out getRootLogger(), as obsolete. To do regression testing, run log_test.py and compare the created files stdout.log and stderr.log against the files stdout.exp and stderr.exp. They should match except for a couple of exception messages which give absolute file paths. Updated python_logging.html to remove links to logging_pydoc.html, which has been removed from the distribution. Changed default for raiseExceptions to 1. From mwh at python.net Wed Nov 27 06:06:19 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 27 Nov 2002 11:06:19 GMT Subject: do you guys help newbies?? References: Message-ID: <7h3n0nvqnrs.fsf@pc150.maths.bris.ac.uk> "malik martin" writes: >
I find it very hard to read posts that do this, so if a newbie posts in HTML, I don't help him or her. Cheers, M. -- I wouldn't trust the Anglo-Saxons for much anything else. Given they way English is spelled, who could trust them on _anything_ that had to do with writing things down, anyway? -- Erik Naggum, comp.lang.lisp From aleax at aleax.it Wed Nov 20 06:55:19 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 20 Nov 2002 11:55:19 GMT Subject: stopping SimpleHTTPServer References: Message-ID: dsavitsk wrote: > "Alex Martelli" wrote in message > news:AptC9.28393$744.1027998 at news1.tin.it... >> dsavitsk wrote: > > * * * > >> In your subclass, you need to override method handle_error, which by >> default processes all exceptions (including the SystemExit exception >> raised by sys.exit) by printing a traceback and continuing. Check if >> the exception is SystemExit and then re-raise it, otherwise delegate >> to your base-class's handle_error for normal error processing... >> > right. I am not getting something very fundamental, so this is a good > learning opportunity ... Here's the simplest toy example I can put together -- it may help e.g. in case you made any confusion between handler and server classes: import BaseHTTPServer as B import SimpleHTTPServer as S import sys class myServer(B.HTTPServer): def handle_error(self, request, client_address): print 'handle_error', request, client_address raise class myHandler(S.SimpleHTTPRequestHandler): def do_GET(self): sys.exit(1) S.test(myHandler, myServer) running this, then doing e.g. urllib.urlopen('http://localhost:8000/whatever') from another terminal on an interactive session, results in output: Serving HTTP on 0.0.0.0 port 8000 ... handle_error ('127.0.0.1', 50636) and a return to the prompt. Alex From dsavitsk at e-coli.net Wed Nov 13 20:50:14 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Thu, 14 Nov 2002 01:50:14 GMT Subject: python gui rant References: <3dd217e2$0$231$4d4ebb8e@news.nl.uu.net> Message-ID: "Gumuz" wrote in message news:3dd217e2$0$231$4d4ebb8e at news.nl.uu.net... > i am using wxPython at the moment as my python gui. Coming from a nice IDE > like Delphi it's really frustrating to get a nice layout together. I tried > some tools. The one i liked most, because of it's simplicity was wxGlade, > but still... it's not there yet. I might have missed something here and I > don't want to complain, but I think that a good, robust gui-designer will > open up a lot of posibilities for python. i might give it a shot! unless you are needing cross-platform-ination from your gui, why not just use Delphi and either use PythonCOM for the code. I do this w/ VB quite a bit. Or, you might use Python for Delphi (http://membres.lycos.fr/marat/delphi/python.htm). If you do need cross platform, port your code to Kylix and tie it to Python ... has anyone done this, btw? -doug From donn at u.washington.edu Wed Nov 20 13:28:43 2002 From: donn at u.washington.edu (Donn Cave) Date: 20 Nov 2002 18:28:43 GMT Subject: exception thrown from I/O interrupted by signal References: Message-ID: Quoth Volker Apelt : | | Which exception is thrown from a I/O operation that is | interrupted by a signal? | | Which specification will catch it? | | try: | line = f.readline() | except WhatIsIt, e: | print e The exception will actually be raised by the library function that you have called, and they each raise their own exception. Optimistically assuming you have a bona fide file object there, you may specify IOError. The errno attribute of the exception will match errno.EINTR. Donn Cave, donn at u.washington.edu | ----- python lib docu | _underline_ added by me. | http://www.python.org/doc/current/lib/module-signal.html | | 7.1 signal -- Set handlers for asynchronous events | # When a signal arrives during an I/O operation, it is _possible_ that the | I/O operation raises _an_exception_ after the signal handler returns. This | is dependent on the underlying Unix system's semantics regarding | interrupted system calls. From kemu at sdf-eu.org Thu Nov 28 08:20:27 2002 From: kemu at sdf-eu.org (Jonas Geiregat) Date: Thu, 28 Nov 2002 14:20:27 +0100 Subject: what does is ? In-Reply-To: <3de4a6dd$0$86531$ba620e4c@news.skynet.be> References: <3de4a6dd$0$86531$ba620e4c@news.skynet.be> <3DE4B96D.1060808@Linux.ie> Message-ID: <3de617bb$0$216$ba620e4c@news.skynet.be> Gerhard H?ring wrote: > Padraig Brady wrote: > > >Gerhard H?ring wrote: > > > >>Jonas Geiregat wrote: > >> > >> > >>>I saw something > >>>import string > >>>string._StringType is str > >>>what does this specially that IS > >> > >>The "is" operator compares object *identity*, rather than equality, > which > >>the "==" operator does. > > > >Well why does the following happen on 2.2? > >Is Python being clever about merging variables? > > > >s1="123" > >s2=s1[:] > >s1 is s2 #true? > > > Yes. Certain strings (not all) are being "interned". And certain ints > (not all) > are interned, too: > > >>> a = 5 > >>> b = 10/2 > >>> a is b > 1 > >>> x = 1000000000000 > >>> y = 2000000000000 / 2 > >>> x is y > 0 > > But it seems to me that the [:] slicing has an additional > optimization, apart > from interning. why is x is y 0 and a is b 1 I don't get it it's the same code only different and bigger numbers From maney at pobox.com Wed Nov 20 11:37:08 2002 From: maney at pobox.com (maney at pobox.com) Date: Wed, 20 Nov 2002 16:37:08 +0000 (UTC) Subject: matching multiple regexs to a single line... References: Message-ID: Alex Martelli wrote: > Alexander Sendzimir wrote: >> # I will say that what I don't like about the approach you propose is that >> # it throws information away. Functionally, it leads to brittle code which >> # is hard to maintain and can lead to errors which are very hard to track >> # down if one is not familiar with the implementation. > > I suspect it would be possible to construct utteances with which I > could disagree more thoroughly than I disagree with this one, but > it would take some doing. I think that, since re patterns support > the | operator, making use of that operator "throws away" no > information whatsoever and hence introduces no brittleness. Just to prove that someone else is reading this thread (barely)... :-) I can somewhat agree with Alexander, and I think you're overlooking the way that this approach does force the regexps and their associated handler code apart in the source code. Most of his objections, yes, they're misguided, but the loss of the simple nearness of the pattern with the action is one legitimate complaint against the all-in-one-regex approach to this. Of course, the reason the Perl pattern he started with was so clean and straightforward was due to a globally shared "result of last re applied" state, wasn't it? Talk about frangible design! OTOH, it does fall into line with doing things by sensible convnetion rather than strict rules, which you say (elsewhere, not quoted in reply) is Pythonic... > some more normal people following this thread...:-): if the I refuse to admit that I am "normal", please. :-) > In some other cases client code may not only need to have no > constraints against using groups in the RE patterns, but also > want "the match-object" as an argument to the action code. In This is one point on which I agree with Alexander: it seems to me to be the usual case that the regexp both identifies and parses the target. If it isn't being used in that dual mode, then the whole issue addressed here (and in at least two other threads during the past week) doesn't exist. From mike at skew.org Thu Nov 7 18:58:51 2002 From: mike at skew.org (Mike Brown) Date: Thu, 7 Nov 2002 16:58:51 -0700 Subject: Date/Time Conversion References: Message-ID: <3dcafe3b$1_1@omega.dimensional.com> "dapmco" wrote in message news:eeAy9.46$4G5.20100 at news.abs.net... > Thanks Paul.. That worked fine. I looked at the docs but could not figure > out how to do this. A couple of routines looked like they would work but I > couldnt seem to invoke them on my Windows platform > > Input a date in some format ex 01/01/1990.. > Return the number of seconds between 01/01/1970 and the date entered. Yeah, Windows doesn't have time.strptime(). Try something like this... import re, time s = '01/01/90' pat = re.compile(r'(\d+)/(\d+)/(\d+)') m,d,y = pat.match(s).groups() # assuming USA (month first) y = int(y) y += 1900 + 100 * (y < 70) # Beware! Y2.07K bug! secs = time.mktime((y,int(m),int(d),0,0,0,0,0,0)) From steve.cassidy at mq.edu.au Sat Nov 9 06:04:47 2002 From: steve.cassidy at mq.edu.au (Steve Cassidy) Date: Sat, 09 Nov 2002 22:04:47 +1100 Subject: PEP 301 -- Package Index and Metadata for Distutils References: Message-ID: On Fri, 08 Nov 2002 17:25:02 +0100, Thomas Heller wrote: > As I've said before (on catalog-sig), I would consider a catalog as > proposed by PEP 301 as *just another way* to search for Python > software, but there are many ways already. > > What I would like is that the catalog either > > - allows to find out (programmatically) the link to the download URL > for the software package, > > - or offers the software package itself. > > The TIP 55 sample implementation seems to implement the second one. TIP 55 defines a package format which includes metadata and one of the metadata fields could well be the package download URL. This metadata could be indexed separately by some service, but CANTCL is an attempt at getting something like CPAN started for Tcl so it assumes that it's storing the packages itself. As for programmatically finding download urls, my approach would be to set up a canonical URL for Tcl packages using a purl (eg. http://purl.org/tcl/cantcl/foobar would get you the foobar package via cantcl). This aside, I see distinct advantages in having compatible metadata between the two systems. Steve From ianb at colorstudy.com Fri Nov 8 20:34:30 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 08 Nov 2002 19:34:30 -0600 Subject: Why is Python popular, while Lisp and Scheme aren't? In-Reply-To: <3d5b5ad8.0211080454.50bc6128@posting.google.com> References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: <1036805670.7989.95.camel@dsl-65-184-205-5.telocity.com> At one time during school I had gotten into Smalltalk, and felt the same way about it as many do about Lisp -- it was a great language and why didn't people use it more? I think many of Smalltalk's flaws are similar to Lisp's flaws (and I still like both languages, but actively use neither). In both cases the syntax is novel. Smalltalk's syntax is actually quite aesthetically pleasing (in comparison to Lisp and most other languages, even Python), but regardless it doesn't look anything like standard Algol-style syntaxes. Speed is more of an issue with Smalltalk, but it's certainly no worse than Python. But I don't think syntax is the biggest problem with either of these languages. Neither Lisp nor Smalltalk allows a person to move gradually between environments. My first experience with Python was using it to create small scripts. They were learning devices to be sure, but they were also useful. My similar experiments with Smalltalk were not useful -- and the only way I could truly be useful in Smalltalk without writing large and complete applications would be to use a Smalltalk environment. I even considered actually doing this -- living in a Smalltalk world, with a Smalltalk browser and email client, storing my documents in Smalltalk objects, the whole deal. But that would be hard, and I never actually made that leap. People have made that same leap with Lisp -- the Lisp Machines of yore. But that's not going to be mainstream. In a heterogeneous environment both Lisp and Smalltalk have serious issues. Their style isn't friendly to outsiders, and even worse their environment usually isn't friendly. Python might not have as many libraries as Perl, but it has a heck of a lot -- and best, a lot of libraries that connect to C libraries of significant functionality. That's not fair, though -- neither language is fundamentally isolationist. So maybe the real blame lies with timing. Python came around when free software/open source was becoming a truly functional. Python gets a lot from that, and it also happens to get a lot from having a single implementation. Together, when something is implemented by one (sharing) person, it is shared among all Python programmers -- not programmers of a specific implementation, nor among everyone who finds it useful enough to pay for. This community could not have come to exist fifteen or twenty years ago, when those other languages were still fresh. There's other important practical issues. It's easy to share Python programs and modules. It's easy to manage the modules you get from others. It's easy to install Python, and while it doesn't start up instantly, it starts up pretty quick (quicker than Common Lisp or Smalltalk to be sure). People can script in Python, they can't in big languages. Scripting is a great way to pull people in, and unlike other languages (*coughperlcough*) they won't be burned when they try something of significant size. These are all details, but they are very important details. Ian From jwbaxter at spamcop.net Mon Nov 11 11:35:09 2002 From: jwbaxter at spamcop.net (John Baxter) Date: Mon, 11 Nov 2002 08:35:09 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h3k7jlwock.fsf@pc150.maths.bris.ac.uk> <3dce96ad$0$12451$edfadb0f@dread11.news.tele.dk> <3DCEB61A.EF3D8E05@alcyone.com> <3DCEBA43.941F62A2@alcyone.com> <3dcf6a25$0$35901$edfadb0f@dread13.news.tele.dk> Message-ID: In article <3dcf6a25$0$35901$edfadb0f at dread13.news.tele.dk>, "Anders J. Munch" wrote: > A fascinating read - like > when they invented garbage collection because they didn't have enough > spare bits for reference counting in the IBM 704 machine word ;) > > on-a-64-bit-machine-would-McCarthy-have-invented-Python-instead?-ly y'rs, We might have found out, had IBM ever gotten "Stretch" to work. --John (36 bits is SO confining) B. From wolfson at uchicago.edu Mon Nov 18 18:28:32 2002 From: wolfson at uchicago.edu (Ben Wolfson) Date: Mon, 18 Nov 2002 17:28:32 -0600 Subject: Hmm... An idea: if a,b==c,d: References: <3DD974C6.CD626D0A@alcyone.com> Message-ID: On Mon, 18 Nov 2002 15:16:22 +0000, Erik Max Francis wrote: > Even if you group parentheses to avoid this, you get > > (a, b) == (c, d) > > which also already has a meaning; it's a comparison of the tuples, not > the pairwise comparison of the elements. I was under the impression that a comparison of two tuples of equal length amounts to a pairwise comparison of the elements anyway. -- I certainly seem to be enjoying myself in the same way, smacking my lips, sighing and moaning, dripping [REDACTED] on my shirt and smearing it into my moustache ... But ... If I snuck a lick of your cone, I wouldn't smack my lips. -- Ted Cohen From dwelch at nospam.vcd.hp.com Tue Nov 12 13:41:20 2002 From: dwelch at nospam.vcd.hp.com (djw) Date: Tue, 12 Nov 2002 10:41:20 -0800 Subject: newbie question: how to get directory of script? References: <4cce07d5.0211120957.6d4934@posting.google.com> Message-ID: os.getcwd() /d/ From cliechti at gmx.net Sun Nov 17 10:39:33 2002 From: cliechti at gmx.net (Chris Liechti) Date: 17 Nov 2002 17:39:33 +0200 Subject: Redirect question References: Message-ID: k.weinert at gmx.net (Karsten Weinert) wrote in news:fa576652.0211170745.2328fe56 at posting.google.com: > I have a question about redirecting. Here is a small program I found > on the web which I slightly modified; but now it does not run: > > import win32ui, sys > > class Redirect: > def __init__(self): > self.s="" > def write(self, s): > self.s+=s > def flush(self): > win32ui.MessageBox(s) that cannot work. def flush(self): win32ui.MessageBox(self.s) self.s = "" has better chances > sys.stdout = sys.stderr = Redirect() > > print 'Hidey Ho' > sys.stdout.flush() chris -- Chris From scott at aao.gov.au Fri Nov 1 02:35:37 2002 From: scott at aao.gov.au (Scott Smedley) Date: Fri, 01 Nov 2002 18:35:37 +1100 Subject: Combining Python/Tk & Tcl/Tk Message-ID: <3dc23e70@dnews.tpgi.com.au> Hi all, I'm new to Python & come from a Tcl/Tk background. Is it possible to integrate/embed Python/Tk with Tcl/Tk? I've read about a project called Minotaur, but that seems to be dead ... really dead. I'm interested because I've developed part of a GUI in Tcl/Tk & a project partner wants to develop their part of the GUI in Python/Tk. Thanks for any help/pointers. SCoTT. :) From smulloni at bracknell.smullyan.org Mon Nov 4 10:52:42 2002 From: smulloni at bracknell.smullyan.org (Jacob Smullyan) Date: 4 Nov 2002 10:52:42 -0500 Subject: old SimpleXMLRPCLib classes References: Message-ID: In article , Robin Becker wrote: > Under 2.1 I used a version of the SimpleXMLRPCServer module that > contained support for intermittent XMLRCPC via a class called > CGIXMLRPCRequestHandler. > > Under 2.2 it seems that SimpleXMLRPCServer has gone into the library, > but the CGI support classes are gone. Anyone know of a replacement? This > feature was really useful. This is the xmlrpc server support module I use; it is based on code from SimpleXMLRPCServer and scripts by F. Lundh and E. Kidd. It supports the standard system methods, and works with CGI and SkunkWeb: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/skunkweb/skunkweb/pylibs/xmlrpchandler.py?rev=HEAD&content-type=text/vnd.viewcvs-markup From dieter.menszner at web.de Sat Nov 9 03:07:20 2002 From: dieter.menszner at web.de (Dieter Menszner) Date: Sat, 09 Nov 2002 09:07:20 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <9b8hqa.eo3.ln@beastie.ix.netcom.com> Message-ID: <3DCCC238.6090304@web.de> David Eppstein wrote: > In article , > Carl Banks wrote: > > >>Python is more like Lisp than most other languages, though. It's >>similar semantically. > > > This makes little sense to me. Even the most basic data structures are > different: Lisp is based around singly linked lists while Python uses > vectors (with efficient random access unlike Lisp lists) and > dictionaries. They are also not especially similar in programming > This is just wrong. To say 'Lisp is based around singly linked' is similar as saying C is build around the ASCII character set. Not totally wrong but ... Common Lisp has built-in all the usual data types including hash tables. From tim.one at comcast.net Wed Nov 6 21:51:16 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 06 Nov 2002 21:51:16 -0500 Subject: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up In-Reply-To: Message-ID: [Tim] >> Write it in a platform-independent way. If you *intended* this >> literal to mean "a 1 bit followed by 31 zero bits", then stick an >> L on the end of the literal. [/F] > ...and remove it again when you get to Python 2.5. You can if you want. The PEP continues to allow it until Python 3.0. From chumphries at devis.com Sun Nov 10 03:49:33 2002 From: chumphries at devis.com (Chris Humphries) Date: Sun, 10 Nov 2002 03:49:33 -0500 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h31y5uyj81.fsf@pc150.maths.bris.ac.uk> <3DCD6038.7E6EC76B@kolumbus.fi> Message-ID: <3DCE1D9D.48F393C8@devis.com> where are you getting these "normal" definitions from? they do not exist. probably the closest thing to that being standardized is man style on *bsd, or the linux kernel coding doc about coding standards for code (forget the name). the people have enough of a time just keeping a language standard, much less the syntax. i use C syntax of openbsd's man style, lisp syntax that emacs uses, and python syntax i use at work that we agreed to use. standards are syntax are generally relative to what scope you are in when actually coding, not as some universal rule. -chris Richard Dillingham wrote: > > > > (if (a) > > > (if (b) > > > (if (c) > > > (asdf) > > > (zzzz) > > > ) > > > (foo) > > > ) > > > (bar) > > > ) > > > > > > > (if (a) > > (if (b) > > (if (c) > > (asdf) > > (zzzz)) > > (foo)) > > (bar)) > > > > Would be the normal way to write this. > > > > -- > > I know, but I personally find the way I wrote it to be easier to read. > You'll also note that I didn't use the normal C coding standard in the C > examples, and instead used the Java/C# standard (Which I prefer). > > The normal C way to use {}s being: > > if (a) > { > asdf; > } > > etc. > > -- > http://mail.python.org/mailman/listinfo/python-list From peter at abbnm.com Fri Nov 15 17:05:02 2002 From: peter at abbnm.com (Peter da Silva) Date: 15 Nov 2002 22:05:02 GMT Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DD0113D.79EC23F6@earthlink.net> <3DD01596.A3420862@san.rr.com> <3DD01A21.2E4968D7@earthlink.net> Message-ID: In article <3DD01A21.2E4968D7 at earthlink.net>, Benjamin Goldberg wrote: > > A binding isn't a procedure. > That depends on your interface to Tk ... in perl, a binding *is* a > procedure. In Tcl it isn't. It's a string. -- I've seen things you people can't imagine. Chimneysweeps on fire over the roofs of London. I've watched kite-strings glitter in the sun at Hyde Park Gate. All these things will be lost in time, like chalk-paintings in the rain. `-_-' Time for your nap. | Peter da Silva | Har du kramat din varg, idag? 'U` From maney at pobox.com Sun Nov 24 18:16:14 2002 From: maney at pobox.com (maney at pobox.com) Date: Sun, 24 Nov 2002 23:16:14 +0000 (UTC) Subject: Guido's regrets: filter and map References: <9PvekLArvL49Ewa2@jessikat.fsnet.co.uk> <3GBMGUASiS49EwqD@jessikat.fsnet.co.uk> Message-ID: Robin Becker wrote: > In article , maney at pobox.com writes > ..... anything with a lambda is already doomed as the lambda time Right, and that's the way I would normally have had to use them (before list comprehensions came along)... and of course, that's why you're asking for more non-lambda facilities. The problem is that once you go beyond a few basic operations, most or all of which have already been implementated, there's a vast range of tests and translations, far too many to implement them all in case they shuold be needed. > dominates. As for the del I use it to remove the possibility that memory > use from the first test will cause problems for the second etc Of course. I only remarked it because I thought it was a small error that it was contained inside range of code that was timed, and then because moving the del outside those ranges caused an easily visible change for the map and comprehension test, but not for the explicitly coded loop. From hamish_lawson at yahoo.co.uk Fri Nov 29 11:27:19 2002 From: hamish_lawson at yahoo.co.uk (Hamish Lawson) Date: 29 Nov 2002 08:27:19 -0800 Subject: Newbie Question: Giving names to Elements of List/Tuple/Dict References: Message-ID: <915a998f.0211290827.245c64b@posting.google.com> Alfredo P. Ricafort wrote: > It seems that when you define a data structure in the form of a List, Tuple, > or Dict., there is no way to give names to each element. Dictionaries actually *must* be keyed by an explicitly provided key, often a string: customer = {'name': 'Bob Smith', 'address': '12 Main St', 'TelNo': '768 8686'} print customer['name'] Hamish Lawson From ark at research.att.com Wed Nov 13 14:45:20 2002 From: ark at research.att.com (Andrew Koenig) Date: Wed, 13 Nov 2002 19:45:20 GMT Subject: Arrays? References: <3dd2a4fc$0$28317$fa0fcedb@lovejoy.zen.co.uk> Message-ID: Taz> Hi all, right... wanted to create an array in my python program Taz> (2 dimensional), but I dont think it can, o-rather it can, it Taz> just doesnt call it an array (damm stupid thing :p) Taz> So im looking to creat a list? If so, how do I make it 2 dimensional? The answer is likely to depend on what kind of computation you want to do -- so can you give us a little more detail? -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From jan at jandecaluwe.com Wed Nov 27 15:48:17 2002 From: jan at jandecaluwe.com (Jan Decaluwe) Date: Wed, 27 Nov 2002 21:48:17 +0100 Subject: Issue with new-style classes and operators References: <3DE215D1.D9A3FEF9@jandecaluwe.com> <5ApE9.52343$744.1917235@news1.tin.it> <3DE2893A.CCB631D6@jandecaluwe.com> <3DE449BD.1040503@something.invalid> <3DE48ECC.8FC9AE53@jandecaluwe.com> Message-ID: <3DE52F91.3DA4ED8F@jandecaluwe.com> Terry Reedy wrote: > > "Jan Decaluwe" wrote in message > news:3DE48ECC.8FC9AE53 at jandecaluwe.com... > > Ok, let me explain better. Suppose - for the sake of the > > argument - that I have a legitimate need for mutable numbers. > > To me, the concept 'mutable number' doesn't 'compute' very well. > > A label or pointer that is attached to or points to different > (eternally existing) numbers at different times (a 'variable') make > sense, and we have such. > > A container whose number contents change also make sense, and we also > have that. > > One could regard a count as a (changeable) collection of units, but > that is similar to the above and can be modeled either with list or > set/dict. > > So what do you mean by mutable number, such that it could be needed > but not available today? Too long to explain here - really. I promise I will though (in another thread, at another time). I propose to concentrate on the main point here: whether Python works as promised or not. At this moment - and with your help - I believe I can show it doesn't. Regards, jan -- Jan Decaluwe mailto:jan at jandecaluwe.com From neal at metaslash.com Tue Nov 12 22:03:18 2002 From: neal at metaslash.com (Neal Norwitz) Date: Tue, 12 Nov 2002 22:03:18 -0500 Subject: pythonic way to optimize access to imported value? References: <3DD1AB92.3030409@something.invalid> Message-ID: On Tue, 12 Nov 2002 20:32:02 -0500, Greg Ewing wrote: > Bengt Richter wrote: > >> >>> def mkfoo(): >> ... from math import pi >> ... def foo(): >> ... return pi >> ... return foo >> ... >> >> What would be best Pythonic practice for getting a foo2? It seems like >> if there were a way to say "do this part once at compile time" > > > It's not really compile-time that we want to do it, but module load > time, or perhaps function definition time. > > One way would be to use a default-argument hack: > > import math > > def foo(m = math): > return m.pi > > but this has all the usual drawbacks of the default-argument hack. > > This suggests that perhaps there should be a way of getting something > that is just like a default argument, except that it's not part of the > argument list. Maybe > > def foo(): > const m = math > return m.pi > > The "const" statement would be evaluated when the "def" was executed, > and "m" would appear in the local namespace when the function was > called. > > Although "const" might not be the best name for it, since it's not > really a constant, more like a local with an initial value. You can *kinda* do this with 2.1 (at least) and up: >>> import math >>> def foo(): return foo.pi ... >>> foo.pi = math.pi >>> foo() 3.1415926535897931 I realize this isn't exactly what you are asking for, but it is a way that works today. Neal From rnd at onego.ru Sun Nov 10 08:57:22 2002 From: rnd at onego.ru (Roman Suzi) Date: Sun, 10 Nov 2002 16:57:22 +0300 (MSK) Subject: RE - non-greedy - some greediness - complete greediness In-Reply-To: Message-ID: On Sun, 10 Nov 2002, Doru-Catalin Togea wrote: Probably sgrep (Structure GREP) is up to the task. There are Python hook into sgrep. > Hi! > > I am working on a little project where i need REs with a self-defined > level of greediness. > > I am processing text in a Latex like manner, for those of you who are > familiar with it. > > I want to be able to recognize Latex-like commands within my text. A > command starts with a character, say '\' followed by the command's name > and followed by the text on which the command applies enclosed in curly > brackets. Examples: > > \footnote{some text} > \cite{some referance} > \section{some title} > > Recognizing such patterns and retriving the name of the command and the > text on which the command applies is not so difficult to achieve. Things > get complicated though when one encounters nested commands. > > Say I have the following string: > > "abcd \footnote{efgh \cite{myRef1} ijkl} mnop \footnote{hello there}" > ^ ^ ^ > closing bracket of nested \cite | | | > closing bracket of first \footnote | | > closing bracket of second \footnote | Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From andymac at bullseye.apana.org.au Thu Nov 21 05:15:40 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 21 Nov 2002 20:15:40 +1000 (est) Subject: python-dev Summary, 2002-11-01 through 2002-11-15 In-Reply-To: <20021120085035.28636.00000048@mb-bj.aol.com> Message-ID: On 20 Nov 2002, TeaAndBikkie wrote: > This restriction seems a bit unfriendly... is there any direction to getting > python compilable on/for windows with an open source compiler, eg. gcc, mingw, > etc? As the timbot mentioned, Cygwin is actively supported, and someone is looking into a MingW build. I have used MingW to compile extensions for the PythonLabs MSVC distro - did require a bit of library mangling to get a usable Python DLL import library, but there are instructions on how to do that. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From jfontain at free.fr Thu Nov 7 02:29:22 2002 From: jfontain at free.fr (Jean-Luc Fontaine) Date: 6 Nov 2002 23:29:22 -0800 Subject: tcl/python interaction problem Message-ID: <4244613b.0211062329.12d7d601@posting.google.com> I am the author of the tclpython library, which, as its names implies allows the embedding of python code inside tcl scripts. I recently moved to redhat 8.0, which includes python 2.2.1 and tcl 8.3.3. When I recompiled the tclpython library, I found it hanging when creating a new python interpreter from tcl, as in: package require tclpython 2 set i [python::interp new] # the above just hangs (never returns) The tclpython library used to work before with both python 1.5 and 2.0. I could simplify the code and traced it to the following: --- tcl/python test library code --- #include #include int Ppp_Init(Tcl_Interp *interpreter) { PyThreadState *state; Py_Initialize(); PyEval_InitThreads(); state = Py_NewInterpreter(); return Tcl_PkgProvide(interpreter, "ppp", "1.0"); } --- tcl test code --- $ tclsh > load ./ppp.so -- strace -e trace=signal --- rt_sigaction(SIGPIPE, {SIG_IGN}, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRTMIN, {0x404f191c, [], SA_RESTORER, 0x400ea238}, NULL, 8) = 0 rt_sigaction(SIGRT_1, {0x404f0c68, [], SA_RESTORER, 0x400ea238}, NULL, 8) = 0 rt_sigaction(SIGRT_2, {0x404f19a4, [], SA_RESTORER, 0x400ea238}, NULL, 8) = 0 rt_sigprocmask(SIG_BLOCK, [RTMIN], NULL, 8) = 0 rt_sigaction(SIGPIPE, {SIG_IGN}, {SIG_IGN}, 8) = 0 rt_sigaction(SIGHUP, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGINT, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGQUIT, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGILL, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGTRAP, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGABRT, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGBUS, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGFPE, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGKILL, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGUSR1, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGSEGV, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGUSR2, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGPIPE, NULL, {SIG_IGN}, 8) = 0 rt_sigaction(SIGALRM, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGTERM, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGSTKFLT, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGCHLD, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGCONT, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGSTOP, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGTSTP, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGTTIN, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGTTOU, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGURG, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGXCPU, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGXFSZ, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGVTALRM, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGPROF, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGWINCH, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGIO, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGPWR, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGSYS, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_3, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_4, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_5, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_6, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_7, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_8, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_9, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_10, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_11, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_12, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_13, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_14, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_15, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_16, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_17, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_18, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_19, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_20, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_21, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_22, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_23, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_24, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_25, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_26, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_27, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_28, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_29, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_30, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_31, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGINT, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGINT, {0x404f58c4, [], SA_RESTORER, 0x400ea238}, NULL, 8) = 0 rt_sigprocmask(SIG_SETMASK, NULL, [RTMIN], 8) = 0 rt_sigsuspend([] --- hung right above --- Then I made a simple test program using the same code, but launched directly through the command line, not via the Tcl interprepreter: --- C test code --- #include int main(int argv, char **argc) { PyThreadState *state; Py_Initialize(); PyEval_InitThreads(); state = Py_NewInterpreter(); return 0; } -- strace -e trace=signal --- rt_sigaction(SIGRTMIN, {0x4002591c, [], SA_RESTORER, 0x4011d238}, NULL, 8) = 0 rt_sigaction(SIGRT_1, {0x40024c68, [], SA_RESTORER, 0x4011d238}, NULL, 8) = 0 rt_sigaction(SIGRT_2, {0x400259a4, [], SA_RESTORER, 0x4011d238}, NULL, 8) = 0 rt_sigprocmask(SIG_BLOCK, [RTMIN], NULL, 8) = 0 rt_sigaction(SIGPIPE, {SIG_IGN}, {SIG_DFL}, 8) = 0 rt_sigaction(SIGHUP, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGINT, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGQUIT, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGILL, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGTRAP, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGABRT, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGBUS, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGFPE, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGKILL, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGUSR1, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGSEGV, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGUSR2, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGPIPE, NULL, {SIG_IGN}, 8) = 0 rt_sigaction(SIGALRM, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGTERM, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGSTKFLT, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGCHLD, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGCONT, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGSTOP, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGTSTP, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGTTIN, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGTTOU, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGURG, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGXCPU, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGXFSZ, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGVTALRM, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGPROF, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGWINCH, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGIO, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGPWR, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGSYS, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_3, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_4, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_5, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_6, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_7, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_8, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_9, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_10, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_11, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_12, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_13, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_14, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_15, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_16, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_17, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_18, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_19, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_20, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_21, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_22, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_23, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_24, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_25, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_26, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_27, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_28, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_29, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_30, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGRT_31, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGINT, NULL, {SIG_DFL}, 8) = 0 rt_sigaction(SIGINT, {0x400298c4, [], SA_RESTORER, 0x4011d238}, NULL, 8) = 0 --- program finished normally --- As you can see, the rt_sigprocmask() and rt_sigsuspend() calls never occur in the later case and the program exits as expected. When it hangs, in the tclpython library case, I traced it to the following instruction in Python-2.2.1/Python/pythonrun.c source file: static void initsite(void) { PyObject *m, *f; m = PyImport_ImportModule("site"); // <<< hangs here <<< if (m == NULL) { ... I am just guessing that the problem is related to signals and threads... I would really appreciate any pointers or hints to solve this problem. Many thanks in advance, Jean-Luc From mwilson at the-wire.com Fri Nov 15 10:10:39 2002 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 15 Nov 2002 10:10:39 -0500 Subject: Accessing Dictionary values from within the Dictionary References: Message-ID: In article , pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) wrote: >Probably this would work for you: > > dict = {'var1': 1, 'var2': 2, 'var3': dict['var1'] + dict['var2']} I doubt it: Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> dict = {'var1': 1, 'var2': 2, 'var3': dict['var1'] + dict['var2']} Traceback (most recent call last): File "", line 1, in ? NameError: name 'dict' is not defined >>> If the original poster had said *which* syntax error.. To the original poster: Consider just dict = {'var1':1, 'var2':2} First the Python interpreter builds a dictionary using the expression `{'var1':1, 'var2':2}` If this succeeds, then the interpreter associates the dictionary object with the name `dict` in one of its own symbol dictionaries. So when you try to refer to the `dict` dictionary within the expression that builds the dictionary that later will be called `dict`.. you find there is no such thing. .. if you're lucky. If there's a different object called `dict` at the time your statement is executed, that will be used instead. That had better be what you want. It goes beyond Python .. most common computer languages .. certainly the FORTRAN- or Algol-flavoured ones ,, work this way. Regards. Mel. From sismex01 at hebmex.com Tue Nov 26 10:22:44 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 26 Nov 2002 09:22:44 -0600 Subject: Newbie IDLE - import issues Message-ID: > From: Kenny Tilton [mailto:ktilton at nyc.rr.com] > Sent: Tuesday, November 26, 2002 9:25 AM > > sismex01 at hebmex.com wrote: > >>From: Kenny Tilton [mailto:ktilton at nyc.rr.com] > >>Sent: Tuesday, November 26, 2002 9:10 AM > >> > >>sismex01 at hebmex.com wrote: > >> > > > >>>I can only say that this sounds like some module you're > >>>trying to import isn't in your sys.path. > >> > >>no, but I supply the path: > >> > >> import cells.cell > >> > > > > > > > > Ahh! I *almost* know what's going on... > > > > > ..... > > > > does the "cells" directory have a "__init__.py" file, even if > > it's an empty file? > > yes, i had to sneak those in when I tried FROM in the hopes it would > solve the problem. first it didn't work, then i got those in > there and From /did/ work, so I am pretty sure that is all OK. > Hmmm... strange... So I'll wait for more concrete info. :-) -gustavo From jdhunter at ace.bsd.uchicago.edu Sun Nov 24 11:19:20 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 24 Nov 2002 10:19:20 -0600 Subject: Regular expression question In-Reply-To: <9a5f3d1c.0211240636.7614b51a@posting.google.com> (jonah13579@hotmail.com's message of "24 Nov 2002 06:36:02 -0800") References: <9a5f3d1c.0211231857.78125e43@posting.google.com> <9a5f3d1c.0211240636.7614b51a@posting.google.com> Message-ID: >>>>> "Jonah" == Jonah writes: Jonah> Thanks for the well-thought out response. I was wondering Jonah> whether a function map would be necessary. I know that in Jonah> a production environment, the line I use gives the user too Jonah> much power, but I use this for my own purposes, and I Jonah> control the source and the script. As for thinking in Jonah> python, I'm still at the very earliest stages of looking at Jonah> python (and ruby for that matter) as a possible replacement Jonah> for/addition to perl. You can forgo the function map and instead use a single function 'process' as a dispatcher, to lower case WHATEVER and eval a call to the lowered string import re def whatever(v): return 'WhAtEvEr' + v def want(v): return 'WaNt' + v def process(m): variable = '!' # your $variable return eval(m.group(1).lower() + '(variable)') print re.sub('%%(.*?)%%', process, 'I will do %%WHATEVER%% you %%WANT%%') The extra overhead is much lower. It has the downside of using the eval, but you seem aware of these risks. With thought, this could probably be converted into a one liner as in perl, but that is not usually an instinct around here, except for didactic purposes of course. John Hunter From hancock at anansispaceworks.com Thu Nov 14 05:09:47 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 14 Nov 2002 02:09:47 -0800 Subject: Visual programming, looking for graphics layer In-Reply-To: <20021114073103.7797.84412.Mailman@mail.python.org> References: <20021114073103.7797.84412.Mailman@mail.python.org> Message-ID: Hi Ian, On Wednesday 13 November 2002 11:31 pm, Ian Bicking wrote: > After implementing a little Logo interpreter, I wanted to do > something more novel and interesting, like > Boxer. ?In the extremely likely case you don't know anything about > Boxer, the website is at: > > ? http://www.soe.berkeley.edu/boxer/ > > It's a neat teaching language, where it has some graphical ways to > present programming structure. ?Sadly its only available for Macs, and I > don't know if development is active. ?But I've put up a little graphic > taken from one of the papers (and fixed up a bit) to give a feel: > > ? http://colorstudy.com/tmp/boxer-capture.gif I've always been interested by visual metaphors for programming (I've never found one of actual practical use to me, but I keep hoping to -- there's a couple, like "overflow" that I want to spend some time to learn). Anyway, that's fairly interesting (not really enough information on the web pages to form a real opinion, though -- might have to dig deeper). > The hard part is that this sort of layout is fairly hard to do. ?Not > only do you have text inside different sorts of boxes, but an important > part of the language is that you also have non-text literals (like > colors and shapes, and even lists may be represented in a graphical > fashion). ?All these need to be manipulatable. Most of these things seem like fairly common GUI widgets to me -- the sticky part is probably editing them interactively. > I'm hoping to get some advice or pointers on something already available > that can make this easier. ?I could use pygame, maybe even with pyui, > but that's still a long way from what I'd have to do for even the most > minimal functionality. ?I've also had a hard time understanding pyui's > architecture -- there's something magic in there and I can't tell where > things actually get *done*... but I'm sure that's surmountable. ?Maybe > that's where I should be looking. I've been tinkering with PyUI (trying to implement the AWT renderer so it can be used in Jython -- following up the browser applets thread I started a few days ago). Clearly, I'm not an expert yet, but I plan to spend a lot of time with it -- maybe we can figure it out together? Briefly, it appears to me that a PyUI renderer starts up and calls a program to run under PyUI using that renderer. The program creates widgets to respond to various events. At that point, the program idles, waiting for events posted from the renderer to PyUI's events mechanism which drives the modification of the GUI model inside of PyUI. The model is rendered to the display by the renderer. Interestingly, it doesn't really appear to matter whether the renderer polls for events or catches events (as in interrupts). The renderer is pretty simple, and just has to handle drawing and catching the events. So far the most complicated thing seems to be fonts. I'm not sure what exactly you meant by "things" and "done", but I hope that summary is helpful in some way. The one thing I find frustrating with PyUI (as it is now), is that many of the primitive data structures "rect", "pos", "font" aren't really very well defined. I'm not sure if this is a problem for the application programmer, though. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From sismex01 at hebmex.com Wed Nov 13 17:19:44 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 13 Nov 2002 16:19:44 -0600 Subject: My (late) beef with Simple Generator syntax (PEP 255) Message-ID: > From: Cameron Horn [mailto:camhorn at mac.com] > Sent: Wednesday, November 13, 2002 4:20 PM > > On Wednesday, Nov 13, 2002, at 02:16PM, David Eppstein > wrote: > > >On 11/13/02 2:11 PM -0800 Cameron Horn wrote: > >>> What I wonder is, why does it need to be a generator? > What's wrong with > >>> def foo(): return ( ) > >>> ? > >> > >> You're right if it's a one-time thing. However, if I've got a > >> scaffolding like this, then it matters. > >> > >> def process_generator(function): > >> for x in function(): > >> print x > > > >How does the function foo() I defined above fail to work in this > >scaffolding? > > In the "TypeError: iteration over non-sequence" sort of way. > An empty tuple is a sequence also; the "return ( )" thing is returning an empty tuple, not "None". You can make it clearer by using "return tuple()" rather than "return ()". -gustavo From rodrigobamboo at hotmail.com Tue Nov 19 11:07:51 2002 From: rodrigobamboo at hotmail.com (Rodrigo B. de Oliveira) Date: 19 Nov 2002 08:07:51 -0800 Subject: Python embedding question: how to expose a new "builtin"? Message-ID: I've built an ISAPI module that allows .py files to be executed by IIS, everything is working fine and the performance is great. Now I want to expose an object in such a way that every imported module could see it, I tried the following code but it didn't quite work: PyObject* __builtin__ = PyImport_ImportModule("__builtin__"); PyObject_SetAttrString(__builtin__, "application", (PyObject*)_pyapplication); Py_DECREF(__builtin__); Notes: * _pyapplication is an instance of a C new style class The problem is: the modules can see the name "application" but dir(application) returns [] and if I try to access any of application's attributes I get an AttributeError. Thoughts? Thanks in advance, Rodrigo B. de Oliveira PS: the ISAPI module will go Open Source in a few days... From paul at boddie.net Wed Nov 6 10:23:38 2002 From: paul at boddie.net (Paul Boddie) Date: 6 Nov 2002 07:23:38 -0800 Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DC8623B.88753C16@earthlink.net> <3DC8CDDD.7050103@mindspring.com> <3pE8dhAtvNy9EwoQ@jessikat.fsnet.co.uk> Message-ID: <23891c90.0211060723.22fd36bc@posting.google.com> Robin Becker wrote in message news:<3pE8dhAtvNy9EwoQ at jessikat.fsnet.co.uk>... > > it seems that only those with sufficient muscle can force this on the > world eg Sun/IBM/M$. They can clearly see the need to support only one > backend. ...each. ;-) Well, I suppose Sun and IBM are sort of sharing. Paul P.S. Projects like Parrot only really tend to succeed if they either produce results quickly enough for casually interested parties or have enough direction and motivation for the prolonged period of time that they aren't producing highly usable output. Despite hearing about Parrot occasionally, I'm not so sure that Parrot exhibits either of these properties, but it would be nice to be proved wrong. From max at alcyone.com Wed Nov 13 18:34:05 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 13 Nov 2002 15:34:05 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCF83B2.2030008@web.de> <3DD0D765.3030907@web.de> <3DD16CAF.41214BBA@alcyone.com> <3DD1DE6A.1BBEFE5A@alcyone.com> Message-ID: <3DD2E16D.6831402D@alcyone.com> Paul Foley wrote: > I know. But, as I said, Scheme and Lisp are very different languages. > I.e., Scheme is /not/ a good introduction to Lisp (and vice versa), > any more than, say, INTERCAL is a good introduction to Java :-) Again, that's why I said "Lisp-like languages," not Lisp. After all, if I were so inclined, I could turn the nitpicking apparatus back onto you: Which variety of Lisp do you mean when you say Lisp? There are a great number that are not only "Lisp-like" but actually have the word _Lisp_ in their names. > [What do you mean by "Lisp-like language" anyway? Python seems pretty > Lisp-like to me...] Languages that look and act like Lisp. One might argue that Logo qualifies (as a once-removed cousin), but I don't see how you can really argue that Python looks and acts like Lisp. If Python is Lisp-like then what isn't? -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Experience is the name everyone gives to their mistakes. \__/ Oscar Wilde WebVal / http://www.alcyone.com/pyos/webval/ URL scanner, maintainer, and validator in Python. From csshi99 at yahoo.com Thu Nov 7 17:36:14 2002 From: csshi99 at yahoo.com (Mindy) Date: Thu, 7 Nov 2002 14:36:14 -0800 (PST) Subject: Question about print format? In-Reply-To: Message-ID: <20021107223614.57256.qmail@web21210.mail.yahoo.com> Actually, I want to get a neat list of information about index,sybol,binding_file,to_file (which are 4 columns). The attachment is my program and the output I want and I got. Could someone help me with this output format stuff? Thanks very much! ===== Cheers -Mindy __________________________________________________ Do you Yahoo!? U2 on LAUNCH - Exclusive greatest hits videos http://launch.yahoo.com/u2 -------------- next part -------------- A non-text attachment was scrubbed... Name: test_file Type: application/x-unknown Size: 1312 bytes Desc: test_file URL: From bokr at oz.net Mon Nov 4 01:36:09 2002 From: bokr at oz.net (Bengt Richter) Date: 4 Nov 2002 06:36:09 GMT Subject: import Image vs from PIL import Image vs import PIL.Image References: Message-ID: On Sun, 3 Nov 2002 21:42:11 -0800, Brian Lenihan wrote: >In article , bokr at oz.net says... >> I backtracked and took alternate routes and hacked here and there on the way >> to the goal, so there were probably numerous places where something could have >> gone wrong, but it seems to work if -- and here's where my question comes in -- >> I put 'from PIL ' in front of the import statements in documentation examples. > >The examples assume you have a PIL.pth file in site-packages. > >Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 >Type "help", "copyright", "credits" or "license" for more information. >>>> import Image >>>> Image.core > >>>> > >C:\Python22\Lib\site-packages>cat PIL.pth >PIL Thanks, but that wasn't the problem. I had caused it with hacking detritus. Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import Image >>> Image.core >>> ^Z [22:20] C:\pywk\pilt>cat D:\python22\lib\site-packages\PIL.pth PIL But I notice an interesting difference in the name and place of the dll. Yours is right under site-packages\ as PIL_imaging.pyd and mine is under site-packages\PIL\ as _imaging.pyd. Did you install via the binary installer? BTW, if the effbot is lurking, I would offer a patch to Image.py which would have made what I did to myself more obvious: --- D:\pilbuild\Imaging-1.1.3\PIL\Image.py Thu Mar 14 11:55:04 2002 +++ D:\Python22\Lib\site-packages\PIL\Image.py Sun Nov 03 22:07:31 2002 @@ -35,8 +35,13 @@ class _imaging_not_installed: # module placeholder + def __init__(self, reason): + self.reason = reason def __getattr__(self, id): - raise ImportError, "The _imaging C module is not installed" + raise ImportError( + "The _imaging C module is not installed because:\n" + "%s" % self.reason + ) try: # give Tk a chance to set up the environment, in case we're @@ -53,8 +58,8 @@ import _imaging core = _imaging del _imaging -except ImportError: - core = _imaging_not_installed() +except ImportError, e: + core = _imaging_not_installed(str(e)) import ImagePalette import os, string, sys Regards, Bengt Richter From loewis at informatik.hu-berlin.de Wed Nov 27 09:11:09 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 27 Nov 2002 15:11:09 +0100 Subject: Implementation of the global statement References: <8ef9bea6.0211270526.5a1278c5@posting.google.com> <7h3adjvqgs4.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson writes: > > Yes, you guessed right, out of pure curiosity: is this list > > accessible from Python? > > Don't think so, as the list only exists during compiling and you can't > hook into it or only execute one phase of it. To some degree, you can find out by looking at co_names, and removing all names which are also in co_varnames (both are attributes of the code object). Of course, you can't tell afterwards if a global name was considered global because there was no assignment to it, or whether there was a global declaration. Also, globals that are not used don't appear in co_names. HTH, Martin From patrickw106 at yahoo.com.au Wed Nov 20 23:57:31 2002 From: patrickw106 at yahoo.com.au (Patrick W) Date: 21 Nov 2002 15:57:31 +1100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <3DDBD838.10406@nyc.rr.com> <3DDC5851.5060001@nyc.rr.com> Message-ID: <87wun7tt8k.fsf@key.localdomain> Kenny Tilton writes: > [...] But I for one am porting my Cells project: > > http://www.tilton-technology.com/cells_top.html > > ...to Python /precisely/ (a) to swim in a bigger pond (uh, pond with > more fish?) and (2) because there is (I hear) a x-platform GUI, Several in fact. > TKinter. And it's fun learning a new language, recommended so highly > by a CL worthy such as Norvig. Not trying to twist your arm but in case you weren't aware of it, Qt (and PyQt) is just as portable as Tkinter (on platforms that matter) and has a few advantages (snappier performance, more 'native' look, more (and IMO, better) widgets, easy integration with opengl, stable and reliable, distributed under 'free' or commercial licences, arguably more popular in industry, etc). They guy who maintains PyQt (the Python bindings to the Qt C++ libraries) does a great job of keeping up with the latest Qt releases. Perhaps worth a look if you haven't checked it out already. http://www.trolltech.com (for info on Qt) http://www.riverbankcomputing.co.uk/pyqt/index.php (for PyQt) From aleax at aleax.it Mon Nov 25 08:28:33 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 25 Nov 2002 13:28:33 GMT Subject: Issue with new-style classes and operators References: <3DE215D1.D9A3FEF9@jandecaluwe.com> Message-ID: <5ApE9.52343$744.1917235@news1.tin.it> Jan Decaluwe wrote: > Hi: > > I'm confused by the following behavior of new-style classes > and operators: > > class MyInt(object): > def __init__(self, val): > self.val = val > def __getattr__(self, attr): > return getattr(self.val, attr) > > >> python > Python 2.2.2 (#1, Oct 16 2002, 19:59:11) > [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> from MyInt import MyInt >>>> a = MyInt(3) >>>> a.__add__(4) > 7 >>>> a + 4 > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand types for +: 'MyInt' and 'int' > > > > I don't think is can be the intention. Or can it? Yes it can. The idea is that operators should rely on special methods defined by the TYPE (class) of the object they're working on, NOT on special methods defined just by the OBJECT itself and not by its class. Doing otherwise (as old-style classes did, and still do for compatibility) is untenable in the general case, for example whenever you consider a class and its metaclass (given that the metaclass IS the class object's type, no more and no less). So, for example, a + b now looks for a potential __add__ special method, NOT in a itself, but rather in type(a) [except, for compatibility, when a instances an old-style class]. I had some difficulty understanding that, early on in the lifecycle of Python 2.2, but when the notion "clicked" I saw it made a lot of sense. So, to wrap an arbitrary object X in such a way that X's special methods will be used by any operator, you need to ensure you do the wrapping with a _class_ that exposes said special methods. That's generally easiest to do with a factory function with a nested class that uses inheritance, but you have many other choices depending on what exactly you're trying to accomplish. Alex From jon+usenet at unequivocal.co.uk Thu Nov 7 14:20:29 2002 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Thu, 07 Nov 2002 19:20:29 -0000 Subject: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up References: Message-ID: In article , Martin v. L?wis wrote: >> > I would still recommend to use 0x8000000L instead; it saves you one >> > computation, and is more readable. >> >> But that *won't work* on later versions of Python! > > How do you know? Later versions of Python have not been released! Because PEP237 tells me so ;-) >> It means I will have a line in my code which I know will suddenly >> stop working at some point in the future and I will have to make a >> new release and everyone will have to upgrade their copies of my >> module just because I put in code which I knew wasn't going to work. > > Yes, provided your code is still in use when that happens. Ooh, bitchy. From anton at vredegoor.doge.nl Sun Nov 24 16:59:41 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sun, 24 Nov 2002 22:59:41 +0100 Subject: Python IRC dictatorship References: <29304.91T434T13743504threeseas@earthlink.net><743utuoi3l31t8e8tt9v3sncosuk2gqi02@4ax.com><1239.92T1047T4844497threeseas@earthlink.net><4992.92T2618T9825720threeseas@earthlink.net> <9655.93T1847T6905169threeseas@earthlink.net> Message-ID: On Sun, 24 Nov 2002 16:34:56 GMT, "Timothy Rue" wrote: >On 23-Nov-02 17:05:04 John Hunter wrote: > >>This scenario was repeated many times, and it took me a long time to >>learn that when you are the client, you need to tell them what you >>need to do, not how to do it. > >Not in this case, for I cannot do that. It'd simply take to long for me to >give all the infinte examples of possibilities. Therefore that only leaves >what? Use the sequencer: http://home.hccnet.nl/a.vredegoor/sequencer It provides infinite possibilities, and if nothing else it should be able to confuse a lot of people. It surely does confuse me :-) Anton. From aleax at aleax.it Fri Nov 8 06:49:54 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 08 Nov 2002 11:49:54 GMT Subject: Newbie-list-problem: how to supress constraining 2 lists - a=b ? References: <813cfe33.0211080235.5d4b8c9e@posting.google.com> Message-ID: HugOnline wrote: > Hello, > > I'm a Python - newbie and I can not solve the following problem: > >>>>a=[8,7,6,5,4] # set this list to a >>>>b=a # I' want to have two same lists: a and b >>>>b.sort() # b should be sorted >>>>print b # it's ok > [4,5,6,7,8] >>>>print a > [4,5,6,7,8] # but a is sorted, too !!! > > How can I suppress the constraining of a and b? I want to have in the > result two list - a unsorted and b sorted. Is there a switch to supress > it? When you want a copy, you ask for a copy. There are MANY ways to ask for a copy of a string: b = a[:] b = list(a) b = [item for item in a] import copy b = copy.copy(a) etc, etc. Alex From roccomoretti at netscape.net Sat Nov 9 18:35:33 2002 From: roccomoretti at netscape.net (Rocco Moretti) Date: 9 Nov 2002 15:35:33 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: "Johannes Gr?dem wrote in message news:... > * Carl Banks : > > > Python uses infix notation for math. Most humans were brought up to > > understand infix. > > Because Lisp has a powerful macro system, it is actually possible to > have an infix-macro, which lets you use infix-syntax. And you can > write macros to support all sorts of weird syntax, if you want. I've heard this argument a number of times, and have never really bought it. To me it seems equivalent to saying "Because (Brainf*ck/ Intercal/ Unlambda/ Malbourge /etc) are Turing Complete, you can write any program in them." Sure, you *can*, but why bother? It's the same reason why using lists and dictionaries are so much better in Python than in C. Sure, you *could* write your own type and various accessory methods to do the same thing, but why should you have to deal with the boilerplate code to make the language do it? It's doubly hard when beginning Lisp books only teach the prefix notation - the beginner could change it, but who, thus thouroghly vexed, has the stamina to wait until chapter 23 to learn how? That's why the common rebuttal directed toward Lisp critics is that they don't *really* know the language. Lisp is a powerful language, but you have to have the patience and the masochism to make it all the way to chapter 23. If-I-wasn't-lazy-I-would-be-doing-it-longhand From cliechti at gmx.net Thu Nov 14 15:25:14 2002 From: cliechti at gmx.net (Chris Liechti) Date: 14 Nov 2002 22:25:14 +0200 Subject: simple rsh and python question References: Message-ID: rwadkins at flash.net (Randy Wadkins) wrote in news:d453156a.0211141053.7de1422 at posting.google.com: > Is there any way to rsh from a shell script to nodes in a cluster and > execute a python script that will run in the background on each node? > It appears that the execution is stopped once the rsh command is > completed. > rsh x$ python myscript.py "&" look up "nohup". otherwise any programm attached to the terminal are terminated when the terminal is closed. (HangUP signal) chris -- Chris From cnetzer at mail.arc.nasa.gov Fri Nov 15 00:15:58 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Thu, 14 Nov 2002 21:15:58 -0800 Subject: A really bad idea. In-Reply-To: References: Message-ID: <200211150515.VAA19770@mail.arc.nasa.gov> On Thursday 14 November 2002 20:49, Paul Foley wrote: > On Thu, 14 Nov 2002 15:33:33 -0800, Russell E Owen wrote: > > On the other hand, I like zip just fine (though I lament the lack of an > > unzip counterpart). > > Eh? Zip is its own inverse! Hmmm... Python 2.2.2 (#4, Oct 15 2002, 04:21:28) >>> a = [1,2,3] >>> b = ['a','b', 'c'] >>> zip(a,b) [(1, 'a'), (2, 'b'), (3, 'c')] >>> zip(zip(a,b)) [((1, 'a'),), ((2, 'b'),), ((3, 'c'),)] >>> c,d = zip(zip(a,b)) Traceback (most recent call last): File "", line 1, in ? ValueError: unpack list of wrong size So, not quite. But, after some thought, I see that you mean this (which is cool): >>> c,d = zip(*zip(a,b)) >>> c (1, 2, 3) >>> d ('a', 'b', 'c') ie. it's its own inverse, if you consider some extra syntax (and getting tuples, not lists). -- Bay Area Python Interest Group - http://www.baypiggies.net/ Chad Netzer cnetzer at mail.arc.nasa.gov From donn at u.washington.edu Wed Nov 20 13:00:22 2002 From: donn at u.washington.edu (Donn Cave) Date: 20 Nov 2002 18:00:22 GMT Subject: Understanding PyEval_InitThreads References: <7kf83526.fsf@python.net> Message-ID: Quoth Robin Becker : | In article <7kf83526.fsf at python.net>, Thomas Heller | writes ... |> Unfortunately it won't work this way. |> |> Think of call_some_c_code() being the C standard library's qsort |> function, and call_back_into_python() is the function pointer I gave |> qsort to do the comparison. There's no way to pass the thread state to |> the callback function! |> |> Storing the thread state in a global variable would be possible, but |> in this case it wouldn't be thread safe, I assume, and *only* work if |> the callout into C is done by my extension module. | .... | I think there's an issue here though. If the ctypes call is started in | thread A then it makes sense to ensure that thread A receives the | callback. Of course this is moot when only one python thread is running. | Perhaps this is the mainthread only issue with tkinter and the like. The callback will happen in thread A, of course (unless it doesn't, but that's a separate question.) In _my_ code that supports multithreaded callbacks, the callback has access to its original thread state and uses it in PyEval_AcquireThread(), but that isn't a requirement as far as I can see. One (OS) thread can set up as many new (Python) thread states as it requires on its way in and out of the interpreter, subject to availability of the resources involved (massive recursion might pose a problem.) They're just a mechanism to avoid internal concurrency. I call PyEval_InitThreads in my modules. Donn Cave, donn at u.washington.edu From mayhew at cis.ohio-state.edu Wed Nov 13 18:29:06 2002 From: mayhew at cis.ohio-state.edu (Michael Mayhew) Date: Wed, 13 Nov 2002 18:29:06 -0500 Subject: Newbie response, was Re: Why is Python popular, while Lisp and Scheme aren't? References: <20021111084619.3410.38803.Mailman@mail.python.org> Message-ID: <3DD2E042.5070801@cis.ohio-state.edu> Anton Vredegoor wrote: > On Mon, 11 Nov 2002 19:55:27 -0800, Terry Hancock > wrote: > > There's a lot of truth in this, as in the other part's of your - > greatly appreciated - post, but I would like to add that it's often > not possible for language designers to design a language that is not > *considered* difficult and that is also not difficult in a more > objective sense. We are living in a world where drinking brown colored > and fizzling water with added sugar and artifical taste producing > chemicals out of an aluminium (!) can is considered to be more natural > than just drinking water. > > Regards, > Anton. I concur with my esteemed colleague and I appreciate your post Mr. Hancock considering that I myself am an established newbie. (I can't seem to stay put either!) As a newbie to both Python and the open source community that the patience of the user and, more importantly, forum-frequenting community has helped motivate me to learn and better hone my open source skills while simultaneously granting me that warm and gooey feeling one only gets from being a part of something special and larger than oneself. Anyway, I'm off to consume mass quantities of brown colored and fizzling water with added sugar and artificial taste so that I can stay up and code in Python! ;-) Michael From aleax at aleax.it Sun Nov 10 05:34:50 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 10 Nov 2002 10:34:50 GMT Subject: indexed looping, functional replacement? References: <3fe406f0.0211091037.2795e538@posting.google.com> <9Xcz9.15450$XO.672555@news2.tin.it> Message-ID: Bengt Richter wrote: ... > also a lazy zip, to avoid building lists you don't use (untested beyond > what you see ;-) > > >>> from __future__ import generators > >>> def xzip(*args): > ... for i in xrange(min(map(len,args))): > ... yield tuple([x[i] for x in args]) > ... > >>> for f,s in xzip(fl,sl): > ... f(s) > ... > f1: bbb > f2: sdf > f3: sdw I think that xzip can be simplified a bit -- as code, the for statement is threateningly complex, and the tupleization of the yielded sublists just a bit of conceptual and runtime overhead, for most practical purposes. So, I might code it, instead: def xzip(*args): iters = map(iter, args) while True: yield [x.next() for x in iters] the key idea here is that the first iterator to run out will let the fact be known by raising StopIteration, and xzip just lets that exception propagate, thus in turn letting its caller know that xzip has also run out of items to iterate on. Of course, the semantics are slightly different. The original xzip needs arguments that are sequences (i.e., can be passed to 'len', and indexed by integers 0 and up), while this simpler one accepts arguments that are iterable (can be subjected to iter). All sequences are iterable, but not vice versa (file objects open for reading, for example, are iterable, but not sequences). So, for example, this simpler xzip could be used to print out a textfile's lines with numbering: for line, linenumber in xzip(open('the.txt'), xrange(sys.maxint)): print '%d: %s' % (linenumber, line), while the original would die with a TypeError if used in this way (the file object can be iterated on, but not indexed, nor can it be passed as the argument to built-in 'len'). However, it seems to me that the simpler xzip's greater generality is not a substantial problem -- simplicity IS nice to have. Alex From pyth at devel.trillke.net Fri Nov 29 10:01:15 2002 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 29 Nov 2002 16:01:15 +0100 Subject: Newbie Question: Giving names to Elements of List/Tuple/Dict In-Reply-To: <20021129141954.GA1876@hishome.net>; from oren-py-l@hishome.net on Fri, Nov 29, 2002 at 09:19:54AM -0500 References: <1038571003.6023.20.camel@localhost.localdomain> <20021129141954.GA1876@hishome.net> Message-ID: <20021129160115.C11257@prim.han.de> Oren Tirosh wrote: > On Fri, Nov 29, 2002 at 07:56:44PM +0800, Alfredo P. Ricafort wrote: > > Hi, > > > > I'm quite new to Python. So far I find it to be easy to learn and > > simple to program. However, one thing that I missed, especially someone > > coming from C language, is 'struct'. It seems that when you define a > > data structure in the form of a List, Tuple, or Dict., there is no way > > to give names to each element. > ... > > Now my problem is that when the structure of the record change, your > > index has to change also. So in the example above, when the 'Name' > > element is moved(say as the 3rd element - Customer[i][2]), then you have > > to look all over your code and change accordingly. > > > > My question now is, how can I assign names to the elements? Or is there > > a better way of doing this? > > Many Python programmers use an empty class for this: > > class Struct: > pass > > s = Struct() > s.name = "John Doe" > s.phone = "555-5127" > etc. > > It has no predefined structure - you can add any field you like and use > the same class for different types of data. You can delete attributes > with a del statement (e.g. 'del s.phone') and test for the presence of > an attribute using hasattr ('if hasattr(s, "fax"):') Additionally using class Struct: def __init__(self, **kw): self.__dict__.update(kw) is also a nice idiom. You can then say >>> one = Struct(name='guido', phone='5555') >>> one.name 'guido' >>> one.phone '5555' >>> regards, holger From erno-news at erno.iki.fi Fri Nov 8 03:16:37 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 08 Nov 2002 10:16:37 +0200 Subject: Getting SSL certificate References: Message-ID: In article , martin at v.loewis.de (Martin v. Loewis) writes: | "Stuart D. Gathman" writes: || The httplib modules supports SSL, but does not check certificates. | It would, if you would pass key_file and cert_file arguments to | HTTPSConnection. Atleast theoretically; I doubt this has been tested | much. what do these arguments do? i had been under the impression that key_file is for sending a client certificate, and cert_file was for a certificate authority that the server cert should be checked against. but it is a faint impression :) in case it is so, this still does not let you at the server certificate... -- erno From ktilton at nyc.rr.com Thu Nov 21 11:03:52 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Thu, 21 Nov 2002 16:03:52 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <3DDBD838.10406@nyc.rr.com> <3DDC5851.5060001@nyc.rr.com> <87wun7tt8k.fsf@key.localdomain> Message-ID: <3DDD0445.4000502@nyc.rr.com> Patrick W wrote: > Not trying to twist your arm but in case you weren't aware of it, Qt > (and PyQt) is just as portable as Tkinter (on platforms that matter) Is this a reference to it not being available for the Mac? Tiny share, yes, but it matters. Kinda like CL. :) > Perhaps worth a look if you haven't checked it out already. Thx for the lead. I gather the non-commercial Qt is pretty decent? Is that just licensing/support/add-ons? ie, It is otherwise current with commercial Qt? (The Qt site wanted my life story before it would take me to the pricing page. ) -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From newsfroups at jerf.org Tue Nov 19 00:12:31 2002 From: newsfroups at jerf.org (Jeremy Bowers) Date: Tue, 19 Nov 2002 05:12:31 GMT Subject: classifier systems re-coded in Python? References: <182dnaFhsdyUN0SgXTWcrg@comcast.com> Message-ID: On Tue, 19 Nov 2002 03:48:25 +0000, Robert Oschler wrote: > Terry, > > Is google() a real command from some Python module, or were you just being > Programmer-ish? If it's from a module, is it PyGoogle, or something else? > > thx To my knowlege, that's not a function in any python module, but perhaps it should be. I think you'll find this implementation meets the specs: import urllib import webbrowser def google(s): webbrowser.open("http://www.google.com/search?" + \ urllib.urlencode({"q":s})) google('Holland learning classifier Python') From tim.one at comcast.net Thu Nov 7 12:23:51 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 07 Nov 2002 12:23:51 -0500 Subject: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up In-Reply-To: Message-ID: [Martin v. L?wis] > I would still recommend to use 0x8000000L instead; I recommend another trailing 0 . > it saves you one computation, and is more readable. [Jon Ribbens] > But that *won't work* on later versions of Python! It means I will > have a line in my code which I know will suddenly stop working at some > point in the future and I will have to make a new release and everyone > will have to upgrade their copies of my module just because I put in > code which I knew wasn't going to work. There's no code you can write today that's guaranteed to work in Python 3.0. In the Python 2 line, do as Martin keeps suggesting you do. Note that the line about adding warnings for long literals in 2.5 has been removed from the PEP. From theller at python.net Thu Nov 14 07:26:20 2002 From: theller at python.net (Thomas Heller) Date: 14 Nov 2002 13:26:20 +0100 Subject: windll event loop leaks References: Message-ID: Robin Becker writes: > Hi, I'm trying to implement a calldll/windll backend for the anygui > project. I have working code, but it leaks so I'm looking for assistance > with how one should program/debug such a loop. > > My test prog is a simple blank window. Using process explorer I can see > that the working memory increases when I just move the mouse around over > the window. > > For comparison I tried Sam Rushing's dynwin/button.py and lo and behold > it also leaks. Sounds like a leak in calldll? So the only advice is to build a debug version and run it with a debugging build of Python to either use - the (undoumented) sys.getobjects() function to find leaking objects. - or step through calldll's code with the MSVC debugger. You should be able to find some messages on python-dev were Tim Peters explains what getobjects() does. Another approach ;-) would be to give up calldll/windll and try the ctypes module - this way you would have me debugging the thing (in case it leaks). Thomas From wlfraed at ix.netcom.com Fri Nov 22 20:56:37 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 22 Nov 2002 17:56:37 -0800 Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <093kra.3n3.ln@beastie.ix.netcom.com> Message-ID: Donn Cave fed this fish to the penguins on Friday 22 November 2002 10:01 am: > > Sure, but that's just the first O in OOP. Objects have attributes, > anyone can penetrate this mystery. The question is, given the initial > statement of a programming problem, like ``turn MIDI data into a > printed score'', where do the objects come from and how do they help? > If your grasp of Python is strongly OO, you'll find answers that you > can explain, but you probably won't be able to explain how you found > them. We don't think by enumerating facts about the tools we use. > Very sloppy requirements -- Are we talking a live MIDI instrument stream or data file; one instrument track or multiple? However, the courses/books I have on OO Analysis/Design (regardless of target programming language) tend to focus on Nouns and Verbs (noun->object, verb->method, and extending some what, adjectives->attributes). turn (verb) MIDI data (noun) into (accessory verb?) a printed (adjective? or more likely a verb) score (noun). So from that simple statement we have two objects already: score MIDI data In truth, I would consider the analysis faulty... the primary object is the NOTE, which has attributes of pitch and duration. Both the printed score and the MIDI data are equivalent representations of a stream of notes. There is the next object; the stream -- probably more familiar as a "track". What does a track have for attributes? Well, maybe an instrument (or voice), and a list of notes. I'd revise the definition of score now to include multiple parallel tracks. So now I have: SCORE (attribute: track(s), track count) TRACK (attribute: voice; attribute: note(s)) NOTE (attribute: pitch; attribute: duration) No methods listed yet... I suspect the easy ones would be: SCORE: add new track; delete track TRACK: add note; delete note; set voice NOTE: set(pitch, duration); get(pitch, duration) Little more analysis would probably give me an object for MIDI stream, and an object for Music printer. The MIDI stream object would have methods for GetEvent, SendEvent. The Music printer would have attributes for staves/page, notes/bar, etc. Methods for getting/setting those parameters, and for feeding voice/track and note information. The main processing would be a loop getting events from the MIDI stream and parsing them into needed score, score.track, score.track.note methods. At end (of file, or some manual interrupt for live streams) run a loop over the score object retrieving the notes and feeding them to the printer object. Now, this is a very sloppy analysis -- what do you expect for a 20 minute effort (the OOA/OOD classes ran some 40 hours each, and seldom got more detailed than a calculator or ATM/bank/user configuration). > So the first challenge may be to learn to think in Python, but then > you need to learn to think beyond it. > Whereas I prefer to "think in" the abstract, and /then/ apply transforms to map the abstract constructs to the target language. -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From vze4rx4y at verizon.net Mon Nov 18 02:55:56 2002 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Mon, 18 Nov 2002 07:55:56 GMT Subject: popkey() method for dictionaries? References: Message-ID: > [ 639806 ] Optional argument for dict.pop() method > > at: > https://sourceforge.net/tracker/index.php?func=detail&aid=639806&group_id=54 70&atid=105470 > > Sorry but I just saw that my proof-of-concept code in python got squashed by > SF. I didn't know that SF removed all leading whitespace, hence destroying > indentation. Here it is again for reference: Do you have use cases demonstrating the value of a default rather than an exception? Also, discuss why similarity with dict.get() applies instead of symmetry with list.pop() or dict.popitem(). Raymond Hettinger From anton at vredegoor.doge.nl Tue Nov 5 08:44:33 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 05 Nov 2002 14:44:33 +0100 Subject: GUI with blocking database access References: <5ec37a54.0211050322.e663b54@posting.google.com> Message-ID: On 5 Nov 2002 03:22:06 -0800, scheff at bigfoot.de (Tim Scheffler) wrote: >Dear all, > >I would like to construct a GUI to access an external database. >Unfortunately I have to use a (non-opensource) python dll (WIN32) >module provided by the database to write/read from/to it. If I/O is >done via this module all execution is stopped if I try to run it in a >separate thread in the GUI. Can you get any I\O at all? I have had some success using Cygwin and popen2 for buffered I\O and some trouble with using Windows 98 Python for the same script. My situation is a bit different from yours I think because I am on Windows 98 and I\O is broken for that platform to begin with. The problem in my case is that I want to use pipes between two console apps and have a python script in the middle to communicate with the two apps. Luckily I have the sourcecode for the console apps so I could in principle insert some flush calls in the code and unblock I\O this way. Unluckily the console apps are large and obscure so I had to write a smaller app for testing purposes. > >Does somebody have an idea how to construct a GUI, that can trigger >such an I/O module? I thought about to run two separate processes on >WIN-NT one that provides the GUI and one that runs the I/O and let >them communicate through a pipe or something like that. But here I >dont know how to start two processes from one python script as fork() >wont work on WIN-NT. Popen2 can have multiple pipes open at same time even on Windows 98. It's just a problem to have the apps flush stdout. On cygwin this problem does not exist I think. If you can compile, this can be used as a test program: (project3.cpp for Borland C++ Builder 4, adjust for your compiler) #include #include #include int main(void) { char input[100]; char finish[10]; int i = 1; strcpy(finish,"quit\0"); while(i!=0){ scanf("%s",&input); printf("%s\n",input); i = strcmp(input,finish); flushall(); } return 0; } For gcc the corresponding flush() call would be fflush(stdout). Use this python script to test popen2 I\O on windows or cygwin: (for cygwin insert "./" or something like that in the executables path) import os from string import strip def process(s, inf, outf): outf.write("%s\n" %s) line = inf.readline() return strip(line) def test(): outf,inf = os.popen2("project3.exe") outf1,inf1 = os.popen2("project3.exe") line = process("hello",inf,outf) line1 = process(line,inf1,outf1) print line1 process("quit",inf,outf) process("quit",inf1,outf1) if __name__=='__main__': test() >Any help is deeply appreciated. I hope this helps. I am not sure I read your question correctly however since I am a bit drained by jobhunting activities. Isn't calldll used to communicate with dll's rather than creating processes via popen2? You seem to be able to open one process though so I went for it. Good luck! Anton. From see_reply_address at something.invalid Mon Nov 25 23:36:15 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Tue, 26 Nov 2002 17:36:15 +1300 Subject: Hmm... An idea: if a,b==c,d: References: Message-ID: <3DE2FA3F.8010006@something.invalid> Richard Dillingham wrote: > It doesn't have ()s, so it ain't two tuples. Easy enough, da? Sorry, it's not that easy. Commas make tuples in Python, not parentheses. Try this if you don't believe me: a = 1, 2 print a -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From mwh at python.net Thu Nov 21 09:00:02 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 21 Nov 2002 14:00:02 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: Message-ID: <7h3isyrt4ar.fsf@pc150.maths.bris.ac.uk> nandrats at mail.mdanderson.org writes: > I thought that this is a python list where every kind of language > related question can be posed. But this thread in my opinion is > getting out of range. It's hard to stop people posting to a thread they're interested in. This thread is pretty on topic compared to some -- we haven't had any discussions about esperanto or trans-finite cardinals or what sort of water pasta is best cooked in. python-list tends to go in for wildly off-topic threads. I don't mind, because they're usually pretty interesting. > Besides, I really think that this is a very friendly list, but right now, I'm > getting more emails about this thread than really relevant mails for a newbie! This however suggests you need a better way of reading this list. Having all of the traffic for this list slam into one's inbox would be pretty bad, I imagine. The best way to read it, IMHO, is as a newsgroup. If your organization or ISP has a news server, just point your news client at it and ask for comp.lang.python. Same content as the list, but news readers usually have convenient interfaces for "I don't want to see this thread" and such. If you don't have easy access to a news server, but do have internet access, you can point your news reader at "news.gmane.org" and ask for (I think) gmane.comp.python.general. If your stuck getting it as email, you want to persuade something in the email delivery chain to divert messages with the header: List-Id: General discussion list for the Python programming language to a special python-list mailbox. From headers, you seem to be using Lotus Notes (could be wrong), in which case you have my pity, and I can't help you with this bit. Hope that helped! Cheers, M. -- First of all, email me your AOL password as a security measure. You may find that won't be able to connect to the 'net for a while. This is normal. The next thing to do is turn your computer upside down and shake it to reboot it. -- Darren Tucker, asr From aleax at aleax.it Wed Nov 20 09:41:21 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 20 Nov 2002 14:41:21 GMT Subject: how does import work ? References: <2259b0e2.0211200633.2ed7e075@posting.google.com> Message-ID: Michele Simionato wrote: ... > Suppose now I import ONLY the function f2, but not f1: > >>>> from f1f2 import f2 That's basically equivalent to: import f1f2 f2 = f1f2.f2 del f1f2 except that if you already had an f1f2 identifier it's not disturbed. > therefore Python has imported f1 too, but is some hidden way, since > f1 is not in the current namespace dictionary: Of course not, but it's in sys.modules['f1f2'] 's namespace, right where it should be. > This behavior is quite confusing to me, somebody can explain what is > happening ? HTH... Alex From peter at engcorp.com Wed Nov 27 00:29:14 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 27 Nov 2002 00:29:14 -0500 Subject: simple problem with running scripts References: Message-ID: <3DE4582A.6302DD61@engcorp.com> nandrats at mail.mdanderson.org wrote: > > I've the following problem with Win98: > > When I open a script with IDLE, it's possible to execute it.But when I open it > in a different environment (like wscite) and try to start it, I always get the > error message: > " pythonw -u xxxxx.py Application not found". I assume that I have to set some > environment variables? I tried to include my python path to PATH in > autoexec.bat, but no luck. Can you show what you tried adding to PATH? Or just type PATH and post the results here. It should work fine that way. There's nothing special about the pythonw.exe: it's in the Python folder with the rest of the stuff. Have you checked the FAQ? http://www.python.org/cgi-bin/faqw.py?req=show&file=faq08.018.htp -Peter From writeson at earthlink.net Wed Nov 6 10:29:30 2002 From: writeson at earthlink.net (Doug Farrell) Date: 6 Nov 2002 07:29:30 -0800 Subject: wxPythonGTK and Python2.2.1 problems on RedHat 8.0 Message-ID: <88bc63c6.0211060729.183dbd8e@posting.google.com> Hi all, We just installed RedHat 8.0 on our servers and we're having a problem with Python. The system comes with Python2.2. I installed wxPythonGTK (what's currently available as a binary on wxpython.org) and ran into some trouble. One of our other engineers is working on a system using Python and wxPython for an application. She has been working on Python2.2 (latest release from the python.org site) and wxPython2.3.2.1, which was previously available on the wxpython.org site. Her application worked fine under that setup on RedHat Linux 7.3. However, now the splitter window won't show it's contents with the setup I described above for Linux 8.0 and wxPythonGTK. Does anyone have any idea how I might fix this or what is going on? Thanks, Doug Farrell Scholastic, Inc dfarrell at grolier.com From wlfraed at ix.netcom.com Tue Nov 26 21:30:32 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 26 Nov 2002 18:30:32 -0800 Subject: Python IRC dictatorship References: <29304.91T434T13743504threeseas@earthlink.net> <1038264655.1697.137.camel@software1.logiplex.internal> Message-ID: <8oa1sa.vq3.ln@beastie.ix.netcom.com> Martijn Faassen fed this fish to the penguins on Tuesday 26 November 2002 12:40 pm: > > Interestingly, people have been calling him ruebot since before he > posted on comp.lang.python; try google searches (or google groups > searches) for him and you'll see they've been calling him ruebot > since at least '99. > As I recall, he was a bit of a pain in comp.sys.amiga.* too. My oldest archive (that I can access; older stuff is likely in an Amiga generated LHA archive on CD) is mid 1998. -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From kbass1 at nc.rr.com Tue Nov 5 19:22:45 2002 From: kbass1 at nc.rr.com (Kevin Bass) Date: Wed, 06 Nov 2002 00:22:45 GMT Subject: Newbie Question: Sockets References: Message-ID: "Grant Edwards" wrote in message news:slrnase1hp.b0s.grante at localhost.localdomain... > In article , Kevin Bass wrote: > > > I am attempting to process data within a socket. The socket establishes = > > communications on both servers but the data does not come out the way = that > > I want it. How do I store the retrieved data into an array or = another > > value? If there are multiple values, how can I store this = information? > > Thanks! > > > > > > client.py > >=3D=3D=3D=3D=3D=3D=3D > > Enough with the MIME stuff already... :) > > Since you don't say what's wrong, (and I don't care to run your code and try > to figure out what it's supposed to do) I'll take a guess: You're using a > TCP/IP connection and you expect it to act like a datagram service when it's > actually a byte stream service. > > There are no record boundaries in TCP/IP. > > One end may call send() four times with 25 bytes each time. The other end > may receive that data as a single 100 byte chunk, as 5 20-byte chunks, or as > 100 single byte chunks. > > > > > And for the love of Usenet, ditch the HTML... > > -- > Grant Edwards grante Yow! The FALAFEL SANDWICH > at lands on my HEAD and I > visi.com become a VEGETARIAN... Thanks for responding. :) I will try to be a little more clear this time :) I received the results of 'The received data is Mousey MooMousey MooMousey MooMousey MooMousey MooMousey MooMousey Moo' when executing my socks. I hoped to get the result of ''The received data is Mousey Moo' I have limited the number of bytes received in my code (data = conn.recv(50)) and I have recieved favorable results. I received the results of 'The received data is Mousey Moo'. Can the received data be placed into another value should as an array or list? From wlfraed at ix.netcom.com Tue Nov 12 15:27:28 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 12 Nov 2002 12:27:28 -0800 Subject: How do I reply to an item in the list ? References: <44ee1dc2.0211120501.2c9e3215@posting.google.com> Message-ID: Patrick.Carabin at MyRealBox.COM fed this fish to the penguins on Tuesday 12 November 2002 05:01 am: > with Re : in Subject line, with groups.google, it DIDN'T place in the > thread, but as a separate message( new thread, NOT answer In a thread > ). Now trying with NO Re : in the subject Well, I'd suggest finding a real newsserver, and using a real news client -- instead of some web based gateway... I can't answer for google, I don't use it for anything except web searches. -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From -$P-W$- at verence.demon.co.uk Tue Nov 26 07:16:25 2002 From: -$P-W$- at verence.demon.co.uk (Paul Wright) Date: 26 Nov 2002 12:16:25 -0000 Subject: if : References: Message-ID: In article , wrote: >David Brown wrote: >> correctness. This particular "feature" is a huge source of bugs and >> frustration in C programming - mixing up "=" and "==" in conditions is >> probably the biggest single cause of C program bugs. Python, on the other > >Are you speaking from experience, or is this as well-founded as the >hysterical wails about how Python's use of indentation is just wrong? >It certainly isn't remotely near my own experience (which covers a bit >more than two decades, during much of which C was used more than >anything else). This is a regular question on comp.lang.python. There's another thread on this where I've posted some statistics from a study which found that that feature caused errors roughly once in every 3000 lines of code: Assignment in expressions is banned in C written for some safety related applications for that reason. -- Paul Wright | http://pobox.com/~pw201 | From uwe.schmitt at procoders.net Wed Nov 27 11:07:30 2002 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 27 Nov 2002 16:07:30 GMT Subject: using com object written in python from iis/asp Message-ID: Hi, I wrote a python script for the implementation of a com server. If I use a python script as client, everything is o.k. But if I try to contact the com object from an ASP script, I get: Python COM Server Internal Error- Fehler '80004002' Unexpected Python Error: exceptions.ImportError: No module named com_planefit due to the "--debug" option I get further information: Object with win32trace dispatcher created (object=None) Traceback (most recent call last): File "C:\Python22\Lib\site-packages\win32com\server\dispatcher.py", line 27, in _CreateInstance_ self.policy._CreateInstance_(clsid, reqIID) File "C:\Python22\Lib\site-packages\win32com\server\policy.py", line 199, in _CreateInstance_ myob = call_func(classSpec) File "C:\Python22\Lib\site-packages\win32com\server\policy.py", line 634, in call_func return apply(resolve_func(spec), args) File "C:\Python22\Lib\site-packages\win32com\server\policy.py", line 623, in resolve_func module = _import_module(mname) File "C:\Python22\Lib\site-packages\win32com\server\policy.py", line 642, in _import_module __import__(mname) ImportError: No module named com_planefit The COM object is registered as 'PlaneFit', the serverscript is named 'com_planefit.py'. Can anybody help me ??? Greetings, Uwe -- Dr. rer. nat. Uwe Schmitt Computer science is no more about Computers, uwe.schmitt at num.uni-sb.de than astronomy is about telescopes. (Dijkstra) http://www.procoders.net From graham.lee at wadham.ox.ac.uk Tue Nov 5 07:20:05 2002 From: graham.lee at wadham.ox.ac.uk (Frodo Morris) Date: Tue, 05 Nov 2002 12:20:05 +0000 Subject: A vision for Parrot In-Reply-To: <20021105221004.339206f3.occitan@esperanto.org> References: <20021105221004.339206f3.occitan@esperanto.org> Message-ID: Daniel Pfeiffer wrote: > Hi, > Apache would essentially have a mod_parrot. Maybe, if this can be tested very hard, we'd even have a Parrot kernel module for all Unices supporting that. Then exec() could perform compiled scripts right away, like machine code :-) Gah! Scary line-wraps! Anyway, I would have thought that a more platform-independent version of this would be, say, a parrotd, which sits on top of the kernel, intercepts calls to exec() bytecode and spawns the relevant processes. I may be wrong. This parrotd system would also help in projects like Beowulfs (although why you'd be using byte-compiled languages in parallel computing is beyond me), because you could use inetd or similar to spawn a parrot when data was received on a certain port. Just my ?0.02 -- FM From ianb at colorstudy.com Mon Nov 11 22:40:53 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 11 Nov 2002 21:40:53 -0600 Subject: newbie Q: shortcuts for long module names? In-Reply-To: <3DD076B1.B0A5CA12@alcyone.com> References: <3DD076B1.B0A5CA12@alcyone.com> Message-ID: <1037072453.2707.2267.camel@dsl-65-184-205-5.telocity.com> On Mon, 2002-11-11 at 21:34, Erik Max Francis wrote: > Try > > import this.is.a.long.module.name as name > > or > > import this.is.a.long.module.name as somethingElse or from this.is.a.deep.package import name Ian From sanjay2kind at yahoo.com Thu Nov 7 12:26:41 2002 From: sanjay2kind at yahoo.com (sanjay) Date: 7 Nov 2002 09:26:41 -0800 Subject: HTML parser problem Message-ID: <63170f57.0211070926.50387a9f@posting.google.com> Hi, Any one has suggestion for following problem. Some word documents have been converted to HTML page in Ms-Word. Want to filter html tags like.. ,   , etc. I couldn't solve using SGMLParser. Thanks, Sanjay From fdsdfs at dasdsa.com Thu Nov 7 09:26:56 2002 From: fdsdfs at dasdsa.com (ffdsfdsfds) Date: Thu, 07 Nov 2002 15:26:56 +0100 Subject: variable name lookup Message-ID: Hi, I would like to know which method of the dictionary object is used for the lookup of variables at execution of the bytecode.\ Thanks. SB From tjreedy at udel.edu Sat Nov 23 08:48:30 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 23 Nov 2002 08:48:30 -0500 Subject: rss.py for win32. References: Message-ID: "Dave Pawson" wrote in message news:Xns92CF7551B3417DaveP at 195.112.4.37... > http://orchard.sourceforge.net/doc/RSS-parser.py > > Appears to be *nix only. Why do you think that? The string 'nix' is absent from both the main and overview pages. A quick look at the code referenced above and the ones it imported revealed no unixisms that I could see. > Has anyone seen a win32 version please? Have you tried it on a Win system? If there are any particular problems, I imagine the Orchard developers would want to know. Terry J. Reedy From op73418 at mail.telepac.pt Fri Nov 15 10:33:07 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Fri, 15 Nov 2002 15:33:07 +0000 Subject: Seeking advice on locking iterators References: <3dd3fa25$0$13656$e4fe514c@dreader6.news.xs4all.nl> Message-ID: On Fri, 15 Nov 2002 15:12:15 +0000, Gon?alo Rodrigues wrote: >On Thu, 14 Nov 2002 19:29:49 +0100, Ype Kingma >wrote: > >>Gon?alo Rodrigues schreef: >> >>> Hi, >>> >>> My problem is the following: I have a top object Application, roughly >>> corresponding to the main thread, that spawns some child threads - >>> objects on their own sake, deriving from the Thread class in the >>> threading module. They communicate when they need to via queues in the >>> usual way. So far so nice. >>> >>> The problem is that those same child objects expose some public >>> attributes (or properties, or methods, does not matter) that the >>> Application object may need to change/call and doing the change via the >>> queue mechanism is conceptually wrong (and a real PITA). The solution is >>> obvious: wrap the attributes with locks around it. What is not so >>> obvious is when these attributes are complex objects themselves, in >>> particular they are iterables. In order to call iter() on these objects >>> safely I coded the following helper class: >>> >>> #WARNING: Brittle - use this at your own risk. >>> class TIter(object): >>> """The TIter helper class, wrapping an iterator for thread safe >>> acess.""" >>> >>> def __init__(self, lock, iterator): >>> super(TIter, self).__init__(lock, iterator) >>> self.__lock = lock >>> self.__iterator = iter(iterator) >>> #Acquire lock => You cannot change the underlying structure >>> #while iter not exhausted. >>> self.__lock.acquire() >>> self.__acquired = 1 >>> >>> #Iterator protocol. >>> def __iter__(self): >>> return self >>> >>> def next(self): >>> try: >>> ret = self.__iterator.next() >>> except StopIteration: >>> self.__lock.release() >>> self.__acquired = 0 >>> raise StopIteration >>> else: >>> return ret >>> >>> def __del__(self): >>> if self.__acquired: >>> self.__lock.release() >>> >>> The idea is that for the wrapping of a given attribute one has an >>> associated lock (a reentrant lock, usually) that is passed to the ITer >>> constructor. I have to ensure two things, though: >>> >>> * The lock is acquired while the iterator is alive. >>> * The lock is released when the iterator is disposed of. >>> >>> So, finally, my question is: Is the above enough to ensure this? Can I >> >>In general, no. Some reasons: >>One can never be sure from the code shown when the __del__ method will be >>called, since this depends on when the last reference to the iterator goes >>out of scope. >>Although CPython more or less guarantees that the __del__ method will be >>called quite soon after the last reference goes out of scope, the language >>by itself does not make such a guarantee. In Jython, you are at the mercy >>of a separate a garbage collecting thread in the JVM to call the __del__ >>method, ie. it might take more than a few million CPU cycles before the >>__del__ method is called. >> >>> be sure that __del__ is called if the iterator is garbage collected >>> before being exhausted? Or is there a better (e.g. safer) mechanism for >>> this? >> >> >>One safe way is: >> >>yourObject.lock() >>try: >> # use an iterator on yourObject. >>finally: >> yourObject.unlock() >> # and don't use the iterator again. >> >>Ie. I don't see the point of locking the iterator, as you seem to want to >>lock an object, ie. one the attributes you mentioned above. >> > >I want to lock the iterator because I want the wrapped object to have >the same interface as the object it wraps. > >>The lock() and unlock() methods need to be added to the class of yourObject >>for this to work. > >Anyway I think I have found a solution: The problem lies in the fact >that the object I am iterating over and the iterator itself can be >different objects => while the iterator acquires the lock it may get >garbage collected before it releases it. Therefore I just wrap the >object in a way that the wrapper is its own iterator and the problem >disappears. >> Actually the problem does not disappear completely since the iterator itself may still get confused if some thread in the middle of some iterating decides to alter the structure. A bit like the altering-the-structure-of-an-iterable-while-iterating-over-it problem. And for *that reason* I do have to add lock/unlock methods. Oh well. Just goes to show the importance of the Queue module when dealing with threads... >>Have fun, > >I am. Python *is* fun. > >>Ype > >With my best regards, >G. Rodrigues With my best regards, G. Rodrigues From maxm at mxm.dk Fri Nov 15 03:40:29 2002 From: maxm at mxm.dk (maxm) Date: Fri, 15 Nov 2002 09:40:29 +0100 Subject: Variable names on the fly? References: <3dd3f5fd$0$28311$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <3DD4B2FD.3090306@mxm.dk> e-tones.co.uk wrote: > Hi all, does python allow the creation of variable names on the fly, more > importantly lists. You can most certainly generate variable names on the fly, but most likely you don't want to! If you get into that habbit, you risk overwriting some of the built in names or overwriting class attributes. Especially if you get user input. So don't pick up that habbit. lists and dicts are there so you don't have to. regards Max M From alessandro.bottoni at infinito.it Sat Nov 2 07:00:54 2002 From: alessandro.bottoni at infinito.it (Alessandro Bottoni) Date: Sat, 2 Nov 2002 13:00:54 +0100 Subject: Textbooks on Perl/Python In-Reply-To: References: <87b0ada6.0211011453.1df4d216@posting.google.com> Message-ID: <200211021409.gA2E9MO02208@mail2.infinito.it> Alle 10:55, sabato 2 novembre 2002, Alex Martelli ha scritto: > > BTW, this would be an opportunity to write such a book, maybe as a > > collective effort coordinated by the educational SIG (special interest > > group) of python, maybe starting from the very good book of Alan Gauld. > > This approach could cope with the small market available for the book. > > And where would you find the volunteers, experienced AND happy > with both Perl and Python, to do the writing? Quite a few > Pythonistas do have Perl experience, but few have any _liking_ > for it (there are surely exceptions, such as our homonym who's > now working for our previous employer, but I have my doubts that > there are enough of them...). Right! I was thinking to a book completely devoted to Python, actually. > > > (Here, I suppose you need a book devoted to programming with Perl or > > Python, not a book on creating language interpreters). > > A book with a definitely-tiny market BUT perhaps enough enthusiasm > level among prospective authors to make it a reality would indeed > be one explaining how to write interpreters in C and Java, using > Classic Python and Jython as the worked-out examples;-). I agree. I bought a few different books regarding compiler and interpreters building and I never found a really _usable_ one. It would be the kind of work I greatly appreciate. I met (on the net) someone who was writing a book on interpreter building based on Java (both as the implementation language and the target one). I asked him about the expected publishing date two years ago and he told me that it was late. Maybe now it is available... --------------------- Alessandro Bottoni From wlfraed at ix.netcom.com Mon Nov 25 14:38:53 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 25 Nov 2002 11:38:53 -0800 Subject: Multi Recipients With smtplib? References: Message-ID: John Abel fed this fish to the penguins on Monday 25 November 2002 07:14 am: > Sorry for the confusing question, but you got the gist of it (Phew!). > I'm pulling the list of addresses out of .ini file, e.g. > > mailfrom=me at mydomain.org > mailto=you at yourdomain.org,me at myotherdomain.org > > Basically, what I was doing, was passing the mailto value to > .sendmail(). The header seem correct (viewed via Mozilla, with > headers set to all), which is what was confusing me. > The "header" is transparent to actual SMTP interfacing. The actual SMTP handshake would look like: HELO mydomain.name MAIL FROM: from at address RCPT TO: address at one RCPT TO: address at two ... DATA By just using a comma separated string you are generating a single RCPT TO: address at one, address at two... which is not accepted. Most email clients do extract the recipient addresses from the "envelope" headers, but that is convenience. One could generate RCPT TO: address at one RCPT TO: address at two ... RCPT TO: address at fifty DATA From: you at localhost To: addresses at world Subject: Trace this spam If you can! . QUIT -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From pyth at devel.trillke.net Mon Nov 11 06:28:34 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 11 Nov 2002 12:28:34 +0100 Subject: something like "if" that returns a value? In-Reply-To: ; from Paul_Rudin@scientia.com on Mon, Nov 11, 2002 at 09:38:42AM +0000 References: Message-ID: <20021111122834.T30315@prim.han.de> Paul Rudin wrote: > > I'm having a little play with python, just to try it out; and one > thing that I find I miss from other languages is something like lisp's > if: > > (if x y z) > > which returns y if x is true and z otherwise. > > I realise that I can define a function that does this for me; but is > there a succinct way of expressing this in the base language? for me x and y or z basically does what you want. But you *need* to be sure that 'y' is true. some people don't like this 'abuse' but many use it on a regular basis (without big problems i'd say). regards, holger From mgerrans at mindspring.com Fri Nov 22 02:58:33 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Thu, 21 Nov 2002 23:58:33 -0800 Subject: Popular conceit about learning programming languages References: Message-ID: I disagree. I've learned a number of languages and Python was by far the fastest. This was probably due to the fact that it is not just easy to learn, but also fun. Also, the aid of the interactive prompt facilitates quick learning immensly. An intelligent and motivated person should be able to zip through "Learning Python" in two or three weeks to get a start and be quite proficient in just a few months practice. Of course, after a few years when you go back and look at the early stuff you wrote when you first learned it, you will find cleaner and more idiomatic ways of doing some things, but this phenomenon is by no means unique to Python. From jbauer at rubic.com Wed Nov 27 09:32:21 2002 From: jbauer at rubic.com (Jeff Bauer) Date: Wed, 27 Nov 2002 08:32:21 -0600 Subject: Get yesterday's date Message-ID: <3DE4D775.EAFD3185@rubic.com> Michel, you can use my NormalDate module: http://starship.python.net/crew/jbauer/normaldate/ >>> from normalDate import ND >>> today = ND() >>> yesterday = today - 1 >>> yesterday 20021126 >>> Regards, Jeff Bauer Rubicon Research Michel COMBE wrote: >I need to run a SQL query on a MySQL database to get yesterday's records. >How do I specify "yesterday" ? >Isn't there some kind of date arithmetic in Python or should I use an >external library ? >Which library ? > >Thanks for your answer From fperez528 at yahoo.com Thu Nov 7 14:50:46 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 07 Nov 2002 12:50:46 -0700 Subject: power TypeErrors References: <7h3ptthzlf0.fsf@pc150.maths.bris.ac.uk> <7h31y5xyzgx.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson wrote: > What specific problems involve complex input or > output? Side post (I'd already replied). A simple, specific example: In [1]: import scipy In [2]: scipy.roots? Type: function Base Class: String Form: Namespace: Currently not defined in user session. File: /usr/lib/python2.2/site-packages/scipy/basic1a.py Definition: scipy.roots(p) Docstring: Return the roots of the polynomial coefficients in p. The values in the rank-1 array p are coefficients of a polynomial. If the length of p is n+1 then the polynomial is p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] In [3]: scipy.roots([1,0,1]) Out[3]: array([-0.+1.j, 0.-1.j]) These are just the roots of the trivial 'x^2+1=0'. Both complex (+/-i, in usual notation). >> but I can tell you that python is gaining very stronng support in >> scientific computing. >Given what I hear of IDL, this doesn't surprise me :) Indeed, hating IDL is one of the things that drove me to python. While IDL has admittedly nice graphics libraries, the language _SUCKS_ like nothing I've ever seen. It's absolutely, positively horrible. I'm glad I don't use that thing anymore. Pyhton+IPython+(Gnuplot/Grace)+Mayavi is a far more pleasant environment. Cheers, f. From malik_martin at hotmail.com Wed Nov 27 05:27:43 2002 From: malik_martin at hotmail.com (malik martin) Date: Wed, 27 Nov 2002 05:27:43 -0500 Subject: do you guys help newbies?? Message-ID: An HTML attachment was scrubbed... URL: From tdelaney at avaya.com Sun Nov 17 18:37:04 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 18 Nov 2002 10:37:04 +1100 Subject: How to write Inline Functions in Python? Message-ID: > I understand that this thread has gone in a couple of different > directions. Just to be clear, I'm talking about python and addressing > your assertion that modern compilers/computers obsolete the necessity > for programmer-requested inline functions. I am talking about > 'inline'ing code solely for the purpose of speed; avoiding the > function call/stack overhead for small operations. Yes - but this is a completely separate issue. The question asked was about "inline functions". Inlining code is not an *inline function*. Python has no concept of *inline functions*. > The example I gave was the first one that occured to me, and not at > all dissimilar from things I've done in the past. If the python > compiler was supposed to inline that (being a modern compiler and all) > then it failed. I wouldn't mind if I could do "inline def(...):", but > I can't. The python compiler does absolutely no optimisations unless you use -O, and even that is simply removing cruft that is *added* to aid developers. And the difference is going away almost completely in 2.3. This boils down to "if you are worried about the performance of your program, then Python may not be the right language for you". There are of course *idiomatic* optimisations in Python - and explicitly inlining code because you know the performance characteristics of Python name lookups and function calls is one. However, it is even more idiomatic not to worry about such performance characteristics until they prove to be a problem. But none of this has anything to do with *inline functions* which is what the original poster asked about. A language which (supposedly) gets so close to the metal as to expose the implementation details of the code produced (such as via an "inline" hint) *should* these days have highly-optimising compilers. If your compiler does not have such optimisations, then the "inline" hint is probably useless. If it *does* have such optimisations, then the "inline" hint is also probably useless. Humans have been shown time and again to be exceptionally bad guessers as to what needs optimising. As such, humans should concentrate on making their code as clear and readable as possible, and let the automated systems (such as a compiler) work out what is the best optimisation. And yes, I have produced *highly* optimised code in Python (two orders of magnitude improvement in performance over the naive implementation). In each case, the majority of the performance improvement was by improved algorithms (most importantly, only doing things when you absolutely have to). Using optimisation "tricks" (inlining code, using default parameters for function names to avoid global lookups, etc) have only been used in one particular project (a coverage tool) where absolute best possible performance is a requirement (and the final result is an overall increase in runtimes when run under the coverage tool of around 50%). Tim Delaney From david at no.westcontrol.spam.com Sun Nov 3 10:03:47 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Sun, 3 Nov 2002 16:03:47 +0100 Subject: Protect Python Source References: <30770aa4.0211020028.1434bd34@posting.google.com> Message-ID: Comments below... "TuxTrax" wrote in message news:30770aa4.0211020028.1434bd34 at posting.google.com... > "David Brown" wrote in message news:... > > "TuxTrax" wrote in message > > > > > > > > Your comments reveal a thoughtful and curious approach that is quite > > healthy. > > > It also reveals a world view that has in large part been shaped by the > > > philosophies of proprietary software companies. > > > > > > Is a python compiler available for linux? I don't know. I do know that no > > > Linux users I know would even consider using one. It would never cross our > > > minds to make our source closed to others. This is where the whole open > > source > > > software movement takes a completely different world view. In open source > > > software, you retain the right to make a profit from your work, while > > still > > > granting others the right to copy, distribute, modify and view the source > > > code. Just a year ago, this whole concept was horrifying to me. I could > > > not concieve of allowing others to have free access to my source code. As > > > a Long time windows user, I had some un-learning to do. But unlearn I did. > > > I started thinking in terms of the advantages of open source. First, it > > keeps > > > you honest; you write your best code because you know that your peers are > > > going to be seeing it all over the world. Second, with open source, once > > > you release it, other programmers may modify it helping it to become more > > > than you ever could have made it on your own (unless you choose to forbid > > > the modification of your code, but that's another subject). Third, the > > > distribution of your product using the open source community, has no > > equal, > > > and will cost you nothing. You can provide support to your users via > > > that same community at little or no cost to you, and support is the number > > > one ongoing cost that software developers get saddled with. You can use > > > the resources of such organizations as the free software foundation to > > > defend your copyright (don't let the "free" in FSF throw you; you can > > still > > > market your product using the GPL licence). > > > > > > And finally, you get to give something back. This is a philosophical point > > > for me, but giving something back to the community that you benefit from, > > > whether it be your local community, or the computer community, is very > > > important for us as people. It is a common and refreshing view that you > > > will find in the open source world, and one reason that I left the > > > windows world for good. But thats a soapbox for another time. > > > > > > Cheers, > > > > > > Mathew > > > > > > > I think you are making the mistake many "born again" open-source advocates > > make, and one that many anti-open-source people also make. There is plenty > > of place in the world for both open and closed source software. > > Indeed this is true. Did I leave you with the impression that I was > saying > anything against closed source? The fact is I happen to agree with > you, but > shamelessly took an oppotunity to pitch the case for open source since > the OP seemed not to have considered it. > Your comments *did* leave me with the impression that you were advocating writing open-source software to the complete exclusion of closed-source. It was the "I do know that no Linux users I know would even consider using one. It would never cross our minds to make our source closed to others" that did it. If you were just exagerating the one case to counter arguements in favour of the other, then I guess that's fair enough. But it certainly looked like fanatisism to me, and that's never good for your cause. > > In some situations, one is far better than the other > > OK. > > > in some cases either will do > > the job. Saying that everything should be open source is as bad as saying > > everything should be closed source. It's a common misunderstanding about > > Linux ("Software companies should not write for Linux because then they > > would have to give away all their source code..."). > > And it is a common misconception (perpetuated by some proprietary > software houses) that open_source == zero_profit. The fact is, open > sourcing the program will not negatively impact the profitablility of > the product. This flies in the face of conventional wisdom, but such > companies as red hat have proven the business model. > True. > At any rate, I don't believe I said everything should be open source. > I did not intend to imply it. > Again, I think you did imply it (hence my first posting), but it looks like we have actually have a pretty similar view on open- and closed- source development. > > Consider, for example, the program I am writing at the moment. It is in > > Python - a language whose licence is very clear in stating that all > > Python-licenced code can be used in open and closed source software (keeping > > copyright messages intact). The program provides a gui for an embedded > > motor controller card, and our customer is paying good money for me to write > > the program. He intends to sell the cards on to his customers, with this > > controller program to go with it. In the future, he will want a bigger > > version of the program (supporting several cards simultaneously). He may > > well want to charge his customers for that software upgrade. He certainly > > won't want his customers to have full access to the code - they may modify > > it for use with other supplier's motor cards. > > fine. Then make a license agreement that forbids the modification of > the code for use with other brands of motor control equipment. That > has nothing to do with open sourcing it. When you open source your > code, you provide greater value to your customers, because you give > them the power to meet future needs as they expand, by applying the > same codebase to new hardware/software platforms. They can also see > and verify that the code is not filled with bugs/backdoors. > Open source gives more to the customer, that is without question. But it is not necessarily in the supplier's interests to give them more. In a great many such cases, there is no real advantage to the customer to have the source code. They want us to write the stuff for them - that's what they pay us for. Depending on the exact contract, they may also pay for the source code - not so that they can work with it themselves, but as a protection in case of problems (such as our company going bankrupt, or otherwise being unable to continue work on the project). They know the software has no (intentional) backdoors, and is as bug-free as we can make it - again, that's what we're paid for. If they did not trust us to do the job, the customer would go elsewhere (that's part of the benifits of a competitive world - compare it to closed source software with monopoly power). Even though a licence agreement might be as good as closed-source at stopping abuse of the source code (these sorts of customers are responsible people - they are not going to knowingly break agreements), there are two problems with that. Licences that are open-source, yet restrictive about use, are in a no man's land, and would lead to all sorts of complications. The biggest problem, though, is how to deal with a customer who has fiddled with the code. Imagine the joys of supporting code when the user has "customised" the software, and now it doesn't work. For specialised software, it is far better that we do the modifications - we get paid for it, and the customer gets the guarentee that it will work. If they could do as good a job at writing and modifying the software themselves, they wouldn't have come to us in the first place. > > This is not a program for > > which either myself or my customer will gain any benifits from releasing it > > as open source - no one is going to be making improvements to it that will > > benifit us. > > see above > > > However, there are certainly *parts* of the program that could > > be released seperately. For example, I may seperate out the graphing parts > > of the gui into a nice, modular graph widget. That could easily be released > > as open source (Python licence), for the benifit of others and for our own > > benifit - if people like it, they will contribute improvements which I can > > then use. If I make any changes or improvements to the pyserial module that > > I am using, then I certainly will pass those changes back to the community. > > But by the time I get as far as making distribution copies of the program, > > I'll be making two sorts of packages - py2exe packages for easy installation > > on Windows machines, and .pyc byte-code files for use on Linux (and for > > Windows users who already have Python). > > > > I fully agree that there are often direct benifits from making your own > > software open source. There is also the personal satisfaction factor - I > > have not written much that could be of direct benifit to others (my job is > > embedded systems development - you need our company's hardware to run our > > software), but I have enjoyed the feeling I get from the few direct > > contributions I have made. But there are many reasons to write closed > > source code as well. You do not speak for the Linux-using community when > > you say that writing closed source is against your principles. From a > > user's viewpoint, open source is definitely an advantage - just like lower > > cost, better documentation or more functionality is an advantage. But from > > the writer or sellers viewpoint, it is a mixed blessing which must be > > considered sensibly - just like the selling price, the level of > > documentation and the functionality of the software. The aim of all > > businesses is to make money - preferably by providing good products and > > services to their customers. If that end can be best achieved by openning > > their software, great. If it is best achieved by closing their software, > > then that's the way it is. > > Thank you for your thoughts. And for yours. >The OP was asking about securing code and > I wanted to impress two things: > > 1) you can't secure your code This is true - you can never be entirely secure. You must look at each case - what is it that you want to protect, from whom, and how far are you willing to go for the protection? But there are many levels of security. > > 2) open source is not a bad thing, it is, in fact, a very good option. It often is a good option. My point is merely that, while it often is the best option, there are many cases where it is *not* the best option. > > cheers, > > Mathew mvh. David From cliechti at gmx.net Fri Nov 1 16:15:15 2002 From: cliechti at gmx.net (Chris Liechti) Date: 1 Nov 2002 23:15:15 +0200 Subject: Sending null byte to serial port in Windows using PySerial? References: <49f4e27a.0211010930.56788863@posting.google.com> Message-ID: sundae1888 at hotmail.com (sundae) wrote in news:49f4e27a.0211010930.56788863 at posting.google.com: > I'm having troubles sending the null byte (0x00) to the serial port in > Windows using PySerial on ActivePython 2.2.1 build 222. Currently I'm > doing something like this: > > com = serial.Serial("COM1", 9600, timeout=1) sidenote: i sugest to use numbers i.e. 0 <-> "COM1" that makes it easier if you want to run the prog on other platforms or with jython. > com.write(chr(0)) well i'm reading and writing null characters en masse. so no problem. the port is configured for binary data transmition on all platforms. > The device should reply a single byte upon receiving this byte, but I > never got anything in reply. well i suspect that something is wrong with your setup. you're sure your device is connected to the right port and listening with the same baudrate? you're reading from the port as you expect, you use a timeout. does the read function return before your device answers? chris -- Chris From engsol at teleport.com Sun Nov 10 16:59:35 2002 From: engsol at teleport.com (engsol at teleport.com) Date: Sun, 10 Nov 2002 21:59:35 GMT Subject: NEWBIE: Extending Python with C References: <3dcc7e2c.3568851@news.earthlink.net> <3dcd6aee.7793165@news.earthlink.net> Message-ID: <3dceb920.8008485@news.earthlink.net> On 10 Nov 2002 06:17:44 GMT, bokr at oz.net (Bengt Richter) wrote: >On Sat, 09 Nov 2002 20:15:31 GMT, engsol at teleport.com wrote: > >>On 9 Nov 2002 09:54:01 GMT, bokr at oz.net (Bengt Richter) wrote: >> >>>On Sat, 09 Nov 2002 03:48:35 GMT, engsol at teleport.com wrote: >>> >>One example of the legacy requirement is: we have a custom plug-in card which needs to be >PCI? All done via IO ports or has DMA? Uses interrupts? Time-critical parts? > >>loaded with data, then triggered to output the data stream to the system under test. The >>driver for the card works well, and it'd be nice to not have to rewrite it. The source can >How do you use "the driver" now? Are you saying "driver" just in the loose sense of any software >that lets you use some hardware in some way? Or do you really mean "driver" as in developed using >DDK or equivalent and put in C:\WINNT\system32\drivers\whizzomatcard.sys? Or a privileged app? > >>be recompiled as a DLL(?) module...I think. Or at the least as a library header >Why do you think you want to do that? (I'm not suggesting it's a bad idea, I'm just wondering >what leads you to think you may need to do that). How do you currently operate, and how do >you hope to operate, at the user interface level? > >>file..again..I think. >> >It's still hard (for me anyway) to tell what your situation. > >Regards, >Bengt Richter LOL...this is a bit embarrassing....but here's more detail. Please keep the groans to a minimum...:) The test application is written in C. It's a DOS 6.22 application, compiled using Borland 3.0. We've tried newer versions, but they won't compile our source as is. The source is 3/4 million lines, including comments, blank lines, dead code, etc.,and the executable is about 1 meg. It uses COM1, COM2 and COM3 to "talk" to the test fixture, plus it talks to a couple of in-house designed and built ISA cards refered to above. One card's output is a pair of BNC coax connectors which in turn are connected to the test fixture. The other custom ISA card is attached to the test fixture using a 37 conductor ribbon cable. The application provides a console-like user interface, command line style. The app has the facility to run 'scripts', loosely based on a C-like syntax, which is how we write our test scenarios to automate product software testing. The app also has "drivers" to run the cards, IO ports, user interface, etc. As background, the app began 10-12 years ago as a simple thing, then as time went on, became larger and larger as more capabilty was added. Concurrantly, the products under test became faster, more complicated, etc. We're now to the point that maintenance is almost a full time job, we're out of memory (lots of page swapping/overlays), speed is an issue (we really need an RTOS....events of interest are sub-millisecond now), background sequencers are at their limits (threads would be nice), on and on. Plus it locks up a lot these days, which is not good when trying to run a two day test suite over the weekend. Soooo what is the new tool to look like? Which platform/OS is the "right" one? Which script language would provide the testers with what they need? Having to compile scripts, if it were C or C++, doesn't seem like a good idea, and not very newbie friendly. Perl, while powerful,is a bit obtuse. TCL is a bit limited, although named pipes are handy. Plus, "bread-boarding" quickie tests from the command line would be awkward at best. How best to implement a user GUI, and still maintain a command line interface? We're in the exploration mode, as it were, to answer some of these questions. After a lot of reading and web searching, we discovered Python. I'd done some tcl/tk, and while it was fun, didn't seem to be a suitable script language for inexperienced test people. But Python does. I've been writing routines in Python, just to get a feel for the difficulty in implementing some "bread and butter" functions. Guess what...I was amazed at how easy it was to perform rather complicated encoding schemes in Python...1-2 pages of code... as compared to doing it in C, which takes 3-6 pages of code. As another "test", I also wrote a Python routine to parse test log files (big, and lots of them, scattered in different directories...thanks, glob), and make a formatted CSV file. Then hand it off to Access for report generation. Piece of cake...gotta love them REs...:) That's why I'm a convert. Then I wondered about IO port access....not much mention of that in the Python docs...sockets, yes....direct control of the UARTs, no. But thanks to Mark Hammond and Andy Robinson's book re Win32 API...that looks do-able with no particular tricks. Then the thought occurs....will we be forced to write some things in C/C++? ISRs? RTOS interface? Driving the custom cards? Timers? I don't know, but it's possible there will be some tasks which will benefit from extending Python. If so, what's involved? How do you do that...exactly? This is why I posted the request for help/info to this great newsgroup. I need to figure out the process of extending Python...if it's needed. To end my rambling...the answer to the driver question above has answered itself, I think. Why would I want to port a 16-bit DOS module to NT/2K/Linux, as is? Thanks to the discussion on this helpful newsgroup..I don't think I do. But I still need to understand the process of adding Python modules, when to use DLLs if it makes sense, how to expose them to Python, how to use them, etc. I need the "process"...I can figure out the code, I hope...:) (Now, if I can just find a good COM book per Alex's suggestions.....) Regards, Norm From robin at jessikat.fsnet.co.uk Wed Nov 20 05:33:15 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 20 Nov 2002 10:33:15 +0000 Subject: need help porting ctypes to Linux References: <8yzp5pgv.fsf@python.net> <++UOYJA+sq29EwYj@jessikat.fsnet.co.uk> Message-ID: In article , Thomas Heller writes >Robin Becker writes: > >> >extension. I'll have to see if I can get my rather poor mingw to do >> >that. Haven't had much success with the .dll either. The cygwin build >> >was a nightmare as I recall with libtool etc etc :( >> Thomas can't you use distutils with cygwin? Looked in cygwincompiler and >> it says >> ..... It also contains >> the Mingw32CCompiler class which handles the mingw32 port of GCC (same >> as cygwin in no-cygwin mode). > >Robin, don't bother any more. I'll convert the libffi assembler code >into MSVC syntax by hand. > >Thanks, > >Thomas good luck, I think this may have already been done by people in the java world. -- Robin Becker From soufle at yahoo.com Mon Nov 11 14:04:26 2002 From: soufle at yahoo.com (noyb) Date: Mon, 11 Nov 2002 14:04:26 -0500 Subject: Follow-up to: Complex numbers, abs resluts in ... Message-ID: <111120021404268196%soufle@yahoo.com> I had previously posted the following: ************************** I am trying to find out how to get the phase or angle of a complex number in Python 2.2. Yes, I have Numpy installed. I have found how to get the magnitude of a complex number, use "abs". I have also found how to get the real and imaginary parts but am stumped by the angle. I am using something like: my_complex_variable = (a +bj) and I can do abs(my_complex_variable) to get the magnitude. I realize the angle is atan(b,a) but I need to use my_complex_variable as input and not a,b. Hope someone knows of a comand I am missing. David **************************** and Alex kindly replied: **************************** import math def phase(mcv): return math.atan2(mcv.imag, mcv.real) I don't think there's any Python built-in that does this. Alex **************************** I should have explained that "mcv" is a rank 1 array and not a scalar. atan2 does not seem to accept anything other than a scalar. Is a "for" loop in my future? David (python neophyte) From LogiplexSoftware at earthlink.net Thu Nov 21 18:02:19 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 21 Nov 2002 15:02:19 -0800 Subject: [wxPython] I'd like to catch mouse click events within a text control In-Reply-To: <3ddd24d9@news.swissonline.ch> References: <3ddd24d9@news.swissonline.ch> Message-ID: <1037919738.26202.1370.camel@software1.logiplex.internal> On Thu, 2002-11-21 at 10:24, F. GEIGER wrote: > I'd like to catch mouse click events within a text control and then read the > mouse pointer position. Alas, the only events I found in the dox are, > EVT_TEXT, EVT_TEXT_ENTER, EVT_TEXT_URL, EVT_TEXT_MAXLEN. Those events are specific to the wxTextCtrl, but you can also use the events that are common to *all* controls: from wxPython.wx import * class ClickableText(wxTextCtrl): def __init__(self, parent, id): wxTextCtrl.__init__(self, parent, id) EVT_LEFT_DOWN(self, self.OnClick) def OnClick(self, event): print event.GetX(), event.GetY() raise SystemExit app = wxPySimpleApp() frame = wxDialog(None, -1, "Test") text = ClickableText(frame, -1) frame.ShowModal() -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 -------------- 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 bdeck at lycos.co.uk Tue Nov 19 15:06:38 2002 From: bdeck at lycos.co.uk (deckerben) Date: 19 Nov 2002 12:06:38 -0800 Subject: telnet.py without fork() Message-ID: <2761b08f.0211191206.56107d9b@posting.google.com> Hello. I need telnet.py to run in a single-tasking environment (i.e. without posix.fork())for PythonD as a demo of the socketmodule. It seems that socketmodule runs exactly as it should, but the terminal output is sometimes a little confusing ... (i.e. CR needs to be pressed more than normal) As I still have limited experience with python itself (other than porting it) and even less with socketmodule, I was hoping for a couple pointers on how this could run better. This is a non-forking telnet client for PythonD based on the socket/telnet.py sample that accompanies the 2.2.1 source distribution. begin code: ########################################################################## #! /usr/bin/env python # Minimal interface to the Internet telnet protocol. # # It refuses all telnet options and does not recognize any of the other # telnet commands, but can still be used to connect in line-by-line mode. # It's also useful to play with a number of other services, # like time, finger, smtp and even ftp. # # Usage: telnet host [port] # # The port may be a service name or a decimal port number; # it defaults to 'telnet'. import sys, nt, time from socket import * BUFSIZE = 1024 # Telnet protocol characters IAC = chr(255) # Interpret as command DONT = chr(254) DO = chr(253) WONT = chr(252) WILL = chr(251) def main(): host = sys.argv[1] sock_bit = chr(66) try: hostaddr = gethostbyname(host) except error: sys.stderr.write(sys.argv[1] + ': bad host name\n') sys.exit(2) # if len(sys.argv) > 2: servname = sys.argv[2] else: servname = 'telnet' # if '0' <= servname[:1] <= '9': port = eval(servname) else: try: port = getservbyname(servname, 'tcp') except error: sys.stderr.write(servname + ': bad tcp service name\n') sys.exit(2) # s = socket(AF_INET, SOCK_STREAM) # try: s.connect((host, port)) except error, msg: sys.stderr.write('connect failed: ' + `msg` + '\n') sys.exit(1) # parent -- read socket, write stdout while 1: def readsock(sock_bit): iac = 0 # Interpret next char as command opt = '' # Interpret next char as option data = sock_bit + s.recv(BUFSIZE) # print ord(sock_bit) # for displaying test char cleandata = '' for c in data: if opt: print ord(c) s.send(opt + c) opt = '' elif iac: iac = 0 if c == IAC: cleandata = cleandata + c elif c in (DO, DONT): if c == DO: print '(DO)', else: print '(DONT)', opt = IAC + WONT elif c in (WILL, WONT): if c == WILL: print '(WILL)', else: print '(WONT)', opt = IAC + DONT else: print '(command)', ord(c) elif c == IAC: iac = 1 print '(IAC)', else: cleandata = cleandata + c sys.stdout.write(cleandata) sys.stdout.flush() def sendsock(): line = sys.stdin.readline() s.send(line) sock_bit = s.recv(2) if sock_bit != '': readsock(sock_bit) sendsock() readsock('\n') try: main() except KeyboardInterrupt: pass ############################################################################## As you can see, my biggest problem is finding a routine to smoothly merge user input with output that is returned from the server. Does anyone happen to know if there is a definite telnet character(s) that signal the client terminal that user input is now required? Is there perhaps a socketmodule function that would serve this purpose? Thanks ben From jdhunter at nitace.bsd.uchicago.edu Tue Nov 12 16:18:01 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Tue, 12 Nov 2002 15:18:01 -0600 Subject: matching multiple regexs to a single line... References: Message-ID: >>>>> "Alexander" == Alexander Sendzimir writes: Alexander> To do this in Python and be able to get at the match if a Alexander> regex succeeds means I have to break up the if's because That's what I usually end up doing for line in myfile: m = r1.match(line) if m: do_something() break m = r2.match(line) if m: do_something_else() break John Hunter From bokr at oz.net Mon Nov 11 14:46:37 2002 From: bokr at oz.net (Bengt Richter) Date: 11 Nov 2002 19:46:37 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h3k7jlwock.fsf@pc150.maths.bris.ac.uk> <3dce96ad$0$12451$edfadb0f@dread11.news.tele.dk> <3DCEB61A.EF3D8E05@alcyone.com> <3DCEBA43.941F62A2@alcyone.com> <3dcf6a25$0$35901$edfadb0f@dread13.news.tele.dk> Message-ID: On Mon, 11 Nov 2002 08:35:09 -0800, John Baxter wrote: >In article <3dcf6a25$0$35901$edfadb0f at dread13.news.tele.dk>, > "Anders J. Munch" wrote: > >> A fascinating read - like >> when they invented garbage collection because they didn't have enough >> spare bits for reference counting in the IBM 704 machine word ;) >> >> on-a-64-bit-machine-would-McCarthy-have-invented-Python-instead?-ly y'rs, > >We might have found out, had IBM ever gotten "Stretch" to work. > I thought there was a "Stretch" doing production work at a Navy lab in the 60's. Regards, Bengt Richter From bondpaper at earthlink.net Wed Nov 6 15:04:59 2002 From: bondpaper at earthlink.net (Tom) Date: Wed, 06 Nov 2002 20:04:59 GMT Subject: Long overflow problem Message-ID: Hello, I have a function that I'm using, but I need to pass it some values that could range between int and longint values. It looks something like this: def myFunc (i, j): do cool stuff... If I call the function as such: myFunc(2382373743L, 2382772391L), I get the following error: OverflowError: Long int too long to convert to int. I can't seem to get myFunc to understand that i and j are long integers. How would I go about doing this? Thanks. Tom From owen at nospam.invalid Wed Nov 13 19:11:32 2002 From: owen at nospam.invalid (Russell E. Owen) Date: Wed, 13 Nov 2002 16:11:32 -0800 Subject: geometry problem with Tkinter Message-ID: I've run into a problem displaying a fairly simple geometry; it displays, but goes into an infinite loop trying to grid everything (on my display the scroll bar shimmies back and forth a bit and the CPU usage is high). Dragging the window to a new size stops it. Here's a very simplified bit of code that demonstrates the problem (more at the end): from Tkinter import * root = Tk() mainFrame = Frame(master = root) logFrame = Frame(master = mainFrame) logText = Text(master=logFrame) logText.grid(row=0, column=0, sticky="nsew") logScroll = Scrollbar (master = logFrame, orient = "vertical") logScroll.grid(row=0, column=1, sticky="ns") logFrame.columnconfigure(0, weight=1) logFrame.grid(row=0, column=0, sticky="nsew") mainFrame.columnconfigure(0, weight=1) mainFrame.grid(row=0, column=0, sticky="nsew") root.mainloop() Any idea what, if anything, I am doing wrong, and how best to fix it? If necessary, I can put everything in one frame, but it ruins a logical architecture. -- Russell Details: This is extracted from code that: - Defines a log widget class that inherits from Frame that contains a text widget, scroll bar and some other stuff - Defines a command/reply widget that also inherits from Frame that contains a log widget and a command input field. Yes I could combine them, but the log widget is useful on its own and I'd rather subclass it. I've ripped out most or all nonessentials, including: - rowconfigure commands that are needed for the correct window resize behavior - code to connect the text widget and the scrollbar: You can leave out the logText (cutting two more lines of code), but that makes the window hard to see and the infinite loop so tight that it can be hard to abort). From cbrown at metservice.com Thu Nov 28 21:49:40 2002 From: cbrown at metservice.com (Colin Brown) Date: Fri, 29 Nov 2002 15:49:40 +1300 Subject: Q: serial port transmit pending count References: <3de40f51$1@news.nz.asiaonline.net> <3de415a7$0$22175$a1866201@newsreader.visi.com> Message-ID: <3de6d5c5$1@news.nz.asiaonline.net> "Grant Edwards" wrote in message news:3de415a7$0$22175$a1866201 at newsreader.visi.com... ... > TIOCOUTQ returns the number of buffered tx chars. For some > drivers (e.g. 16x50 UARTS) it doesn't appear to include > characters in the hardware FIFO. For some others, I know it > does. > > import termios,fcntl,struct > > def txCount(fd): > s = fcntl.ioctl(fd,termios.TIOCOUTQ,TIOCM_zero_str) > return struct.unpack('I',s)[0] I tried to implement but was unable to figure out what TIOCM_zero_str should be from the different options available in ioctl or termios. >From my pySerial instance (ser) the file descriptor ser.fd (as used in serialposix.write) in the above function without the 3rd (optional) argument gave me an IOError: [Errno 14] Bad address. Printing ser.fd returned the number 3. Further assistance would be appreciated. Colin Brown From jdhunter at nitace.bsd.uchicago.edu Sun Nov 17 11:05:57 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Sun, 17 Nov 2002 10:05:57 -0600 Subject: What is the best way to merge two lists? In-Reply-To: <3DD7B7E8.2020402@attglobal.net> (Pierre Rouleau's message of "Sun, 17 Nov 2002 10:38:16 -0500") References: <3DD71094.2030606@attglobal.net> <3DD7B7E8.2020402@attglobal.net> Message-ID: >>>>> "Pierre" == Pierre Rouleau writes: Pierre> Is there a more efficient way to merge heterogenous lists Pierre> than the brute force approach used by uniq() above? Your question really boils down to getting unique items from a list, stably. You can always just concatenate your two lists and then unique them, so the merge question is secondary. Take a look at Tim Peter's recipe at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560. His approach is to try alternate methods in order of decreasing efficiency, moving to the next if the previous fails. I think his sort based approach for non-hashable elements will offer improved performance over your brute force approach. However, the builtin sort is not stable, so I don't think it will meet your criterion of deterministic output. But there is a fair amount of discussion on that page about the best way to get uniqueness in the presence of possibly unhashable elements, and various approaches for dealing with stability -- see Alex's comments after the recipe. Search google groups for dsu group:*python* DSU (Decorate Sort Undecorate) is a common idiom for handling sorts when you are worried about stability. Also, there is a nice, informative chapter in The Python Cookbook devoted to the subject, which basically focuses on the DSU approach. JDH From fclift at verio.net Fri Nov 8 17:40:25 2002 From: fclift at verio.net (Fred Clift) Date: Fri, 8 Nov 2002 15:40:25 -0700 (MST) Subject: complicated class question In-Reply-To: Message-ID: <20021108153329.A58763-100000@vespa.dmz.orem.verio.net> > > OK, something like: > > ## C.py > > import A > import B > > class new_a: > .... > > # Save the original 'a' in '_a', > # install 'new_a' in it's place. > A._a = A.a > A.a = new_a > > b = B.b() > > ## b should use new_a now. > > Did this work? > > -gustavo > This almost works, and with a small change, it works just like I want -- thanks for the idea and the help!. rather than class new_a: I do class new_a(A.a): This way, I can then in my new_a definition, override just one one thing I want, and I still have the rest of methods/attributes of the class available. Thanks a lot! -- Fred Clift - fclift at verio.net -- Remember: If brute force doesn't work, you're just not using enough. From jason at omeninternet.com.au Tue Nov 26 15:04:31 2002 From: jason at omeninternet.com.au (Jason Friedland) Date: Wed, 27 Nov 2002 07:04:31 +1100 Subject: Reading MS Excel Files ? References: <3de2e939$1_1@news.iprimus.com.au> Message-ID: <3DE3D3CF.8090408@omeninternet.com.au> Peter Skipworth wrote: > Quite a few of the scripts I develop need to be able to parse a Microsoft > Excel spreadsheet - with Perl, this was quite simple, using a module called > Spreadsheet::ParseExcel. Does anything similar exist for Python ? > > Note that I'm working on a Linux platform and thus need a non-Win32-centric > solution. Hi Peter There's a CSV module available from http://www.object-craft.com.au/projects/csv/ Hopefully that'll help you. Jason Friedland From dvass at felis.uni-freiburg.de Sun Nov 10 03:13:25 2002 From: dvass at felis.uni-freiburg.de (Joerg Woelke) Date: Sun, 10 Nov 2002 09:13:25 +0100 Subject: How to execute a command line in a Python program? References: Message-ID: <3DCE1525.32432E0C@felis.uni-freiburg.de> Mindy wrote: > > Hey, in my python program, I want to call another > program or command, say, emacs filename&, how to get > to this? I found there's execfile() function in > Python? Do I need to write a shell program which calls > "exec emacs filename&" and then, in my python progam, > use execfile to execute this shell program? Is there > any simple way? Yes, os.system("emacs %s &" %filename) > Thanks! HTH, J"o! -- sigfault From vlindberg at verio.net Thu Nov 14 23:32:13 2002 From: vlindberg at verio.net (VanL) Date: Thu, 14 Nov 2002 21:32:13 -0700 Subject: rm -rf in python? Message-ID: <3DD478CD.2080608@verio.net> Is there a way (short of executing a shell command) that I can do a rm -rf on a directory from python? It raises an OSError if you try to delete a directory that has contents. I suppose that I could recurse down through, deleteing as I went, but it seems that there must be an easier way. Anyone know it? Thanks, VanL From matt at mondoinfo.com Sun Nov 3 21:18:01 2002 From: matt at mondoinfo.com (Matthew Dixon Cowles) Date: 04 Nov 2002 02:18:01 GMT Subject: Tkinter problem References: <369fc45d.0211031751.7ad1276@posting.google.com> Message-ID: On 3 Nov 2002 17:51:42 -0800, Benson Ngai wrote: > Is there another command that I can use so > that it just close that 1 sub windows? here is the code! > okButton=Button(msgWin,text="OK",command=msgWin.quit,justify=CENTER) > #^^^^^^ Problem on this line^^^^^^^^^^^^^^^^^^^^^###### The method destroy does what you want. Regards, Matt From usenet at soegaard.net Wed Nov 13 15:48:54 2002 From: usenet at soegaard.net (Jens Axel Søgaard) Date: Wed, 13 Nov 2002 21:48:54 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCF83B2.2030008@web.de> <3DD0D765.3030907@web.de> <3DD16CAF.41214BBA@alcyone.com> <3dd1ffd7$0$63936$edfadb0f@dread15.news.tele.dk> Message-ID: <3dd2bcf0$0$63850$edfadb0f@dread15.news.tele.dk> Terry Reedy wrote: > "Jens Axel S?gaard" wrote in message > news:3dd1ffd7$0$63936$edfadb0f at dread15.news.tele.dk... > >> Beating >> >> http://www.htdp.org > > Thanks. I'll learn a few things from this. However, apropos to the > thread topic, I am somewhat flabbergasted that anyone could think that > Scheme's > > (sort (cons 1297.04 (cons 20000.00 (cons -505.25 empty)))) > ;; expected value: > (cons 20000.00 (cons 1297.04 (cons -505.25 empty))) > > (section 12.2) is a sensible list notation to inflict on anyone, let > alone newcomers, This is in the beginning of the book. Later you will learn to write (list 1 2 3) or '(1 2 3). There is a *very* good explanation. Read on. [For the Pythonians that does not know Scheme. Note that the Scheme-list called a linked list in som other languages. A python list is called a vector in stead.] But why? HTDP uses DrScheme. In DrScheme there are several teaching language levels. Ranging from beginner, intermediary, advanced. Then one is ready to use Pretty Big Scheme. The language levels enables DrScheme to provide the user with error messages that the student understands. In most languages a simple syntax error can provoke an error message using concepts the beginner does not yet understand. DrScheme has the most beginner-friendly error messages I have ever seen. Back to the issue, whether to write (cons 1 (cons 2 empty)) or (list 1 2). This choice is made to learn the beginner the representation of a list. What is a list of numbers? A list of numbers is either empty, or constructed by the first number of the list followed by the rest of the list. Thus a list-of-numbers is either empty or (cons a-number a-list). Examples of lists: empty (cons 1 empty) (cons 2 (cons 1 empty)) Examples of first and rest: (first (cons 2 (cons 1 empty))) = 2 (rest (cons 2 (cons 1 empty))) = (cons 1 empty)) This is important! If you know this we kan write follow the design recipe for developing list processing function to make functions that handle list automatically (i.e. without thinking too much). Let make a function that counts the number of elements in a list (don't worry it's already in Scheme - it's just an example) (define (length a-list) (cond [(empty? a-list) 0] [(cons? a-list) (+ 1 (length (rest a-list)))])) In prose this says, if a-list is empty, then the length of the list is 0, if the list is cons-tructed then the length is 1 (there is a first element) plus the length of the rest of the list. If in constrast you learned to make lists like '(1 2 3) which gets printed as (1 2 3), then you wouldn't know how to make list processing functions. When you master how to make the functions, it is ok to learn the notational short cuts. In more general terms: in the teaching languages values are printed in the same notation that are used to construct them. For example: "Hello world" gets printed as "Hello world". This a good thing for beginners - they are less likely to get confused by the internal and the printed representation of the various datatypes. If you haven't looked at the tour, then take a look at which shows that bitmaps are a builtin datatype, which can be put directly in the editor: http://www.drscheme.org/tour/202/tour-Z-H-5.html Another beginner friendly thing is the Stepper, which alows you to execute your programs in small steps also backwards! http://www.drscheme.org/tour/202/tour-Z-H-8.html Finally there are builtin support for XML for making homepages: http://www.drscheme.org/tour/202/tour-Z-H-11.html Have fun, -- Jens Axel S?gaard From jsyn at nthought.com Mon Nov 4 01:42:11 2002 From: jsyn at nthought.com (jsyn) Date: Sun, 3 Nov 2002 22:42:11 -0800 Subject: Is there a good checksum system for OPENBSD? In-Reply-To: ; from lists@webcrunchers.com on Sun, Nov 03, 2002 at 10:27:27PM -0800 References: Message-ID: <20021103224211.H31507@exetazo.nthought.com> On Sun, Nov 03, 2002 at 10:27:27PM -0800, John D. wrote: > I'm looking for a Program that compares md5 file checksums in a file against actual files and reports discrepancies. A commercial program like "Tripwire" does this, but isn't there an Open Source program that can do this. Check out aide: http://www.cs.tut.fi/~rammer/aide.html Within OpenBSD, this is available at ports/security/aide. jsyn From pieroul at attglobal.net Sun Nov 17 14:51:06 2002 From: pieroul at attglobal.net (Pierre Rouleau) Date: Sun, 17 Nov 2002 14:51:06 -0500 Subject: What is the best way to merge two lists? References: <3DD71094.2030606@attglobal.net> <3DD7B7E8.2020402@attglobal.net> Message-ID: <3DD7F32A.3070809@attglobal.net> Wojtek Walczak wrote: > print mergelist(a,b,c,d,e) > --- > > ...and it returns that: > ['a', 1, 2, 3, 4, 5, 6, 7, 8, , 'b'] > It works but it flattens the members that are lists or sequence. In that sense it modifies the members, which i don't want. -- Pierre From oren-py-l at hishome.net Fri Nov 29 09:19:54 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Fri, 29 Nov 2002 09:19:54 -0500 Subject: Newbie Question: Giving names to Elements of List/Tuple/Dict In-Reply-To: <1038571003.6023.20.camel@localhost.localdomain> References: <1038571003.6023.20.camel@localhost.localdomain> Message-ID: <20021129141954.GA1876@hishome.net> On Fri, Nov 29, 2002 at 07:56:44PM +0800, Alfredo P. Ricafort wrote: > Hi, > > I'm quite new to Python. So far I find it to be easy to learn and > simple to program. However, one thing that I missed, especially someone > coming from C language, is 'struct'. It seems that when you define a > data structure in the form of a List, Tuple, or Dict., there is no way > to give names to each element. ... > Now my problem is that when the structure of the record change, your > index has to change also. So in the example above, when the 'Name' > element is moved(say as the 3rd element - Customer[i][2]), then you have > to look all over your code and change accordingly. > > My question now is, how can I assign names to the elements? Or is there > a better way of doing this? Many Python programmers use an empty class for this: class Struct: pass s = Struct() s.name = "John Doe" s.phone = "555-5127" etc. It has no predefined structure - you can add any field you like and use the same class for different types of data. You can delete attributes with a del statement (e.g. 'del s.phone') and test for the presence of an attribute using hasattr ('if hasattr(s, "fax"):') Oren From alpot at mylinuxsite.com Fri Nov 29 10:10:16 2002 From: alpot at mylinuxsite.com (Alfredo P. Ricafort) Date: 29 Nov 2002 23:10:16 +0800 Subject: Newbie Question: Giving names to Elements of List/Tuple/Dict In-Reply-To: References: Message-ID: <1038582615.6023.34.camel@localhost.localdomain> Hi Paul, Thanks. I think your suggestion comes close to what I am looking for i.e. an array of objects rather than an array of strings (which is what I original had in mind). AL On Fri, 2002-11-29 at 20:41, Paul Simmonds wrote: > >I'm quite new to Python. So far I find it to be easy to learn and > >simple to program. However, one thing that I missed, especially someone > >coming from C language, is 'struct'. It seems that when you define a > >data structure in the form of a List, Tuple, or Dict., there is no way > >to give names to each element. > > > >For example: > > > >In C: > > struct Customer { > > char * Name; > > char * Address; > > char * TelNo; > > } Customer[]; > > > > printf("Customer Name is %s\n",Customer[i].Name); > > > > > >In Python: > > Customer=[ [Name,Addres,TelNo], [Name,Address,TelNo],.....] > > > > print "Customer Name is %" Customer[i][0] > > > Hmmm. I'm dealing with that sort of thing at the moment, and I find that > Python classes come in really useful. Try: > > class Customer(object): > """Default Customer Definition""" > def __init__(self): > self.name="" > self.address="" > self.telno="" > > This is so much more flexible than the C structure. For example: > > >>>from randomobj import * > >>>custlist=[Customer(),Customer()] > > Gives you 2 Customer class instances, each with its own set of variables as > you defined above(not strictly correct, but good enough for simple > explanation): > > >>>custlist.append(Customer()) # Add another customer > >>>print custlist # Actually a list of 'pointers' > [, 0x811ebcc>, ] > >>>print custlist[0].__dict__ # Access all attributes > {'telno': '', 'name': '', 'address': ''} > >>>custlist[0].name='Paul Simmonds' # Accessing by name > >>>custlist[0].telno='123456' > >>>print custlist[0].__dict__ # Changed attributes > {'telno': '123456', 'name': 'Paul Simmonds', 'address': ''} > > This form will probably do as much as you want, but you can include more > functionality by wrapping the 'object' special functions. However, the > Python.org Reference Manual section 3.3 explains it better than I can. > > HTH, > Paul > > > >Thanks. > > > >AL > > > >-- > >http://mail.python.org/mailman/listinfo/python-list > > > _________________________________________________________________ > Add photos to your e-mail with MSN 8. Get 2 months FREE*. > http://join.msn.com/?page=features/featuredemail -- Alfredo P. Ricafort Home From imbosol at vt.edu Sun Nov 3 23:50:06 2002 From: imbosol at vt.edu (Carl Banks) Date: Sun, 3 Nov 2002 23:50:06 -0500 Subject: can't assign value to array element References: Message-ID: Joe Heafner wrote: > Hi. > In my attempt to seriously learn Python (2.2.1 running on Mac OS X), I've > been trying to code some simple numerical algorithms. Here is my code for > one routine: > > a=0. > b=1.4 > y0=0. > m=10 > > h = (b-a)/m > t = zeros(m, Float) > t[0] = a > y = zeros(m, Float) > y[0] = b > > for j in range(0,m,1): > print j # for debugging purposes > t = t[j] > y = y[j] > k1 = h*fprimexy(t,y) > k2 = h*fprimexy(t+h/2., y+0.5*k1) > k3 = h*fprimexy(t+h/2., y+0.5*k2) > k4 = h*fprimexy(t+h, y+k3) > y[j+1] = y+(k1+2.*k2+2.k3+k4)/6. > t[j+1] = a+h*(j+1) > > When run, this code give the error "TypeError: object does not support > item assignment" for hte next to last line. I presume the last line would > give the same error. I'm very new to Python and haven't been able to find > documentation about htis specific problem, and I've been working > (literally) all day on this. What am I doint wrong? I'd appreciate any > help. A variable name can't be used as both an array and a scalar (i.e. this isn't Perl). The line y = y[i] rebinds y to the value of the scalar y[i], and so y is no longer an array. When you try to index it later, Python complains because it now considers y a scalar. The solution is to rename the scalar y, maybe to yi or something. Same thing with t. I have couple other minor suggestions: 1. Since you're interested in numerical methods, you're probably interested in speed. You should put the code inside a function, like this: def main(): main() This is the single easiest thing you can do to speed up code. Variables defined inside a function are faster than those defined at top level. (Although for some numerical applications, the numerical time dominates and it won't make too much of a difference.) 2. If you intend to do long simulations (more than a few thousand time steps), you might want to use xrange(0,m,1) instead of range(0,m,1). The reason is that range allocates a large block of memory (probably about m*4 bytes) and fills it with sequential integers (which might involve more allocation), all before the first iteration. xrange returns integers on-the-fly each iteration. -- CARL BANKS From martyn_quick at yahoo.co.uk Wed Nov 27 16:57:50 2002 From: martyn_quick at yahoo.co.uk (Martyn Quick) Date: 27 Nov 2002 13:57:50 -0800 Subject: Distutils: correct setup script Message-ID: I think I am misunderstanding the correct way to create a setup script for distutils. I've written a collection of python modules with the follow structure: basedir: contains most of the modules and a script 'myscript.py' which is the one I run python on. basedir/data: a package containing a file '__init__.py' (as it should) and then various data files I tried a setup of the following type: # setup.py from distutils.core import setup setup(name="MQscript", packages = 'data', py_modules = ['module1', 'module2', ... ]) However, this gave the error that I'm not allowed to list modules and packages at the same time. What's the correct form for my setup file? Cheers, Martyn From user at domain.invalid Wed Nov 20 14:43:18 2002 From: user at domain.invalid (user at domain.invalid) Date: Wed, 20 Nov 2002 11:43:18 -0800 Subject: Permuting data Message-ID: <3DDBE5D6.20501@domain.invalid> Hi, I have encountered a following problem: I need to permute randomly 200 lines of data 100 times... Meaning that each iteration, data lines are in the random order. What would be the proper way to do it? Thanks, Lena. From rmunn at pobox.com Wed Nov 27 17:07:20 2002 From: rmunn at pobox.com (Robin Munn) Date: Wed, 27 Nov 2002 22:07:20 GMT Subject: tempfile.mktemp() and symlink attacks References: <3ygu9.105734$La5.330766@rwcrnsc52.ops.asp.att.net> Message-ID: Aahz wrote: > [I'm reposting this because nobody followed up to it. I tried doing > some research because I know there have been changed for Python 2.3, but > I wasn't able to find the relevant posts on python-dev.] > > In article <3ygu9.105734$La5.330766 at rwcrnsc52.ops.asp.att.net>, > Kent Hu wrote: >>Is using tempfile.mktemp() vulnerable to symlink attacks? The reason I ask >>is that the documentation for os.tempnam() and os.tmpnam() has warnings >>about symlink attacks, but the documentation for tempfile.mktemp() does >>not. Also, running os.tempnam() and os.tmpnam() actually brings a >>RuntimeWarning, while I tried comparing the implementations, but couldn't >>find the source for os.tempnam() and os.tmpnam() in os.py (I'm using >>version 2.2.1). >> >>Now, if tempfile.mktemp() is vulnerable, I think the docs should say so. >>And if it's not vulnerable, the docs for os.tempnam() and os.tmpnam() >>should refer readers to tempfile.mktemp() instead of os.tmpfile(), since >>tempfile.mktemp() is more functionally similar. >> >>Kent Hu >> >> >>Relevant links: >>http://www.python.org/doc/current/lib/os-file-dir.html >>http://www.python.org/doc/current/lib/module-tempfile.html Strange, I distinctly remember following up to this post some time ago. *google google google* Funny, Google doesn't seem to have it. I'll see if I have a copy of my response lying around anywhere. If not, I'll try to repost it -- but I'm about to leave on Thanksgiving break and may be out of touch with the 'Net for a few days; I might not be able to repost until next Monday. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From danielk at aracnet.com Thu Nov 14 00:51:12 2002 From: danielk at aracnet.com (Daniel Klein) Date: Wed, 13 Nov 2002 21:51:12 -0800 Subject: How to comment a block of codes in Python? References: Message-ID: <9de6tuosphno6pglr531tq5svu04836nfk@4ax.com> On Wed, 13 Nov 2002 20:50:39 -0800 (PST), Mindy wrote: >Hey, this might be easy but I don't figure out myself. >How to comment a block of codes(including a bunch of >lines with indentation)? Now, I just use "#" to >comment every line and it's so clumsy when I want to >test part of the codes. Yes, it's easy :-) See... http://epydoc.sourceforge.net/docstrings.html Dan. From donnal at donnal.net Wed Nov 6 10:32:46 2002 From: donnal at donnal.net (Donnal Walter) Date: 6 Nov 2002 07:32:46 -0800 Subject: using the PSF license for one's code References: <918bc22f.0211051301.2010d077@posting.google.com> <3dc867de$0$24754$7b0f0fd3@reader.news.newnet.co.uk> Message-ID: <918bc22f.0211060732.47b2198d@posting.google.com> David Brown: > There are basically two categories of open source licences, as far as I can > see - gpl-type licences (you can use our source, but you have to apply the > same licence to the modified code) and bsd-type licences (you can use our > source for anything you want, but you have to acknowledge the copyright). I > am a great believer in the spirit of a licence rather than the letter of the > licence, and as far as I can see, the Python licence is in the same spirit > as the BSD licence. I don't know how that would stand up in court, however, > but hopefully it will never have to. Well, I'm not likely to take anyone to court, and neither is my University for that matter. For entities like PSF that distribute a lot of copies of their software, it probably makes sense to write their own specific licenses, but for everyone else (like me) it seems to boil down to choosing GPL or BSD. Who would have guessed that it could be this simple? (And I am not being sarcastic; this thread has helped me considerably.) Thanks. Donnal Walter Arkansas Children's Hospital University of Arkansas for Medical Sciences From wlfraed at ix.netcom.com Thu Nov 28 23:22:10 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Thu, 28 Nov 2002 20:22:10 -0800 Subject: if : References: <3o3buus1f8kv1psdps2nsq3ed8ltq5ece8@4ax.com> <7iof8a1hd4.fsf@enark.csis.hku.hk> <3DE692D5.7050704@something.invalid> Message-ID: Greg Ewing fed this fish to the penguins on Thursday 28 November 2002 02:04 pm: > > A statement which starts out looking like one of > these and part way through changes into the other > can be confusing. > Ah yes... Like the difference between the ancient FORTRAN do 10 i = 1 , 20 and do 10 i = 1 . 20 {I wonder if they've finally made spaces significant } -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From e_viola at libero.it Fri Nov 15 14:29:06 2002 From: e_viola at libero.it (bart) Date: Fri, 15 Nov 2002 19:29:06 GMT Subject: BUG URLLIB2 References: <3DD43DA7.5070004@libero.it> Message-ID: <3DD54ADD.70205@libero.it> > That's not a bug in urllib2; google.it is *really* returning 403 > FORBIDDEN. > It appears that this google behaviour is triggered by the header > > User-agent: Python-urllib/2.0a1 > > that urllib2 sends, which, in turn, suggests that Google explicitly bans > urllib2. > Complain to them. > > Regards, > Martin > Thanks to all them that helped me swiftly!!! How can I change User-Agent field presents inside "urllib2"? I find two variables that (I think) define user agent in "urllib2" library: "__name__" and "__version__". I tested to set them following way: __name__="Mozzilla" __version__="5.0" but it failed yet!!! Whatever suggest is accept!!! - Ennio Viola - From see_reply_address at something.invalid Wed Nov 27 22:52:28 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 28 Nov 2002 16:52:28 +1300 Subject: Issue with new-style classes and operators References: <3DE215D1.D9A3FEF9@jandecaluwe.com> <5ApE9.52343$744.1917235@news1.tin.it> <3DE49BB7.80D199FB@jandecaluwe.com> Message-ID: <3DE592FC.6020101@something.invalid> Jan Decaluwe wrote: > But what makes operator methods so special that they should be treated > so differently from ordinary methods? I think it all stems from the unfortunate fact that a class's dict contains a mixture of instance variables of the class itself and metadata about instances of that class. This wasn't a problem with old-style classes, because classes and instances were completely different types of object, so you always knew what you were dealing with. But a new-style class object is both a class *and* an instance at the same time. Applying the old-style lookup rules to such an object would lead to ambiguity in the case of things like __add__ and __getattr__ that can apply to *any* type of object. If you looked up one of those in a class, you wouldn't know whether you had found an unbound method of instances of the class, or a bound method of the class itself. So something had to give, and what gave was the lookup rules. By always starting in the class rather than the instance, the ambiguity is removed. I probably haven't explained this very well -- it all tends to get rather brain-exploding, and I may have got some details wrong. See PEPs 253 and 254 for the full story (but mind your brain). -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From pinard at iro.umontreal.ca Thu Nov 14 10:18:33 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 14 Nov 2002 10:18:33 -0500 Subject: RELEASED: Pymacs 0.19 Message-ID: Hello, my friends. It has been a long time since the last Pymacs bug! Here is a new release. * One may now correctly iterate overs Emacs Lisp lists from Python using a short `for' form. Just for illustrating Pymacs to newcomers, here is a simple, but complete example. Once Pymacs installed, and after putting the following file as `essai.py' somewhere on on the Python search path: from Pymacs import lisp def essai(list): for element in list: lisp.message('%s' % element) the following commands given within in Emacs: M-x pymacs-load RET essai RET RET M-: (essai-essai '(a b c d)) RET will append five lines "'a", "'b", "'c", "'d" and "nil" to the Emacs `*Messages*' buffer. The last "nil" is merely the return value of the Python `essai' function. * On the Emacs side, the function `(pymacs-call FUNCTION ARGUMENT...)' is added for convenience. It works like `pymacs-apply', except that arguments are given separately instead of bundled into a single list. * The documentation has been slightly revised towards Python 2 times. For specifying the Emacs interactive behaviour of Python functions, it suggests that we prefer function attributes over a global dictionary, unless there is a real portability concern for older Python versions. -------------------- Pymacs is a powerful tool which, once started from Emacs, allows both-way communication between Emacs Lisp and Python. Yet, Pymacs aims Python as an extension language for Emacs rather than the other way around; this assymetry is reflected in some design choices. Within Emacs Lisp code, one may load and use Python modules. Python functions may themselves use Emacs services, and handle Emacs Lisp objects kept in Emacs Lisp space. `http://www.iro.umontreal.ca/~pinard/pymacs/' contains a copy of the Pymacs documentation in HTML form. The canonical Pymacs distribution is available as `http://www.iro.umontreal.ca/~pinard/pymacs/Pymacs.tar.gz'. Report problems and suggestions to `mailto:pinard at iro.umontreal.ca'. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From pyth at devel.trillke.net Wed Nov 13 12:05:20 2002 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 13 Nov 2002 18:05:20 +0100 Subject: Raw Newbie: What's the "; from KZEMBOWER@jhuccp.org on Wed, Nov 13, 2002 at 11:15:51AM -0500 References: Message-ID: <20021113180520.B30315@prim.han.de> KEVIN ZEMBOWER wrote: > I'm just now beginning my learning about python, and have to modify a system written in python, the ezmlm-browse system, which allows ezmlm mailing lists to be accessed via a web interface. > > I've found templates which look like this: > >
["%(type)s" not shown] > >
> >
%(markup_urls(html(body)))s
> indeed strange :-) > Obviously, this is python code embedded in HTML, very similar to php in HTML, with which I am more familiar. However, I can't find any references to the " > The specific problem I'm working on involves the line '
'. I'd like to change the width to "100%", but the percent sign must be interpreted as a special character. It causes strange errors. I've tried escaping it with 'width="100\%"', but this doesn't seem to work, either. Any help on this small problem? probably you can do %% (the percent sign escapes itself :-) regards, holger From martin at v.loewis.de Sat Nov 9 01:56:59 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 09 Nov 2002 07:56:59 +0100 Subject: Getting SSL certificate References: Message-ID: "Stuart D. Gathman" writes: > In my case, there is only one cert that the application will trust - but > I need to make sure it hasn't been forged. I think this is done by passing the certfile argument. > >> and cert_file was for a certificate authority that the server cert > >> should be checked against. but it is a faint impression :) > > That would make sense, but the docs say that checking the server certificate > is not implemented. Did you try? Python passes the cert_file argument to SSL_CTX_use_certificate_chain_file. It might be a problem that Python never calls SSL_get_verify_result, though (but then, I understand that the default verify callback will return preverify_ok, so if the server certificate could not be verified, the TLS handshake will be terminated). > Definitely, because even if the checking for level (1) above were > automatic (as the arguments seem intended for), the application still > needs to get at the server certificate in some form to check that they > are talking to the right entity. Anybody and their dog can get a signed > certificate. No. Not from the CA in the chain you are passing. In any case, if you get to the SSL object, invoking .server() and .issuer() on it will tell you the identity of the server (after the connection has been established). That, of course, can only complement the check that the certificate has not been forged; you really need to pass a certificate chain for validation. Regards, Martin From imbosol at vt.edu Fri Nov 15 16:00:49 2002 From: imbosol at vt.edu (Carl Banks) Date: Fri, 15 Nov 2002 16:00:49 -0500 Subject: wrapping all class methods References: Message-ID: Robin Becker wrote: > ..... it seems I was asking a question that Python cannot answer as > traceback.print_exc() will only print a traceback back to the point > at which it's caught. The stack frames are there and can be listed > further, but I don't think that the line number information is > always good beyond the exception handler. Since you're using anygui, maybe it would be more helpful to wrap your callbacks. The Python GUIs I've used (gtk and tkinter) swallow exceptions that reach the event loop, which seems typical, but they do print the traceback to stdout. Maybe anygui doesn't even print the traceback, or maybe it't not showing up in your programming environment. -- CARL BANKS From tdelaney at avaya.com Thu Nov 14 01:20:40 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 14 Nov 2002 17:20:40 +1100 Subject: How to write Inline Functions in Python? Message-ID: > From: arivu at qmaxtest.com [mailto:arivu at qmaxtest.com] > Can any one please explain how to write a Inline Function in Python? No. See below. > Is Inline Functions available in python? No. I assume you're coming from C++. In that case, I suggest you take a good hard look at why you want to write inline functions/methods anyway. If you're doing it for performance reasons, your compiler is almost certainly going to be better at deciding what to inline, and has the option to do so unless you explicitly tell it not to. If you're doing for any other reason (such as putting code in header files) I strongly advise against it. Inline was developed when computers were slower and compilers were more stupid. These days I see no need to inline whatsoever. Tim Delaney From mwh at python.net Tue Nov 26 05:30:39 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 26 Nov 2002 10:30:39 GMT Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <2259b0e2.0211210838.7647301a@posting.google.com> <093kra.3n3.ln@beastie.ix.netcom.com> <7h3of8dsrkj.fsf@pc150.maths.bris.ac.uk> Message-ID: <7h3adjwsk32.fsf@pc150.maths.bris.ac.uk> Lulu of the Lotus-Eaters writes: > |Lulu of the Lotus-Eaters writes: > |> The term 'strict' has another antonym that is probably more useful: > |> 'lazy'. > > Michael Hudson wrote previously: > |But I think in technical pointy-eared CS speak, 'lazy' has a technical > |meaning that differs slightly from what Haskell does. > |I used to know the difference, but I've forgotten; something like lazy > |means you evaluate a subexpression *each* time its value is used? > |Haskell doesn't do that. > > There might well be a difference between "non-strict" and "lazy" that I > am unaware of. I know these things only casually, not in a pointy-eared > CS way. > > But for a pure functional language to evaluate a subexpression each > time its value is used is just plain foolish. Since you know--by > definition once state is removed--that a subexpression will always > evaluate to the same thing, deciding never to cache that value is > pointless. I kinda suspect that whatever "lazy" really means precisely, > it isn't "burns cycles needlessly" :-). Yeah, I kinda thought that. I went and looked it up in the foldoc. Turns out a function `func' is "non strict" if func bottom is something other than bottom. To quote the foldoc, "lazy evaluation" is a _reduction strategy_ combinining normal order evaluation with updating. So it's a bit absurd to describe a language as non-strict, except to mean that it is possible to write non strict functions in the language. Lazy evaluation is a way of arranging that to be possible. I don't know if Haskell98 mandates lazy evaluation. Cheers, M. -- The PROPER way to handle HTML postings is to cancel the article, then hire a hitman to kill the poster, his wife and kids, and fuck his dog and smash his computer into little bits. Anything more is just extremism. -- Paul Tomblin, asr From costanza at iai.uni-bonn.de Tue Nov 26 10:17:27 2002 From: costanza at iai.uni-bonn.de (Pascal Costanza) Date: Tue, 26 Nov 2002 16:17:27 +0100 Subject: Popular conceit about learning programming languages References: Message-ID: <3DE39087.9030806@iai.uni-bonn.de> Daniel Silva wrote: >>Pascal Costanza wrote: >>So what I have in mind is not only a way to make use of Common Lisp >>libraries from Python. I am pretty sure that this is already possible. > > I > >>rather think that implementing Python in Common Lisp has several >>advantages beyond mere reuse options. Here are some ideas. >> > > > Do you know of anyone working on that right now? (Python in Lisp, not > Lisp libraries for Python) No, I am not aware of any such project. (But, of course, there might be one.) I would consider doing it if I had more time. ;) Pascal -- Pascal Costanza University of Bonn mailto:costanza at web.de Institute of Computer Science III http://www.pascalcostanza.de R?merstr. 164, D-53117 Bonn (Germany) From david at no.westcontrol.spam.com Fri Nov 15 03:15:03 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Fri, 15 Nov 2002 09:15:03 +0100 Subject: How to write Inline Functions in Python? References: Message-ID: "Chad Netzer" wrote in message news:mailman.1037309063.10598.python-list at python.org... > On Thursday 14 November 2002 04:47, David Brown wrote: > > > The question then is when will gcc support such > > link-time code generation, because until then, inlined functions in headers > > will remain an issue. > > I'm guessing there may be patent issues in this particular area, which > could restrict gcc's ability to implement some of these features. > Really? It's an obvious idea - I thought of it years ago, and I have never written a compiler. I couldn't imagine that anyone who has really thought about it would see it differently. The implementation, on the other hand, could be tough (and presumably is tough - or it would have been done long ago), especially for gcc where the linker is very much a seperate entity from the compiler. From mgarcia at cole-switches.com Thu Nov 21 14:50:57 2002 From: mgarcia at cole-switches.com (Manuel M. Garcia) Date: Thu, 21 Nov 2002 19:50:57 GMT Subject: My Python Editor "ActiveState Python 2.2 - Python Win IDE" does not refesh References: Message-ID: I just noticed that when a module A is imported in a module B is imported in a module C, when A is changed, both A and B need to be refreshed. Again, this is because PythonWin does everything as a single continuous Python session Manuel From agcolston at buckman.com Mon Nov 25 17:27:25 2002 From: agcolston at buckman.com (Tony Colston) Date: 25 Nov 2002 14:27:25 -0800 Subject: DCOracle2 performance tuning References: <%uQD9.122449$1O2.8846@sccrnsc04> <3DE06FE1.3010602@epost.de> <3DE14CCC.2010700@computer.org> Message-ID: I have noticed also that Python is quite a bit slower if you leave the arraysize parameter alone when using cx_Oracle. If you change the arraysize on the cursor you can get much better performance. The amount of data that is being pulled across the network makes a HUGE difference of course also. For a large sized table in rows (250,000) and in columns 56 the time to pull * from the table in my case is about 250 seconds. If you change the arraysize to 50 then you will pull the data in about half the time (123 seconds). Changing the arraysize to greater than 50 in my case brought only slightly better results which also makes sense. If you are not pulling back the entire table then time decreases a lot also, 72 seconds for 3 fields. If change the arraysize then you can get down to 13 seconds. The important thing is pick and choose the amount of data that you really want to pull across the network. Most applications will not need to pull an entire table of data like this... or you would hope. The other thing that you need to consider for Oracle at least is the execution plan for your queries. In both of my cases you always get a full table scan. Once again this makes sense cause you are pulling ALL of the data. Also depending on your Oracle version you MUST have tables with valid statistics or none of your testing will matter at all... since the Oracle optimizer relies on stats. Probably the only thing that bothers me out of this is that I wrote a simliar testing program for Java and got much better performance for an out of the box experience. The Java test program took only 24 seconds to pull the fields... as compared to the 72 seconds for Python. When you change the arraysize in Python on the cursor you can get the same performance and even better. I did not take the time to optimize the Java version of the test though I imagine I could get better than 24 seconds there also. Tony SQL> select count(*) from order_invoice_detail; COUNT(*) ---------- 243727 SQL> select count(*) from all_tab_columns 2 where table_name = 'ORDER_INVOICE_DETAIL' and 3 owner = 'GRASP'; COUNT(*) ---------- 56 ---------------------------------------------------------------------- Table Access Full on order_invoice_detail Case 1. Select * from order_invoice_detail (no arraysize set) Total time: 252.318585463 Total time: 251.900257156 Total time: 249.472460327 Case 2. Select * from order_invoice_detail (arraysize = 50) Total time: 123.798607644 Total time: 122.675535298 Total time: 122.581093128 Case 3. Select * from order_invoice_detail (arraysize = 100) Total time: 118.943308158 Total time: 119.487127275 Total time: 117.969179044 ---------------------------------------------------------------------- Table access full Case 10. select sales_order_no, extended_price, industry_lookup_id from order_invoice_detail (no arraysize set) Total time: 72.1730837299 Total time: 72.516651418 Total time: 70.934486925 Case 11. select sales_order_no, extended_price, industry_lookup_id from order_invoice_detail (arraysize=50) Total time: 17.6729447458 Total time: 17.6347633568 Total time: 17.621397971 Case 12. select sales_order_no, extended_price, industry_lookup_id from order_invoice_detail (arraysize=100) Total time: 13.1321153946 Total time: 13.1474268378 Total time: 13.1184346055 Case 13. select sales_order_no, extended_price, industry_lookup_id from order_invoice_detail (arraysize=20) Total time: 23.0417743037 Total time: 23.005110426 Total time: 23.0129290175 From straton at lampsacos.demon.co.uk Sun Nov 3 12:00:45 2002 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Sun, 3 Nov 2002 17:00:45 +0000 Subject: loggin out automatically References: <1036253358.19897.0@doris.uk.clara.net> <3dc3fcf4$0$7369@echo-01.iinet.net.au> <3DC451D3.4060907@cyberspace.org> Message-ID: In article <3DC451D3.4060907 at cyberspace.org>, trewornan writes >> >> Some combination of the above, I'd say. Some people might suggest that you >> were silly to not just /try/ your command in a python interpreter, e.g.-- >> > >Good point but I don't have one running on linux and the installation of > linux on another computer is being considered but is dependent on the >feasibility of some system to limit access on a timed basis. > >Anyway thanks for letting me know why it won't work - I'll look more >thoroughly at the linux documentation for possible answers. > >M > > You can get python to run a telnet session to the linux machine, without human intervention. change to super user, change to any other user, kill processes, whatever. Better not to send your root password though. -- Ken Starks From whisper at oz.net Thu Nov 14 02:28:26 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 13 Nov 2002 23:28:26 -0800 Subject: How to comment a block of codes in Python? In-Reply-To: <3DD33D47.B338A887@alcyone.com> Message-ID: You could also just put """ around the block? David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Erik Max Francis > Sent: Wednesday, November 13, 2002 22:06 > To: python-list at python.org > Subject: Re: How to comment a block of codes in Python? > > > Mindy wrote: > > > Hey, this might be easy but I don't figure out myself. > > How to comment a block of codes(including a bunch of > > lines with indentation)? Now, I just use "#" to > > comment every line and it's so clumsy when I want to > > test part of the codes. > > You can put the whole thing in an if 0: ... indentation, or use your > text editor to block comment a whole region. This is the kind of thing > your text editor should be doing for you. > > -- > Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ > __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE > / \ I woke up this morning / You were the first thing on my mind > \__/ India Arie > The laws list / http://www.alcyone.com/max/physics/laws/ > Laws, rules, principles, effects, paradoxes, etc. in physics. > -- > http://mail.python.org/mailman/listinfo/python-list From wilk-spamout at flibuste.net Fri Nov 29 15:59:10 2002 From: wilk-spamout at flibuste.net (William) Date: 29 Nov 2002 21:59:10 +0100 Subject: catch output of threads References: <87of88723i.fsf@flibuste.net> Message-ID: <87el946qjl.fsf@flibuste.net> martin at v.loewis.de (Martin v. L?wis) writes: > William writes: > > > Is it possible to catch the output from print of differents threads ? > > In a single thread, i can change the value of sys.stdout... but with > > differents thread i don't know ? > > You can still change the value of sys.stdout, even for multiple > threads. The print statement internally uses sys.stdout itself. > > If multiple threads interleave print statements, you will get mixed > output on your replaced sys.stdout, just as you would with the > standard sys.stdout. It's why i cannot use this method... I specialy want to catch the output to don't mix the ouput from all the threads. Is there a way to redefine print ? (i don't think so but...) -- William Dode - http://flibuste.net From irmen at NOSPAM-REMOVETHIS-xs4all.nl Sat Nov 23 18:04:41 2002 From: irmen at NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sun, 24 Nov 2002 00:04:41 +0100 Subject: Python IRC dictatorship In-Reply-To: <29304.91T434T13743504threeseas@earthlink.net> References: <29304.91T434T13743504threeseas@earthlink.net><743utuoi3l31t8e8tt9v3sncosuk2gqi02@4ax.com><1239.92T1047T4844497threeseas@earthlink.net> <4992.92T2618T9825720threeseas@earthlink.net> Message-ID: <3de00985$0$11754$e4fe514c@news.xs4all.nl> About the shared list of variable -- value pairs. What about Linda Tuple Space? http://www.google.com/search?hl=en&lr=&ie=UTF-8&oe=utf-8&q=linda+tuple+space+python&btnG=Google+Search From newt_e at blueyonder.co.uk Tue Nov 5 14:09:45 2002 From: newt_e at blueyonder.co.uk (Newt) Date: Tue, 05 Nov 2002 19:09:45 GMT Subject: Str and instance concatanation error References: Message-ID: "Bengt Richter" wrote in message news:aq74tb$idp$0 at 216.39.172.122... > On Mon, 04 Nov 2002 23:01:05 GMT, "Newt" wrote: > > >I keep getting the following error when trying to write to a file. > >TypeError: cannot concatenate 'str' and 'instance' objects > > > >This occurs in a class module (called globals.py). This is used to hold all > >my global variables, and also has a method (called save_char) to write these > >to a file. > > > >self.creator is initialised in the __init__ as "". Should I create it as a > >stringVar instead, or am I doing something incredibly stupid. > > > Well, the error message is a strong clue, but if it doesn't make sense, > what do you do when you don't know why something like self.creator is causing > a problem (besides post a question ;-) ? I'm not being sarcastic, I'm wondering > why you wouldn't just plunk in a print statement to see what everything involved > is. You say you think it is initialized to as "", which shouldn't cause a problem. > So what could it have become so that it does cause a problem? What can you do to > find out what it is at the point where it causes the problem? > > Well, make the program tell you more. E.g., just before the file.write above, put > > print 'self.creator =', `self.creator` > > or > print 'self.creator =', repr(self.creator) > > (I recommend the back ticks or repr just to make sure you get something you can see, > like '' for a null string etc.) > > If you mustn't touch the code, make a safe copy, and verify that you've restored it > afterwards, or make a wholesale hacking copy and just mess with it any way that forces > it to tell you what you want to know. > > Often, it will be less typing and faster than posting a question. > HTH > > Regards, > Bengt Richter I didn't plunk in a print statement as I thought the problem was within my class module, or something strange/supid I'd done.I expected to get the same sort of error. However, I plunked in a print statement, and strangely got back a number. I then realised what the problem was. It's got nothing to do with my class module. I have a couple of functions to set or get the value of creator. I also have another module that imports my globals.py The upshot is that I called my set_creator function with the return from an Entry command (which is the instance of the Entry command, and not the text that is typed in (once I added the .get() to the end it all worked fine!). Newt From cezary at bigfoot.com Fri Nov 8 06:54:36 2002 From: cezary at bigfoot.com (Cezary Biernacki) Date: Fri, 08 Nov 2002 12:54:36 +0100 Subject: PySol Windows binaries, anyone? References: Message-ID: <3DCBA5FC.3030902@bigfoot.com> Christian Tismer wrote: > Dear Python Community, > > my wife is unhappy. She used to play PySol for years. My wife too :-) > Recently, I tried to install the latest version, > but didn't get it to work. Unfortunately, I wiped > the old installation before. :-( Simply download source code, create Windows shortcuts and ten minutes later your wife will be happy. I did this two months ago. > As the last resort, I also could write the missing C functions, > but I really hope somebody has them still around. I'm also > not sure what else is missing. On Windows only Python is really required. Cezary From steve.cassidy at mq.edu.au Fri Nov 8 07:10:30 2002 From: steve.cassidy at mq.edu.au (Steve Cassidy) Date: Fri, 08 Nov 2002 23:10:30 +1100 Subject: PEP 301 -- Package Index and Metadata for Distutils References: Message-ID: On Fri, 08 Nov 2002 16:43:12 +1100, Richard Jones wrote: > This PEP proposes several extensions to the Distutils packaging system. These > enhancements include a central package index server, tools for submitting > package information to the index and extensions to the package metadata to > include Trove information. > If you'll pardon an intrusion from over the fence in comp.lang.tcl, it's very interesting that this proposal and the related ones share a lot in common with my own TIP 55 proposal for Tcl ( http://www.purl.org/tcl/tip/55.html) and the associated trial implementation of CANTCL (http://www.ics.mq.edu.au/~cassidy/cgi-bin/cantcl). It strikes me that it might be worthwhile consulting with each other to share experiences and perhaps even standardise metadata formats between our two sets of repositories. With the close relationship between Python and Tcl (eg. Tkinter, Snack, typcl) there might even be an argument for a joint repository. Any and all discussion welcomed, please maintain the cross post so that both sides of the fence can hear. Steve For the benifit of c.l.t I'll retain the PEP text below: > PEP: 301 > Title: Package Index and Metadata for Distutils > Version: $Revision: 1.1 $ > Last-Modified: $Date: 2002/11/08 02:59:18 $ > Author: Richard Jones > Status: Draft > Type: Standards Track > Content-Type: text/x-rst > Created: 24-Oct-2002 > Python-Version: 2.3 > Post-History: > > > Abstract > ======== > > This PEP proposes several extensions to the Distutils packaging system > [1]_. These enhancements include a central package index server, > tools for submitting package information to the index and extensions > to the package metadata to include Trove [2]_ information. > > This PEP does not address issues of package dependency. It also does > not address storage and download of packages as described in PEP 243 > [6]_. Nor is it proposing a local database of packages as described > in PEP 262 [7]_. > > Existing package repositories such as the Vaults of Parnassus [3]_, > CPAN [4]_ and PAUSE [5]_ will be investigated as prior art in this > field. > > > Rationale > ========= > > Python programmers have long needed a simple method of discovering > existing modules and systems available for their use. It is arguable > that the existence of these systems for other languages have been a > significant contribution to their popularity. The existence of the > Catalog-SIG, and the many discussions there indicate that there is a > large population of users who recognise this need. > > The introduction of the Distutils packaging system to Python > simplified the process of distributing shareable code, and included > mechanisms for the capture of package metadata, but did little with > the metadata save ship it with the package. > > An interface to the index should be hosted in the python.org domain, > giving it an air of legitimacy that existing catalog efforts do not > have. > > The interface for submitting information to the catalog should be as > simple as possible - hopefully just a one-line command for most users. > > Issues of package dependency are not addressed due to the complexity > of such a system. The original proposal for such a system, PEP 262, > was dropped as the author realised that platform packaging systems > (RPM, apt, etc) already handle dependencies, installation and removal. > > Issues of package dissemination (storage on a central server) are > not addressed because they require assumptions about availability of > storage and bandwidth that I am not in a position to make. PEP 243, > which is still being developed, is tackling these issues and many > more. This proposal is considered compatible with, and adjunct to > the proposal in PEP 243. > > > Specification > ============= > > The specification takes three parts, the `web interface`_, the > `Distutils register command`_ and the `Distutils Trove > categorisation`_. > > > Web Interface > ------------- > > A web interface is implemented over a simple store. The interface is > available through the python.org domain, either directly or as > packages.python.org. > > The store has columns for all metadata fields. The (name, version) > double is used as a uniqueness key. Additional submissions for an > existing (name, version) will result in an *update* operation. > > The web interface implements the following commands/interfaces: > > **index** > Lists known packages, optionally filtered. An additional HTML page, > **search**, presents a form to the user which is used to customise > the index view. The index will include a browsing interface like > that presented in the Trove interface design section 4.3. The > results will be paginated, sorted alphabetically and only showing > the most recent version. The most recent version information will > be determined using the Distutils LooseVersion class. > > **display** > Displays information about the package. All fields are displayed as > plain text. The "url" (or "home_page") field is hyperlinked. > > **submit** > Accepts a POST form submission of metadata about a package. The > "name" and "version" fields are mandatory, as they uniquely identify > an entry in the index. **Submit** will automatically determine > whether to create a new entry or updating an existing entry. The > metadata is checked for correctness where appropriate - specifically > the Trove discriminators are compared with the allowed set. An > update will update all information about the package based on the > new submitted information. > > There will also be a submit/edit form that will allow manual submission > and updating for those who do not use Distutils. > > **user** > Registers a new user with the index. Requires username, password and > email address. Passwords will be stored in the index database as SHA > hashes. If the username already exists in the database: > > 1. If valid HTTP Basic authentication is provided, the password and > email address are updated with the submission information, or > 2. If no valid authentication is provided, the user is informed that > the login is already taken. > > Registration will be a three-step process, involving: > > 1. User submission of details via the Distutils *register* command, > 2. Index server sending email to the user's email address with a URL > to visit to confirm registration with a random one-time key, and > 3. User visits URL with the key and confirms registration. > > Several user Roles will exist: > > Admin > Can assign Owner Role - they decide who may submit for a given > package name. > > Owner > Owns a package name, may assign Maintainer Role for that name. The > first user to register information about a package is deemed owner > of the package name. The Admin user may change this if necessary. > > Maintainer > Can submit and update info for a particular package name > > Manual (through-the-web) user registration is also available through > an HTML form. > > **roles** > An interface for changing user Role assignments. > > **password_reset** > Using a supplied email address as the key, this resets a user's > password and sends an email with the new password to the user. > > The **submit** command will require HTTP Basic authentication, > preferably over an HTTPS connection. > > > Distutils *register* Command > ---------------------------- > > An additional Distutils command, ``register``, is implemented which > posts the package metadata to the central index. The *register* > command automatically handles user registration; the user is presented > with three options: > > 1. login and submit package information > 2. register as a new packager > 3. send password reminder email > > On systems where the ``$HOME`` environment variable is set, the user > will be prompted at exit to save their username/password to a file > in their ``$HOME`` directory in the file ``.pythonpackagerc``. > > Notification of changes to a package entry will be sent to all users > who have submitted information about the package. That is, the original > submitter and any subsequent updaters. > > The *register* command will include a ``--verify`` option which > performs a test submission to the index without actually committing > the data. The index will perform its submission verification checks > as usual and report any errors it would have reported during a normal > submission. This is useful for verifying correctness of Trove > discriminators. > > The index server will return custom headers (inspired by PEP 243) > which the *register* command will use to give feedback to the user: > > **X-Pypi-Status** > Either "success" or "fail". > > **X-Pypi-Reason** > A description of the reason for failure, or additional information > in the case of a success. > > > Distutils Trove Categorisation > ------------------------------ > > The Trove concept of *discrimination* will be added to the metadata > set available to package authors through the new attribute > "classifiers". The list of classifiers will be available through the > web, and added to the package like so:: > > setup( > name = "roundup", > version = __version__, > classifiers = [ > 'Development Status :: 4 - Beta', > 'Environment :: Console (Text Based)', > 'Environment :: Web Environment', > 'Intended Audience :: End Users/Desktop', > 'Intended Audience :: Developers', > 'Intended Audience :: System Administrators', > 'License :: OSI Approved :: Python License', > 'Operating System :: MacOS X', > 'Operating System :: Microsoft :: Windows', > 'Operating System :: POSIX', > 'Programming Language :: Python', > 'Topic :: Communications :: Email', > 'Topic :: Office/Business', > 'Topic :: Software Development :: Bug Tracking', > ], > url = 'http://sourceforge.net/projects/roundup/', > ... > ) > > It was decided that strings would be used for the classification > entries due to the deep nesting that would be involved in a more > formal Python structure. > > The original Trove specification that classification namespaces be > separated by slashes ("/") unfortunately collides with many of the > names having slashes in them (e.g. "OS/2"). The double-colon solution > (" :: ") implemented by SourceForge and FreshMeat gets around this > limitation. > > The list of classification values on the module index has been merged > from FreshMeat and SourceForge (with their permission). This list > will be made available through the web interface as a text list which > may then be copied to the ``setup.py`` file. The *register* command's > ``--verify`` option will also check classifiers values. > > Unfortunately, the addition of the "classifiers" property is not > backwards-compatible. A setup.py file using it will not work under > Python 2.1.3. It is hoped that a bugfix release of Python 2.2 will > relax the argument checking of the setup() command to allow new > keywords, even if they're not actually used. It is preferable that > a warning be produced, rather than a show-stopping error. > > > Reference Implementation > ======================== > > Reference code is available from the SourceForge project: > > http://sourceforge.net/projects/pypi/ > > A demonstration will be available at: > > http://www.amk.ca/cgi-bin/pypi.cgi > > ===== =================================================== > Done Feature > ===== =================================================== > Y Submission > Y Index > Y Display > Y Search > Y User registration > Y User verification > Y Password reset > Y Admin interfaces for user/package maintenance > N Trove > ===== =================================================== > > In the two days of the 22nd and 23rd October 2002, after the first > announcement to the Catalog-SIG (22nd) and Distutils-SIG (23rd), the > initial prototype had 45 visitors (not including myself), two of whom > used the *register* command to submit package information. > > > References > ========== > > .. [1] Distutils packaging system > (http://www.python.org/doc/current/lib/module-distutils.html) > > .. [2] Trove > (http://tuxedo.org/~esr/trove/) > > .. [3] Vaults of Parnassus > (http://www.vex.net/parnassus/) > > .. [4] CPAN > (http://www.cpan.org/) > > .. [5] PAUSE > (http://pause.cpan.org/) > > .. [6] PEP 243, Module Repository Upload Mechanism > (http://www.python.org/peps/pep-0243.html) > > .. [7] PEP 262, A Database of Installed Python Packages > (http://www.python.org/peps/pep-0262.html) > > > Copyright > ========= > > This document has been placed in the public domain. > > > Acknowledgements > ================ > > Anthony Baxter and Martin v. Loewis for encouragement and feedback > during initial drafting. > > A.M. Kuchling for support including hosting the second prototype. > > The many participants of the Distutils and Catalog SIGs for their > ideas over the years. > > > .. > Local Variables: > mode: indented-text > indent-tabs-mode: nil > sentence-end-double-space: t > fill-column: 70 > End: From grante at visi.com Wed Nov 13 12:49:07 2002 From: grante at visi.com (Grant Edwards) Date: 13 Nov 2002 17:49:07 GMT Subject: python gui rant References: <3dd217e2$0$231$4d4ebb8e@news.nl.uu.net> <3dd27ed6$0$4440$a1866201@newsreader.visi.com> Message-ID: <3dd29093$0$22234$a1866201@newsreader.visi.com> In article , Bengt Richter wrote: > On 13 Nov 2002 16:33:26 GMT, grante at visi.com (Grant Edwards) wrote: >> >> >>One warning: there is a very special place reserved in hell for >>people who design GUI dialogs with hard-wired widget locations >>so that the dialogs can't be resized. One of the reasons I >>really hate working with MS-Windows because of all the dialog >>boxes that use 80% of the space in a dialog for useless crap, >>and then show only four lines in a list-box containing 100+ >>elements. A decent GUI would let you resize the dialog so you >>could see more of the stuff in the list-box. But not >>MS-Windows.... >> >> > > Well, the above is just a snapshot of the state of a bunch of > properties. In Delphi you can easily add code to vary them > dynamically however you want and have the visual appearance > automatically keep up in most cases. That's good to hear. I do realize that it's possible to design resizable dialog boxes under MS-Windows. My one effort at an MS-Windows app does it -- or rather lets wxWindows do it. > You can also design dialogs that would behave to your specs. > It's not windows the OS (though there's plenty of other stuff > to rant about ;-) or Delphi that you're ranting against, it's > product of particular app coders ;-) You're right. Nailing everything down does seem to be SOP for 99% of the Widnows apps I run across. -- Grant Edwards grante Yow! Look DEEP into the at OPENINGS!! Do you see any visi.com ELVES or EDSELS... or a HIGHBALL??... From LogiplexSoftware at earthlink.net Mon Nov 4 19:00:35 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 04 Nov 2002 16:00:35 -0800 Subject: wxPython style question In-Reply-To: References: Message-ID: <1036454435.3127.95.camel@software1.logiplex.internal> On Mon, 2002-11-04 at 12:24, Gary Pajer wrote: > I'm trying to learn my way around wxPython. I'm relatively new to python. > > I have (at least) two choices when it comes time to create an object (say a > wxPanel). The first is what most demos seem to do: I can make it an > instance attribute of the Frame (referred to by self): > > def __init__(self, ...): > self.panel1 = wxPanel(self, ...) > etc. > > And then reference to the Panel is always available via self.panel1 > > Or I can call the constructor without "self" in which case (if I > understand the mechanics) the wxWindow object is created, but the wxPython > object that wraps it dissapears after __init__ finishes. > > def __init__(...): > panel1 = wxPanel(self, name="panel1", ... ) > etc. > > > Now, if I want to change an attribute of the Panel: > In the former case, I call > > self.panel1.wxSetWhatever(). (where self is the wxFrame instance) > > > In the later, I need to find the wxWindow version of the Panel. I can do > this by giving the Panel a name at creation, and then searching for the name > later, e.g. in a callback routine: > > def ProcessMenuSelection(self,event): > panel = self.FindWindowByName("panel1") > panel.wxSetWhatever() > etc. > > The later method has some asthetic appeal to me because it does not litter > the source code with so many selfs, and it doesn't create attributes that > might serve no purpose. > These reasons may not be good reasons. Is there some reason for preferring > one approach over the other? While either approach will work, maintaining unique names for windows would seem to be a major PITA (I rarely even bother changing the default name argument when using wxPython). The approach I usually use is to save references to windows that I know I'll need later on (or more likely, add the references as I need them), and not save them for ones I don't. This gives you easy access to the objects you need while not creating "attributes that might serve no purpose." BTW, if you're *that* concerned about aesthetics, avoid GUI programming - you'll go mad trying to balance your sensibilities with the possibility of getting anything useful done ;) > Am I missing some key point? GUI programming sucks. wxPython just makes it suck less. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From maney at pobox.com Wed Nov 13 17:59:32 2002 From: maney at pobox.com (maney at pobox.com) Date: Wed, 13 Nov 2002 22:59:32 +0000 (UTC) Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3dce5e2f$0$35917$edfadb0f@dread13.news.tele.dk> <7h3smy5zj8k.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson wrote: > come up with it. Isn't there a pithy quote along the lines of > "constraints spark creativity"? Form is liberating? Though a slightly mangled old saw like "desperation is the mother of invention" seems more like what you're looking for. :-) > The only biggy for me is the lack of Lisp style (with-... ) macros; > which of these do you prefer: > > def You got cutoff here, or the article got truncated on its way. Want to try again? I expect I'd enjoy seeing what you were going to say. From djc at object-craft.com.au Tue Nov 19 22:31:28 2002 From: djc at object-craft.com.au (Dave Cole) Date: 20 Nov 2002 14:31:28 +1100 Subject: csv module 1.0 released Message-ID: WHAT IS IT: The CSV module provides a fast CSV parser which can split and join CSV records which have been produced by Microsoft products such as Access and Excel. The module is available here: http://www.object-craft.com.au/projects/csv/download/csv-1.0.tar.gz The module home page is here: http://www.object-craft.com.au/projects/csv/ NOTES: The most important change for this release is that the basic quote handling has been modified to exactly match the observed behaviour of Excel. A comprehensive test suite has been added to test this observed behaviour. If the module does not conform to Excel behaviour we consider this to be a bug. No problems were reported with the 1.0pre1 release. This release makes the 1.0pre1 release official. CHANGES SINCE 0.5: * Moved to standard BSD template license. * Now using distutils to create source distribution. * Parser's handling of unusual quoting styles was found to be at odds with Excel. In particular, Excel only treats the quote character as special if it appears as the first character in a field, whereas our parser honoured them anywhere. We now produce the same result as Excel - quotes within a field appear in the output. * Introduced Parser.quote_char attribute to replace the hard coded " (double quote). You can now disable quoting by setting quote_char to 0 or None. * Introduced Parser.escape_char attribute which is used to escape special characters when quote_char is specified is disabled. * Introduced Parser.strict attribute which controls whether the parser will raise an exception on malformed fields rather than attempting to guess the right behaviour. * Introduced a suite of unit tests. -- http://www.object-craft.com.au From bokr at oz.net Thu Nov 7 23:30:43 2002 From: bokr at oz.net (Bengt Richter) Date: 8 Nov 2002 04:30:43 GMT Subject: Any modules to write a wav file References: Message-ID: On Fri, 8 Nov 2002 02:07:45 +0000 (UTC), Sreekant Kodela wrote: >Hi folks > >Does anyone know of a module which I can use basically to create a wav file >or other sound format file, using the various numbers generated by a >different snippet. > >Any soundformat will do. > I've used the read capability, but I haven't tried writing using the wave module. But it looks straight forward. Check out (I am on windows 2.2.2 here): http://www.python.org/doc/current/lib/module-wave.html or >>> import wave >>> help(wave) Help on module wave: NAME wave - Stuff to parse WAVE files. [... about reading ...] Writing WAVE files: f = wave.open(file, 'w') where file is either the name of a file or an open file pointer. The open file pointer must have methods write(), tell(), seek(), and close(). This returns an instance of a class with the following public methods: setnchannels(n) -- set the number of channels setsampwidth(n) -- set the sample width setframerate(n) -- set the frame rate setnframes(n) -- set the number of frames setcomptype(type, name) -- set the compression type and the human-readable compression type setparams(tuple) -- set all parameters at once tell() -- return current position in output file writeframesraw(data) -- write audio frames without pathing up the file header writeframes(data) -- write audio frames and patch up the file header close() -- patch up the file header and close the output file You should set the parameters before the first writeframesraw or writeframes. The total number of frames does not need to be set, but when it is set to the correct value, the header does not have to be patched up. It is best to first set all parameters, perhaps possibly the compression type, and then write audio frames using writeframesraw. When all frames have been written, either call writeframes('') or close() to patch up the sizes in the header. The close() method is called automatically when the class instance is destroyed. HTH Regards, Bengt Richter From paustin at eos.ubc.ca Sat Nov 23 20:00:12 2002 From: paustin at eos.ubc.ca (Philip Austin) Date: 23 Nov 2002 17:00:12 -0800 Subject: Boost.Python sans Jam References: Message-ID: Mark writes: > Now, I realized I needed to do one thing before running [not necessarily > before compiling my "boostable" extension]: > > export LD_LIBRARY_PATH=~/lib > > To compile, I used the following command line [there may be some unnecessary > stuff in here]: > > g++ hello.cpp -I/home/mfenner/include -I/usr/include/python2.2/ > -L/usr/lib/python2.2/config -L/home/mfenner/lib -lpython2.2 -lboost_python > -o hello.so -shared 1) If you want to remove the dependence on LD_LIBRARY_PATH, you can pass the runpath to the loader directly like this: g++ hello.cpp -I/home/mfenner/include -I/usr/include/python2.2/ -Wl,-rpath,/home/mfenner/lib -L/usr/lib/python2.2/config -L/home/mfenner/lib -lpython2.2 -lboost_python -o hello.so -shared You can check to make sure this works with ldd hello.so which should find all of the relocatable libraries linked by hello.so 2) If you want to see what bjam is really passing to g++, invoke bjam during the boost build with the flags -and2 You'll see that boost recommends something like this for a typical compile: g++ -c -Wall -ftemplate-depth-100 -DBOOST_PYTHON_DYNAMIC_LIB -DBOOST_PYTHON_V2 -g -O0 -fno-inline -fPIC -I/nfs/kite/common/python2.2.2/include/python2.2 -idirafter"/nfs/kite/common/boostv2_gcc3.2.1" -o num_util.o Regards, Phil From phil at river-bank.demon.co.uk Sat Nov 16 10:41:25 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Sat, 16 Nov 2002 15:41:25 +0000 Subject: pykde on mandrake 9 In-Reply-To: <63921a7c.0211160727.23dd93bc@posting.google.com> References: <63921a7c.0211160727.23dd93bc@posting.google.com> Message-ID: <200211161541.25113.phil@river-bank.demon.co.uk> On Saturday 16 November 2002 3:27 pm, hannibal wrote: > i built pyqt and pykde on my mandrake 9.0 system. > When i try to run the examples of pykde i receive "import > error:qcommonstyle not found". > Any idea ? Read the PyQt FAQ. Phil From grante at visi.com Wed Nov 27 00:16:48 2002 From: grante at visi.com (Grant Edwards) Date: 27 Nov 2002 05:16:48 GMT Subject: Python Tutorial Was: Guido's regrets: filter and map References: <3de39ce9$0$22220$a1866201@newsreader.visi.com> <3DE44D27.3030904@something.invalid> Message-ID: In article <3DE44D27.3030904 at something.invalid>, Greg Ewing wrote: > In the case of lambda, however, you can always get > the same effect using an explicitly declared function, > bound method, etc. So lambda isn't really needed > anyway, regardless of whether list comprehensions > exist. Technically, you can do everything with nothing but binary NAND operators, so things like addition, subraction, etc. aren't really required. That doesn't make it a good idea to eliminate things just because they can be replace by more complicated sets of operations. -- Grant Edwards grante Yow! I think I'll do BOTH at if I can get RESIDUALS!! visi.com From wolfson at uchicago.edu Mon Nov 11 15:14:55 2002 From: wolfson at uchicago.edu (Ben Wolfson) Date: Mon, 11 Nov 2002 14:14:55 -0600 Subject: Can python find fibonacci series in a single line of code? References: Message-ID: On Mon, 11 Nov 2002 14:26:25 +0000, Mel Wilson wrote: > In article , > mwilson at the-wire.com (Mel Wilson) wrote: >>In article , >>a_human_work at hotmail.com (Pittaya) wrote: >>> [ ... ] find fibanicci series in >>>a single line of [Perl] code. >>>perl -le '$b=1; print $a+=$b while print $b+=$a' > >> One-liner contests are noxious, but what the heck; the >>first 10, governed by the xrange .. > > Well, one-liners clearly are not your forte. > >>print reduce (lambda x,y: (x[1],x[0]+x[1], x[2]+[x[1]]), xrange(10), (0,1,[]))[2] > > Pretty lame compared to > > print reduce (lambda x,y: x + [x[-1]+x[-2]], xrange(10), [1, 1] ) > > right? Yabbut how about this one: import sys;x=lambda a,b:(sys.stdout.write('%s\n'%a),x(a+b,a));x(0,1) Though that does depend on the maximum recursion depth. This one doesn't have that problem, but it pretty wide: import sys,operator as o;x=lambda a=[1,0]:(sys.stdout.write('%s\n'%a[-1]),o.setslice(a,0,2,[a[1],a[1]+a[0]]));list(iter(x,x)) This one is shorter but uses more memory: import sys;x=lambda a=[1,0]:(sys.stdout.write('%s\n'%a),a.extend([a[-1],a[-2]+a[-1]]));list(iter(x,x)) -- BTR BEN WOLFSON HAS RUINED ROCK MUSIC FOR A GENERATION -- Crgre Jvyyneq From blah at blah.org Fri Nov 29 17:03:12 2002 From: blah at blah.org (nospam sumofan) Date: Fri, 29 Nov 2002 17:03:12 -0500 Subject: python 2.2.2 install has unworking IDLE in windows 2000 References: Message-ID: <5wRF9.67396$e%.1592073@news20.bellglobal.com> I think I've been able to answer my own question on what the error is, but yet without a resolution. During the install, it has an Advanced settings button. It basically is asking do you want some files on C:\ or all on the directory of your install. (In my case E:\). So i tried it once to E:\ and when that failed once to C:\, just to rule it out as an error on my part. No error windows or anything but not working either. loaded pythonwin extentions so I at least get a GUI tool replacement. Yep, Win2k sp3. However, I did find the root cause. I tried it again but this time from the command dos like window. It gave errors on Tk/Tcl not being found, although it's clearly installed on my system from a previous interpreter. It's possible that a previous Ruby install which also has Tk/Tcl version is somehow not being allowed to work with python or only works with Ruby. Neither is the python install forcing itself to install the Tk/Tcl version that works with python. No Tk/Tcl icons or links either. Ruby is loaded in Cygwin with Tk/Tcl, so this looks more to be the issue here than Windows 2000, and I'll focus my energies there for now. thanks sumofan "Robin Becker" wrote in message news:u2ZKKiA32y59Ewi8 at jessikat.fsnet.co.uk... > In article , nospam > sumofan writes > >Hey, > > > >I've just installed python 2.2.2 and although the command line interpreter > >works okay, the IDLE gui doesn't even run. I've loaded this both ways under > >Advanced settings, even checked Task Manager for hung processes. Nothing. > >Any ideas? I can't find anything out there about it ;) > > > >TIA > ...... I just tries starting idle.pyw from the command line and it came > up fine. I have Python-2.2.2 & Win2k sp3. Which advanced settings are > you using? > -- > Robin Becker --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.423 / Virus Database: 238 - Release Date: 11/25/2002 From fabien.henon at caramail.com Sat Nov 23 20:47:21 2002 From: fabien.henon at caramail.com (Fabien HENON) Date: Sun, 24 Nov 2002 02:47:21 +0100 Subject: to PYQT gurus Message-ID: <3de030bd$0$18232$626a54ce@news.free.fr> I have written an GUI app using Pyton, Tkinter and PWM. It is mainly an editor for POV, with color syntax highlighting and many nice features. I can be found at : http://pyvon.sourceforge.net My question is simple : I am learning to use QT. Do you think it is feasible to transfer my from Tkinter to PYQT. I would like to benefit from QT's quickness. Thanks Fabien HENON From p.thibault at bigfoot.com Tue Nov 26 01:05:48 2002 From: p.thibault at bigfoot.com (Pierre Thibault) Date: Tue, 26 Nov 2002 01:05:48 -0500 Subject: IDLE on Mac OS 10.2.2 References: Message-ID: In article , Brian Lenihan wrote: > It is fairly easy to do what you want using the idle-fork project from > SourceForge and Python 2.3a0 from CVS. Doing it with Python 2.2.2 is > possible, but much more difficult. Look in the pythonmac-sig archive > for more info: > > http://mail.python.org/pipermail/pythonmac-sig/ Thank you! I'll ask to the mailling list. Regards. -------------- Pierre From threeseas at earthlink.net Fri Nov 22 22:58:59 2002 From: threeseas at earthlink.net (Timothy Rue) Date: Sat, 23 Nov 2002 03:58:59 GMT Subject: Python IRC dictatorship Message-ID: <29304.91T434T13743504threeseas@earthlink.net> Python Dicktatorshit. ?Connect? Looking up host "irc.debian.org"... ?Connect? Attempting connection to host "irc.freenode.net" (196.40.71.132) on port 6667... ?Connect? Connected. Now doing login... ?Log? Logging inactive. ?Server? [irc.debian.org] *** Looking up your hostname... ?Server? [irc.debian.org] *** Checking ident ?Server? [irc.debian.org] *** Found your hostname ?Server? [irc.debian.org] *** Got ident response ?Welcome? Welcome to the freenode IRC Network ThreeSeas ?Host? Your host is epoch.josepablo.net[epoch.josepablo.net/6667], running version dancer- ircd-1.0.31+maint8-fn6 ?Server? [irc.debian.org] *** Your host is epoch.josepablo.net[epoch.josepablo.net/6667], running version dancer-ircd-1.0.31+maint8-fn6 ?Server? This server was cobbled together Fri Nov 1 03:31:07 UTC 2002 ?Server? anthony.freenode.net is vdancer-ircd-1.0.31+maint8-fn6, accepting user modes abBcCdDeEfFgGhHiIkKlLmMnNopPrRsSUvVwWxXyYzZ0123459*@ and channel modes bcdefFghiIklmnoPqstv. ?Lusers? There are 3674 victims and 4066 hiding on 22 servers ?Lusers? 35 flagged staff members ?Lusers? 2 unknown connection(s) ?Lusers? 3179 channels formed ?Lusers? I have 1601 clients and 0 servers ?Lusers? Current local users: 1601 Max: 2496 ?Lusers? Current global users: 7740 Max: 14747 ?Server? Highest connection count: 2497 (2496 clients) (73959 since server was (re)started) ?MOTD? - anthony.freenode.net Message of the Day - ?MOTD? - Welcome to the freenode server in San Jose, Costa Rica! ?MOTD? - Thanks to Josepablo P?rez for sponsoring this server. ?MOTD? - ?MOTD? - ANTHONY, PIERS [1934-Present]. Piers Anthony was born in Oxford, England. ?MOTD? - His parents did relief work in Spain during the Spanish Civil War of 1936 to ?MOTD? - 1939. Piers and his sister joined them when the war ended, and he never ?MOTD? - returned to his native country. To begin writing, his wife Cam, a computer ?MOTD? - programmer, agreed to work for a year so he could pursue fiction writing full ?MOTD? - time. It didn't work out, so he became an English teacher. That didn't ?MOTD? - work out and in 1966 he went back to writing. His novels include Chthon, the ?MOTD? - very large Xanth series, the Incarnations of Immortality, and more. He is ?MOTD? - also a Linux user. ?MOTD? - ?MOTD? - freenode is a service of Peer-Directed Projects Center, a Texas nonprofit ?MOTD? - corporation, IRS 501(c)(3) application pending. If you find the service ?MOTD? - useful, please consider contributing financially to help us improve ?MOTD? - (http://freenode.net/contrib.shtml). For network policy, see our web site ?MOTD? - (http://freenode.net/policy.shtml). Thank you for using the network! ?MOTD? - ?MOTD? End of /MOTD command. --> You have joined channel #python. ?Topic? Topic for channel #python is Don't let the carrots fool you. The time for action is... umm... sometime next week. ?Topic? Topic for channel #python has been set by ameoba on 20:22:29 22-11-2002 ?Names? Users on #python: ThreeSeas Taranis_ dida cliechti_ red_one proteusguy jmones ivan foohbah jafo_ a3ws00 itamar gp sayke inapt tvon MisterP booyeah dash tsiar Kengur fog|zZzZ attila flippo_ kemu ameoba duplexer sulf TWD asqui jonI cliechti dan deus_x _AleX_ seme Crast r0kwork ry Netikular jor Tangent glyph d0rt r0ky_ joona alb Taranis- juri _jacob radix rc scn liiwi xeno42 colyte kittonian dunker z0mbie Thunder- exarkun af h3x deltab grib john zbir frangen ?Names? Users on #python: phed hhg Taaus ketaset paolo msm skylan noa_ jonez Yhg1s sjj plaisthos vegai steinn cmg eikeon teratorn Erwin[work] drewp Matt|| moshez Tmu Acapnotic wnp22 Sublime VladDrac sprocket_ mr_smith TenOfTen Fade psy gresco Setzer Lerris- snibril rik tig benz007 flippo Therion pyn skreech LordVan datazone zl0- tav|hiber _moshez Logan jamiebecker acct ?Names? End of /NAMES list. ?Time? anthony.freenode.net :Friday November 22 2002 -- 20:19:10 -06:00 -ChanServ- [#python] Welcome to #python, puny fleshlings. See the #python FAQ at http://www.purl.org/wiki/python/PythonFaq - see also http://python.org/ for docs and links. And remember: there is no PSU. ?Mode? Current modes for #python: no messaging ?Mode? Channel #python was created on 02:27:37 11-06-2002 ameoba JAVA! sayke duct tape splint applied, and i can still sorta type slowly dash ameoba: i'm crushing your head, i'm crushing your head sayke without using tho two outside fingers on my left hand ameoba HA! I laugh at your puny crushings! --> aum (~aum at l76-152.world-net.co.nz) has joined this channel. ameoba sayke : ice it and STOP USING IT for a while. if problems persist, you're fucked. TWD hrm oh well I don't need it... sayke haha sayke i stopped using it sayke its splinted ThreeSeas Question: how do you keep read/write collisions on a file from happening in python? is there like a prohibit function of something? dash ThreeSeas: that's not a python problem ameoba ThreeSeas : you mean locks? ThreeSeas locks? Hmmm sayke holy shit --> fariseo (~qq at 62.65.165.134) has joined this channel. sayke i noticed having this splinted gives me a weird bump on the inside of my hand ameoba your palm? sayke yea! sayke you know the pads on the palm sayke opposite the knuckle ameoba where the fingers meet the hand? sayke yea. sayke in between the two outermost pads on my left hands sayke is a bump sayke but * foohbah wants to see a sayke's hand webcam sayke i'd like to show you! dash "talk to the hand"? ameoba sayke : do you see one on the right hand too? ameoba sayke : it sounds like my hand... sayke the bump rises when i strighten out the hurt pinkie finger foohbah sayke: hold it toward Boston sayke no, there's not one on the right hand sayke haha ameoba sayke : well... get an x-acto knife, dig in and figure out what's wrong. sayke har foohbah ah. anatomical debugging. interesting. ameoba you shouldn't be afraid of exploring your own body. dash ameoba: warning, contains no user serviceable parts ThreeSeas Dash: I have several tasks, of which anyone of them might access a file to read or write to it. If they were just reading, no problem. But if one need to modify the file, the others need to wait.... dash ThreeSeas: yes. lock the file ameoba 3s: what's a 'task' ? dash yes. what do you mean by "task"? ameoba are we talking independant processes/threads? or just different parts of the same process? ThreeSeas ameoba: task as in a spawned chunk of code running on a multi-tasking system dash ThreeSeas: "chunk" as in "process"? ThreeSeas yes ThreeSeas threads ameoba OS-level file locking. dash ThreeSeas: "thread" != "process" ThreeSeas thanks dash ThreeSeas: you dont need threads. --> gene9 (gene9 at 194.158.216.247) has joined this channel. ?Nick? Taranis_ is now known as Taranis. dash ThreeSeas: describe the problem you are trying to solve with threads -- there is almost definitely a better way dash especially if you're having file contention issues ThreeSeas I'm not the coder but rather needing to provide a solution direction to a coder in order to solve a problem. ameoba ThreeSeas : if you're not a coder, you should leave those kinds of arcitechture decisions up to somebody who is one. jafo_ software suspend under Linux *ROCKS*. --> Glammie (~amacleod at h009027ad5e42.ne.client2.attbi.com) has joined this channel. ThreeSeas the situation is that several processes might try to access a file at the same time. But if an update is being made, then ....... deltab so make sure that doesn't happen jafo_ The APM suspend used to work fine on my laptop, but IBM has released some firmware updates that just hosed it. It's gotten a little better lately, now it's only about a 20% liklihood that it will fail to come back from suspend, unlike the 80% before, but it still sucks. ameoba BACK UP THE FUCKING TRUCK... what makes you sure that you need multiple processes? ThreeSeas ameoba: I didn't say I'm not a coder... I said I'm not the coder... as in the given coding effort ?Quit? Taranis- (~bruce at va-pulaski1a-76.chvlva.adelphia.net) has signed off (Read error: 110 (Connection timed out)). jafo_ Yeah, shouldn't you be using multiple threads instead of processes?!? ameoba If you don't know what a file lock is, and you claim to not be a coder, you should'nt even include things at the level in the spec you hand the coder. deltab either make them take turns, or have only one of them in charge of accessing the file ?Quit? cliechti (~cliechti at dclient80-218-79-66.hispeed.ch) has signed off (Connection timed out). ameoba what you need to do is define interfaces & what functions do. what goes on inside is a black box to be left to be designed by somebody who gets it. jafo_ Oh yeah, if you're not going to be doing the design work, document what you want the results to be and let the designer come up with wether there should be multiple processes or what. ThreeSeas ameoba: you don';t know what you are talking about <-- cliechti_ (~cliechti at dclient80-218-79-66.hispeed.ch) has left this channel ("Client Exiting"). jafo_ I love non-designers who can't keep their hands out of the design. jafo_ NOT! ?Quit? gene9 (gene9 at 194.158.216.247) has signed off (). --> cliechti (~cliechti at dclient80-218-79-66.hispeed.ch) has joined this channel. ThreeSeas OK Jerks... I need variables and their values stores in files... files that many fucking prograMS VCAN POSSIBLY ACCESS AT THE SAME FUCKING TIME ThreeSeas What the fuck don't youy get? sayke hehe ThreeSeas pissing all pof the damn place with arrogance jafo_ I have a love hate relationship with users to try to influence the design. Only without the love. sayke ThreeSeas: sounds like you need locks then sayke you can do it at a filesystem level jafo_ Or a database... ThreeSeas yeah... probably... thanks jafo_ Or you could use atomic updates. jafo_ Or a semaphore, which unfortunately the base Python doesn't include. inapt huh? ameoba jafo_ : are semaphores really appropriate for separate program instances? jafo_ ameoba: Yeah. inapt jafo_: threading has all the locking stuff, including semaphores jafo_ I usually do locking using the "jlock" add-on module, not suprisingly. It does dot-locking. jafo_ inapt: Are those actually interfaces to the system semaphores, or are they implemented in the Python interpreter? I believe it's the latter and multiple processes won't be synchronized by them, only threads in a single program. inapt jafo_: yep. you're correct. they're for multithreaded programs only. jafo_ It's a curse... inapt In the end, they use whatever thread_{nt|os2|pthread|...}.h uses jafo_ Perhaps, but the API is that you create a semaphore object and then acquire/release that. Which doesn't really work across processes. inapt nope inapt i'm not very experienced with the multi-process model, anway (to say the least) inapt but would it not be possible to use shared memory for locks? jafo_ Yes. If you're careful... jafo_ extremely careful... jafo_ semaphores will work with SMP and other things where multiple CPUs can be running the same code at the same time. ameoba semaphores would be safer than shm... inapt are you talking about these "POSIX semaphores" ? ameoba POSIX HAS SEMAPHORES!?!??!? --> lament (~lament at h24-78-145-92.vc.shawcable.net) has joined this channel. ?AutoAway? arning:AutoAWAY in 1 minute! ?Quit? jmones (~jmones at 65-BAR2-X88.libre.retevision.es) has signed off ("Client Exiting"). jafo_ I think I'm talking about SVID semaphores. ?AutoAway? ote:You are now set AWAY due to inactivity. ?Away? We'll miss you inapt (I know zero about either) ameoba semaphores are easy. using them correctly can be trouble. inapt but it looks like yet another funny cross-platform issue to me. jafo_ I don't know what posix semaphores are. jafo_ SVID semaphores use "semget", which is fairly well implemented. inapt Posix semaphores are described in my glibc manual. 1) pinfo libc 2) "POSIX semaphores" inapt I've seen them used in fog's psycopg ThreeSeas How to cause limitations ?Away? Does this mean you're really back? ameoba heh... I'd assume that POSIX semaphores were SVID semaphores that had been included in a new standard. jafo_ So, I have a "shmbench" I wrote a long time ago which sets up two processes talking to eachother using shared memory. It can run in two ways -- one way it uses "spin locks", where one process writes a string into the shared memory at offset +1, then writes a 1 at offset 0, then waits for that 0 to change to 1. The other process does the inverse. ameoba the other way? using semaphores & shm? jafo_ Running in that mode with spinlocks (just checking for the 0 to change to a 1 by checking all the time), I get a rate of 31 laps per second because of scheduler latency. jafo_ If I run it in semaphore mode, I get 150,000 laps per second. jafo_ That's on a UP box. If I run it on an SMP box, spinlocks really kick ass... inapt I might sound clueless ... inapt but is that stuff I can see with 'ipcs' related? inapt 'semaphore arrays' jafo_ Yes. inapt ah. inapt i needed to clear a PostgreSQL related one once. --> sam22 (~chatzilla at dsl-64-131-107-217.telocity.com) has joined this channel. dash tee hee dash good old timmy inapt hey dash dash ThreeSeas: Read this: come back when you've come up with an original argument - >http://www.kuro5hin.org/story/2002/11/18/22112/860 ameoba jafo : are spinlocks sufficiently faster on a SMP machine to offset their lameness on a UP machine? inapt ah. moshez' article. ThreeSeas dash: looking for an excuse? inapt I've read it and found it quite good. dash ThreeSeas: No. just looking to not repeat myself for the umpty-jillionth time tig what does this statement mean: "strictly speaking, the operand of the logical operators should be boolean expressions, but Python is not very strict." dash tig: it means "i am a narrow-minded git and i dislike python" inapt tig: Python works with nonzero-ness inapt tig: if something is nonzero, it is considered true tig dash: eh? inapt tig: otherwise, it is considered false dash or has a nonzero length tig inapt: thx inapt tig: None, "", [], empty tuples, are all zero. inapt tig: about everything else is nonzero. dash ThreeSeas: anyway, if you aren't writing the code, then you aren't qualified to talk about it inapt tig: that's why None or 5 yields 5. ThreeSeas Christ! I don't have to read but a little of that to know you have no idea what I'm trying to do. ameoba tig : he says that the things compared by and/or/not should be true/false values (as in the result of ==, >,<, !=, in, etc) instead of other values. tig inapt: but an operand as a boolean expression? inapt tig: sorry? dash ThreeSeas: ok. so what, exactyl, does that article and following comments not address? tig inapt: "the operands of the logical operators should be boolean expressions" ameoba (a != 0) and (b !=0) instead of a and b tig oh tig i see inapt hmm dash tig: which is why i said what i did jafo_ ameoba: Yeah, I don't recall what it was I was seeing performance wise, but IIRC spinlocks on a SMP machine were like 100x faster than semaphores for this benchmark. inapt in the mathematical sense, a value is probably just defined as the minimal form of an expression :) jafo_ Obviously, you want to decide wether it makes sense and perhaps auto-detect if they make sense before using them. inapt i. e. True|False lament tig: that's very disgusting, by the way, and it's great python doesn't do that tig lament: i agree, but dont most languages? lament Don't know about "most languages" ameoba damn... stil not worth offsetting the 7000x faster semaphores were on the UP machine unless you were certain taht you were going to be on an SMP box ameoba tig : what mean you by 'most languages'? lament ameoba: probably C and C++ tig i guess i meant the most popular languages these days lament tig: yes, that's quite different from 'most' tig c, c++, perl, java, c#, etc ameoba c & C++ also work on non-zeroness, but python has slightly different handling of the actual value returned. inapt the c-ish crap :-P ameoba I know that Excell doesn't have such an idea of truth jafo_ ameoba: Hence my saying that you probably want to auto-detect. dash ameoba: well, because python doesn't make a distinction between "values" and "objects" ameoba with Excel, you need to have an actual true/false value. exarkun Damned Excel! dash also with java exarkun Also a damned creation. ThreeSeas Dash: what does the internet not address? ameoba my dad's taking a class in excel, so I find myself doing a lot of ugly nested conditionals in excel dash ThreeSeas: ok, back up dash ThreeSeas: you said "you have no idea what i'm trying to do" dash ThreeSeas: why did you say that? ThreeSeas 419 comments .......is that alll? ameoba o/` you are the best listener I've ever met / you're my best friend / best friend with benefits o/` dash ThreeSeas: answer the question. exarkun ThreeSeas: So what *are* you trying to do, anyway? * Glammie used to hate Alanis. Glammie Now I like to listen to her music. ThreeSeas I'm trying to insure read/write collision doesn't happen. inapt USE LOCKS ThreeSeas And there may be a solution that is not mentioned --> _Kengur (~kengur at access-038-201.moscow.eur.slb.com) has joined this channel. dash inapt: or, "only do one thing at a time" dash ThreeSeas: "may"? dash ThreeSeas: why do you say that? inapt or go to #twisted, where they'll explain to you how to do one thing at a time ThreeSeas inapt: I've been looking in ORiely books for locks and don't find much on it inapt ThreeSeas: what's your requirements? ameoba ThreeSeas : man flock inapt ThreeSeas: then we can suggest a solution. inapt files & locks => flock, for example ThreeSeas serial stream... priority given to process with higest unique number in the event of a tie... dash ThreeSeas: why? ameoba what'd handle the stream? ThreeSeas flocks? Ah..... ameoba fcntl.flock() in python inapt ThreeSeas: how many readers? how many writers? dash more importantly, what are they doing? ?Quit? sulf (sulf at dsl-130-182.aei.ca) has signed off (). ThreeSeas unix only ThreeSeas number of readers and writers.... unknown inapt and they all access a single file? exarkun ThreeSeas: You don't even have an order of magnitude? exarkun ThreeSeas: 1? 100? 10000? dash heh. does it matter? there's only "one or more" ThreeSeas how is stdout schedualed when several programs or process are trying to writ to it at the same time? dash ThreeSeas: It isn't. ThreeSeas dash... and there is the solution dash ThreeSeas: please answer my question exarkun dash: Sure it matters dash exarkun: keep in mind who you're talking to ThreeSeas variable ; tag ; value exarkun dash: Well, if we were discussing a real situation instead of a hypothetical in someone's fantasy world... dash exarkun: then it might matter :) ThreeSeas file of variabls ; tags; values dash ThreeSeas: why? inapt ThreeSeas: one file? if yes, then, as dash says, 'why?' ThreeSeas Because that is the way it is. inapt ok. dash ThreeSeas: what does this data signify? why multiple processes writing to it? what are the processes doing with the data? ThreeSeas they are VIC variables ThreeSeas where more than one instance of a VIC can be running inapt ThreeSeas: I'd use a SQL database dash why more than one instance? ameoba perhaps having them communicate w/o a file might be better... ThreeSeas normally a VIC would have it's exclusive set/file for variables... but in some cases there is a sharing in both read and write dash inapt, ameoba, exarkun: you guys all done? inapt dash: yes, hearing 'VIC', I'm out ThreeSeas SQL for what? ?OP? ChanServ gives channel operator status to dash inapt ThreeSeas: accessing the data. ?Kick? You have been kicked out of channel #python by dash: the doctor is [OUT] ?Error? Python That channel doesn't exist --> You have joined channel #python. ?Topic? Topic for channel #python is Don't let the carrots fool you. The time for action is... umm... sometime next week. ?Topic? Topic for channel #python has been set by ameoba on 20:22:29 22-11-2002 ?Names? Users on #python: ThreeSeas _Kengur sam22 lament cliechti Glammie fariseo aum Taranis dida red_one proteusguy ivan foohbah jafo_ a3ws00 itamar gp sayke inapt tvon MisterP booyeah dash tsiar Kengur fog|zZzZ attila flippo_ kemu ameoba duplexer TWD asqui jonI dan deus_x _AleX_ seme Crast r0kwork ry Netikular jor Tangent glyph d0rt r0ky_ joona alb juri _jacob radix rc scn liiwi xeno42 colyte kittonian dunker z0mbie Thunder- exarkun af h3x deltab grib john zbir ?Names? Users on #python: frangen phed hhg Taaus ketaset paolo msm skylan noa_ jonez Yhg1s sjj plaisthos vegai steinn cmg eikeon teratorn Erwin[work] drewp Matt|| moshez Tmu Acapnotic wnp22 Sublime VladDrac sprocket_ mr_smith TenOfTen Fade psy gresco Setzer Lerris- snibril rik tig benz007 flippo Therion pyn skreech LordVan datazone zl0- tav|hiber _moshez Logan jamiebecker acct ?Names? End of /NAMES list. -ChanServ- [#python] Welcome to #python, puny fleshlings. See the #python FAQ at http://www.purl.org/wiki/python/PythonFaq - see also http://python.org/ for docs and links. And remember: there is no PSU. ?Mode? Current modes for #python: no messaging ?Mode? Channel #python was created on 02:27:37 11-06-2002 dash inapt: no dash inapt: well actually dash inapt: why not --> xcabbage (x at ACA7A5D2.ipt.aol.com) has joined this channel. ThreeSeas what is your problem dash? xcabbage gres, why did you paste that huge emacs manual into #flood? exarkun ThreeSeas: You're a waste of time dash ThreeSeas: you're incoherent, uncommunicative, and as exarkun says, a waste of time ThreeSeas says which dictatorship? dash ThreeSeas: you aren't writing this code, you aren't explaining how the decisionsare being made... what do you want from us? dash ThreeSeas: why do you expect us to tolerate your nonsense? ThreeSeas you have a problem in understanding the files access? inapt /IGNORE -replies *!3seas@* ALL inapt <-- is that correct IRC syntax? dash threeseas: _you_ have a problem understanding that we are not here to rubber-stamp your ideas dash inapt: you can probably drop the '-replies' <-- xcabbage (x at ACA7A5D2.ipt.aol.com) has left this channel. inapt /IGNORE *!3seas@* ALL inapt sorry. ThreeSeas I asked a question, python related... dash threeseas: yes. if you ask a question here, it takes work to get it answered; work on your part, and ours dash threeseas: if you aren't willing to put forth the effort to explain what you're doing and why, then i dont see why we should feel obligated to either ThreeSeas I'm a genius... If I can't answer your question I will try and make out that you don't know what you are talking about..... but are there really 120 users here that hail to ...... dash exarkun Haha. exarkun dash: just finish it ?Quit? MisterP (~lister at 66.138.124.76) has signed off (Remote closed the connection). ameoba MUAHAHAHHAHAHAHAHAAHHAH ameoba ThreeSeas : isn't it a little suspicious that NOBODY has ever understood your grand ideas? ?Quit? Kengur (~kengur at moscow-pp3.access.sinet.slb.com) has signed off (Read error: 110 (Connection timed out)). ThreeSeas a few claim that ameoba ThreeSeas : there's always the possibilty that you're so far above us that we're left in your dust... but isn't there a possibility, however remote, that YOU ARE OFF YOUR ROCKER? inapt I'm pretty sure that they'll be much easier to implement in a more flexible language. inapt He might want to join #perl instead. ameoba #lisp dash ameoba: Probably. inapt fine with me too ;-) ThreeSeas a file exist which holds a list of --- variable name ; a tag value ; and a variable value ameoba 3s : consider http://www.paulgraham.com/icad.html ThreeSeas the file can be read and written to by more than one process/program. ThreeSeas The concern is over read/write collision. dash ThreeSeas: Why? dash ThreeSeas: Why should these processes attempt to share the file? ameoba asuming that this program is going to be some sort of shell/command interpreter/user interface/etc, if they need to share state, a file isn't going to cut it. ameoba s/file/flat file/ ThreeSeas why is there such a thing as global? dash ThreeSeas: Irrelevant. Answer the question. ThreeSeas only with a file other things are possible dash ThreeSeas: Wrong. ThreeSeas why? dash ThreeSeas: I can think of at least three or four other ways to solve the problem, but you have not told us what the real problem is ThreeSeas sure I have dash ThreeSeas: i'm not going to explain each one at length in hopes one of them is the correct one for your problem. ThreeSeas you just don't want to hear it dash ThreeSeas: ok, one last chance: ThreeSeas a file exist which holds a list of --- variable name ; a tag value ; and a variable value dash ThreeSeas: what are you doing that requires multiple processes to share state? ThreeSeas the file can be read and written to by more than one process/program. dash ThreeSeas: wrong answer. ameoba that's all fine and dandy. what are the variables for? ThreeSeas to pass values dash ThreeSeas: pass from what to what? inapt Ok, I'll go play UT. The S/N ratio is much better in the UT chats :-P exarkun dash: why bootheerrr dash inapt: yes. ameoba if you have 5 instances, and each one of them is setting and unsetting variables willy-nilly, using a file to share this data is a Bad Idea. dash exarkun: i'm nearly done inapt cu exarkun ok, cool. ?Nick? inapt is now known as inapt|detached. teratorn ameoba: i cant see how it would ever be a good idea ameoba inapt : S/N is better, for sufficiently large valuations of penis/gay/fart jokes foohbah teratorn: conceptual art? dash foohbah: no :) ameoba teratorn : I can't say it'd be the best idea, but if the 'variables' are really more of a configuration system than a variable/state thing, it'd be right.. dash ameoba: no it wouldn't dash ameoba: there's no difference ameoba dash : everything uses files for config. dash ameoba: if it's a configuration system, you dont write to it at runtime exarkun If you need to interoperate with something else that can't be changed and expects configuration to be in a file and also respects file locks, it might be an ok idea dash exarkun: sure, but remember the context. ;) exarkun Yes ameoba of course that's an outside case, and sounds unrelated to the task at hand. exarkun The context is "My name is ThreeSeas, and I am a retard." so it's not applicable foohbah Flying pigs might also be a good idea, but I'm not sure it's worth discussing at length. itamar exarkun: saw my comment on #twisted? dash foohbah: why not! pigs are cheap, affordable air travel for everyone ameoba foohbah : flying pigs are scheduled to be included after the DWIMer (which, IIRC, is going to be in 2.7) dash foohbah: although the people under the porcine airways might complain about the pollution * foohbah hopes we can find something or someone else to torment soon dash ThreeSeas: where'd you go? ThreeSeas several programs are writing to stdout....by redirecting stdout to a file append.... a variable that shows up more than once is set to the last value given.... problem solved ameoba riiiight --> aggregate (aggy at ip68-1-95-9.pn.at.cox.net) has joined this channel. dash ThreeSeas: you didn't answer my question dash ThreeSeas: pass from what to what? ThreeSeas from a to b exarkun ThreeSeas: You are stupid exarkun ThreeSeas: You are stupid exarkun ThreeSeas: You are stupid exarkun ThreeSeas: And do not forget exarkun ThreeSeas: You are stupid dash ThreeSeas: what are 'a' and 'b'? * ameoba hands around the ceremonial LARTs dash ThreeSeas: if you aren't going to _try_ to cooperate, then you need to go. ThreeSeas what do you use variables for? to pass value around ameoba "I am considering transporting a product between two points. What type of snow tires would you recomend?" dash ThreeSeas: No. You do not understand. You cannot answer a question with another question. ThreeSeas I also gave the answer dash ThreeSeas: No, you didn't. dash "from a to b" is not an answer. ThreeSeas to pass value around ameoba The socratic method is reserved for the one who understands what is going on. dash ThreeSeas: "pass" from where to where? ameoba ...in which case, NONE OF US can use it. foohbah the troll method is reserved for trolls ThreeSeas from where it is set to where it is used. dash foohbah: we had a good troll by here earlier dash ThreeSeas: Also not an answer. foohbah msg dash better than threeseas? ThreeSeas define variable dash. dash ThreeSeas: No. ameoba ThreeSeas : you're the one using the term, what do YOU think it means dash ThreeSeas: Game over, man. If you cant answer questions coherently, it's time to go. Come back when you can explain what's going on in your head. ?Quit? foohbah (~chatzilla at pool-141-154-242-2.bos.east.verizon.net) has signed off ("sheepishly practices typing slashes. Slashes wrists. Goes to bed."). ?OP? ChanServ gives channel operator status to dash ?Kick? You have been kicked out of channel #python by dash: your time is up ?Error? You are banned from channel #python. --- *3 S.E.A.S - Virtual Interaction Configuration (VIC) - VISION OF VISIONS!* *~ ~ ~ Advancing How we Perceive and Use the Tool of Computers!* Timothy Rue What's *DONE* in all we do? *AI PK OI IP OP SF IQ ID KE* Email @ mailto:timrue at mindspring.com >INPUT->(Processing)->OUTPUT>v Web @ http://www.mindspring.com/~timrue/ ^<--------<----9----<--------< From csshi99 at yahoo.com Thu Nov 7 23:18:29 2002 From: csshi99 at yahoo.com (Mindy) Date: Thu, 7 Nov 2002 20:18:29 -0800 (PST) Subject: Help me out with bugs in my list ? In-Reply-To: Message-ID: <20021108041829.55163.qmail@web21203.mail.yahoo.com> Hey, I have two lists like: binding_list = ["ls","ls","ls","netscape","netscape","lib","lib"] to_list = ["ls","lib","ls","netscape","ls","lib","lib"] I want to get non-duplicated pairs of strings from them like (binding_list[i],to_list[i]) by eliminating the duplicated pairs. For the above two lists, I want to get two new lists: binding_list = ['ls', 'ls', 'netscape', 'netscape', 'lib'] to_list = ['ls', 'lib', 'netscape', 'ls', 'lib'] My codes are like the following, but I got the result as: binding_list = ['ls', 'ls', 'netscape', 'netscape', 'lib','lib'] to_list = ['ls', 'lib', 'netscape', 'ls', 'lib','lib'] With the last two pairs duplicated. I know I was wrong because at the last loop, index1 = 4, index2 =1, even though the fifth pair is the same with the fourth pair, my codes can't detect this. Could anyone help me to get a correct piece of codes? Thanks so much! My codes: ---------------- for i in range(1,len(binding_list)): if (i == len(binding_list)): break index1 = binding_list.index(binding_list[i]) index2 = to_list.index(to_list[i]) if ((index1 >=0)and(index2 >=0)and(index1==index2)): del binding_list[i] del to_list[i] print binding_list print to_list ===== Cheers -Mindy __________________________________________________ Do you Yahoo!? U2 on LAUNCH - Exclusive greatest hits videos http://launch.yahoo.com/u2 From fperez528 at yahoo.com Sun Nov 24 02:36:37 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Sun, 24 Nov 2002 00:36:37 -0700 Subject: Python Tutorial Was: Guido's regrets: filter and map References: Message-ID: Thomas Guettler wrote: > >> Hello, >> >> I just read Guido's "python regret's" slide's from OSCON, >> http://www.google.com/search?hl=en&ie=ISO-8859-1&q=OSCON+%22python+regrets%22 >> and one thing i can't work out is, >> he is saying we can do map() and filter() with list comprehensions (it's >> faster too) eg. > > Thank you for this link. And for those of us who don't use powerpoint, the pdf version is also available (prettier than google's html-ized ppt): http://www.python.org/doc/essays/ppt/regrets/PythonRegrets.pdf Cheers, f. From loewis at informatik.hu-berlin.de Thu Nov 7 13:35:52 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 07 Nov 2002 19:35:52 +0100 Subject: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up References: Message-ID: Jon Ribbens writes: > > I would still recommend to use 0x8000000L instead; it saves you one > > computation, and is more readable. > > But that *won't work* on later versions of Python! How do you know? Later versions of Python have not been released! > It means I will have a line in my code which I know will suddenly > stop working at some point in the future and I will have to make a > new release and everyone will have to upgrade their copies of my > module just because I put in code which I knew wasn't going to work. Yes, provided your code is still in use when that happens. Regards, Martin From wasjaja at gmx.de Sat Nov 16 13:07:40 2002 From: wasjaja at gmx.de (Christian Rapp) Date: Sat, 16 Nov 2002 19:07:40 +0100 Subject: Get Stdout from external script startet through python References: Message-ID: Seems to work, thanks! Greets C. Rapp "Wojtek Walczak" schrieb im Newsbeitrag news:slrnatd4f4.8d.gminick at hannibal.localdomain... > Dnia Sat, 16 Nov 2002 12:40:30 +0100, Christian Rapp napisa?(a): > > I need to start an external script from inside python. This works just fine. > > The called script produces some output on StandardOut, that I need within > > the python-script. How do I get this Output into python? > > >>> import os > >>> print os.popen.__doc__ > popen(command [, mode='r' [, bufsize]]) -> pipe > Open a pipe to/from a command returning a file object. > >>> a = os.popen("/bin/date") > >>> print a.read(), > Sat Nov 16 19:42:59 CET 2002 > >>> a.close() > > Is that what you wanted ? > > -- > [ Wojtek gminick Walczak ][ http://gminick.linuxsecurity.pl/ ] > [ gminick (at) hacker.pl ][ gminick (at) underground.org.pl ] From thorsten at goertz.com Thu Nov 7 16:41:33 2002 From: thorsten at goertz.com (Thorsten Goertz) Date: Thu, 07 Nov 2002 22:41:33 +0100 Subject: Embedded Threading Question References: <32355ee1.0211071215.1c26afe7@posting.google.com> Message-ID: <3DCADE0D.2E06C5E3@goertz.com> Tim Dietz wrote: > When I test the module within the Python interpreter from > DOS, it's happy as a clam. But, the problem is that when I > include the exact same module within the application, the > app hangs forever and I have to kill the process. You should give us some more information about your code. How do you initialize the embedded Python interpreter? Is your C/C++ code that will be called from Python thread safe? Is it always from Python to C or sometimes the other way around? > How can I find out if the DLL that we're using supports > threads? If it does, is there anything special I need to > do to get them working fully in my app? Are you using the installer from python.org? With 2.2.x I make heavy use of the embedded interpreter in a multithreaded application and it works very well in both directions, from C++ to python and (call-) back. > I am using the thread module as the threading module won't > work at all under the application. Again, you should show us some code... From usenet at soegaard.net Mon Nov 11 10:27:01 2002 From: usenet at soegaard.net (Jens Axel Søgaard) Date: Mon, 11 Nov 2002 16:27:01 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h3k7jlwock.fsf@pc150.maths.bris.ac.uk> <76c4da8e.0211101357.6a804d20@posting.google.com> Message-ID: <3dd165fb$0$63910$edfadb0f@dread15.news.tele.dk> Vlad S. wrote: > anton at vredegoor.doge.nl (Anton Vredegoor) wrote in message >> Wouldn't it be possible to write a macro for Lisp so that it uses >> newlines and indentation instead of parens? > > Yes, it's been done before. > http://www-cgi.cs.cmu.edu/afs/cs/project/ai- > repository/ai/lang/lisp/code/syntax/0.html Nobody really cared about > the efforts though. Right now, PLT is trying to do something similar > by including tools to let you embed and design new grammars more > easily. The 200 versions come with their example Algol-60 > implementation. ;-) That is not the purpose at all. The purpose is to show how easy it is to use the PLT (DrScheme) to write parsers/interpreters/compilers. That and to show off the superb module system. I guess the choice fell on Algol 60 because it were a significant programming language that influenced a lot of languages. It's "the mother of all lexically scoped bloak languages". -- Jens Axel S?gaard From jepler at unpythonic.net Sat Nov 23 22:38:31 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Sat, 23 Nov 2002 21:38:31 -0600 Subject: Regular expression question In-Reply-To: <9a5f3d1c.0211231857.78125e43@posting.google.com> References: <9a5f3d1c.0211231857.78125e43@posting.google.com> Message-ID: <20021123213820.A13007@unpythonic.net> You're doing a number of "unpythonic" things in this code. It's best to learn to speak Python like a native, to get beyond building up a "phrasebook" to translate Perl statements into Python statements. The biggest "unpythonic" thing is referring to an arbitrary global variable by its name at runtime. This is very bad, since it lets a user refer to any function. Besides that, you'll probably encapsulate the Python version in a module (since it's longer than a line or two), but the Python "globals()" returns the globals of the current module, not the calling module. Anyway, here's an attempt at a Pythonic version of the perl code you posted. Yes, it's longer than the Perl version. To use it, you'd write def f(s): return s.upper() def g(s): return s.title() function_map = {'f': f, 'g': g} print substitute_template("The lessons are: '%%f%%' and '%%g%%'", function_map, "python is not perl") # Test out error handling print substitute_template("At the tone, time time is 10PM: %%z%%", function_map, "") (The third argument corresponds to $variable in your example) Here's the code to implement the 'substitute_template' function: import re # Since python wouldn't just refer to a global 'variable', a Subfunc # class records the desired argument and the function map for later use. # You can call a Subfunc instance just like it was a plain function class Subfunc: def __init__(self, function_map, arg): self.function_map = function_map self.arg = arg def __call__(self, s): fname = s.group(1).lower() # Error handling should probably be more sophisticated. # But hell, it's better than terminating the whole program... try: f = function_map[s] except KeyError: return "*** ERROR: bad substitution %r ***" % fname return f(self.arg) # Compile the regular expression, since we expect to be matching it frequently subre = re.compile("%%(.?)%%") # Here's the function you call. It creates a Subfunc instance and passes # it on to re.sub def substitute_template(template, function_map, arg): return subre.sub(Subfunc(function_map, arg), template) Enhancing the code to let $variable be an arbitrary parameter list is fairly easy. You'll need to learn about *args (and maybe **kw) parameters, and either the f(*args, *kw) calling convention or the apply function. Jeff From usenet at imperialviolet.org Thu Nov 28 10:46:17 2002 From: usenet at imperialviolet.org (Adam Langley) Date: Thu, 28 Nov 2002 15:46:17 +0000 Subject: python path References: <3de63380$0$86565$ba620e4c@news.skynet.be> Message-ID: On Thu, 28 Nov 2002 16:18:56 +0100, Jonas Geiregat wrote: > on linux > how can add new path's to my sys.path var not with append cause when the > programme closes or interpreter it changes again ? > so save it somewhere ? set $PYTHONPATH in your shell rc file (e.g. ~/.bashrc) From martti.halminen at kolumbus.fi Sat Nov 9 14:21:28 2002 From: martti.halminen at kolumbus.fi (Martti Halminen) Date: Sat, 09 Nov 2002 21:21:28 +0200 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h31y5uyj81.fsf@pc150.maths.bris.ac.uk> Message-ID: <3DCD6038.7E6EC76B@kolumbus.fi> Richard Dillingham wrote: > > The only thing that could make me at all comfortable with using Lisp > > would be if I had an editor that would color-highlight not keywords or > > strings, as color-highlighting usually goes, but levels of parenthesis > > indentation. So that this: > > > > (a (b (c (d e)))) > > I wonder why you aren't writing > (a > (b > (c > (d e) > ) > ) > ) A lisp programmer would write it like this: (a (b (c (d e)))) or the original: (a (b (c (d e)))) if using so short names and no control structures causing special indentation. > The issue with 'Python being easier to read than Lisp,' IMHO, is mainly that > Python FORCES you to use indentation, whereas Lisp does not. > > Since Lisp does not force you to write readable code, you have to force > yourself to use indentation. For a beginner it might be forcing, for the professionals it is a major tool. Not using the canonical indentation style is a sure sign of a newbie in comp.lang.lisp. > But I don't see a bunch of C programmers typing > if (a) { if (b) { if (c) { asdf; } else { zzzz; }} else { foo; }} else > {bar;} > like a Lisp coder might type > (if (a) (if (b) (if (c) (asdf) (zzzz)) (foo)) (bar)) > (if (a) > (if (b) > (if (c) > (asdf) > (zzzz) > ) > (foo) > ) > (bar) > ) > (if (a) (if (b) (if (c) (asdf) (zzzz)) (foo)) (bar)) Would be the normal way to write this. -- From max at alcyone.com Tue Nov 5 16:28:04 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 05 Nov 2002 13:28:04 -0800 Subject: More about simple question References: Message-ID: <3DC837E4.D8ED7A3D@alcyone.com> xinghua shi wrote: > I still have another question. If I have a file named: > foo.py. then how can I get an excetable, say foo? > In C, I could use > % gcc foo.c -o foo > > So how can I do similar in Python? > %python foo.py -o foo > doesn't work of course. Give it a bangpath that points to Python as the first line: #!/usr/bin/env python or maybe #!/usr/local/bin/python and make it executable. Then you can run it as ./foo.py. If you prefer to run it without the the .py extension, then just rename the file to foo. In UNIX and UNIX-like operating systems, executable scripts are discerned by their bangpath, not by their file extension. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ It is one thing to praise discipline, and another to submit to it. \__/ Cervantes Rules for Buh / http://www.alcyone.com/max/projects/cards/buh.html The official rules to the betting card game, Buh. From theller at python.net Thu Nov 21 05:24:11 2002 From: theller at python.net (Thomas Heller) Date: 21 Nov 2002 11:24:11 +0100 Subject: ctypes and delphi dll References: Message-ID: Bernd Zimmermann writes: > Meanwhile I got it .... providing the procedures > arguments in inverse sequence lets the bell ring! > > I am happy with ctypes ! > > Bernd Searching for Delphi calling conventions, I found this page: http://info.borland.com/techpubs/delphi/delphi5/oplg/procfunc.html#8406 It seems your dll uses the pascal calling convention, while ctypes only supports cdecl and stdcall. Below is a sketch (untested) of subclasses which should do the trick: class PascalFunction(_DynFunction): def __call__(self, *args): pascal_args = list(args) pascal_args.reverse() return _DynFunction.__call__(self, *pascal_args) class PascalDLL(CDLL): def __getattr__(self, name): func = PascalFunction(name, self) setattr(self, name, func) return func pascaldll = _DLLS(PascalDLL) Should ctypes support the pascal calling convention 'natively'? Maybe later... Thomas From mwh at python.net Tue Nov 19 06:56:47 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 19 Nov 2002 11:56:47 GMT Subject: changing the Python grammar ? References: <2259b0e2.0211181221.2eab9db7@posting.google.com> Message-ID: <7h3zns5vkrf.fsf@pc150.maths.bris.ac.uk> mis6 at pitt.edu (Michele Simionato) writes: > Browsing on the on-line refencence manual you can find the formal > definition of the Python grammar: http://python.org/doc/current/ref/grammar.txt Bear in mind that that is a descriptive grammar. The real one is Grammar/Grammar in the source distribution. > But now a question arise to me: can I modify the grammar ?? If yo're prepared to build from source, yes. > Suppose for instance I want to make able Python to recognize identifiers > starting with some funny symbol, say "@". All I must do is to modify > the first line of the grammar as Ah, that's the lexer. > identifier ::= > ["@"] (letter|"_") (letter | digit | "_")* > > In the best of the worlds, I would look for some file in the Python > source distribution containing the grammar, I would change that line, > and recompiling I would have a new Python able to understand identifiers > starting with "@". Is this possible in practice ? You're asking two questions here (though you might not realize it): Hacking the Grammar is certainly possible. You then usually need to hack Python/compile.c too. This can be hard. Python/compile.c is not the friendliest code in the world. However, to what you want to do, you need to hack Parser/tokenizer.c (I think). This also isn't the friendliest code in the world, but it's not too bad. I've done similar things without too much wailing and gnashing of teeth. > Notice that I do NOT want to introduce ugly perlish-like identifiers in > Python, I simply want to know how much it is possible to customize the > Python grammar: is this a simple hack or a nightmare ? Somewhere between those. As your customizations get more ambitious, you'll probably find yourself rapidly heading for the "nightmare" end of that scale. Cheers, M. -- Two decades later, well-known hacker Henry Spencer described the Perl scripting language as a "Swiss-Army chainsaw", intending to convey his evaluation of the language as exceedingly powerful but ugly and noisy and prone to belch noxious fumes. -- the jargon file From srumbalski at prodigy.net Wed Nov 27 01:24:08 2002 From: srumbalski at prodigy.net (Steven Rumbalski) Date: Wed, 27 Nov 2002 06:24:08 GMT Subject: Why not a, b += i, j? (augmented assignment via tuple unpacking) References: <3de3e129$0$4437$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: > In article , Steven > Rumbalski wrote: > >> In python I can write: >> >> a, b = i, j >> >> but the following is not legal: >> >> a, b += i, j >> >> Is there a reason that allowing this would be bad? > > If it were allowed, what do you propose it would do? > >> Why does Python forbid this? > > First tell us what you think it would do were it legal. :) > I was imagining it working like >>> a += i >>> b += j I suppose it could appear that I meant >>> a, b = (a, b) + (i, J) The first is intuitive to me because of how the following behaves >>> a, b = i, j but I guess it's not intuitive to others. By the way, I did not ask the above question because I thought that Python was wrong, but because I want to understand the language better. Steven Rumbalski From mgarcia at cole-switches.com Thu Nov 14 17:01:41 2002 From: mgarcia at cole-switches.com (Manuel M. Garcia) Date: Thu, 14 Nov 2002 22:01:41 GMT Subject: Open and reading a file... References: Message-ID: On Thu, 14 Nov 2002 22:43:36 GMT, Robin Munn wrote: (edit) >Let us know if you have any more questions that this answer didn't cover. Now I feel ashamed for being a smartass. But it was so difficult to resist. From bokr at oz.net Sun Nov 10 17:47:31 2002 From: bokr at oz.net (Bengt Richter) Date: 10 Nov 2002 22:47:31 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h3k7jlwock.fsf@pc150.maths.bris.ac.uk> <3dce96ad$0$12451$edfadb0f@dread11.news.tele.dk> Message-ID: On Sun, 10 Nov 2002 20:00:51 +0100, "Anders J. Munch" wrote: >"Jens Axel S?gaard" wrote: >> > >> > I'm curious: what exactly did McCarthy's new syntax look like? Have >> > you got any pointers to specs, examples or such on the web? >> >> I can't remember a link - but if you want to Google for them, >> they were calles M-expressions. > >Tried that, but every professor teaching Lisp/Scheme seems to mention >M-expressions in passing before proceeding to S-exprs, drowning any >useful information. > >I wonder if M-expressions changed the concrete syntax but preserved >the abstract syntax? I mean did it preserve the basic >everything-is-a-cons-or-atom model just adding some infix syntactic >sugar on top, or was it fundamentally different? > Quoting from James Allen's "Anatomy of Lisp" (C) 1978 McGraw Hill: (where *italic* and **bold**) "In essence, then, there are *two* LISP's: there is the algorithmic language and there is the programming language. The programming language is a data structure representation of the algorithmic language. The algorithmic language is called the **meta-language** or **M-expr LISP**, and for historical purposes, the programming language is called **S-expr LISP**." I have encountered no other book that so clearly focuses attention on the distinction between abstractions and representations. I suspect a major part of the attraction of Python is that it lets us program with a goodly set of clean powerful abstractions, and that that is probably the basis for feelings of a kind of kinship with lisp, whatever the differences in representation syntax. Regards, Bengt Richter From skodela at btopenworld.com Sat Nov 9 04:49:41 2002 From: skodela at btopenworld.com (Sreekant Kodela) Date: Sat, 9 Nov 2002 09:49:41 +0000 (UTC) Subject: Any modules to write a wav file References: Message-ID: Many thanks I will try that. regards sreekant Bengt Richter wrote: > > I've used the read capability, but I haven't tried writing using the wave > module. But it looks straight forward. Check out (I am on windows 2.2.2 > here): > > http://www.python.org/doc/current/lib/module-wave.html > From jdhunter at ace.bsd.uchicago.edu Tue Nov 19 19:29:44 2002 From: jdhunter at ace.bsd.uchicago.edu (jdhunter at ace.bsd.uchicago.edu) Date: Tue, 19 Nov 2002 18:29:44 -0600 Subject: A really bad idea. In-Reply-To: <15834.52340.168573.470992@montanaro.dyndns.org> (Skip Montanaro's message of "Tue, 19 Nov 2002 17:42:44 -0600") References: <3DDABEF2.BE342B47@alcyone.com> <15834.52340.168573.470992@montanaro.dyndns.org> Message-ID: >>>>> "Skip" == Skip Montanaro writes: Skip> I passed the earlier solution along to Barry Warsaw, Elisper Skip> Extraordinaire. He apparently hadn't seen it before. Look Skip> for it in a future python-mode.el, coming to a disk near Skip> you... Great! Will you give us a head up when it makes it into CVS? Thanks, John Hunter From bokr at oz.net Tue Nov 12 06:52:12 2002 From: bokr at oz.net (Bengt Richter) Date: 12 Nov 2002 11:52:12 GMT Subject: Can python find fibonacci series in a single line of code? References: Message-ID: On Tue, 12 Nov 2002 09:32:35 +0000 (UTC), Duncan Booth wrote: >a_human_work at hotmail.com (Pittaya) wrote in >news:fa61a3d8.0211110720.16a645f8 at posting.google.com: > >> My Perl-addicted friend shows me that he can find fibanicci series in >> a single line of code. >> >> perl -le '$b=1; print $a+=$b while print $b+=$a' >> >> can python do something like this? >> >Ca you explain please (because I don't really know Perl) what a program >that prints 1.#INF over and over again has to do with Fibonacci (at least >thats who who I think you meant)? > >Jeff's nice clear Python program prints out a Fibonacci series, but the >Perl one just seem to print a bit of a Fibonacci series which doesn't >strike me as terribly useful. Even the numbers it does print are mostly >approximations. > Here's another variant that will keep printing non-approximations (assuming a doesn't pre-exist): while 1: print vars().setdefault('a',[1,1]) and a.append(a.pop(0)+a[0]) or a[0] Regards, Bengt Richter From leazen at uol.com.ar Tue Nov 5 10:11:16 2002 From: leazen at uol.com.ar (Leazen) Date: Tue, 05 Nov 2002 12:11:16 -0300 Subject: How does Python handle probing to see if a file already exists? References: <3DC7DDC2.6070306@uol.com.ar> Message-ID: <3DC7DF94.1030008@uol.com.ar> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Oh, access is in the os module. Leazen Leazen wrote: > The other answers are probably better but if you like the C way you can use: > > access(path, mode) > Check read/write/execute permissions for this process or existence of > file path. mode should be F_OK to test the existence of path, or it can > be the inclusive OR of one or more of R_OK, W_OK, and X_OK to test > permissions. Return 1 if access is allowed, 0 if not. See the Unix man > page access(2) for more information. Availability: Unix, Windows. > > F_OK > Value to pass as the mode parameter of access() to test the existence of > path. > > Just like you could in C. > > Leazen > > > > Christopher R. Culver wrote: > >>Hello all, >> >>I've just begun learning Python after already getting pretty proficient in >>C. However, I'm having a problem with a simple copying program. Ideally, >>the program would check to see if the destination already exists and >>prompt the user. In this this would be as easy as saying: >> >>probe_destination = fopen(/usr/bin/foo, 'r') >>if (probe_destination) >>{ >>some code here; >>} >> >>However, translating that directly into Python doesn't work because if >>Python can't find a file to open, it doesn't just return 0, it gives an >>error and exits. How can I write this functionality in Python so that it >>returns 0 and continues, or does Python have a totally different way of >>handling this problem than C? >> >>Christopher Culver >> >> > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.0 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQE9x9+ShcKLjUu3XMkRAmjCAKDUk2Gi0Zn2qdjCWUYDP2+Vrd1jugCfXgS5 m4VwkLbJp5+HVOodH80KkL4= =e+VR -----END PGP SIGNATURE----- From see_reply_address at something.invalid Wed Nov 27 22:41:43 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 28 Nov 2002 16:41:43 +1300 Subject: Issue with new-style classes and operators References: <3DE215D1.D9A3FEF9@jandecaluwe.com> <5ApE9.52343$744.1917235@news1.tin.it> <3DE2893A.CCB631D6@jandecaluwe.com> <3DE449BD.1040503@something.invalid> <3DE48ECC.8FC9AE53@jandecaluwe.com> Message-ID: <3DE59077.9070405@something.invalid> Jan Decaluwe wrote: > Ok, let me explain better. Suppose - for the sake of the > argument - that I have a legitimate need for mutable numbers. > > The point is then that I want to "inherit" the operators > from the (mutable) value. If I understand you correctly, then no, you can't turn an *existing* piece of immutable state into mutable state -- the best you can do is add a new piece of mutable state. But then you won't be able to re-use the existing operators simply by inheriting them, because they'll be looking for the state in the old place. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jrandom at mddd.com Mon Nov 18 10:14:45 2002 From: jrandom at mddd.com (J. Random Hacker) Date: Mon, 18 Nov 2002 10:14:45 -0500 Subject: wxPython question References: Message-ID: On Sun, 17 Nov 2002 21:26:44 +0200, Chris Liechti wrote: > "joshua solomon" wrote in > news:lNRB9.2743$fY3.294687 at newsread2.prod.itd.earthlink.net: > >> Basically I have a loop within the OnPaint handler which I am using for >> bouncing a ball around on a screen. > > don't do the loop for the animation in the event handler. do it in a > separate thread nad call Refresh() or us a wxClientDC to draw in that loop > directly. > > GUI rule 1: event handlers have to be short (in time) > > so no animations and workers. use Threading instead. > But don't always use threads, especially if you don't need to. I mention it here, because things like your bouncing ball routine don't really need threads. Threads come in handy when you want to schedule some long running process that would be difficult or impossible to run in the main thread. This solution works well, because having a few threads for throwing some long running task to is cheap. But in your case, there is no long running task that you have to break out. All you are doing is changing some variables (the ball) at regular intervals (thats all animation is). Changing variables doesn't take much time at all, so its OK to do this in a event handler. This is a prime job for a timer handler (a wxTimer). Basically, write your bouncing ball actor in such a way that you can update it on a frame by frame basis. It just needs some attributes like vx, and vy (velocity). Then use a wxTimer at an apporpriate rate (say 40ms), to call a handler. The handler simply: updates the ball vars (calculate new x and y values), and then draws. class Canvas(wxPanel): def __init__(self, parent, id): ... tid = wxNewId() self.timer = wxTimer(self, tid) self.timer.Start(40) ... EVT_TIMER(self, tid, self.OnNextFrame) def OnNextFrame(self, event): ... update ball variables self.Refresh() From aleax at aleax.it Fri Nov 15 09:19:11 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 15 Nov 2002 14:19:11 GMT Subject: property problems References: <46a101c28bb2$6f2d1420$7635bcc3@blueyonder.net> <1wOA9.85898$MGm1.48783@news02.bloor.is.net.cable.rogers.com> Message-ID: Antonio Cuni wrote: > Alex Martelli wrote: > >> What really determines if x is a new-style class is x's metaclass, >> and rather than inheriting it from x's base (which is the normal >> way to do it) you may alternatively choose to assert it explicitly >> by a __metaclass__ attribute in class scope (or a global variable >> __metaclass__ in module scope if x has no bases). x is new-style >> iff x's metaclass is the built-in type object named 'type'. > > uhm... type inherit from object, but object's metaclass is type: isn't > there a recursion problem? > > ciao Anto > PS & OT: what's the english for "circolo vizioso"? "Vicious circle" is fine. There isn't one in the case you mention, though. Suppose you had a bunch of thingies with two attributes each: athingy.mybase the thingy that's athingy's base, or None athingy.mytype the thingy that's athingy's type, or None and in particular that object and type were names of two thingies, now: object.mytype = type type.mybase = object where is the "recursion problem"? Thingies ARE allowed to point to each other -- what problem do you see with this? If you write CODE that tries to navigate this graph, you do of course have to be aware that it's not necessarily an acyclic graph (depending on what set of links you consider). So...? Your code may indeed have "recursion problems" if it unwarrantedly assumes it's navigating an acyclic graph where the assumption doesn't hold, of course. But that would hardly be surprising -- whenever you write code that assumes more conditions than can be guaranteed, problems of one kind or another are likely to arise. Alex From aleax at aleax.it Thu Nov 21 13:03:53 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 21 Nov 2002 18:03:53 GMT Subject: Problem with list assignment References: Message-ID: Jesse Lawrence wrote: ... > # here's the problem area: > header = [] > i = 0; > for r in row: > header[i] = r[0] > i = i + 1 > return header change this snippet to, for example: header = [] for r in row: header.append(r[0]) return header or more concisely to the single line: return [r[0] for r in row] You can't assign to items of a list that do not yet exist: you can append to the list, or build the list in one gulp with the list-comprehension construct I've used in the "single line" version. Alex From aleax at aleax.it Fri Nov 22 04:51:49 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 22 Nov 2002 09:51:49 GMT Subject: matching multiple regexs to a single line... References: <9k3D9.35511$744.1314342@news1.tin.it> Message-ID: John Hunter wrote: ... > That said, I too am unsatisfied with the M*N performance of the (rgx, > func) pattern: > > for line in lines[:M]: > for rgx in regexs[:N]: > mo = rgx.match(line) > if mo: do_something(mo) If you need to process the match objects for ALL the RE's that match, I don't think you can do _substantially_ better in general. > You've mentioned named rgx's in your previous posts. In the case of > differential processing of match objects based on the regex match, is > there a more efficient way to process the mo's than this M*N approach? If in a given application the case of 'no matches' is very frequent, then a first-pass check on the line to see whether it does match at least one of the RE's may give practical advantages, but I don't think it can possibly change the O() behavior, just potentially give better multipliers. And if you need to process mo's for all matches with the various RE's, rather than just the first match with one of the RE's taken in some order of priority, then I think that's about it in terms of the speedups that you can get (without getting into detailed processing of the patterns involed, and even then, whether you can get any benefit _at all_ depends on WHAT set of paterns you have). Alex From nicholas.y at NOSPAM.immersivetechnologies.com Tue Nov 26 19:52:44 2002 From: nicholas.y at NOSPAM.immersivetechnologies.com (Nicholas Yue) Date: Wed, 27 Nov 2002 08:52:44 +0800 Subject: CVS References: Message-ID: <3de41768$0$18756@echo-01.iinet.net.au> "Ali K" wrote in message news:X4UE9.128865$WL3.60156 at rwcrnsc54... > What is CVS? http://www.cvshome.org/ http://sourceforge.net/projects/cvsgui Cheers -- Nicholas Yue From mwh at python.net Thu Nov 14 09:49:18 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 14 Nov 2002 14:49:18 GMT Subject: lists changed to tuples unexpectedly! References: Message-ID: <7h3vg30xl9l.fsf@pc150.maths.bris.ac.uk> spam at fisher.forestry.uga.edu (Chris Fonnesbeck) writes: > A very strange thing is occurring to me in Python 2.2.2; I have a module > that builds a tuple of nested lists like the following: > > # All possible action combinations > actions = [(((i,0),),((j,j),)) for i in (0,1,2,3,4) for j in > (0.0,0.1,0.2)] > > I then pass this list as an argument to a class within the module, and it > magically becomes a tuple of tuples: This seems unlikely, in the face of it. > class QOptimizer(ReinforcementLearning.GradientDescentWatkinsQ): > 'Optimization using Q(Lambda) RL algorithm' > > def __init__(self, > actions, > states, > init_state, > state_dynamics_function, > objective_function, > rounding = 0, > roundto = 50000, > Alpha = 0.1, > Epsilon = 0.2): > > print actions > > ... etc. > > This gives: > > [[[ [ 0. 0. ]] > [ [ 0. 0. ]]] > [[ [ 0. 0. ]] > [ [ 0.1 0.1]]] > [[ [ 0. 0. ]] > [ [ 0.2 0.2]]] > [[ [ 1. 0. ]] > [ [ 0. 0. ]]] > [[ [ 1. 0. ]] > [ [ 0.1 0.1]]] > [[ [ 1. 0. ]] > [ [ 0.2 0.2]]] > [[ [ 2. 0. ]] > [ [ 0. 0. ]]] > [[ [ 2. 0. ]] > [ [ 0.1 0.1]]] > [[ [ 2. 0. ]] > [ [ 0.2 0.2]]] > [[ [ 3. 0. ]] > [ [ 0. 0. ]]] > [[ [ 3. 0. ]] > [ [ 0.1 0.1]]] > [[ [ 3. 0. ]] > [ [ 0.2 0.2]]] > [[ [ 4. 0. ]] > [ [ 0. 0. ]]] > [[ [ 4. 0. ]] > [ [ 0.1 0.1]]] > [[ [ 4. 0. ]] > [ [ 0.2 0.2]]]] That's not the output you get when you print any of the native types of Python. It looks a bit like a Numeric.array, though. > Why did I make lists, and get tuples? Can you post a complete piece of code showing the problem? Cheers, M. -- The only problem with Microsoft is they just have no taste. -- Steve Jobs, (From _Triumph of the Nerds_ PBS special) and quoted by Aahz Maruch on comp.lang.python From rmunn at pobox.com Fri Nov 29 13:44:24 2002 From: rmunn at pobox.com (Robin Munn) Date: Fri, 29 Nov 2002 18:44:24 GMT Subject: importing question ? References: <3de62963$0$214$ba620e4c@news.skynet.be> Message-ID: Martyn Quick wrote: > On Thu, 28 Nov 2002, Jonas Geiregat wrote: > >> >>> import classes >> >>> a = veryBigSnake() >> Traceback (most recent call last): >> File "", line 1, in ? >> NameError: name 'veryBigSnake' is not defined >> >>> from classes import * >> >>> a = veryBigSnake() >> >> why doesn't the first import work ? >> and the second does >> >> and what is the difference between those two ? > > With the first you are importing the command in the form > classes.veryBigSnake, so the following would work: > > import classes > a = classes.veryBigSnake() > > and would give the same as > > from classes import * > a = veryBigSnake() > > The difference is that the second hides where veryBigSnake comes from and > can cause confusion if you were to change the meaning of the function in > the middle of your code. With the first you're less likely to do this. > > Experts can explain this in the proper technical language better than I > can. ;-) The "proper technical language" for this sort of thing is "namespaces". Python names (function names, variable names, class names, whatever) live in namespaces. Namespaces themselves also have names -- or, rather, they're attached to named objects. Let me explain. Say you create a class "myClass", like so: class myClass: foo = 1 bar = "Testing' The name "myClass" refers to a class object. That class object has a namespace attached, and that namespace contains two names, foo and bar. You can access these names as "myClass.foo" and "myClass.bar". Modules also have namespaces. If the above class definiton was in a module called "mymodule.py", this would be the correct way to access "foo" and "bar" from the myClass definition: import mymodule print mymodule.myClass.foo print mymodule.myClass.bar Note that myClass is inside the mymodule namespace, so it is accessed via the dot operator (which looks up names in namespaces). If you wanted myClass to get imported into the global namespace, the way to do it is: from mymodule import myClass print myClass.foo print myClass.bar "from import " finds the name in the namespace of that module, and imports that name into the namespace that you are currently running in (usually this will be the global namespace). It is *always* a bad idea to do "from import *"! A few modules are designed to be used this way, but they specifically say so in their documentation and usually have naming conventions designed to prevent namespace collision. One last concept: the global namespace. The global namespace is the highest-level namespace. When you run a Python program, it first starts executing in the global namespace, and all assignment statements, import statements, etc. place names into the global namespace. Other namespaces can be accessed through names, like "myClass.foo" which accesses the myClass namespace via the name myClass -- a name that resides in the global namespace. But the global namespace does not have a name attached to it (which namespace would that name reside in, anyway?). Sometimes you might need to get access to the global namespace, and that is what the globals() function is for -- it returns the global namespace (as a Python dictionary, IIRC). You can then use that object for whatever purposes you needed (like executing a particular bit of code in the global namespace instead of a local namespace, for example). I hope this helps someone understand namespaces better. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From shalehperry at attbi.com Wed Nov 20 23:01:26 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 20 Nov 2002 20:01:26 -0800 Subject: A simple question: How to exit from a python script? Just like the exit() in C++ In-Reply-To: <006801c29111$bf776660$d001a8c0@dctc.cs> References: <006801c29111$bf776660$d001a8c0@dctc.cs> Message-ID: <200211202001.26633.shalehperry@attbi.com> On Wednesday 20 November 2002 19:54, Wang Hanbo wrote: > Hi, > > I have a simple question as is written in the header, how can I > exit from a python program using a call such as "exit()" in C++? > > I am a novice on this list, and also a rookie on python > language, all of you answers will be my best impetus! > Thanks > > > Hanbo > 2002-11-21 a) import sys sys.exit() # takes the same parameter C++'s exit() takes b) raise SystemExit # for when you do not want to import sys From tjreedy at udel.edu Sat Nov 23 08:25:34 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 23 Nov 2002 08:25:34 -0500 Subject: Confusing list& Test References: Message-ID: Yes, you have made it to the real python news/mail group. comp.lang.python is a newsgroup python-list at python.org is a mailing list python.org has a gateway that connects the two together: messages sent to one are automatically sent to the other. (Except, perhaps, for obvious spam and other junk.) This lets people with access to both choose the interface they prefer and those with access to just one get that one. > After a little web search I found yet anotherr python-list at python.org, which > seems to be the same list, and another hit (from 99) said that the cwi.nl list > had been moved to python.org. Yes, cwi.nl was a previous host, years ago > Isn't it about time to get the Reply-To field changed to the correct address? > What exactly is that yahoogroups list doing in all this? I believe anything connected with yahoogroups is unofficial with respect to python.org and the python developers. Anyone can set up a yahoo group on any topic and become the owner. If a change is needed, please contact the group owner. You should be able to do this thru the yahoo web interface. Terry J. Reedy From dsavitsk at e-coli.net Wed Nov 20 02:29:12 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Wed, 20 Nov 2002 07:29:12 GMT Subject: Telnetlib help. I need a case function. References: <1d4aad28.0211191310.6300984a@posting.google.com> Message-ID: "higgeldy Piggeldy" wrote in message news:1d4aad28.0211191310.6300984a at posting.google.com... > Hi, > I wrote this script a while ago to renew my library books for me. wow. what an age we live in. From a.schmolck at gmx.net Sun Nov 24 19:50:19 2002 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 25 Nov 2002 00:50:19 +0000 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <3DDBD838.10406@nyc.rr.com> <3DDC5851.5060001@nyc.rr.com> <3DE040DF.EACC7D3A@kolumbus.fi> <87bs4fef72.fsf@key.localdomain> Message-ID: Patrick W writes: > Martti Halminen writes: > > > Alexander Schmolck wrote: > > > > > for item in container: ; no convienient idiom (?) > > > print item > > [...] > And for acting upon each item within a container, the usual idiom is > (mapcar #'function list) or (map 'output-type #'function sequence). > The various mapping functions in Lisp remove a lot of the need for > explicit loops (similar to the way in which list comprehensions > replace many loops in modern Python). While functional programming constructs like map replace the need for loops in many cases, they don't replace the need for a generalized iteration protocol (in python you can ``map`` or ``filter`` over any container). alex From bkc at Murkworks.com Wed Nov 13 17:30:38 2002 From: bkc at Murkworks.com (Brad Clements) Date: Wed, 13 Nov 2002 17:30:38 -0500 Subject: Graham's spam filter References: <20021113220949.2daa7540.christophe.delord@free.fr> Message-ID: <3dd2cfa7$1_5@goliath.newsgroups.com> You may wish to check out http://spambayes.sf.net -- Novell DeveloperNet Sysop #5 _ "Christophe Delord" wrote in message news:20021113220949.2daa7540.christophe.delord at free.fr... > Hello, > > There was discussion on this group about spam filtering using Graham's > filter. I'm surely not the first to do it but I found the exercise > interesting and I wrote my own filter. My filter is still very young (and > maybe not very stable) but it is efficient (on my little spam corpus I > only miss 5 per 100 spams. I know I'm far from Graham's results). So those > who are interested (and adventurous) can find it here: > http://christophe.delord.free.fr/en/popf > > This filter is yet another POP3 proxy, uses an automatic white list (ie > the list of people the user has sent emails before) and is fast enough to > be used on a personal computer (it doesn't accept multiple connections at > the same time but you can have multiple POP3 accounts). The filter decodes > base64 attachments too. When a spam is detected, the subject is tagged and > the mail client has to be configured to move those tagged spams in the > spam corpus. > > Of course it is written in Python ;-) I'm using it on Linux, don't know if > it work with windows. > > Best regards, > Christophe. > > > > > > > -- > > (o_ Christophe Delord _o) > //\ http://christophe.delord.free.fr/ /\\ > V_/_ mailto:christophe.delord at free.fr _\_V -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From max at alcyone.com Sun Nov 10 14:36:13 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 10 Nov 2002 11:36:13 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h3k7jlwock.fsf@pc150.maths.bris.ac.uk> <3dce96ad$0$12451$edfadb0f@dread11.news.tele.dk> Message-ID: <3DCEB52D.98B12B05@alcyone.com> Roy Smith wrote: > Jens Axel Sogaard wrote: > > > I can't remember a link - but if you want to Google for them, > > they were calles M-expressions. > > Not (plus s 1) expressions? :-) You mean (1+ s)? :-) -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ With such a weapon I could boil the Earth to vapor. \__/ Chmeee CSBuddy / http://www.alcyone.com/pyos/csbuddy/ A Counter-Strike server log file monitor in Python. From claird at lairds.com Mon Nov 11 16:41:09 2002 From: claird at lairds.com (Cameron Laird) Date: Mon, 11 Nov 2002 21:41:09 -0000 Subject: Is python a good choice for this task? References: Message-ID: In article , Fernando P?rez wrote: >Ron Lau wrote: > >> My question is, What language is best suited for this? Perl, Python, or >> shell scripts? > >Well, from each of the groups you posted to you'll get a different answer. But >of course, two of them will be wrong. You should use python :) > >Kidding aside, such a simple task can be done in any of those without any >effort. I'd still suggest python because it's a better language than the >others for a number of things (yes, I've used all three extensively). >Especially if you have a scientific computing background: if you poke around >the web a bit, you'll find that python is becoming very popular in scientific >computing circles, and for good reason. See http://scipy.org/ or . . . Yes. I have a soft spot for Tcl in this role. I think Tcl's sub- process spawning is perceptibly easier than the {popen,popen2, popen3} we most often recommend to newcomers. Moreover, Tcl has the slickest Tk integration, so that it's falling-off-a- log-like for even a beginner to wrap such legacy applications with a simple GUI . The December issue of the *C/C++ Users Journal* elaborates this. However, I entirely agree with the main conclusions: * Mr. Lau will be happy wrapping up his old program, and, for as thin a layer as he currently wants, any of the common languages will do fine. * Python has the most headroom. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From maxm at mxm.dk Sat Nov 30 06:19:41 2002 From: maxm at mxm.dk (Max M) Date: Sat, 30 Nov 2002 12:19:41 +0100 Subject: Newbie Question: Giving names to Elements of List/Tuple/Dict In-Reply-To: References: <1038571003.6023.20.camel@localhost.localdomain> Message-ID: <3DE89ECD.2040203@mxm.dk> Duncan Booth wrote: > Oren Tirosh wrote in news:mailman.1038579643.30978.python-list at python.org: > Or a nearly empty class if you want to be lazier when creating > the objects: > > >>>>class Struct: > > def __init__(self, **args): > vars(self).update(args) There is a special notes in the docs warning against changing the values that are returned from vars() This is the more "correct" way to do it. class Struct: def __init__(self, **kw): self.__dict__.update(kw) regards Max M From capsthorne at yahoo.co.uk Tue Nov 5 05:48:14 2002 From: capsthorne at yahoo.co.uk (Geoff) Date: Tue, 05 Nov 2002 10:48:14 +0000 Subject: Book recommendation please References: <1036349092.40578.0@iapetus.uk.clara.net> <1036355743.4079.0@doris.uk.clara.net> Message-ID: <1036493255.33402.0@doris.uk.clara.net> On Mon, 04 Nov 2002 15:55:19 +0000, Cameron Laird wrote: > To congratulate you on your insight that worthwhile languages need not > be compiled (in the usual sense), let me reinforce it: Python (and > other high-level languages) have a record of achievement that compares > favorably to those of C++, Java, ... in every way, apart from marketing. > ... Thanks, it is remarkable how quickly one's views can change. To take another example, I began by thinking that the interpreter could onlly be a toy and that any useful "five finger exercises" I might write would inevitably need to be in a script. Wrong again ... Regards, Geoff From ark at research.att.com Wed Nov 27 13:29:35 2002 From: ark at research.att.com (Andrew Koenig) Date: Wed, 27 Nov 2002 18:29:35 GMT Subject: More pythonic way to change an element of a tuple? References: Message-ID: Richard> I frequently have to change a single element of a tuple, Why are you using tuples if you want to change the elements? -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From jepler at unpythonic.net Fri Nov 29 16:16:50 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 29 Nov 2002 15:16:50 -0600 Subject: Embedding Python and built-in types In-Reply-To: <000b01c297ea$de27d8d0$9600000a@ashe> References: <000b01c297ea$de27d8d0$9600000a@ashe> Message-ID: <20021129151649.B6957@unpythonic.net> On Fri, Nov 29, 2002 at 10:04:11PM +0100, Mickael Putters wrote: > Well, I was talking about the assignment operator, maybe it's not =. > Yeah well guess I'll have to modify the source, I thought maybe there would > be a way to do that already present in Python/C. > Anyway, thanks. There is no "assignment operator for integers". The code to execute x = v is the same no matter the type of v (or the type x may have had before the assignment, as long as you ignore the possible destructor call on decref). (In C, for a function local variable x, it's basically a decrement of the reference count of the old local, an increment of the reference count of 'v', and a store of the 'v' in the locals array) "Everything is a reference" If you want to override assignments like o.x = v then you can override __setattr__ for the object o. Similarly, there are __setitem__ and __setslice__. In 2.2 and newer, when you subclass object you can use property() to do the same thing as __setattr__ in a nicer way. Jeff From costanza at web.de Sun Nov 10 08:45:30 2002 From: costanza at web.de (Pascal Costanza) Date: Sun, 10 Nov 2002 14:45:30 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7b8f89d6.0211081548.f91b468@posting.google.com> <3DCE003C.9080505@mindspring.com> Message-ID: Andrew Dalke wrote: > Pascal Costanza: > >> I have recently switched over to Common Lisp as my language of choice >> and have written an article about it, to be found at >> http://www.pascalcostanza.de/lisp/guide.html - you might find it >> worthwhile. > > It's a discussion of Lisp, with only a few points specifically of > why you switched from Java to Lisp and one mention of Python. (There > were two references to Monty Python, from which Python the language got > its name.) I was hoping for a more philosophical rumination of why > you chose Java over Python. :( This was merely an accident. Back in 95 I based my diploma thesis on Java, and this decision was influenced by many factors. It wasn't until recently that I learned about Python. > Some points that are weaker in a Python/Lisp comparison are > > - Python doesn't have as many "funny names" as Lisp I guess you are referring to "car", "cdr" and the like. They're actually not funny but very useful. ("car" returns the first element of a list, "cdr" the list of all elements but the first. You can also use "first" and "rest" instead, and also "second", "third", and so on, and also "nth".) > - Python also does run-time typing rather than static typing Yes, I like that. :) > - You say > > Please remember that due to their syntax, C-like languages and Pascal > > might also run into trouble when curly braces or begin/end keywords > > are used incorrectly in conjunction with control statements (like if, > > while, switch/case, and so on) > > But Python doesn't have that problem, given neither braces nor begin/end > keywords. Indeed, you seem to suggest that all Algol-derived languages > are like C/C++/Pascal/Java in having explicit delimiters, a separate > compilation step, static typing, You're right, I should be more careful with my wording in this regard. I will check that. > - You say: > > A nice thing about Lisp is that it doesn't noticeably distinguish > > between built-in functions and user-defined functions. > > The same is true for Python. :) > You talk about Lisp's macro feature. That's come up several times > on c.l.py. I understand at least theoretically the usefulness of > macros. However, I am quite worried about the supportability of > defining your own language on the fly. For the comparison I would > have like to have seen, I was hoping for comments on the > maintainability of macros, especially given that some people like > you have found "them to be conceptually quite simple and easy to > write" while others find them "seemingly hard to understand." I > believe the answer is you want a language which emphasises your > personal expressive power and not which which emphasises the > team's/project's/group's power. I don't think that Lisp favors personal expressive power over group's power. Maybe the group that uses Lisp has to agree on more conventions than in other languages (but I am not sure about that). Macros are conceptually very simple: they just process lists of code before it is actually executed. This gives you lots of power, but of course you need to be a good programmer to be able to wisely use this power. Lisp is a programming language for experts. > I read your mention that Lisp allows recoverability at the place > where the exception took place. I recall reading in my progamming > languages book back in college that that ends up not being all that > useful, but I can't provide a reference for that now. In my > own current thinking, I agree with the book. It can be useful in some situations. For example, imagine you have a big and expensive calculation running, and after, say, three days there is a little bug in some code section that handles a very special case. In Common Lisp there's a chance that this bug throws a correctable error (exception) - this is reported at the Lisp prompt. Then you can correct the buggy code section and try to restart the calculation at the spot where the error occurred, without any loss of intermediate results. Similar situations are conceivable for example in the case of web applications that you usually don't want to shut down, etc. I think that correctable errors are less useful in languages that don't offer some form of interactivity. > So I would also have prefered more examples of why a feature was > not only available in Lisp but why that feature is useful for > most programming tasks. (And you are a fan of "practical things > that you need in every-day programming" so should stress usefulness > over ability.) Thanks a lot for your very useful feedback - I will try to incorporate it into future versions of my article. All the best, Pascal -- Given any rule, however ?fundamental? or ?necessary? for science, there are always circumstances when it is advisable not only to ignore the rule, but to adopt its opposite. - Paul Feyerabend From Patrick.Carabin at MyRealBox.COM Wed Nov 13 03:32:46 2002 From: Patrick.Carabin at MyRealBox.COM (Patrick.Carabin at MyRealBox.COM) Date: 13 Nov 2002 00:32:46 -0800 Subject: How do I reply to an item in the list ? - testing without preview References: <44ee1dc2.0211120441.465eeb62@posting.google.com> Message-ID: <44ee1dc2.0211130032.6a0d4d56@posting.google.com> this time i remove everything , and ask Google ? Post message - NO preview ? From pan-newsreader at thomas-guettler.de Mon Nov 11 13:55:25 2002 From: pan-newsreader at thomas-guettler.de (Thomas Guettler) Date: Mon, 11 Nov 2002 19:55:25 +0100 Subject: Search Engine Message-ID: Hi! I need a search engine which can handle this kind of data: {"1": #Object one {"foo_attribute1": "my data", "foo_attribute2": "foo bar, bla blu", ...}, "2": #Object two {"foo_attribute1": "bau", "foo_attribute2": "next one", ... } ... } The attributes can contain several MByte of text. The text should be searchable. There will be several thousand objects I need the following API: search_engine.addObject(myObj) search_engine.search( { "foo_attribute1": "word1", "foo_attribute2": "word2" }) search_engine.deleteObject(id="1") Up to now I have two possible solutions: 1. Hack htdig to do the things I want to, and add a python interface 2. Use ZCatalog What do you think? Has some experience with python-based searchengines? thomas -- Thomas Guettler http://www.thomas-guettler.de From wlfraed at ix.netcom.com Mon Nov 4 00:22:04 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sun, 03 Nov 2002 21:22:04 -0800 Subject: can't assign value to array element References: Message-ID: Joe Heafner fed this fish to the penguins on Sunday 03 November 2002 06:23 pm: > m=10 > > y = zeros(m, Float) > > for j in range(0,m,1): > y[j+1] = y+(k1+2.*k2+2.k3+k4)/6. > t[j+1] = a+h*(j+1) > > When run, this code give the error "TypeError: object does not support > item assignment" for hte next to last line. I presume the last line > would give the same error. I'm very new to Python and haven't been > able to find documentation about htis specific problem, and I've been > working (literally) all day on this. What am I doint wrong? I'd > appreciate any help. > Uhmmm... Assuming zeros(m, Float) produces an array indexed from 0..(m-1), then won't the last iteration of the for loop generate y[10] =... IE, out of range... -- -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From claird at lairds.com Fri Nov 1 21:08:58 2002 From: claird at lairds.com (Cameron Laird) Date: Sat, 02 Nov 2002 02:08:58 -0000 Subject: Textbooks on Perl/Python References: <87b0ada6.0211011453.1df4d216@posting.google.com> <3DC32F83.8990DEC9@alcyone.com> Message-ID: In article <3DC32F83.8990DEC9 at alcyone.com>, Erik Max Francis wrote: >Jalab wrote: > >> Any help in finding a university level textbook on the subject of >> "Scripting languages" I am mainly looking for a book that covers Perl >> and Python only as the 2 main scripting languages and that is written >> for students, i.e. chapter summary, exercises, etc. I hate to force my >> student to buy and study from two separate books. > >I doubt you'll find one that will really cover both subjects adequately, >since they're totally different languages. The only thing I can think >of that comes close is the "little language" books, that give a brief >summary of a wide variety of "little," high-level languages. The one >I'm familiar with (though I don't own it) is _HPL: Little Languages and >Tools_ by Salus (editor). . . . I'm plenty opinionated on this subject. There isn't such a book as Jalab wants. It'd be great fun to write one, but there isn't a market ... well, I'll just say such a book doesn't exist now. What's your goal for the students? To be ready to go out in industry and solve problems? To understand the theory and practice of industrial-strength "scripting languages"? To pad their r?sum?s? To safety-proof them so they don't hurt themselves the first time they're asked to write a dynamic Web page? To supplement an academic course on DSLs? I know what *I*'d do in each case--and they're not all the same answer. I'm all for people buying *Little Languages and Tools*, incidentally. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From Marten.Bauer at gmx.net Sat Nov 16 05:31:45 2002 From: Marten.Bauer at gmx.net (Marten Bauer) Date: Sat, 16 Nov 2002 11:31:45 +0100 Subject: Python als PHP ersatz? Message-ID: Hallo, ich habe ein Datenbank und die entsprechenden Software dazu in Python geschrieben. Nun m?chte ich f?r den User eine Weboberfl?che programmieren. Ich habe schon ein Version in HTML+PHP vorliegen. Ist dasselbe auch mit HTML+Python m?glich? Womit kann ich das machen? - ModPython f?r Apache - Twisted Web (Netzwerk Library) ? Kann mir da jemand weiterhelfen? MfG Marten From bokr at oz.net Sat Nov 23 10:42:01 2002 From: bokr at oz.net (Bengt Richter) Date: 23 Nov 2002 15:42:01 GMT Subject: Proposal: min(None, x) and max(None, x) return x References: Message-ID: On Fri, 22 Nov 2002 14:53:42 GMT, Andrew Koenig wrote: >Eric> So I told myself: wouldn't it be great if max(None, x) or >Eric> min(None, x) always simply returned x? > >My first thought was that this was an excellent idea. > >Then I thought again. > >Here's the problem: The notion that max(None, x) and min(None, x) >should both return x is one of three desirable properties that cannot >all be true at once. Here are the other two: > > 1) Whenever x < y, min(x, y) is x and max(x, y) is y. > > 2) < is an order relation over all types. > >The desirability of (1) should be obvious. (2) is more subtle, but >it is necessary for it to be possible to sort a vector of heterogenously >typed objects. > >Now, if max(None, x) and min(None, x) both yield x, and (1) is true, >then x > None and x < None must both be true. But then (2) cannot >be true. > >So the cost of your proposal would be either to break the consistency >between max/min and >/<, or to render unsortable vectors of values >that include None. > >I don't think it's worth it. > How about adding optional keyword args to min and max, so the semantics would be something like (not very tested ;-): >>> class private_sentinel: pass ... >>> def mymax(*seq, **kw): ... exclude = kw.get('exclude', private_sentinel) ... empty = kw.get('empty', private_sentinel) ... try: ... return max(filter(lambda x: not isinstance(x, exclude), seq)) ... except ValueError: ... if empty == private_sentinel: raise ... return empty ... >>> mymax(None, 2, 3) 3 >>> mymax(None, 2, 3, exclude=(int,type(None)),empty='nothing left') 'nothing left' >>> mymax(None, 2, 3,'a string', exclude=(int,type(None)),empty='nothing left') 'a string' (oops, that 'if empty == ...' would have been better as 'if empty is ...') Regards, Bengt Richter From bokr at oz.net Tue Nov 5 20:23:06 2002 From: bokr at oz.net (Bengt Richter) Date: 6 Nov 2002 01:23:06 GMT Subject: More about simple question References: <3DC7BF20.95768C4@felis.uni-freiburg.de> Message-ID: On Tue, 05 Nov 2002 13:52:48 +0100, Joerg Woelke wrote: >Bengt Richter wrote: >> >> On Mon, 4 Nov 2002 21:11:52 -0800 (PST), xinghua shi wrote: >> >> >--0-1493159574-1036473112=:21756 >> >Content-Type: text/plain; charset=us-ascii >> > >> > >> >> >> >> import sys,os,string >> >> >> >> pid = os.getpid() >> >> >> >> filename = ".ld.mon." + str(pid) > >Maybe you are interested in os.tempnam, os.tmpfile or >os.tmpnam? > I think you may be confusing me with someone else, who might be interested ;-) >[ snip ] > >> Regards, >> Bengt Richter > >HTH, J"o! > >-- >sigfault Regards, Bengt Richter From bokr at oz.net Thu Nov 7 12:56:44 2002 From: bokr at oz.net (Bengt Richter) Date: 7 Nov 2002 17:56:44 GMT Subject: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up References: Message-ID: On Thu, 07 Nov 2002 17:16:53 -0000, Jon Ribbens wrote: >In article , Tim Peters wrote: >> You didn't answer the question about what you *intended* 0x80000000 to mean. > >I intend it to mean a set bit followed by 31 cleared bits. > >> The answer to your question follows from that. If you intended a 1 bit >> followed by 31 zero bits, then, no, -0x7fffffff-1 doesn't mean that on some >> platforms even today (or even in 1993, for that matter ). > >What platforms doesn't it mean that on? What does it mean on those >platforms? Are you talking about platforms with 16-bit integers? >If so, I don't care. How about BIT31 = 1<<31 and then use BIT31 wherever? Regards, Bengt Richter From jdhunter at ace.bsd.uchicago.edu Fri Nov 15 10:31:11 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 15 Nov 2002 09:31:11 -0600 Subject: keyword arguments and ** In-Reply-To: <3dd51831$0$13642$e4fe514c@dreader6.news.xs4all.nl> (Boudewijn Rempt's message of "Fri, 15 Nov 2002 15:51:32 +0100") References: <3dd51831$0$13642$e4fe514c@dreader6.news.xs4all.nl> Message-ID: >>>>> "Boudewijn" == Boudewijn Rempt writes: Boudewijn> I feel right silly, but for the life of I don't Boudewijn> understand why the variables I pass to f as named Boudewijn> arguments stay remembered: >>>> def f(fields={}, **args): The problem is with fields={}. This is a famous problem that catches everybody at least once that is caused by using use a mutable type as the default value for a keyword argument. A mutable type is one that can be changed (list, dict) and an immutable one is one that cannot (int, string, tuple, ...). To avoid the problem you are seeing, you need to initialize fields within the function itself. The standard idiom is: def f(fields=None, **args): if fields is None: fields = {} print fields fields.update(args) print "XXX", fields f(a=1) f(b=1) For a little more information, take a look at this thread on google groups http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&threadm=mailman.1037195388.11008.python-list%40python.org&rnum=2&prev=/groups%3Fas_q%3Dpitfall%26safe%3Doff%26ie%3DUTF-8%26oe%3DUTF-8%26as_ugroup%3D*python*%26lr%3D%26num%3D30%26as_scoring%3Dd%26hl%3Den John Hunter From bokr at oz.net Fri Nov 8 09:37:34 2002 From: bokr at oz.net (Bengt Richter) Date: 8 Nov 2002 14:37:34 GMT Subject: Virtual Filesystem (was: Adding ftputil to the Python distribution?) References: Message-ID: On 8 Nov 2002 01:20:16 -0800, stephan.diehl at gmx.net (Stephan Diehl) wrote: >Jacob Smullyan wrote in message news:... >> In article , Stephan Diehl wrote: >> > Talking about a future VFS: is there already somethings planned? It >> > would be very nice to access a local filesystem, remote filesystem >> > (over ssh/scp), ftp server, webdav server,... with the same set of >> > commands. >> >> SkunkWeb has a vfs package (which can be used independently) that you >> might be interested in: >> >> http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/skunkweb/skunkweb/pylibs/vfs/ >> >> Features: >> >> 1. implementations for local fs, ftp, zip/tar/tgz archives, and a >> "multifs" in which it is possible to mount other fses with >> considerable flexibility (for instance, it is possible for a mount to >> change its mount point dynamically, which is useful in the context of >> web server document roots, where you may want a document root to shift >> for a particular request while other mounts remain in the same place >> relative to that shift). >> >> 2. Writing a new fs is fairly trivial. The interface is adequate for >> many needs, and supports read-only as well as read-write fses. >> >> 3. an import hook (using Gordon MacMillan's superb iu.py) which >> enables you to import python modules from any fs implementation. This >> is actually a big gain, from my point of view, as struggling with >> import hooks is something I'd rather do once and then forget about. >> Apparently Python Labs feels the same way, which is why we're still >> stuck with having to write them! >> >> There is some code, namely, PathPropertyStore and its illegitimate >> offspring, that you might as well ignore. I was fiddling at one time >> with the notion of providing a general way of storing properties >> associated with vfs files, but came to the conclusion that this level >> of abstraction is not such a hot place, data-integrity-wise, to >> implement that. >> >> Cheers, >> >> Jacob Smullyan > >Thanks, that's excactly what I was thinking of/looking for. And it >shows to me that there is nearly nothing that has not been written in >one form or another. I'd really like to see a vfs in the standard >python distribution. I too. But I believe any given implementation will implicitly reflect conventions with respect to operations in abstract name space, and I think that ought to be laid out in a PEP before adopting any particular implementation. Otherwise there is likely to be special limitations, e.g., not being able to delegate parsing of path tails to other vfs's mounted within the first, etc. Also a virtual name space brings with it opportunity for orderly conventions of use as opposed to ad hoc quilts of usage. A PEP can at least draw attention to LSB/FHS type issues. > >Maybe, one day, we'll have a central register for python libraries. It >seems to me that to many people (including me) are reinventing the >wheel all the time because they just can't find the right library for >the task at hand and just don't know project xyz that already solved >the problem (and doesn't show up when googling) > As a habitual wheel re-inventor, I'll second the thought ;-) OTOH, I think re-inventing has positive aspects sometimes. A certain amount of reinventing is necessary for natural selection to have something to select from in the evolutionary improvement of things. OTOH2, for well-explored problems, it's an indulgence to reinvent something if you can find and use something already implemented. (Of course, it _is_ satifying to find that you have re-invented, even approximately, an algorithm that some real guru has previously invented, and feel that you walked in the same ancient hallowed land, even as you realize that you could have spent your time better for practical purposes). The vfs above is very close to what I was talking about recently. But not exactly, and not quite from the same POV. And any discussion of general or genericized (v)file access will garner reminders that lisp has a lot of prior art ;-) My main thought before was that a virtual name space can be platform independent (or at least contain such a subspace), and that could serve the purpose of platform independence for Python. Regards, Bengt Richter From cnetzer at mail.arc.nasa.gov Mon Nov 18 20:02:16 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Mon, 18 Nov 2002 17:02:16 -0800 Subject: multi-quoted strings for HERE documents In-Reply-To: References: Message-ID: <200211190102.RAA05229@mail.arc.nasa.gov> On Monday 18 November 2002 16:40, Michael P. Soulier wrote: > Now, I can get close in Python with multi-line strings, like so... > > print """ >
> > > >
cell contents
""" [snipped] (regarding unwanted initial newline) > Does anyone have a better way of doing this? print """\
cell contents
""" -- Bay Area Python Interest Group - http://www.baypiggies.net/ Chad Netzer cnetzer at mail.arc.nasa.gov From wolfoxbr at hotmail.com Thu Nov 21 08:27:55 2002 From: wolfoxbr at hotmail.com (Roberto Amorim) Date: 21 Nov 2002 05:27:55 -0800 Subject: Read-only attributes using properties? Message-ID: <82c04a2.0211210527.4d1a4393@posting.google.com> I was thinking about trying to use the new properties on Python 2.2 to implement read-only attributes. So I tried the following: class MyException(Exception): pass class TProp(object): def __init__(self): self.a = 0 def get_a(self): return self.a def set_a(self, v): raise MyException a = property(get_a, set_a, None, "Test a") t = TProp() print t.a t.a = 5 I was expecting that the script would fail with an exception on the "t.a = 5" command. However, I was surprised to see the code fail on the attribution inside __init__ - that is, there is no "inner class scope", or direct access within the class itself, and no clear way to initialize the property. If the property is an alias to the real internal variable (call it size, for instance), it works, but then if I try to add a __slots__ list excluding the internal var and only adding the external reference (__slots__=("a")) it stops working again. Is there any other way to do that? Thanks in advance, Roberto From johnroth at ameritech.net Tue Nov 26 15:56:12 2002 From: johnroth at ameritech.net (John Roth) Date: Tue, 26 Nov 2002 15:56:12 -0500 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <3DDBD838.10406@nyc.rr.com> <3DDC5851.5060001@nyc.rr.com> <3DE040DF.EACC7D3A@kolumbus.fi> <3DE2AEFE.BF188406@kolumbus.fi> <3DE2B626.6000009@nyc.rr.com> Message-ID: "Kenny Tilton" wrote in message news:3DE2B626.6000009 at nyc.rr.com... > > > Martti Halminen wrote: > > Alexander Schmolck wrote: > > >>Well, if you prefer then elt is inconsistent :) > > > > Sure it is. We are talking about a language that had as one of its > > primary design criteria at least some compatibility with existing code > > bases in its predecessors, so many design warts had to be retained. > > Obviously not a problem for people getting to define their language on a > > clean slate. > > And this will set an upper bound on how far Python can go, with an > obligation not to break all the stuff piling up in the Vaults. (Not that > I am aware of any actual desire to take the language in new directions; > I get the feeling "less is more" was the Prime Directive.) I believe he was talking about Lisp in that paragraph, not Python. However, your comment re. Python is IMO correct; there's a desire to avoid gratuitously breaking older code in newer releases. However, that hasn't stopped things like the integer division change, or the new yield keyword for generators. Both of those *will* break code. John Roth > > -- > > kenny tilton > clinisys, inc > --------------------------------------------------------------- > ""Well, I've wrestled with reality for thirty-five years, Doctor, > and I'm happy to state I finally won out over it."" > Elwood P. Dowd > From SBrunning at trisystems.co.uk Mon Nov 4 04:50:50 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Mon, 4 Nov 2002 09:50:50 -0000 Subject: Foot in mouth disease Message-ID: <31575A892FF6D1118F5800600846864DCBDA86@intrepid> > From: aahz at pythoncraft.com [SMTP:aahz at pythoncraft.com] > >3) Ask her for a date > > She lives in Toronto (I'm in California) and I'm not her type. Yeah, but asking her out would put her on the back foot, and you can win the Java vs. Python argument for once and for all. Cheers, Simon Brunning ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From costanza at web.de Mon Nov 11 05:41:12 2002 From: costanza at web.de (Pascal Costanza) Date: Mon, 11 Nov 2002 11:41:12 +0100 Subject: Reading code and writing code References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCD8571.6CACEA04@alcyone.com> Message-ID: <3DCF8948.8040100@web.de> Lulu of the Lotus-Eaters wrote: > Erik Max Francis wrote previously: > |The same goes for Lisp (and all its variants, like Scheme). You might > |have to count parentheses if you had to physically write it down with > |pencil and paper, but in the real world you'll be using an editor, and > |the editor will help you match parentheses and do the gruntwork for you. > > This is not the same real world I live in! > > In my real world, I probably spend at least 10x as much time READING > code as I do WRITING it. I certainly read more of my own code than of > anyone elses, but I still have to *read* it when I come back to it after > more than a few minutes... especially when it is a few months or years. It's actually quite simple to read Lisp source code _once you have gotten used to it_. Lispers aren't a bunch of masochists who like to torture themselves. If Lisp code were so hard to read it wouldn't have survived over 40 years. You wouldn't reject learning, say, Japanese or Chinese _just_ because of their seemingly funny alphabet, would you? ;) It's essentially the same with Lisp: It looks funny and takes one week more to get used to, but then you've basically mastered it. Pascal -- Pascal Costanza University of Bonn mailto:costanza at web.de Institute of Computer Science III http://www.pascalcostanza.de R?merstr. 164, D-53117 Bonn (Germany) From mwh at python.net Tue Nov 5 12:45:36 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 5 Nov 2002 17:45:36 GMT Subject: List slice assignment and custom sequences References: Message-ID: Alex Martelli writes: > Michael Hudson wrote: > > > Ronald Oussoren writes: > > > >> No, I want to replace part of a sequence by another sequence. I don't > >> understand _why_ the RHS must be a list if the LHS is one. > > > > Because Objects/listobject.c:list_ass_slice pokes directly into the > > object passed on the RHS. > > > > A patch to change this would have some chance of getting accepted; > > wouldn't like to guess what, but I'd hazard non-zero. > > Done -- just submitted as patch 633870 on Sourceforge, pls review. Not only reviewed, but BDFL approved and checked in! that-one-went-quickly-ly y'rs M. -- ZAPHOD: Listen three eyes, don't try to outwierd me, I get stranger things than you free with my breakfast cereal. -- The Hitch-Hikers Guide to the Galaxy, Episode 7 From tjreedy at udel.edu Sat Nov 23 20:35:50 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 23 Nov 2002 20:35:50 -0500 Subject: Guido's regrets: filter and map References: Message-ID: "Simon Burton" wrote in message news:pan.2002.11.24.01.35.22.907943 at webone.com.au... > Hello, > > I just read Guido's "python regret's" slide's from OSCON, > http://www.google.com/search?hl=en&ie=ISO-8859-1&q=OSCON+%22python+reg rets%22 > and one thing i can't work out is, > he is saying we can do map() and filter() with > list comprehensions (it's faster too) > eg. > > amapedlist = [ somefunc(x) for x in alist ] > > But how would we do a filter with list comprehensions? filteredlist = [item for item in alist if condition] TJR From nospam at bigfoot.com Tue Nov 5 10:39:47 2002 From: nospam at bigfoot.com (Gillou) Date: Tue, 5 Nov 2002 16:39:47 +0100 Subject: MySQLdb and threads References: Message-ID: Great, Many thanks Piet... Looking for "pool python" or "pool mysql" didn't help. --Gilles "Piet van Oostrum" a ?crit dans le message de news: wziszcvz6s.fsf at localhost.cs.uu.nl... > >>>>> "Gillou" (G) writes: > > >> >>>>> "Gillou" (G) writes: > >> > G> Hi, > G> I plan to make SQL queries in different threads of an application using > G> MySQLdb. > G> Can I use the same Connection object in all threads (each thread having > G> its > G> own cursor) for the queries ? Or should I use a different Connection > G> object > G> for each thread ? > >> > >> The doc says: > >> > > G> [SNIP] > > >> For threaded applications, try using a connection pool. This can be done > >> using the Pool module. > > G> Many thanks Piet for this enlightenment, > > G> Where did you find the Pool module you're writing of ? > > I just copied the doc. > > G> I didn't find it in the standard Python distro (2.1.3) nor with google. > > Google gives me: > http://dustman.net/andy/python/Pool > -- > Piet van Oostrum > URL: http://www.cs.uu.nl/~piet [PGP] > Private email: P.van.Oostrum at hccnet.nl From Paul_Rudin at scientia.com Mon Nov 11 09:11:56 2002 From: Paul_Rudin at scientia.com (Paul Rudin) Date: 11 Nov 2002 14:11:56 +0000 Subject: something like "if" that returns a value? References: Message-ID: >>>>> "hk" == holger krekel writes: hk> Paul Rudin wrote: >> I'm having a little play with python, just to try it out; and one >> thing that I find I miss from other languages is something like >> lisp's if: >> >> (if x y z) >> >> which returns y if x is true and z otherwise. >> >> I realise that I can define a function that does this for me; but >> is there a succinct way of expressing this in the base language? hk> for me hk> x and y or z hk> basically does what you want. But you *need* to be sure that 'y' hk> is true. some people don't like this 'abuse' but many use it on hk> a regular basis (without big problems i'd say). Thanks for the reply. Yes, there are circumstances where this looks ok; but I'm a bit uneasy with this idiom. The main problems being: - (as you say) you need to depend on the value of y; - potentially both y and z are evaluated; and - there's a degree of obfuscation here, the code is less comprehensible than something like: if x then y else z. -- I am a jelly donut. I am a jelly donut. From max at alcyone.com Tue Nov 26 19:22:05 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 26 Nov 2002 16:22:05 -0800 Subject: if : References: Message-ID: <3DE4102D.7D4291F4@alcyone.com> Dave Brueck wrote: > Ugh! Shame on any aspect of a language that burdens the developer this > way. The fact that such strategies as the above have cropped up is, > IMO, > proof that the language is broken in that area. We don't say, "Is > Tuesday > today?" or "Is 5 your age?", either. :) Yes, that convention to avoid mistaking = and == in an if (or other) statement is extremely ugly and seems overkill. I think the =/== confusion in C and its descendent languages is being highly overemphasized in this thread. I came to Python from a C++, C and some Java background, and I certainly don't miss assignment being a full-fledged expression, and agree with avoiding the pitfalls. The =/== mixup is indeed a very common beginner's error, particularly when they come from a BASIC derivative language (where = means both assignment and equality, depending on context). In my experience, however, among experienced programmers, repetition of this mistake is extremely rare. I literally cannot recall the last time that I made this error, and have worked on sizeable teams and cannot recall finding any colleagues' bugs stemming from the same mistake -- and this is not from people who use the awful if (rvalue == lvalue) trick to prevent them from getting it wrong in the first place. I think the severity of the =/== confusion problem in C has been severely overrepresented in this thread. In my opinon, in the real world, among competent software eengineers, it is a tiny issue. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Everyone wants to look good at his own funeral. \__/ Louis Wu PyUID / http://www.alcyone.com/pyos/uid/ A module for generating "unique" IDs in Python. From fperez528 at yahoo.com Thu Nov 7 14:28:25 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 07 Nov 2002 12:28:25 -0700 Subject: power TypeErrors References: <7h3ptthzlf0.fsf@pc150.maths.bris.ac.uk> <7h31y5xyzgx.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson wrote: > What specific problems involve complex input or > output? Well, lattice gauge theory, for one (my field). Not exactly mainstream, mind you :) But _everything_ in there is complex. FFTs are a far more common problem where complex numbers are normal. But as I said, even finding the roots of a simple polynomial or the eigenvalues of a non-symmetric (real) matrix can give you complex output in a heartbeat. And you can't really write many numerical algorithms correctly if they can't wander into the complex plane internally. The real line is awful thin, and it's really easy to fall off of it :) Cheers, f. From aleax at aleax.it Sat Nov 9 09:44:53 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 09 Nov 2002 14:44:53 GMT Subject: How to spawn a program and assign its stdout to a string variable? References: Message-ID: Christopher R. Culver wrote: > I'm working on a pdf2ps frontend script that will use the *nix utility > "file" to determine a file's type without blindly trying to work on it. I > assume the best way to do this is to spawn "file", capture its stdout to a > string variable, and then use regular expressions to search within the > captured stdout for the file type desired (in this case PDF). However, Doubtful assumption, but, OK, it may be one way. > I've tried these: > > capturedstdout = os.system(["file"]+foo) > > capturedstdout = swapvp('P_NOWAIT', 'file', ['file']+foo) > > but these don't work because the return value of file is assigned to the > variable "capturedstdout", not the stdout. How do I spawn a program and > have its stdout assigned to a string variable? >>> foo = 'ch01.xml.pdf' >>> import os >>> capturedstdout = os.popen('file ' + foo).read() >>> print capturedstdout ch01.xml.pdf: PDF document, version 1.3 >>> Alex From andymac at bullseye.apana.org.au Thu Nov 21 05:43:17 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 21 Nov 2002 20:43:17 +1000 (est) Subject: urllib slow on FreeBSD 4.7? In-Reply-To: Message-ID: On Wed, 20 Nov 2002, dsavitsk wrote: > as I say, the site i am testing is on a computer not 8 inches from the > FreeBSD one (attached to the same kvm no less). The files must traverse > nearly 6 feet of cable, 3 other computers were able to download much more > quickly, and the freebsd one has failed all day (even switching network > cable and spots in the switch). > > further, for a 2 meg file on > > Python 2.2.1 (#1, Oct 5 2002, 11:19:44) > [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 > Type "help", "copyright", "credits" or "license" for more information. > >>> import os > >>> os.system('/usr/local/bin/wget > "http://192.168.0.4/index.asp?file=name" -O file.ext') > > takes less than 2 seconds > > while > >>> f = open('file2.ext', 'w') > >>> u = urllib.urlopen("http://192.168.0.4/index.asp?file=name") > >>> f.write(u.read()) > >>> f.close() > > takes about 2 minutes > > so, it seems that using wget is the proper way to preceed, but i would > rather a python solution. I can't test this at the moment, but you should be aware that your python approach is doing something quite different from wget in processing this download - it is reading _the_whole_file_ into memory, and then writing it out in one fell swoop, rather than reading & writing a block at a time (which is how wget & fetch would be doing this). The writing part will be fast, but the building of the in-memory image of the file _may_ be happening in such a way that the memory image is constantly being increased in size to cope with incoming data. Various platform realloc() library routines have radically different performance behaviours in the face of such memory allocation strategies, usually unfavourable. While the FreeBSD memory allocation routines are decent, Python has exposed unfavourable performance behavour on FreeBSD in other situations. FreeBSD is not alone in this - Python has managed to provoke memory allocation issues on most platforms, which have progressively been worked around as they've been identified. Some memory allocation changes were made for 2.2.2 which did improve performance on FreeBSD in certain scenarios, but I doubt your usage would be affected. Still, I would like to know if 2.2.2 helps if you are able to test it (and I would recommend the upgrade from 2.2.1 in any case). -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From wks000 at t-online.de Sun Nov 10 07:50:19 2002 From: wks000 at t-online.de (Wolfgang Strobl) Date: Sun, 10 Nov 2002 13:50:19 +0100 Subject: NEWBIE: Extending Python with C References: <3dcc7e2c.3568851@news.earthlink.net> Message-ID: <72lssu89n13e0smobngvb95f8ggtlv65n9@4ax.com> Alex Martelli : >This is more or less the end of the line in terms of what >os.popen can offer -- due to buffering and suchlike there's >no practical way for python to drive BOTH standard input >and standard-output of another external program. Well, the following snippet, driving nslookup.exe on W2K works for me: import sys,os print sys.version popen2=os.popen2 i,o=popen2("nslookup","t") def prnt(f): print "(---" c=None while c!=">": c=f.read(1) sys.stdout.write(c) print "---)" prnt(o) while(1): cmd=raw_input() if cmd=="stop": i.write("exit\n") break print "cmd:",cmd i.write(cmd+"\n") prnt(o) print "feddich" C:\e\littlepython>cmddriver.py 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] (--- Standardserver: www-proxy.BN1.srv.t-online.de Address: 212.185.249.50 >---) www.python.org cmd: www.python.org (--- Server: www-proxy.BN1.srv.t-online.de Address: 212.185.249.50 Name: fang.python.org Address: 194.109.137.226 Aliases: www.python.org >---) stop feddich -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From david at no.westcontrol.spam.com Wed Nov 6 03:22:19 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Wed, 6 Nov 2002 09:22:19 +0100 Subject: using the PSF license for one's code References: <918bc22f.0211051301.2010d077@posting.google.com> <3dc867de$0$24754$7b0f0fd3@reader.news.newnet.co.uk> Message-ID: "phil (at) linux2000.com" <"phil (at) linux2000.com"> wrote in message news:3dc867de$0$24754$7b0f0fd3 at reader.news.newnet.co.uk... > Martin v. Loewis wrote: > > > > The open source community seems to be shooting itself in the foot on > this particular issue, as far as I can see. > Just for comparison, can you think of any two close-source packages that have the same licence? Most suppliers seem to change their EULAs, Terms and Conditions, etc., faster than they change their software. There are basically two categories of open source licences, as far as I can see - gpl-type licences (you can use our source, but you have to apply the same licence to the modified code) and bsd-type licences (you can use our source for anything you want, but you have to acknowledge the copyright). I am a great believer in the spirit of a licence rather than the letter of the licence, and as far as I can see, the Python licence is in the same spirit as the BSD licence. I don't know how that would stand up in court, however, but hopefully it will never have to. From goldbb2 at earthlink.net Tue Nov 5 19:28:43 2002 From: goldbb2 at earthlink.net (Benjamin Goldberg) Date: Tue, 05 Nov 2002 19:28:43 -0500 Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> Message-ID: <3DC8623B.88753C16@earthlink.net> Frodo Morris wrote: > > Daniel Pfeiffer wrote: > > Hi, > > Apache would essentially have a mod_parrot. Maybe, if this can be > > tested very hard, we'd even have a Parrot kernel module for all > > Unices supporting that. Then exec() could perform compiled scripts > > right away, like machine code :-) > > I would have thought that a more platform-independent version of > this would be, say, a parrotd, which sits on top of the kernel, > intercepts calls to exec() bytecode and spawns the relevant processes. What advantage would this have over putting a #! line in the bytecode? Most existing *nix kernels (except some very old ones) will look at the #!, parse out the path to an executable program, and the run it. > I may be wrong. This parrotd system would also help in projects like > Beowulfs (although why you'd be using byte-compiled languages in > parallel computing is beyond me), because you could use inetd or > similar to spawn a parrot when data was received on a certain port. I don't really see the point of having a parrotd, except if you want to create something vaguely like PersistantPerl. -- my $n = 2; print +(split //, 'e,4c3H r ktulrnsJ2tPaeh' ."\n1oa! er")[map $n = ($n * 24 + 30) % 31, (42) x 26] From gerson.kurz at t-online.de Mon Nov 11 14:33:42 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Mon, 11 Nov 2002 19:33:42 GMT Subject: Understanding some python internals Message-ID: <3dd00611.20878343@news.t-online.de> I'm trying to understand how the python debugger package works. To that effect, I've written a kind of "strace for python", that should tell me each instruction as it happens, in a tracefile. The code basically does this: - use sys.settrace() to attach a tracefunc to every statement executed - try to analyze the arguments passed to the tracefunc So far, so good. Preliminary results can be seen here: http://p-nand-q.com/python/strace.zip The test code I want to analyze is this: ------------------------ test = 60 def test(x): return x*2 i = 0 while i < 5: print test(i) i += 1 exec("test(42)") ------------------------ Nothing too deviant, right? Try to run strace.py over this, and look into the result (STRACE.LOG). Ok, my questions: (1) I want to disassemble the current step that the tracefunc is called for - nothing else. dis.disassemble takes a code object, but will disassemble the *whole* code object, not just some part. (Same, if I pass it frame rather than code). How can I do that? I would guess that it has something to do with the members frame.f_code.co_code and co_lnotab - the "documentation" says the latter is "encoded mapping of line numbers to bytecode indices", can somebody enlighten me on that? (2) I want to print the source for the current step that the tracefunc is called for - nothing else. My first attempt (which is in the current source) is to read the file from frame.f_code.co_filename and read the line that is given in frame.f_lineno). This has two problems: a) if the source spans more than one line, only the first line will be shown b) if the source is in an exec() statement, co_filename is "". (See also question (3)) Is there are a "canonic" way of getting the code about to be executed inside a tracefunc? I tried inspect.getsource(frame) - but that prints the source for the whole code object, not the current frame. Bug or intended behaviour? (3) If the code object is in an exec statement, co_filename is "" and as far as I can see the code executed cannot be read from inside the tracefunc. Or can it? From xx758 at cam.ac.uk Thu Nov 7 04:57:04 2002 From: xx758 at cam.ac.uk (Xiao-Qin Xia) Date: Thu, 07 Nov 2002 09:57:04 +0000 Subject: Placing Tkinter objects in a dictionary References: <3dc9fa87$1_4@nopics.sjc> Message-ID: Adonis wrote: > I have a loop creating Tkinter objects (an Entry text box) all with the > same name and placing its instance in a dictionary: i.e: > > for x in range(10): > myEntry = Entry(frame) > myEntry.grid(row=x, column=0) > > someDict['%s'%x] = myEntry > > now I have another function which will modify myEntry: > > def someFunc(x, data): > someDict[str(x)].config(text=data) # here is my error; the config does > not work; > # no error is raised. > > any help is greatly appreciated. > > Adonis The problem is Entry does use a text config, you need a method to insert the data: def someFunc(x, data): e = someDict[str(x)] e.delete(0, END) e.insert(0, data) Now it will work. Cheers, Xiao-Qin Xia From kowk at earthlink.net Mon Nov 18 20:50:43 2002 From: kowk at earthlink.net (Kow K) Date: Mon, 18 Nov 2002 17:50:43 -0800 Subject: classifier systems re-coded in Python? Message-ID: <50933B53-FB61-11D6-AC9D-00050287C0A6@earthlink.net> Hi Pythoneers, I'm just wondering if anybody has re-coded David Goldberg's Pascal implementation of John Holland's (learning) classifier system in Python. Any pointer will be appreciated. Cheers, Kow From max at alcyone.com Thu Nov 14 19:35:30 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 14 Nov 2002 16:35:30 -0800 Subject: A really bad idea. References: <4STA9.9987$744.345722@news1.tin.it> Message-ID: <3DD44152.69795B9F@alcyone.com> "James J. Besemer" wrote: > I collect pocket reference guides, and FWIW, Python's is the largest! > > Perl 5 (including libraries) is only 48 pages. > > I have C/C++ pocket refs that work out to 8 pages for the language and > 8 > pages for the libraries. I think what's making the difference here is the quality/depth of the reference guides, not the actual languages. A "C/C++" reference that is a total of 16 pages simply not comparable to a Python reference that is 124 pages. C and C++ (two different languages, by the way) are not about 8 times simpler than Python. Far from it, in fact. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Punctuality is the virtue of the bored. \__/ Evelyn Waugh WebVal / http://www.alcyone.com/pyos/webval/ URL scanner, maintainer, and validator in Python. From skip at pobox.com Fri Nov 8 06:00:23 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 8 Nov 2002 05:00:23 -0600 Subject: stripping HTML comments in the face of programmer errors Message-ID: <15819.39239.272250.828957@montanaro.dyndns.org> HTML comments aren't supposed to be nested, nor are they supposed to enclose unescaped HTML tags, but people routinely commit both sins anyway. People also forget to close HTML comments, but for the most part, browsers still seem to display such pages more-or-less correctly. I have an HTML comment stripping function which handles the nesting part okay: def zapcomment(data): data = re.split("()", data) nest = 0 newdata = [] for i in range(len(data)): if data[i] == "": nest = max(0, nest-1) elif nest == 0: newdata.append(data[i]) return "".join(newdata) but I'm sort of at a loss how to handle the case of runaway comments, e.g.: Anybody out there got a bit of code which implements a useful heuristic for that case? Ideally, stripping comments from the above would yield Thanks, -- Skip Montanaro - skip at pobox.com http://www.mojam.com/ http://www.musi-cal.com/ From karthik_qmax at yahoo.co.in Fri Nov 15 23:53:57 2002 From: karthik_qmax at yahoo.co.in (=?iso-8859-1?q?kathik=20thyagarajan?=) Date: Sat, 16 Nov 2002 04:53:57 +0000 (GMT) Subject: My Python Editor "ActiveState Python 2.2 - Python Win IDE" does not refesh Message-ID: <20021116045357.80686.qmail@web8203.mail.in.yahoo.com> Hi Guys, I am having the trouble of having to exit the editor every time I make some changes to my code in order to execute the code using the "ActiveState Python 2.2 - Python Win IDE" editor. DOS work fine but the problem with DOS is that and other editors like gvim is that I am unable to debug my code with them. Is there any problem with theinstallation or is there any other patch to be added? Does any one know. Other wise I have to clos a bunch of files, open them, set break points, make changes, close them again and keep iterating the whole thing. Eagerly awaiting replies. Karthik Catch all the cricket action. Download Yahoo! Score tracker -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Thu Nov 28 19:56:23 2002 From: aahz at pythoncraft.com (Aahz) Date: 28 Nov 2002 19:56:23 -0500 Subject: How to install with -O? References: Message-ID: In article , Michael Gilfix wrote: > > Hi all. I've been using __debug__ in my python programs with the >hope to byte-compile my programs with -O on install and remove the >__debug__ code. However, I haven't figured out quite how to do this >with distutils, and some searching through the documentation didn't >reveal anything. Has anyone solved this problem? Unfortunately, there are only two ways to force optimized mode: running "python -O" and setting PYTHONOPTIMIZE. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From stuart at bmsi.com Fri Nov 15 01:43:42 2002 From: stuart at bmsi.com (Stuart D. Gathman) Date: Fri, 15 Nov 2002 06:43:42 GMT Subject: HTTPSConnection with proxy Message-ID: I cannot figure out how to use a proxy with HTTPSConnection I cannot use urllib because: a) the proxy support in urllib doesn't seem to work for https: b) I need to post data with Content-Type: application/EDIStream, and urllib hardwires application/x-www-form-urlencoded Does anyone know the basic protocol for https? The proxy server logs it as a "CONNECT" request - which makes sense because the client will be doing the encoding. How would one simulate a CONNECT request via telnet? I can translate that to python code. -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From tjreedy at udel.edu Sat Nov 23 19:36:41 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 23 Nov 2002 19:36:41 -0500 Subject: Iteration of strings References: Message-ID: "Bjarke Dahl Ebert" wrote in message news:x0MD9.31653$HU.2395886 at news010.worldonline.dk... > "Terry Reedy" wrote in message > news:faWdnQY6h6rRT0OgXTWcqw at comcast.com... > > > > Some function expects a list of strings, > > Here is the root of your problem. In a real sense, Python functions > > have no expectation as to type. > > Yes they do - the expectation is just not explicitly stated, and it is often > more "vague" than any simple formal type system could express. I was trying to suggest the expection is in the mind of the writer rather than the function itself, and that this is differenct, for instance, from C where all inputs are more or less typed. Terry J. Reedy From op73418 at mail.telepac.pt Wed Nov 6 16:55:05 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 06 Nov 2002 21:55:05 +0000 Subject: newbie re question References: <1osisu81483e4k3j905dun6diio6rt29ao@4ax.com> <3dc98c38$0$24471$79c14f64@nan-newsreader-02.noos.net> Message-ID: On Wed, 6 Nov 2002 22:40:20 +0100, "Noel Minet" wrote: >It seems ':' and '@' are considered as a word breaks >Also, it seems the OP wants to capture 'a.aa' > >a lookahead does it: > >>>> pattern = re.compile(r'(?:\s|^)([\w_][\w\._]*)(?=\s|$)') >>>> pattern.findall('aadf cdase b ad:aa aasa a.aa a@ aa _aa _aafr@ aa_aa >aa__a?jk xxx') >['aadf', 'cdase', 'b', 'aasa', 'a.aa', 'aa', '_aa', 'aa_aa', 'xxx'] > > Thanks! This does the job! Now let me see If I can understand how it works... With my best regards, G. Rodrigues From tjreedy at udel.edu Sat Nov 23 19:30:34 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 23 Nov 2002 19:30:34 -0500 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <3DDBD838.10406@nyc.rr.com> <3DDC5851.5060001@nyc.rr.com> Message-ID: "Alexander Schmolck" wrote in message news:yfsadk0c648.fsf at black132.ex.ac.uk... >> [Aside: the fact that for python dicts one iterates over keys rather than > values seems like a wart to me, most likely caused by the absence of a set > type (now in 2.3), and the consequent frequent abuse of dicts to represent > sets. The resultant unnecessary discrepancy between the interfaces of mapping > and sequence types is somewhat annoying.] There was much discussion about which of dict.iterkeys(), iteritems(), or itervalues() should be the default for 'in dict' both for 'if key in dict' and 'for key in dict'. Note that since 'in seq' means same sequence in both contexts for other containers (and same underlying code is used to get sequence) it was wanted to keep 'in dict' meaning same also. The consensus, considering use cases for both constructions, was that keys are most ofter what is wanted. Think 'is word in dictionary' rather than 'is word,definition in dictionary'. Normal use of phonebook is similar. Terry J. Reedy From mlh at furu.idi.ntnu.no Sat Nov 16 01:51:03 2002 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Sat, 16 Nov 2002 06:51:03 +0000 (UTC) Subject: LCS algorithm References: <3DCD1A12.4070809@nospam.net> Message-ID: In article <3DCD1A12.4070809 at nospam.net>, Drazen Gemic wrote: >Is there an implementation of Largest Common Sequence algorithm >in Python ? I am particulary interested in implementation that >works for character strings. Here is an implementation of Levenshtein distance (edit distance): http://hetland.org/python/distance.py The two are very similar. > > DG -- Magnus Lie Hetland Practical Python The Anygui Project http://hetland.org http://ppython.com http://anygui.org From joconnor at cybermesa.com Fri Nov 8 03:19:59 2002 From: joconnor at cybermesa.com (Jay O'Connor) Date: Fri, 08 Nov 2002 15:19:59 +0700 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <20021108.121940.201305624.9010@cybermesa.com> <20021108.135935.824272813.9010@cybermesa.com> Message-ID: <20021108.151956.846811127.9010@cybermesa.com> In article , "Cameron Laird" wrote: > In article <20021108.135935.824272813.9010 at cybermesa.com>, Jay O'Connor > wrote: > . > . > . >>No, I'm making the point that TCL is syntactically weaker at expressing >>complex structures and this is a qualitative difference between the two >>languages >> >>Expanding beyond just getting a single value from a multidimensional >>list is what happens when you start throwing in lrange for slicing and >>other ways of unwrapping the structure. TCL's approach of using >>'functionName $var1 var2' leads quite easily and naturally to such >>'monstrosities' as a natural consequence of the stucture of the >>language. When you start throwing in heterogenous structures, >>especially dealing with nested arrays (dictionaries) , etc..the >>syntactical shortcut doesn't scale very well to dealing with complex >>data. (incidentally, your example does not do the same thing. >> >>set l1 "1 2 3" >>set l2 "4 5 6" >>set l3 [list $l1 $l2] >>set x [lindex [lindex $l3 1] 1] >>puts $x >> >>results in '5' >> >>using 'set x(1,1) >>results in an error > Yes and no. Tcl is awful for structuring data complexly in analogy to > C. Well actually, TCL is not bad in handling date in comparison to C (and I made that point to my co-workers) However, my comparison was to Python, and in that respect TCL is substandard to both Python(and a whole host of other languages invented since C) > It's at least medi- ocre, though, at handling complex data in its > own idioms. Well, the original analogy was that different approaches to syntax in a language do lead to qualitative differences in the usages of those languages > I'm > saying that all the well-crafted systems for managing matrices in Tcl do > NOT just make them as nested lists. Matrices are a simple data structure. Business data tends to be more complicated. My example was extremely simplistic in comparison the the heterogenous nested data that was trying to be handled using similar techniques. > One possibility for a > nicely-engineered Tcl matrix handler is to refer to the "upper left" > element as "x(1,1)". Which fails when you start trying to put arrays in it. You're thinking of "[lindex[lindex[.. " as indicating a matrix. I'm thinking in terms of a list of records where each record contains both simple data and complex data. As long as you have multi-dimensional data of simple form, it's easy. When the data is a heterogenous mix of values, lists, lists of lists, and arrays, the messines of the code gets quite bad > I'm sorry that your co-workers imposed such an unaesthetic misuse of Tcl as you describe on you. Unfortuately I have yet to see that the usage would be considered 'unaesthetic misuse' simply because I have yet to see a working alternative that is an simpler > has more on the subject. Yes, I notice non of the proposals can scale easily beyond simplistic usage in either size of problem space or complexity of problem. -- Jay O'Connor joconnor at cybermesa.com http://www.r4h.org/r4hsoftware From max at alcyone.com Sat Nov 9 17:00:17 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 09 Nov 2002 14:00:17 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: <3DCD8571.6CACEA04@alcyone.com> Johannes Gr?dem wrote: > * Carl Banks : > > > Python represents logical nesting the same way human read it, by > > indentation. Lisp repesents all nesting with parentheses, [...] > > When you program in Lisp, you (your editor) indents blocks for you, > which makes it easy to see block structure. Noone actually manually > count parentheses. (All sane editors support paren-matching.) Right. Note that this objection to Lisp is analogous to the objection that whitespace-insensitive language users (C, C++, Java, Perl, etc.) often use to discount Python before they've been exposed to it. "If it's whitespace sensitive," they say, "I'll be stuck fighting with indentation to get the results I want." I'm an emacs user, so the first thing I did when I started fiddling around with Python is installed python-mode. Because of that, I have never once counted spaces, never once had space/tab problems, never once had a problem indenting/unintending a region, and whenever I've forgotten the odd colon, good ol' python-mode has made it very clear to me what the problem was. The same goes for Lisp (and all its variants, like Scheme). You might have to count parentheses if you had to physically write it down with pencil and paper, but in the real world you'll be using an editor, and the editor will help you match parentheses and do the gruntwork for you. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ I'm paranoid. But am I paranoid enough? \__/ Louis Wu Official Omega page / http://www.alcyone.com/max/projects/omega/ The official distribution page for the popular Roguelike, Omega. From bokr at oz.net Wed Nov 13 00:23:00 2002 From: bokr at oz.net (Bengt Richter) Date: 13 Nov 2002 05:23:00 GMT Subject: matching multiple regexs to a single line... References: Message-ID: On Tue, 12 Nov 2002 20:04:31 GMT, "Alexander Sendzimir" wrote: > > >How does one match multiple regexs to a single line as in a compiler in >Python? I'm used to doing the following in Perl, for example: > >$line = <>; > >if ( $line ~= /regex1/ ) >{...} >elsif ( $line ~= /regex2/ ) >{...} >elsif (...) >{ etc... } > >To do this in Python and be able to get at the match if a regex succeeds >means I have to break up the if's because I haven't been able to get >Python to make an assignment in an if-statement. In other words, > >if ( myMatch = re1.match( line ) ) : > ... >elif ( myMatch = re2.match( line ) ) : > ... > >doesn't work for me. Perhaps I've missed something simple. > Some might consider this cheating, but you could make a class instance that you can use to grab a value in an expression for later use. E.g., >>> import re >>> re1 = re.compile(r'one\s+(.*)') >>> re2 = re.compile(r'two\s+(.*)') >>> line = 'two This is message two.' >>> class V: ... def __init__(self, v=None): self.v = v ... def __call__(self, *v): ... if v: self.v = v[0] ... return self.v ... >>> v=V() >>> if v(re1.match(line)): ... print v().group(1) ... elif v(re2.match(line)): ... print 'Use it differently:', v().group(1) ... Use it differently: This is message two. Regards, Bengt Richter From martin at v.loewis.de Mon Nov 4 12:09:20 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 04 Nov 2002 18:09:20 +0100 Subject: Encoding of String References: Message-ID: Thomas Guettler writes: > Is there a way to get the encoding of a string? No. The absence of a reliable method to detect the encoding of some arbitrary sequence of bytes is the very reason to introduce explicit declarations of encodings into various protocols and format (e.g. MIME, XML, etc). In the end, this problem is also one of the reasons for Unicode to exist, and the Unicode type in Python as a separate data type: If you have a Python Unicode object, you know how to interpret the elements of the sequence. For an arbitrary string, you don't. That said, there are various heuristics you can apply; search this group for earlier discussions of the matter. Regards, Martin From dsiroky at email.cz Sun Nov 3 17:40:14 2002 From: dsiroky at email.cz (David Siroky) Date: Sun, 03 Nov 2002 23:40:14 +0100 Subject: Numerical & FFT Message-ID: Hi! Functions "fft" and "real_fft" returns some array. What those numbers exactly mean? Especially the first one (DC or what)? Thank you! David From amk at amk.ca Wed Nov 13 17:44:57 2002 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 13 Nov 2002 17:44:57 -0500 Subject: Python documentation in DocBook In-Reply-To: ; from whisper@oz.net on Wed, Nov 13, 2002 at 02:03:01PM -0800 References: <_qSdnaGis_mXXE-gXTWcoQ@speakeasy.net> Message-ID: <20021113174457.A5733@nyman.amk.ca> On Wed, Nov 13, 2002 at 02:03:01PM -0800, David LeBlanc wrote: >How could it not be relevent? If more people know xml then know \tex, then >the number of random people who might be interested in writing python doc is >apt to be greater if python doc is in xml. It seems to me (I could be wrong) Random people are *not* interested in writing documentation. People are not atoms bouncing around until they hit a project and stick. No one says, "Hm... I know LaTeX, so I'll make a list of all projects that use LaTeX and pick one at random to help." Instead, they find themselves using one particular thing -- Python, Apache, whatever -- and find themselves contributing to it. That's highly non-random, and hard to steer. Counting on random people from around the 'net to assemble a document or program or site usually has the same result: a pile of junk. (Insert snide comment about Slashdot here.) Every successful project has a small core of committed developers or editors, who accept and process contributions from everyone; it's important to keep this core happy and not overloaded, because without them the whole process collapses. --amk (www.amk.ca) SIR ANDREW: But I am a great eater of beef and I believe that does harm to my wit. -- _Twelfth Night_, I, iii From tdelaney at avaya.com Wed Nov 20 20:43:41 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 21 Nov 2002 12:43:41 +1100 Subject: Why is Python popular, while Lisp and Scheme aren't? Message-ID: > From: Pascal Costanza [mailto:costanza at web.de] > > Delaney, Timothy wrote: > >>From: Pascal Costanza [mailto:costanza at web.de] > >> > >>Meiner Meinung nach h?ngt das im wesentlichen immer davon > ab, welche > >>Sprache man zuerst gelernt hat, oder welche man am > h?ufigsten benutzt. > >> > >>If you don't understand this, would you consider German to be less > >>readable than English? (Run that sentence through > >>http://babelfish.altavista.com to get my point. ;) > > > > > > Having been involved in these debates before, I now try to > avoid them > > (except when trying to get Python used on a project ;) > > > > However, you measure readability by how readable something > is at comparable > > skill levels. So if I were fluent in both German and > English (I'm not), > > *and* you had provided the English version (not necessarily a direct > > translation, but the equivalent meaning) then I could make > a judgement. If I > > had no fluency in either, I could not make a meaningful judgement. > > No, I am saying that many statements about the readability of > programming languages are made from a perspective of being > fluent in one > but not in the other language. I don't think that there are any > programming languages that are per se more readable than > others. Heck, > this isn't even true for natural languages. That's the whole > point of my > argument. I could have made this example even more extreme by > giving it > in Japanese, or sign language, or Braille language. You asked how to define readability, and then used an example which is completely non-understandable to someone who is not at least passingly fluent in German. This is a strawman argument. Readability can only be determined by someone who has equivalent skill in both domains. Of course people who do not have such qualifications make statements about the readability of one or the other. A person with normal eyesight, who is equally skilled in both reading English and Braille, would be able to judge the readability of a book written (in English) in both a "normal" typeface and Braille (and the result may well be "equal"). A blind person would be unable to make such a judgement, because they are unable to read the non-Braille version. Would you take issue with a blind person saying that a non-Braille book was completely unreadable? I personally would make the point that it may be unreadable for them, but it's perfectly readable for me. Background obviously makes some things more readable than others. Someone whose first language is alphabetic is going to find Japanese, Thai, etc much less readable than their native language even if they are completely fluent in both. > So which of the two following expressions do you find more readable. > According to your statement it should be the first because it's closer > to English. > > 1) ADD A TO B GIVING C > 2) c = a + b Not at all - for three reasons. 1. I have had a *strong* background in languages where #2 has meaning. 2. Whilst it does not mean the same thing as in mathematics, it is related to the mathematical meaning, and uses mathematical symbols that I am used to. In particular, it is similar to the form "if we assume that c equals a plus b" which is commonly used in proofs. 3. I would *never* use the construct you give as #1 - if I were to say anything, it would be "set c equal to a plus b". What I can state, unequivocably, is that as a new python user (some time ago now ;) I was able to understand and modify existing python code very easily. Part of this is due to a background in (primarily) procedural languages, but most of it was because the syntax is so clear and (in general) module and function names are well-chosen. As an expert I am able to take large amounts of existing code and in a relatively short period of time understand most of what it does. I can also state that I have *never* been able to grasp the intention of anything beyond the most trivial Lisp code without studying it in depth. I have had similar experiences with other languages (C, SQL, Prolog, Perl are four examples). Tim Delaney From andersjm at dancontrol.dk Tue Nov 26 05:31:35 2002 From: andersjm at dancontrol.dk (Anders J. Munch) Date: Tue, 26 Nov 2002 11:31:35 +0100 Subject: Python Tutorial Was: Guido's regrets: filter and map References: <20021126043142.4323.25612.Mailman@mail.python.org> Message-ID: <3de3507e$0$71601$edfadb0f@dread11.news.tele.dk> "Terry Hancock" wrote: >(do I recall correctly that you couldn't pass literals to functions > in Pascal? I remember being very annoyed by that, coming from > Fortran). You must be thinking of passing literals by reference. Sure you can pass literals to functions, you just can't do this: program Indiana_House_of_Representatives; procedure Bill246(var pi: real); begin pi := 3.2; end; begin Bill246(3.1415926535897931); end; Fortran-doesn't-have-these-silly-limitations-ly y'rs, Anders From mike at skew.org Wed Nov 6 07:52:37 2002 From: mike at skew.org (Mike Brown) Date: Wed, 6 Nov 2002 05:52:37 -0700 Subject: regex puzzle Message-ID: <3dc91095$1_1@omega.dimensional.com> I need an example of a regular expression that: - matches an empty string - matches a non-empty string - does NOT match a string consisting of only a linefeed So, this test should produce [1, 1, 0]... import re pat = '^(.+)?$' # FIXME [(re.search(pat, s) is not None) for s in ['', 'foo', '\n']] Any suggestions? :) Thanks From anders at gamebox.net Sat Nov 9 05:40:51 2002 From: anders at gamebox.net (A Nilsson) Date: Sat, 09 Nov 2002 11:40:51 +0100 Subject: zip/unzip pictures doesn't work Message-ID: <3DCCE633.5040301@gamebox.net> I've been messing around with the zipfile module and discovered something strange. When I zip/unzip ordinary text files there's no problem but when i use pictures (JPG and GIF) they get corrupted. I believe it is during the unzip operation they get messed up. I've zipped with python, unzipped with python -> doesn't work. Zipped with Winzip, unzipped with python -> doesn't work. Same as above but unzipped with Winzip -> OK. Is there something special you have to consider when unzipping a picture? /Ando N mailto:anders at gamebox.net From graik at web.de Thu Nov 7 13:41:00 2002 From: graik at web.de (Raik Gruenberg) Date: Thu, 07 Nov 2002 19:41:00 +0100 Subject: segmentation fault when unpickling an object in another Python instance References: <3DC96AAD.9090503@web.de> <3DC99AF6.2030906@web.de> <7h3lm45zktm.fsf@pc150.maths.bris.ac.uk> <3DCA5CB1.6060004@web.de> Message-ID: <3DCAB3BC.6000805@web.de> Martin v. L?wis wrote: > Raik Gruenberg writes: > > >>You are right, sort of. The problem is narrowed down: It, basically, >>seems impossible to unpickle a Numeric array of dictionaries (objects >>in general?) in another interpreter instance. I, nevertheless, >>submitted the bug report to the (more active) Python not the Numpy >>project. You shouldn't get a segfault, after all... > > > However, we can nothing do about that. If Numeric decides to crash, > inside its own code, or return garbage data to Python, there is > nothing that the rest of the Python interpreter can do to save itself. OK, I didn't know that the pickling is completely delegated to the array object. I filed the same bug to the Numeric group and added your remark from the python bug list. Thanks for looking into this! Greetings Raik > The guarantee of no segfaults becomes void if there are misbehaving > extension modules. > > Regards, > Martin > From fperez528 at yahoo.com Mon Nov 11 15:51:25 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 11 Nov 2002 13:51:25 -0700 Subject: Is python a good choice for this task? References: Message-ID: Ron Lau wrote: > My question is, What language is best suited for this? Perl, Python, or > shell scripts? Well, from each of the groups you posted to you'll get a different answer. But of course, two of them will be wrong. You should use python :) Kidding aside, such a simple task can be done in any of those without any effort. I'd still suggest python because it's a better language than the others for a number of things (yes, I've used all three extensively). Especially if you have a scientific computing background: if you poke around the web a bit, you'll find that python is becoming very popular in scientific computing circles, and for good reason. See http://scipy.org/ or http://mayavi.sourceforge.net/ for useful things in this direction. The task you described will hardly illustrate the differences between these languages. But when you decide you want to control your fortran CFD code through a high-level language, load NetCDF or HDF5 data files, visualize them with VTK, generate webpages out of the plot results, python will really begin to shine. I recommend you read: http://www.python.org/workshops/1997-10/proceedings/beazley.html before making this decision. It's written from the viewpoint of a scientific computing person, and while a bit old, it remains almost 100% true today. The parts that have changed is simply that many of the tasks described in that article are _far_ easier to do today than they were then. Welcome! f. ps. Other useful links for python and scientific computing: http://www.pfdubois.com/numpy/ http://starship.python.net/crew/hinsen/ http://w3.pppl.gov/~hammett/comp/python/python.html From mwh at python.net Thu Nov 28 05:06:35 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 28 Nov 2002 10:06:35 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <20021128000512.T11257@prim.han.de> Message-ID: <7h3n0nuovvh.fsf@pc150.maths.bris.ac.uk> Courageous writes: > I still disagree with the decision to not have a defgenerator clause > (or equivalent) however. BDFL pronuncements in the PEP notwithstanding. Live with it. > For one thing, had yield not been meant to imply generator in the > context of the function in which it is used, yield could have been > executed in the body of a function which perculated that being > yielded to the first appropriate defgenerator in the invocation > stack, somewhat like a limited kind of continuation. To wit: > > defgenerator g (): > > f() > > def f(): > > while 1: > > yield None > > x = g() > > while x.next(): > > something() > > Ddon't know about actual _implementation_ mind you, but it struck > me that it would be quite useful if "yield" actually raised something > that was next()able. x = g() would therefore be syntactic sugar for > "except Continuable, c:" You'd have to know at compile time whether g() referred to a generator of not, wouldn't you? That ain't gonna work. Cheers, M. -- 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 anton at vredegoor.doge.nl Tue Nov 5 08:59:37 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 05 Nov 2002 14:59:37 +0100 Subject: bug report w\o registering References: Message-ID: On Tue, 5 Nov 2002 14:26:01 +0100, J?rgen Cederberg wrote: >Please see section 6.8 in the Library reference ( http://www.python.org/doc/current/lib/module-popen2.html ), it clearly states how popen2.popen2 should be called. Example > >>>> import os, popen2 >>>> infile, outfile = os.popen2("dir", "b", -1) >>>> outfile, infile = popen2.popen2("dir", -1, "b") >>>> Thanks! Anton. From david at no.westcontrol.spam.com Fri Nov 15 03:31:12 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Fri, 15 Nov 2002 09:31:12 +0100 Subject: How to write Inline Functions in Python? References: <3DD3C06D.61AAB36D@engcorp.com> Message-ID: "Arivazhagan" wrote in message news:c8476101.0211142004.7f97751b at posting.google.com... > Hi > We are extending python to develop a Board Description language for > ATE. say in our project there are 2 modules named a.py( provided by us > ) and b.py.(the end user programs.) > > In a.py > ------- > > import sys > > > class Good : > def __init__(self, name ) : > self.__name = name > > > def createGood( *names ) : > for name in names : > thisGood = Good( name ) > > #The following is done so that the objects created here can be > accessed > #from b.py without using the module name. > #We just want to avoid this. > sys.modules['__main__'].__dict__[name] = thisGood > > > In b.py > ------- > from a import * > > createGood( 'A', 'B', 'C' ) > > #We want to access like this without that additional codes. > print A > print B > print C > > regards > b.arivazhagan > > As far as I can see (and hopefully a more experianced Python programmer will correct me if I'm wrong), you are definitely going about this the wrong way. You do not want to create globals in this manner - if writing "print x.A, x.B, x.C" is going to be a problem, then you are going to have to go back and think about what you are really trying to do. Sure, it would be possible to mess around with globals() and get the effect you want somehow, but it really would be messing around. It would also be incredibly dangerous - think what would happen with " createGood('createGood', 'a', 'print') ". I think you would be much better off having createGood make a list or a dictionary of the Good objects and returning that. From aleax at aleax.it Sun Nov 10 03:12:12 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 10 Nov 2002 08:12:12 GMT Subject: indexed looping, functional replacement? References: <3fe406f0.0211091037.2795e538@posting.google.com> <9Xcz9.15450$XO.672555@news2.tin.it> Message-ID: Bengt Richter wrote: ... >>In Python 2.2, you can try various inferior alternatives, e.g.: >> >>for f, i in zip(fn, range(len(fn))): >> f(str(i)) >> > > Is there something I'm missing, or did the cat distract you ;-) > > >>> for f, s in zip(fl, sl): > ... f(s) > ... > f1: bbb > f2: sdf > f3: sdw > > (fl and sl being alternate names for fn and str as used) Did the OP use str to mean something different than Python's normal builtin str? If so, then it took a very moderate amount of distraction (which my cat does freely supply most of the time) to make me believe that str meant what it most always means -- a constructor for plain strings. Good occasion then to reiterate the usual advice to people who use the names of Python's types (or other builtins, I guess, but for some reason it always seems to be types) for different purposes: don't. By naming your variables &c with such names as int, float, str, file, list, dict, tuple, ..., you're just causing confusion -- and if you don't fall prey to that confusion yourselves, you may still trip up others who are trying to help (or otherwise to read your code). Alex From logistix at zworg.com Thu Nov 14 22:29:34 2002 From: logistix at zworg.com (logistix) Date: 14 Nov 2002 19:29:34 -0800 Subject: parsing python code References: <653cf871.0211141129.681e5dd7@posting.google.com> Message-ID: abidnego25 at yahoo.com (les) wrote in message news:<653cf871.0211141129.681e5dd7 at posting.google.com>... > Hi, > i would like to find out the function call tree of a python > code. i.e. > say i have a code like this: > def fun111(): > .. > def fun11(): > fun111() > > def fun1(): > fun11() > fun12() > > if __name__ =='__main__': > fun1() > then i would like to build a dictionary like this > > d ={ 'root': '__name__', > '__name__': ['fun1'] > 'fun1': [ 'fun11','fun12'], > 'fun11': [ 'fun111'] > } > > it is easy to parse out function names from the code, > but not so easy to jump around to figure the tree structure. > is there a module which exports some function when > given a functionname returns all the functions it calls? > (only those functions that are in the source code) > > so far i have something like this > that removes the function names > but before i try the brute force way,i wanted to ask if there is already > a module that does what i want > > ###################################### > from sys import argv,exit,stdin > > > if __name__ == '__main__': > try: > codefile = argv[1] > except IndexError: > print 'USAGE %s ' % argv[0] > exit(-1) > #pull out function names > fp = open(codefile) > fun_names=[] > for x in fp: > if x[0:3]=='def': > fun_names.append( x.split()[1].split('(')[0]) > print fun_names > fp.close() > # go thought the file again and build nested list > nested={} > fp = open(codefile) > > ################ I NEED HELP HERE > > fp.close() > > thanks The parser module builds Abstract Syntax Trees from text. Unfortunately, you'll still need to figure out how to climb through the trees. Tokenize module will give you one token at a time if you want to build your own tree. Again, it's not automagical, but you can do alot of stuff. compiler module might also be of interest, but I've never used it. And it seems pychecker just looks at the generated bytecode to analyze code. So it looks like there are alot of options, all of which will require some work to get to where you're at. From oracle_vs_ms at yahoo.dk Wed Nov 6 12:11:04 2002 From: oracle_vs_ms at yahoo.dk (Peter Lorenzen) Date: 6 Nov 2002 09:11:04 -0800 Subject: Subclassing the min() build-in function? Message-ID: <18eef4ae.0211060911.2c0a7731@posting.google.com> Hi, I am using Jython to calculate a string like this: "2+3+min(1,2,3)" from my Java pro-gram. This works beautifully. But my problem is that if a user wants to calculate min(1) Python considers this an error. I want it to return 1. If I could figure out how to subclass the min function, so when it was called with one parameter I just returned this parame-ter, and otherwise returned the super min function. It looks like this should be possible, but I am new to Python, so I don't understand the subclass examples I have found. Hope somebody can help me. Regards, Peter Lorenzen From wlfraed at ix.netcom.com Tue Nov 26 20:15:35 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 26 Nov 2002 17:15:35 -0800 Subject: variable name and type confusion... References: Message-ID: Dennis Lee Bieber fed this fish to the penguins on Monday 25 November 2002 10:23 pm: > > Also, you need to define graphs as global to get your results > out of > the routine. > Correction -- since it is a list and you are using .append, you don't need to declare it global; but it shouldn't hurt, and may be safer should the routine undergo modifications in the future -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From bokr at oz.net Sun Nov 10 01:17:44 2002 From: bokr at oz.net (Bengt Richter) Date: 10 Nov 2002 06:17:44 GMT Subject: NEWBIE: Extending Python with C References: <3dcc7e2c.3568851@news.earthlink.net> <3dcd6aee.7793165@news.earthlink.net> Message-ID: On Sat, 09 Nov 2002 20:15:31 GMT, engsol at teleport.com wrote: >On 9 Nov 2002 09:54:01 GMT, bokr at oz.net (Bengt Richter) wrote: > >>On Sat, 09 Nov 2002 03:48:35 GMT, engsol at teleport.com wrote: >> >>>I've read the books, tried some code, and I still just don't get it. >>> > > >>Well, it depends on what kind of coupling you need between your python stuff and the c stuff. >>Some variant of the above may do it, or not ;-) Need more definite requirement statement. > >Thanks for the reply. > >One example of the legacy requirement is: we have a custom plug-in card which needs to be PCI? All done via IO ports or has DMA? Uses interrupts? Time-critical parts? >loaded with data, then triggered to output the data stream to the system under test. The >driver for the card works well, and it'd be nice to not have to rewrite it. The source can How do you use "the driver" now? Are you saying "driver" just in the loose sense of any software that lets you use some hardware in some way? Or do you really mean "driver" as in developed using DDK or equivalent and put in C:\WINNT\system32\drivers\whizzomatcard.sys? Or a privileged app? >be recompiled as a DLL(?) module...I think. Or at the least as a library header Why do you think you want to do that? (I'm not suggesting it's a bad idea, I'm just wondering what leads you to think you may need to do that). How do you currently operate, and how do you hope to operate, at the user interface level? >file..again..I think. > It's still hard (for me anyway) to tell what your situation. Regards, Bengt Richter From see_reply_address at something.invalid Wed Nov 13 18:35:32 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 14 Nov 2002 12:35:32 +1300 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3dce5e2f$0$35917$edfadb0f@dread13.news.tele.dk> Message-ID: <3DD2E1C4.9010100@something.invalid> Carl Banks wrote: > Martin Maney wrote: > > A new syntax would be the best solution, IMHO. For example, the > suppose statement: > > suppose: > do_A() > if test_based_on_A(): > take_action_A() > elsuppose: > do_B() > if test_based_on_B(): > take_action_B() Some time ago I proposed a loop-and-a-half syntax that went while: do_A() gives test_based_on_A(): ... There could be a similar variant for the if-statement: if: do_A() gives test_based_on_A(): take_action_A() elif: do_B() gives test_based_on_B(): take_action_B() -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From duncan at NOSPAMrcp.co.uk Tue Nov 12 09:12:09 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 12 Nov 2002 14:12:09 +0000 (UTC) Subject: Can python find fibonacci series in a single line of code? References: <6q7kfjau4f.fsf@salmakis.intevation.de> Message-ID: bokr at oz.net (Bengt Richter) wrote in news:aqqt9t$vu2$0 at 216.39.172.122: >> python -c "a=b=1;exec'while+1:print+a;a,b=b,a+b'" > > I didn't know exec would parse semicolons that way (I hardly ever use > it). But is that new with 2.2? Does that mean it effectively assumes a > semicolon is the same as a newline and indent to the same level as the > previous statement, until it finds an actual newline? No, it simply means that: while+1:print+a;a,b=b,a+b is a legal line, with or without exec. The while has to be the first statement on the line thoug, which is which you need the exec here (or tricks updating vars()). How about this variant? No sneaky updating vars(), no exec: while 1: g=vars().get;a,b=g('a',1),g('b',1);print a;a,b=b,a+b -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From skip at peterskipworth.com Mon Nov 25 22:22:22 2002 From: skip at peterskipworth.com (Peter Skipworth) Date: Tue, 26 Nov 2002 14:22:22 +1100 Subject: Reading MS Excel Files ? Message-ID: <3de2e939$1_1@news.iprimus.com.au> Hi, I've recently started developing in Python, after quite a few years on Perl. Quite a few of the scripts I develop need to be able to parse a Microsoft Excel spreadsheet - with Perl, this was quite simple, using a module called Spreadsheet::ParseExcel. Does anything similar exist for Python ? Note that I'm working on a Linux platform and thus need a non-Win32-centric solution. Thanks! P From costanza at web.de Mon Nov 25 17:28:44 2002 From: costanza at web.de (Pascal Costanza) Date: Mon, 25 Nov 2002 23:28:44 +0100 Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <093kra.3n3.ln@beastie.ix.netcom.com> <1038199757.350382@yasure> Message-ID: maney at pobox.com wrote: > Jacek Generowicz wrote: > >>When you call a subroutine, you are calling a specific piece of >>code. The caller decides what will be executed. When you pass a >>message, the decision as to which exact code should be executed is >>made elsewhere (some form of dispatch). >> >>But it looks as if my understanding of message passing is different >>from Pascal's. > > > Maybe, but probably less so than you imagine. You're desribing it from > the relatively concrete, implementation side; Pascal has preferred the > fuzzy, metaphorical language that was introduced, IMO, in an effort > either to make a useful but trivial formalism sound like it was > something wonderful, or to hilight the important new ways of thinking > about and structuring programs that the formalism (ie., language > support) made much more convenient. This is Monday, so today I'll say > it was the former, handwaving; on Tuesdays I prefer the metaphor as > pedagogical device. And so it goes through the week... Do I sense some irony here? ;) Pascal -- Given any rule, however ?fundamental? or ?necessary? for science, there are always circumstances when it is advisable not only to ignore the rule, but to adopt its opposite. - Paul Feyerabend From costanza at web.de Sun Nov 24 20:13:11 2002 From: costanza at web.de (Pascal Costanza) Date: Mon, 25 Nov 2002 02:13:11 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <3DDBD838.10406@nyc.rr.com> <3DDC5851.5060001@nyc.rr.com> Message-ID: Alexander Schmolck wrote: > Pascal Costanza writes: > > >>[...] >> >> >>>python: CL: x = list[index] (elt arrayOrList index) >> >>> x = hash[key] (gethash key hash) ;; *why* this arg-order? >>> x = myType[indexOrKey] ; no generalized item access >>> >> >>[etc.] >> >>Unified access is always a bit problematic. You should not access a list >> (in Common Lisp) by index because the list must always be traversed up >>to the index on each access. (As far as I understand, what Python calls > > > Of course you usually don't but then I can't see why this is an argument > against unified access (I don't want to abolish car and cdr and the writing of > nice recursive functions that manipulate lists with them). My guess is that the CL designers wanted us to make conscious decisions in this regard, so they opted for "non-unified" access by default. But I admit that I am not sure about what's the best option here and I see that you have some points. > Also often you just want to iterate over all the items in some container and I > can't really see how not having a good mechanism to this can be a good > thing. Why should I always need to tell LOOP that I want to iterate over a > vector and not a list? > > (loop for i in list) > > as opposed to > > (loop for i across vector) > > why not just: > > (loop for i in container) > Well, you can always do the following. (map nil (lambda (i) (...)) container) And if you want to have a nicer syntax: (defmacro dosequence ((element container) &body body) `(map nil (lambda (,element) , at body) ,container)) Now you can do both. (dosequence (i '(1 2 3)) (print i)) (dosequence (i #(1 2 3)) (print i)) Pascal -- Given any rule, however ?fundamental? or ?necessary? for science, there are always circumstances when it is advisable not only to ignore the rule, but to adopt its opposite. - Paul Feyerabend From aleax at aleax.it Mon Nov 25 04:03:16 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 25 Nov 2002 09:03:16 GMT Subject: index of items in a List in sorted order References: <75e086cd.0211241841.72e35ecf@posting.google.com> Message-ID: Bengt Richter wrote: ... > >>> def ind_of_sorted2(L): > ... items = zip(L,range(len(L))) > ... items.sort() > ... return zip(*items) > ... > >>> ind_of_sorted2(list('rgafrj')) > [('a', 'f', 'g', 'j', 'r', 'r'), (2, 3, 1, 5, 0, 4)] > > Of course, it doesn't eliminate the duplicates, but now there's > probably some time left to do that ;-) If you want to keep the LAST index to any "duplicate" life's easy: >>> def ind_of_sorted3(L): ... items = dict(zip(L, range(len(L)))).items() ... items.sort() ... return zip(*items) ... >>> ind_of_sorted3('rgafrj') [('a', 'f', 'g', 'j', 'r'), (2, 3, 1, 5, 4)] >>> keeping the FIRST index instead ain't quite THAT smooth, e.g.: >>> def ind_of_sorted4(L): ... aux = zip(L, range(len(L))) ... aux.reverse() ... items = dict(aux).items() ... items.sort() ... return zip(*items) ... >>> ind_of_sorted4('rgafrj') [('a', 'f', 'g', 'j', 'r'), (2, 3, 1, 5, 0)] >>> dict, called with a sequence of pairs, is guaranteed to keep the LAST pair out of any subset that has the same first item (key), which is why reversing works here. Of course, these are all 2.2 solutions -- in 2.3 you can slice a list by [::-1] to get its reversed copy more smoothly: >>> def ios5(L): ... items = dict(zip(L,range(len(L)))[::-1]).items() ... items.sort() ... return zip(*items) ... >>> ios5('rgafrj') [('a', 'f', 'g', 'j', 'r'), (2, 3, 1, 5, 0)] >>> However, I think the several-statements approach of ind_of_sorted4 may be preferable -- more readable -- even if the alternate "squash all into one statement" styles are available... Alex From musikintresserad at yahoo.se Mon Nov 18 04:40:08 2002 From: musikintresserad at yahoo.se (Adam S) Date: Mon, 18 Nov 2002 09:40:08 +0000 Subject: Python urllib.urlretrieve vs. Perl getstore References: <3DD3F7E8.519BC0BF@yahoo.se> Message-ID: <3DD8B578.E5EE2F88@yahoo.se> Python code snippet: "file_url" is something like "http://servername.intranet.company.com/serverspace/stored_file.tar.gz" file_name is something like "/export/tmp/directory". urllib.urlretrieve(file_url,file_name) # download the file I'm running Python 2.2. The perl 5.6.1 version uses 'getstore' Adam holger krekel wrote: > Please be more specific and post relevant code-snippets and > which python-library you use. > > IMO perl's as well as python's retrieving functions should be > 99% IO-bound meaning that there shouldn't be a speed > difference unless you are having a Gigabit-Internet-Connection :-) > > regards, > > holger From bushbo at attbi.com Sat Nov 9 19:26:09 2002 From: bushbo at attbi.com (Brian O. Bush) Date: 9 Nov 2002 16:26:09 -0800 Subject: indexed looping, functional replacement? References: <3fe406f0.0211091037.2795e538@posting.google.com> Message-ID: <3fe406f0.0211091626.5277990f@posting.google.com> bushbo at attbi.com (Brian O. Bush) wrote in message news:<3fe406f0.0211091037.2795e538 at posting.google.com>... > I currently have a list of functions and a list of arguments to the > functions (n to n). Is there a way I can get around having to keep an > index into the arguments as I loop through the functions. First, thanks for all your feedback. I was playing around and came up with some alternative solutions: def f1(str): return float(str) def f2(str): return float(str) - 1 def f3(str): return float(str) str = ["2.144", "2.343", "3.14159"] fn = [f1, f2, f3] an alternative imperative approach: z = [] for i in range(len(fn)): z.append(fn[i](str[i])) print z and a functional approach, which I like alot: z = map(lambda f, arg: f(arg), fn, str) print z Cheers, Brian From max at alcyone.com Sun Nov 3 01:38:29 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 02 Nov 2002 22:38:29 -0800 Subject: List slice assignment and custom sequences References: Message-ID: <3DC4C465.4E3B8458@alcyone.com> Ronald Oussoren wrote: > No, I want to replace part of a sequence by another sequence. If the sequence that your splicing into is a custom type, then it's going to depend on whether such splicing is implemented and how. Presumably it would want a sequence on the right-hand side of the same type as the left-hand side. > I don't > understand _why_ the RHS must be a list if the LHS is one. It doesn't > even allow a tuple, even though tuples can be used instead of lists in > almost all code that treats the sequence as read-only. It just sounds like common sense to me; the splicing operation should take the same type of sequence on the right-hand side as the left. Since Python allows you trivial conversion from _any_ sequence to a list with the list function/type, it seems like a non-problem to me if the right-hand side isn't a list to start with. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Weakness of attitude becomes weakness of character. \__/ Albert Einstein WebVal / http://www.alcyone.com/pyos/webval/ URL scanner, maintainer, and validator in Python. From jepler at unpythonic.net Wed Nov 27 10:39:57 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 27 Nov 2002 09:39:57 -0600 Subject: Why not a, b += i, j? (augmented assignment via tuple unpacking) In-Reply-To: <3DE44EF7.3060402@something.invalid> References: <3de3e129$0$4437$a1866201@newsreader.visi.com> <3DE44EF7.3060402@something.invalid> Message-ID: <20021127153956.GB9830@unpythonic.net> On Wed, Nov 27, 2002 at 05:49:59PM +1300, Greg Ewing wrote: > Jeff Epler wrote: > > >but in that case, what is > > a, b += t > >equivalent to? > > > Obviously it's > > a, b = iadd(a, t[0]), iadd(a, t[1]) > > >What about > > t += a, b > > > This is already meaningful: > > t = iadd(t, (a, b)) Right now t = i, j a, b = t del t is equivalent to a, b = i, j except that the temporary t is never created (it resides on the stack) But that means that you'd want t = a, b t += i, j a, b = t del t to be equivalent to a, b += i, j but now 't += (i, j)' has been given two different meanings -- the one it has already, and the one it would need to have to make "augmented assignment via tuple unpacking" work in the "desired" way. Jeff From lbrannma at cablespeed.com Mon Nov 11 20:06:36 2002 From: lbrannma at cablespeed.com (Lance) Date: Mon, 11 Nov 2002 17:06:36 -0800 Subject: text formatting module? Message-ID: Hi All, I would like to write text that word wraps to two or three levels of tab stops. For example.... y = 30*'hello world' s = 'start\t' + y This won't do it... since the string will continue off the screen. Is there a module or can anyone suggest how I might write a procedure to wrap y at the tab stop, irrespective of the length of y? I want the result to look like this: start hello world hello world..... world hello world.... Thanks in advance, Lance From bokr at oz.net Mon Nov 11 13:57:12 2002 From: bokr at oz.net (Bengt Richter) Date: 11 Nov 2002 18:57:12 GMT Subject: NEWBIE: Extending Python with C References: <3dcc7e2c.3568851@news.earthlink.net> <3dcd6aee.7793165@news.earthlink.net> <3dceb920.8008485@news.earthlink.net> Message-ID: On Sun, 10 Nov 2002 21:59:35 GMT, engsol at teleport.com wrote: >On 10 Nov 2002 06:17:44 GMT, bokr at oz.net (Bengt Richter) wrote: > >>On Sat, 09 Nov 2002 20:15:31 GMT, engsol at teleport.com wrote: >> >>>On 9 Nov 2002 09:54:01 GMT, bokr at oz.net (Bengt Richter) wrote: >>> >>>>On Sat, 09 Nov 2002 03:48:35 GMT, engsol at teleport.com wrote: >>>> > >>>One example of the legacy requirement is: we have a custom plug-in card which needs to be >>PCI? All done via IO ports or has DMA? Uses interrupts? Time-critical parts? >> >>>loaded with data, then triggered to output the data stream to the system under test. The >>>driver for the card works well, and it'd be nice to not have to rewrite it. The source can >>How do you use "the driver" now? Are you saying "driver" just in the loose sense of any software >>that lets you use some hardware in some way? Or do you really mean "driver" as in developed using >>DDK or equivalent and put in C:\WINNT\system32\drivers\whizzomatcard.sys? Or a privileged app? >> >>>be recompiled as a DLL(?) module...I think. Or at the least as a library header >>Why do you think you want to do that? (I'm not suggesting it's a bad idea, I'm just wondering >>what leads you to think you may need to do that). How do you currently operate, and how do >>you hope to operate, at the user interface level? >> >>>file..again..I think. >>> >>It's still hard (for me anyway) to tell what your situation. >> >>Regards, >>Bengt Richter > > >LOL...this is a bit embarrassing....but here's more detail. Please keep the groans to a >minimum...:) > >The test application is written in C. It's a DOS 6.22 application, compiled using Borland >3.0. We've tried newer versions, but they won't compile our source as is. The source is >3/4 million lines, including comments, blank lines, dead code, etc.,and the executable is >about 1 meg. It uses COM1, COM2 and COM3 to "talk" to the test fixture, plus it talks to a >couple of in-house designed and built ISA cards refered to above. One card's output is a >pair of BNC coax connectors which in turn are connected to the test fixture. The other >custom ISA card is attached to the test fixture using a 37 conductor ribbon cable. > >The application provides a console-like user interface, command line style. The app has >the facility to run 'scripts', loosely based on a C-like syntax, which is how we write our >test scenarios to automate product software testing. The app also has "drivers" to run the >cards, IO ports, user interface, etc. > It sounds to me you have several kinds of analysis ahead, but the first thing is to decompose the overall problem into pieces that don't have too much to do with each other. E.g., critical interrupt service latency concerns are (or should be) separate from worries about how to train new employees to edit test scripts. I would guess you have to decide how long you need to keep the current thing going with legacy OS and tools (you *do* have well-marked CDs with 100.00000% of the sources **and** tools and scripts **and** OS stuff you need to recover if the building washes out to sea, right ;-). Second and related, your hardware probably has an evolution path of its own. If it's about to take a radical fork requiring much rework of the legacy software, you will be in a tough spot trying to decide how much more to invest in the legacy stuff while seeing that if you can get away with one more patchwork mod, you're probably going to get results faster by doing that than taking on a lot of software design and various little learning curves that add up and mess with schedules. (Incidentally, that economic dynamic is one of the fundamental causes of bloatware IMO). It sounds like timing will be critical to how you build the next generation of your test system, but if it's decomposed appropriately, the most critical aspects could be insulated from the general operating environment. E.g., there are very critical hard real-time requirements in burning CDs, but the hardware is designed with huge buffering to keep those requirements mostly away from PC software. Perhaps running tests can be largely isolated like that, so that hard real time requirements don't affect your ability to use Python in parts of the system that don't have any such hard RT requirements. To see what your options are going to be, I think you will have to get a very clear understanding of what's what timing wise. You should be able to identify every parallel thread of activity in your whole system, including hardware, software, and human activity, and be able to draw parallel time lines across the page for all of them and mark events and draw the triggering/dependency arrows and crosshatched tolerance areas, like the chip guys do. Obviously, you will have different things applying during overnight test runs, vs. whatever interactive monitoring and control modes you may have, vs. data archiving vs. report generation vs. offline script editing and verifying, etc. etc. The key is to identify all the elements affecting critical operation, and get the irrelevancies sidelined. If you have legacy custom hardware designed by people with separate money and scheduling concerns from the software people, you may have legacy software that is doing stuff that really should have been done in hardware, and to tighter timing constraints than necessary (e.g., someone forgot to latch a status signal so it can be read a little longer after the interrupt? What determines how long a board reset line is held?) Things like that should show up in a detailed analysis. Once you know what your critical time constraints are, you can select an OS environment that can handle it. BTW, a dumb polling loop in a DOS program with a dedicated machine is hard to beat, because CPUs are so fast nowadays. The gray area where an interrupt context switch costs about the same as a full polling loop has contracted to a very narrow time range. I'm guessing that a simple loop (or some state machine version that chops the spaghetti in a little more organized fashion) is at the bottom of your DOS test running environment, with interrupts doing minimal critical stuff and setting state that can be polled. I can't believe that a large percentage of that 3/4 million lines of code are concerned with time- critical stuff (unless it's huge data tables for sequencing out timed signal patterns or parsing incoming ones, but data ought to be easy to port). So what do the timing diagrams show about what parts are involved and what parts can be factored out? And which parts cause the compilation problems in migrating to a newer compiler? Do you have hard coded assembly looking at data strucures that change for newer support libraries. Is it easy to identify where the problems are, or (shudder) are there such potential unsafe/unportable-design traps all over? Have you considered an embedded SBC-based controller pod to do the critical timing stuff, and communicating with it with firewire or usb or fast ethernet or whatever to meet bandwidth/qos requirements (which are ... ?!)? A pod with a well-supported PC interface would let you run human interface stuff from laptops or PCs on the bench or whatever, and presumably let you use Python a lot without too many worries (not saying zero ;-). This could be totally blue-sky or not, depending on your situation, people, budgets, market, etc. An interesting site re embedded linux products and software is http://www.linuxdevices.com/ >As background, the app began 10-12 years ago as a simple thing, then as time went on, >became larger and larger as more capabilty was added. Concurrantly, the products under >test became faster, more complicated, etc. We're now to the point that maintenance is >almost a full time job, we're out of memory (lots of page swapping/overlays), speed is an I presume you are swapping/overlaying from files in a RAM disk file system in extended memory? But, yuck anyhow. >issue (we really need an RTOS....events of interest are sub-millisecond now), background >sequencers are at their limits (threads would be nice), on and on. Plus it locks up a lot How many parallel state sequences are you managing? (comes back to the timing diagrams). >these days, which is not good when trying to run a two day test suite over the weekend. > >Soooo what is the new tool to look like? Which platform/OS is the "right" one? Which Maybe it's not a matter of "*the* tool" and "*the* platform" -- i.e., maybe it's a few connected systems each doing what they're best at. >script language would provide the testers with what they need? Having to compile scripts, >if it were C or C++, doesn't seem like a good idea, and not very newbie friendly. Perl, >while powerful,is a bit obtuse. TCL is a bit limited, although named pipes are handy. >Plus, "bread-boarding" quickie tests from the command line would be awkward at best. How Since you are contemplating what language to use to express tests in, have you looked at what standards there are? I.e., I think there are proprietary test languages, and you have something going now that apparently does the job, and there are programming languages, Python being the premier choice, and there may be something else. E.g., have you looked at SMIL? It's used to specify the parallel timed activity required for multimedia using XML syntax, which leverages a bunch of available tools and docs and programmer familiarity. Would your current scripting language be easy to translate to/from other representations? For SMIL, see http://www.w3.org/AudioVideo In a way, preparing and running real time tests would seem to have a lot of parallels with preparing and running a multimedia show. There are disparate media and devices to control in a tightly coordinated fashion, and there are offline editing activites that have no real time demands at all, and others where glitches and dropouts are acceptable albeit annoying. >best to implement a user GUI, and still maintain a command line interface? We're in the >exploration mode, as it were, to answer some of these questions. > I still get too much of a monolith sensation. I can't believe there aren't separate activities best handled according to their separate natures and requirements. >After a lot of reading and web searching, we discovered Python. I'd done some tcl/tk, and >while it was fun, didn't seem to be a suitable script language for inexperienced test >people. But Python does. I've been writing routines in Python, just to get a feel for the >difficulty in implementing some "bread and butter" functions. Guess what...I was amazed at >how easy it was to perform rather complicated encoding schemes in Python...1-2 pages of >code... as compared to doing it in C, which takes 3-6 pages of code. As another "test", I >also wrote a Python routine to parse test log files (big, and lots of them, scattered in >different directories...thanks, glob), and make a formatted CSV file. Then hand it off to >Access for report generation. Piece of cake...gotta love them REs...:) That's why I'm a >convert. Then I wondered about IO port access....not much mention of that in the Python >docs...sockets, yes....direct control of the UARTs, no. But thanks to Mark Hammond and >Andy Robinson's book re Win32 API...that looks do-able with no particular tricks. > >Then the thought occurs....will we be forced to write some things in C/C++? ISRs? RTOS >interface? Driving the custom cards? Timers? I don't know, but it's possible there will be >some tasks which will benefit from extending Python. If so, what's involved? How do you do >that...exactly? This is why I posted the request for help/info to this great newsgroup. I >need to figure out the process of extending Python...if it's needed. > >To end my rambling...the answer to the driver question above has answered itself, I think. >Why would I want to port a 16-bit DOS module to NT/2K/Linux, as is? Thanks to the <~OT> OTOH, I was surprised how good the DOS emulation under windows is if your DOS program does everything according to MS rules (i.e., you don't set interrupt vectors in low memory directly: you use BIOS system calls, etc.) I ran across an old DOS program I had written in MASM 6.11 and it used BIOS interrupts for i/o, stole several interrupt vectors and processed interrupts itself, acccessed text mode video card memory directly to do a text quasi-GUI with pop-up windows and navigation through various input slots etc., and also spawned another program and captured results and *all* those ancient interfaces worked when I just double click started it with windows explorer. I could hardly believe it. The only thing was the DOS console window was a little squashed top to bottom compared to hardware text mode, but all the colors and popups with their drop shadows and everything worked. The cursor blinked and moved properly. Everything. I'm not saying your your app would run as is under NT, but it would be interesting to see what it would do with a hella fast processor and the right .pif parameters. I wouldn't waste a lot of time on it tho ;-) Of course for my app there was no tight timing to worry about, and what was going on behind virtualized interrupts and video card memory access being translated to effects in an NT console window must have involved a *lot* of cycles. But I was impressed, say what you will about MS. Of course, I read that you could *boot* a foreign floppy on a virtual machine under OS/2 control and have it execute in a virtual environment. I wonder if you could boot linux ;-) >discussion on this helpful newsgroup..I don't think I do. But I still need to understand >the process of adding Python modules, when to use DLLs if it makes sense, how to expose >them to Python, how to use them, etc. I need the "process"...I can figure out the code, I >hope...:) > There is good reading at http://www.python.org/doc/current/ext/ext.html and http://www.python.org/doc/current/api/api.html Or if you have MSVC++6.x and want to run an example real quick, download the 2.2.2 sources and follow directions in D:\Python-2.2.2\PC\example_nt\readme.txt (your path may vary). For 2.2.2 they did a really nice job of setting up workspace and project files for everything. (Attaboys to all involved!) You can take a C/C++ program and link in the interpreter and have it do python things under C/C++ control, or you can run the interpreter and have it access C/C++ code in custom extension modules, or you can do stuff where each environment can access things defined in the other both ways. You have a lot of options. But it sounds to me like your critical question is going to be timing, and factoring the system to separate out the critical parts. BTW, if you want to do things with tight timing on windows, I think you will want to look into how multimedia is supported by the OS. I haven't done any MM to talk about, but maybe the game people can advise you. >(Now, if I can just find a good COM book per Alex's suggestions.....) > A lot to think about. Good luck ;-) Regards, Bengt Richter From andrew.gregory at npl.co.uk Thu Nov 7 10:52:44 2002 From: andrew.gregory at npl.co.uk (Andrew Gregory) Date: 7 Nov 2002 07:52:44 -0800 Subject: SWIG /Python problem Message-ID: <2830c89c.0211070752.3e37ca43@posting.google.com> I've just upgraded from SWIG 1.3.11 to 1.3.16. I tested it by re-building an already working Python DLL (using Borland 5.5 C/C++ compiler). On importing it I got the error message: _PyImport_FixupExtension Examining it I found that an extra underscore had appeared in the wrapper file. Previously (1.3.11): /* -------- TYPES TABLE (END) -------- */ #define SWIG_init initpysimple #define SWIG_name "pysimple" Now (1.3.16): /* -------- TYPES TABLE (END) -------- */ /*----------------------------------------------- @(target):= _pysimple.so ------------------------------------------------*/ #define SWIG_init init_pysimple #define SWIG_name "_pysimple" The .def file now looks like this LIBRARY PYSIMPLE EXPORTS initpysimple = _init_pysimple DESCRIPTION 'Simple Python DLL' EXETYPE WINDOWS CODE MOVEABLE DATA MOVEABLE MULTIPLE HEAPSIZE 1024 How do I fix this? Andrew. From imbosol at vt.edu Fri Nov 15 16:20:18 2002 From: imbosol at vt.edu (Carl Banks) Date: Fri, 15 Nov 2002 16:20:18 -0500 Subject: A really bad idea. References: <3DD55D20.4030000@dittmar.net> Message-ID: Daniel Dittmar wrote: >> But these are your *opinions*. > > No. These are criteria (or whatever the plural of criterion is), > although of course there isn't a strict line between 'readable' and 'not > readable'. These are criteria not everyone considers important. To me, ability to search for something has nothing to do with its readability. > Most Python programmers will agree that putting something > into a library is generally a better choice than inventing a new syntax. Usually this is true, if it is something that a library function is capable of. There are a few things in Python that have their own syntax where a library function will do (print, exec), but not many. However, list comprehensions have their own syntax because it's impossibe to do them with a function. This was not a case of someone saying, "we could do this as a function, but it's so important that we have to define a new syntax for it." > Where some disagree is if building a list is so common that a new syntax > makes the code actually more readable because the intentions are more > explicit. Some might argue that list comprehensions are not useful enough or too unsightly to justify adding complexity to the language, but no correct thinker would argue that it should have been a function instead of a new syntax. -- CARL BANKS From ledruker at rogers.com Sun Nov 24 12:56:28 2002 From: ledruker at rogers.com (Ludmila Druker) Date: Sun, 24 Nov 2002 17:56:28 GMT Subject: a % b == b when a is a very small negative number References: Message-ID: "Lee Harr" wrote in message news:uu1uocd4db4be5 at corp.supernews.com... > > I have some code which is storing the direction an object > is moving, and I want to keep that value: 0 <= direction < 2*PI ... > This works fine until direction is some very very small negative number, > like -0.1e-16. ... > Is this not a proper use of the % operator? > Should not a % b always be less than b? Let b > 0. The operation a%b must result in 0 <= x < b. It can be imagined as a snippet x = a while x >= b: x -= b # b=2*pi while x < 0.0: x += b # your case The comparison of x with 0.0 has no problem. The addition of 2*pi for small number results to 2*pi. Use: if a+2*math.pi == 2*math.pi: print '==' else: print '<>' as a test. So, you have what you want. ED From claird at lairds.com Fri Nov 8 16:46:23 2002 From: claird at lairds.com (Cameron Laird) Date: Fri, 08 Nov 2002 21:46:23 -0000 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <20021108.121940.201305624.9010@cybermesa.com> <20021108.135935.824272813.9010@cybermesa.com> Message-ID: In article <20021108.135935.824272813.9010 at cybermesa.com>, Jay O'Connor wrote: . . . >No, I'm making the point that TCL is syntactically weaker at expressing >complex structures and this is a qualitative difference between the two >languages > >Expanding beyond just getting a single value from a multidimensional list >is what happens when you start throwing in lrange for slicing and other >ways of unwrapping the structure. TCL's approach of using 'functionName >$var1 var2' leads quite easily and naturally to such 'monstrosities' as a >natural consequence of the stucture of the language. When you start >throwing in heterogenous structures, especially dealing with nested >arrays (dictionaries) , etc..the syntactical shortcut doesn't scale very >well to dealing with complex data. (incidentally, your example does not >do the same thing. > >set l1 "1 2 3" >set l2 "4 5 6" >set l3 [list $l1 $l2] >set x [lindex [lindex $l3 1] 1] >puts $x > >results in '5' > >using 'set x(1,1) >results in an error Yes and no. Tcl is awful for structuring data complexly in analogy to C. It's at least medi- ocre, though, at handling complex data in its own idioms. Yes, I fully understand that "set x(1,1)" above gives an exception. I'm saying that all the well-crafted systems for managing matrices in Tcl do NOT just make them as nested lists. One possibility for a nicely-engineered Tcl matrix handler is to refer to the "upper left" element as "x(1,1)". I'm sorry that your co-workers imposed such an unaesthetic misuse of Tcl as you describe on you. has more on the subject. . [Jay and Cameron talk past each other more] . . -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From aleax at aleax.it Fri Nov 15 10:09:16 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 15 Nov 2002 15:09:16 GMT Subject: keyword arguments and ** References: <3dd51831$0$13642$e4fe514c@dreader6.news.xs4all.nl> Message-ID: Boudewijn Rempt wrote: > I feel right silly, but for the life of I don't understand why > the variables I pass to f as named arguments stay remembered: > >>>> def f(fields={}, **args): > ... print fields > ... fields.update(args) > ... print "XXX", fields > ... >>>> f(a=1) > {} > XXX {'a': 1} >>>> f(a=1) > {'a': 1} > XXX {'a': 1} >>>> f(b=1) > {'a': 1} > XXX {'a': 1, 'b': 1} >>>> Usual problem: when an argument (here, fields) has a default value that is mutable, that value is determined ONCE, when the def statement executes -- then that single value stays around (the function object references it), and if you mutate it you get such a "memory effect". Usual fix: >>> def f(fields=None, **args): ... if fields is None: fields = {} ... print fields ... fields.update(args) ... print "XXX", fields Alex From guy at lightwork.co.uk Wed Nov 20 10:04:54 2002 From: guy at lightwork.co.uk (Guy) Date: 20 Nov 2002 07:04:54 -0800 Subject: popen / batchfile / environment variables References: Message-ID: "Achim Domma" wrote in message news:... > Hello, > > I want to write a python script with automaticaly builds a VC.Net solution. > To make VS.Net usable from commandline, I first have to execute a batchfile > which sets the required environment variables. In a Dos-Box I would do > something like this: > > path_to\vcvars32.bat > devenv solution_file.sln /rebuild "Release" > > If I use popen or system to do the same, every call runs in his own > environment, so the changes made by the .bat file do not change the settings > for the second call. > > Any idea how to do that in python? > > regards, > Achim Both the ways described are good, I would proberly go for the last one described by logistix at zworg.com. However you can set enviroment vars in python As shown below : I use something like this. Its then possible to execute a bat file with the enviroment that you have set in python using popen. the below function is only a quick function that I made, It works but might need something smoothing round the edges. ENV_PATH = ["C:\Program Files\Microsoft Visual Studio\Common\msdev98", "C:\Program Files\Microsoft Visual Studio\VC98\BIN", "C:\Program Files\Microsoft Visual TOOLS\WINNT", "C:\Program Files\Microsoft Visual Studio\Common\TOOLS", "C:\WINNT\SYSTEM"] AddToEnvroment("PATH",ENV_PATH,";") # AddToEnviroment - Allows a list of items to be added to an enviroment var like PATH,INCLUDE,LIB. def AddToEnvroment(EnviromentVarName,ValuesList=[],Separator=";"): # Gets the enviroment Var, and splits into a list. TotalEnv ="" try: EnvVarValue=os.environ[EnviromentVarName] except: os.environ[EnviromentVarName]="" EnvVarValue=os.environ[EnviromentVarName] if EnvVarValue != "": EnvVarValue=string.split(EnvVarValue,Separator) for Value in ValuesList: EnvVarValue.append(Value) for Value in EnvVarValue: TotalEnv = TotalEnv + Value + Separator os.environ[EnviromentVarName]=TotalEnv else: for Value in EnvVarValue: TotalEnv = TotalEnv + Value + Separator os.environ[EnviromentVarName]=TotalEnv From LogiplexSoftware at earthlink.net Mon Nov 18 17:42:04 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 18 Nov 2002 14:42:04 -0800 Subject: Hmm... An idea: if a,b==c,d: In-Reply-To: References: Message-ID: <1037659323.27904.226.camel@software1.logiplex.internal> On Mon, 2002-11-18 at 13:49, Richard Dillingham wrote: > Kind of like we have multiple assignments in a line (oldx,oldy=x,y), what do > you think of the ability to have multiple tests in an if statement with only > one == or >=. > > This would mean that lines like the following: > if posx>=coords[0] and posy>=coords[1] and posx<=coords[2] and > posy<=coords[3]: > > Could be rewritten like so: > if posx,posy>=coords[0],coords[1] and posx,posy<=coords[2],coords[3] One problem is that this syntax already has a meaning (although it doesn't appear to have the meaning you seem to intend): Python 2.2.1 (#1, Aug 30 2002, 12:15:30) [GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> x, y = 2, 1 >>> x1, y1 = 1, 2 >>> (x, y) > (x1, y1) 1 >>> The other, greater problem is that you are using a *specific* application of tuples (coordinates) and in general the meaning you desire can't be applied to tuples, so a language change is undesirable. Consider that when interpreting tuples as coordinates, (1,2) == (2,1) is probably true since the magnitudes of the vectors are equal (this would be a common interpretation for comparing coordinates), but would probably be considered false for most other applications of tuples. You'll probably be better off creating a Coordinate() class that has the meaning you are looking for, or perhaps search Google to see if someone else already has. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 -------------- 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 arasila at pcu.helsinki.fi.invalid Wed Nov 20 10:27:58 2002 From: arasila at pcu.helsinki.fi.invalid (Antti Rasila) Date: 20 Nov 2002 15:27:58 GMT Subject: Teaching numerics with Python Message-ID: We have a special course on scientific computing at the math. department of the University of Helsinki. In the past the course has been based on the book and software bundle Numerical Recipes in C/C++, and our experience is that this software worked very well for our purposes. Gnuplot is used for graphing purposes. In 2002, we used the C++ version for the first time and also offered to the students the option of using the free GNU Scientific Library GSL instead of the commercial Numerical Recipes. For our purposes, it is important that the course material is available to the students with minor or no cost and also that everything works (without any major extra hacks) with the most popular computing platforms platforms including at least GNU/Linux + GCC and MS Windows/Visual Studio. It seems that the trend in scientific computing is introduction of high level scripting languages as front end to the more efficient Fortran/C/etc. subprogram libraries. For some time we have been studying the possibility of using Python scripting in this purpose. We think that with this approach we might obtain the following benefits: 1) Writing basic applications could become simpler, like in MATLAB, while still having flexibility and performance features of classical programming language like C. 2) Version control and preparation of learning material (such a solutions to weekly home work assignments, lecture handouts) is an iterative process where sometimes 5-10 iterations may be needed. To simplify these tasks, which include several mechanical steps, one would like to use Makefile and CVS like functionality. An example of this kind of application of Python scripting is the Portage package manager system of Gentoo Linux distribution. The functionality could include automatic installation and compiling of the libraries, exercises solutions and also keeping track on updates of various source files. 3) Integration with CGI/Web based environment could become much easier. We have already implemented this kind on applications, i.e. Web-runnable CGI demo applications with Python wrapper. 4) Building graphical front ends and interfaces to the applications with Tkinter would become much easier than in plain C/C++. This becomes more important in future, when even fewer students are familiar with using command line interface. Our experience in this matter is very limited. So, we would like to ask, if 1) ..someone has experience on this kind of usage of Python numerical mathematics? We would be happy to hear from your experiences. 2) ..if some course material and ready program files are available, which we could use as building blocks of our course? 3) ..you have seen a book such as Scientific Computing with Python Links: Spring 2002 course homepage: http://www.math.helsinki.fi/~arasila/nrc02/ From mgilfix at eecs.tufts.edu Thu Nov 28 14:26:44 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Thu, 28 Nov 2002 14:26:44 -0500 Subject: How to install with -O? Message-ID: <20021128192644.GA19109@eecs.tufts.edu> Hi all. I've been using __debug__ in my python programs with the hope to byte-compile my programs with -O on install and remove the __debug__ code. However, I haven't figured out quite how to do this with distutils, and some searching through the documentation didn't reveal anything. Has anyone solved this problem? -- Mike -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From wks000 at t-online.de Sun Nov 10 15:24:19 2002 From: wks000 at t-online.de (Wolfgang Strobl) Date: Sun, 10 Nov 2002 21:24:19 +0100 Subject: NEWBIE: Extending Python with C References: <3dcc7e2c.3568851@news.earthlink.net> <72lssu89n13e0smobngvb95f8ggtlv65n9@4ax.com> Message-ID: Alex Martelli : >Wolfgang Strobl wrote: > >> Alex Martelli : >> >>>This is more or less the end of the line in terms of what >>>os.popen can offer -- due to buffering and suchlike there's >>>no practical way for python to drive BOTH standard input >>>and standard-output of another external program. >> >> Well, the following snippet, driving nslookup.exe on W2K works for me: > >So nslookup.exe on W2K does no more than line-buffering on its output, and >reads its input repeatedly, too. Bully for it (for the sole purpose of >controlling both its stdin and stdout with pipes). Norm (engsol at teleport.com) wrote "I'm using Python 222 on NT". Using nslookup (for example) through a pair of pipes works quite well on NT. One should'nt dismiss the possibility of controlling an external line mode program trough pipes so quickly, IMHO. That's my point. >Most programs aren't as >skittish with their stdin and stdout once they determine they aren't >terminals. It comes somewhat of a surprise to me that the concept of byte streams, pipes and filters works better on NT than on Linux, in this specific example. -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From duncan at rcp.co.uk Thu Nov 28 08:58:47 2002 From: duncan at rcp.co.uk (Duncan Booth) Date: Thu, 28 Nov 2002 13:58:47 +0000 (UTC) Subject: what does is ? References: <3de4a6dd$0$86531$ba620e4c@news.skynet.be> <3DE4B96D.1060808@Linux.ie> Message-ID: Padraig Brady wrote in news:3DE4B96D.1060808 at Linux.ie: > Well why does the following happen on 2.2? > Is Python being clever about merging variables? > > s1="123" > s2=s1[:] > s1 is s2 #true? Slicing a list that way makes a copy, but strings are immutable so the slice operator doesn't bother copying it. Tuples work the same way as strings here: >>> t1 = 1, 2, 3 >>> t2 = t1[:] >>> t1 is t2 1 >>> Without using id() or the is operator, you cannot tell whether or not s1/t1 were copied, so it is a small but useful optimisation to not copy it. Note that the same thing happens if you use copy: >>> from copy import copy, deepcopy >>> copy(t1) is t1 1 >>> deepcopy(t1) is t1 1 But if the tuple contains mutable objects then it can be copied: >>> t3 = (1, [], 3) >>> copy(t3) is t3 1 >>> deepcopy(t3) is t3 0 In general Python will merge some constant strings, and small integers. Don't use 'is' if this matters to you. From wlfraed at ix.netcom.com Fri Nov 22 20:18:01 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 22 Nov 2002 17:18:01 -0800 Subject: Proposal: min(None, x) and max(None, x) return x References: Message-ID: <90lmra.5g4.ln@beastie.ix.netcom.com> Eric Brunel fed this fish to the penguins on Friday 22 November 2002 06:25 am: > > xMax = None > for -whatever-: > -big calculation leading to a value of x- > if xMax is None: > xMax = x > else: > xMax = max(x, xMax) > Well, slightly shorter visually: xMax = None for -whatever-: -big calculation leading to a value of x- if xMax is None: xMax = x xMax = max(x, xMax) -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From grante at visi.com Wed Nov 20 10:24:40 2002 From: grante at visi.com (Grant Edwards) Date: 20 Nov 2002 15:24:40 GMT Subject: Bug in Win32file WaitCommEvent ??? References: <3ddaa58d$0$4459$a1866201@newsreader.visi.com> Message-ID: <3ddba938$0$4464$a1866201@newsreader.visi.com> In article , Bengt Richter wrote: >>> Sounds like the mask location is safe if you don't call >>> GetOverlappedResult?? I've added a call to GetOverlappedResult to my Python app, it hasn't caused problems (nor does it do anything useful). >>I sure don't know. I've found examples that don't call GetOverlappedResult >>and they expect a "delayed" write to *lpfdwEvtMask happen. >> > """ > If the lpo parameter is NULL or the hCommDev handle was opened without specifying > the FILE_FLAG_OVERLAPPED flag, WaitCommEvent does not return until one of the specified > events or an error occurs. > """ > > Did the examples use the FILE_FLAG_OVERLAPPED flag and provide > the lpo parameter for sure? Yes. > Otherwise there is apparently an implicit wait. > >>And I thought it impossible for me to grow to hate Windows even more... > > Well, try to make your solutions portable ;-) -- Grant Edwards grante Yow! Not SENSUOUS... only at "FROLICSOME"... and in visi.com need of DENTAL WORK... in PAIN!!! From malik_martin at hotmail.com Wed Nov 27 06:48:56 2002 From: malik_martin at hotmail.com (malik m) Date: Wed, 27 Nov 2002 11:48:56 GMT Subject: do you guys help newbies?? References: Message-ID: hi yea i messed up here's the code sorry about the html too i was using it through hotmail while i learnd and still am learning how to use newsgroups.... #chapter 3 test control structures 3.3 print "hello, this program will tell me how many miles per gallon your car drives by the \n amount of miles entered by the user along with the size of his/her tank." #initialize variables totalMilesDriven = 0 #total miles driven totalGallonsPerTank = 0 #total gallons per tank counter = 0 #bogus counter #processing phase gallonsPerTank = raw_input("Enter how many gallons your tank holds, -1 to end:") gallonsPerTank = int(gallonsPerTank) milesDriven = raw_input("enter how many miles driven, -1 to end:") milesDriven = int(milesDriven) while gallonsPerTank or milesDriven != -1: averagea = milesDriven / gallonsPerTank counter = counter + 1 print "your miles per gallon are", averagea totalMilesDriven = totalMilesDriven + milesDriven totalGallonsPerTank = totalGallonsPerTank + gallonsPerTank gallonsPerTank = raw_input("Enter how many gallons your tank holds, -1 to end:") milesDriven = raw_input("enter how many miles driven, -1 to end:") #termination phase if counter != 0: average = float( totalMilesDriven ) / float( totalGallonsPerTank ) print "The total miles per gallon is", average else: print "No data entered" From chris.gonnerman at newcenturycomputers.net Wed Nov 20 23:21:10 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Wed, 20 Nov 2002 22:21:10 -0600 Subject: SMTP Relaying References: <3DDC02A5.2090003@yahoo.com> Message-ID: <002701c29115$6c915600$ba01010a@local> ----- Original Message ----- From: "greenbeard" > Hello all, > > I am having trouble getting some mail through to certain addresses. I > get an SMTPRecipientsRefused {to_address, 550 '5.7.1 > ...relaying denied. > > So I am pretty sure that it is due to the target address blocking the > relay - my machine -> my SMTP on another machine -> corporate SMTP - as > most non-corporate address have no problem receiving. So think I am > hitting the RFC2505 wall here but I cant quite seem to figure out what > fields or combination of values to load to let the mail arrive ok. > > All advice appreciated. I hope you aren't SPAMMING 'cause then we have to send the DOGS after you... SERIOUSLY, if the to_address isn't on the server you are connecting to, and they aren't enabled to relay to that domain, then nothing you can do will change that. One of the following: -- You are connecting to the target mailserver directly: you must have screwed up the to_address. -- You are using your ISP's relay: It's mis- configured? Dunno. Maybe they don't like your face :-) -- You are using a third party relay without permission: SPAMMER, GET THEE BEHIND ME! I really hope it's the first. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From rmunn at pobox.com Wed Nov 27 17:34:37 2002 From: rmunn at pobox.com (Robin Munn) Date: Wed, 27 Nov 2002 22:34:37 GMT Subject: With what module can Python handel *.tar.gz file? References: Message-ID: Wang Hanbo wrote: [snip 205 lines] Wow, Outlook Express (or was it Outlook?) really produces some *ugly* HTML. 205 lines for a seven-line message? What a waste of bandwidth. Anyway, please turn off HTML emails in your mail client before asking questions on this newsgroup. Send in Plain Text only -- any other method wastes a lot of bandwidth, plus it looks just plain ugly. Or better yet: ditch Outlook / Outlook Express and get a better mail/news client. (Is mutt available on Windows? What about slrn?) I would have been happy to answer your question, but I didn't want to wade through 200+ lines of HTML to do so. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From zimmermann.edv at t-online.de Wed Nov 20 16:45:37 2002 From: zimmermann.edv at t-online.de (Bernd Zimmermann) Date: Wed, 20 Nov 2002 22:45:37 +0100 Subject: ctypes and delphi dll References: Message-ID: Meanwhile I got it .... providing the procedures arguments in inverse sequence lets the bell ring! I am happy with ctypes ! Bernd From wolfoxbr at hotmail.com Sun Nov 24 00:27:17 2002 From: wolfoxbr at hotmail.com (Roberto Amorim) Date: 23 Nov 2002 21:27:17 -0800 Subject: urllib slow on FreeBSD 4.7? sockets too References: <3ddd8419_3@omega.dimensional.com> <82c04a2.0211220437.3181e213@posting.google.com> <3ddf3f76$1_1@omega.dimensional.com> Message-ID: <82c04a2.0211232127.1a8a2fe1@posting.google.com> > FreeBSD doesn't come with wget, though it's easy to install. fetch, as used > by the ports collection, is functionally equivalent. And yes, it's normal... > > /usr/bin/time fetch http://localhost/4MBfile > Receiving 4MBfile (4343332 bytes): 100% > 4343332 bytes transferred in 0.7 seconds (6.20 MBps) > 0.79 real 0.01 user 0.06 sys > > Off to try some of the other suggestions... Well, since wget is normal, we can rule out TCP/IP settings on FreeBSD. It is probably related to the way Python handles sockets under it (on the C source level). Perhaps it's setting sockets as Linux ones, when they are BSD sockets? I'll try to take a look on the code to see if I find something like that (or perhaps Zope's source code for performance tips). From charles at pentek.com Fri Nov 8 11:33:48 2002 From: charles at pentek.com (Charles Krug) Date: Fri, 08 Nov 2002 16:33:48 GMT Subject: Ethics in abstract disciplines (was: Making a better textbook (was Re: The Deitel book)) References: <87b0ada6.0211011453.1df4d216@posting.google.com> <815e8a38.0211071038.208c7577@posting.google.com> <3DCBD7DE.E132BD77@hotmail.com> Message-ID: On Fri, 08 Nov 2002 15:27:26 +0000, Alan Kennedy wrote: > Cameron Laird wrote: > >> I don't understand this description. It >> certainly interests me, though. I take >> it that "CS" here means the kind of soft- >> ware engineering and technology that's >> typicall taught in college. And you're >> seriously saying that sections on ethics >> appeared in half of your classes? Can >> you give a few examples of such content? > > When I was studying for Computer Science degree, in each of the 4 years > we had a term (semester) of ethics classes, 1 hour per week. These were > usually given by the same lecturers who gave courses in more technical > Comp Sci matters. > > The one that really sticks out in my mind is the following question that > was posed to us in 2nd year (age ~20). > (snip) > We were posed the following scenario: "You are asked to develop a > software simulation of the spread of a chemical warfare agent. The > purpose of the simulation is to maximise the death toll from the use of > that agent". > That's far more interesting than our ethics unit, which dealt exclusively with the Usual Suspects of copy protection and file access. Were you in the real world outside of the Chemwar industry, the same question would be coached in terms of fertilizer dispersal. Your employer would get the same information, but would avoid cluttering up the question with folks emotions. The same graph theory that solves networking problems also solves indistrial logistics problems, and military transport problems. From gustav at morpheus.demon.co.uk Sat Nov 2 11:41:33 2002 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: Sat, 02 Nov 2002 16:41:33 +0000 Subject: "Universal Gateway" References: Message-ID: <1y63gc02.fsf@morpheus.demon.co.uk> Mark Hammond writes: > So it seems there will be 2 universal strategies: > * If you want to implement one or 2 interfaces (eg, the Outlook addin, > where you only need to implement a handful of interfaces out of the > hundreds available) - in this case you stick with the > "RegisterInterfaces()" type calls in the existing examples. > > * You want to implement *all* interfaces in a TLB. In this case you > add a couple of extra annotations to your server class, and magic > happens Am I right in reading into this, the fact that the universal gateway is only for *implementing* general vtable interfaces (as one poster mentioned)? If so, is there a way to *call* an arbitrary interface? (Actually, I imagine that this should be possible using calldll plus a reasonable amount of arcane pointer arithmetic, but it sounds like it could be a bit messy and error prone...) Paul. -- This signature intentionally left blank From alanmk at hotmail.com Tue Nov 19 06:50:41 2002 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 19 Nov 2002 11:50:41 +0000 Subject: My (late) beef with Simple Generator syntax (PEP 255) References: <3DD3A563.B781BE58@hotmail.com> <3DD850D3.8030207@something.invalid> Message-ID: <3DDA2591.958B9EA@hotmail.com> Alan wrote: >> class emptyGenerator: >> def __init__(self): >> raise StopIteration() >> >> def emptyGen(): >> yield emptyGenerator() Greg wrote: > This is quite nice, but it's misnamed slightly. > Something called xxxGenerator should be returning > an iterator when you call it, but this isn't. > It would be nicer if it were called Nothing. > Then you could write > > def emptyGen(): > yield Nothing() While I agree that it was badly named, on thinking further about it, I'm not sure that "nothing" (i.e. "no thing") is the right name. The right name is "no thingS". So that would be class noThings: def __init__(self): raise StopIteration() def emptyGen: yield noThings() hair-splitting-ly yrs :-) -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From grante at visi.com Tue Nov 12 17:14:43 2002 From: grante at visi.com (Grant Edwards) Date: 12 Nov 2002 22:14:43 GMT Subject: pitfall for your amusement References: Message-ID: <3dd17d53$0$4464$a1866201@newsreader.visi.com> In article , Brian Quinlan wrote: > I don't like the augmented operations because, depending on the object, > the operation may or may not be done in-place. > > I think that it is better to be explicit and use assignment or method > call. That way you know what you are getting. If it matters which you get, then that's probably a good idea. I use it quite a bit, and I don't think I don't remember a case where it has mattered. -- Grant Edwards grante Yow! I will establish at the first SHOPPING MALL in visi.com NUTLEY, New Jersey... From rpm at wag.caltech.edu Wed Nov 27 12:58:44 2002 From: rpm at wag.caltech.edu (Richard Muller) Date: Wed, 27 Nov 2002 09:58:44 -0800 Subject: More pythonic way to change an element of a tuple? Message-ID: I frequently have to change a single element of a tuple, and I wind up doing something like this: tmp = list(data_in_tuple) tmp[item] += 1 data_in_tuple = tuple(tmp) Is there a more beautiful way of doing this? Seems a bit awkward. Thanks in advance, Rick From aleax at aleax.it Sun Nov 10 10:39:01 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 10 Nov 2002 15:39:01 GMT Subject: NEWBIE: Extending Python with C References: <3dcc7e2c.3568851@news.earthlink.net> <72lssu89n13e0smobngvb95f8ggtlv65n9@4ax.com> Message-ID: Wolfgang Strobl wrote: > Alex Martelli : > >>This is more or less the end of the line in terms of what >>os.popen can offer -- due to buffering and suchlike there's >>no practical way for python to drive BOTH standard input >>and standard-output of another external program. > > Well, the following snippet, driving nslookup.exe on W2K works for me: So nslookup.exe on W2K does no more than line-buffering on its output, and reads its input repeatedly, too. Bully for it (for the sole purpose of controlling both its stdin and stdout with pipes). Most programs aren't as skittish with their stdin and stdout once they determine they aren't terminals. On Linux, for example, running the same script you've posted gives: (--- Note: nslookup is deprecated and may be removed from future releases. Consider using the `dig' or `host' programs instead. Run nslookup with the `-sil[ent]' option to prevent this message from appearing. > www.python.org and here it hangs forever -- I think nslookup is writing the prompt to standard-error in this case, reserving stdout for output, e.g.: [alex at lancelot examples3]$ echo www.python.org | nslookup 2>/dev/null Server: 192.168.0.12 Address: 192.168.0.12#53 www.python.org canonical name = fang.python.org. Name: fang.python.org Address: 194.109.137.226 [alex at lancelot examples3]$ Alex From cnetzer at mail.arc.nasa.gov Fri Nov 22 18:47:02 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Fri, 22 Nov 2002 15:47:02 -0800 Subject: Iteration of strings In-Reply-To: References: Message-ID: <200211222347.PAA21872@mail.arc.nasa.gov> On Friday 22 November 2002 14:58, Bjarke Dahl Ebert wrote: > When writing small scripts in Python, I often make the same error: > > Some function expects a list of strings, and does something like > for elem in thestringlist: ... > > What do you think? Use an assertion in your function (or script): def dont_allow_string_argument( s ): assert not isinstance( s, type("") ) -- Bay Area Python Interest Group - http://www.baypiggies.net/ Chad Netzer cnetzer at mail.arc.nasa.gov From doug.fort at verizon.net Wed Nov 13 16:40:18 2002 From: doug.fort at verizon.net (Doug Fort) Date: Wed, 13 Nov 2002 21:40:18 GMT Subject: Graham's spam filter References: <20021113220949.2daa7540.christophe.delord@free.fr> Message-ID: check out http://spambayes.sourceforge.net/ -- Doug Fort, Programmer http://www.dougfort.net From deltapigz at telocity.com Thu Nov 7 00:30:57 2002 From: deltapigz at telocity.com (Adonis) Date: Thu, 7 Nov 2002 00:30:57 -0500 Subject: Placing Tkinter objects in a dictionary Message-ID: <3dc9fa87$1_4@nopics.sjc> I have a loop creating Tkinter objects (an Entry text box) all with the same name and placing its instance in a dictionary: i.e: for x in range(10): myEntry = Entry(frame) myEntry.grid(row=x, column=0) someDict['%s'%x] = myEntry now I have another function which will modify myEntry: def someFunc(x, data): someDict[str(x)].config(text=data) # here is my error; the config does not work; # no error is raised. any help is greatly appreciated. Adonis From jacek.generowicz at cern.ch Sun Nov 10 07:18:10 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Nov 2002 13:18:10 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <9b8hqa.eo3.ln@beastie.ix.netcom.com> Message-ID: David Eppstein writes: > Lisp is based around singly linked lists while Python uses > vectors (with efficient random access unlike Lisp lists) Sigh. More FUD. Please look at http://www.lispworks.com/reference/HyperSpec/Body/15_.htm It is the chapter of the Hypertext version of the Common Lisp ANSI standard, which describes that which you imply does not exist. (On second thoughts, don't look at it, because once you have, you may well become disappointed with what Python has to offer in terms of arrays.) > and dictionaries. http://www.lispworks.com/reference/HyperSpec/Body/18_.htm (There are also alists and plists which can serve a similar purpose, and may well be more appropriate is some situations.) > They are also not especially similar in programming style, You'll find plenty of people who disagree. From munja at sipa.kav.vest.hr Thu Nov 28 07:03:20 2002 From: munja at sipa.kav.vest.hr (Ivica Munitic) Date: 28 Nov 2002 12:03:20 GMT Subject: Screen Capture Message-ID: Hello guys!! How can I get a screen capture within a python program ? What module should i install ? Tnx! From s13361562 at spammenot.bach.sun.ac.za Sun Nov 3 04:48:23 2002 From: s13361562 at spammenot.bach.sun.ac.za (Hugo van der Merwe) Date: Sun, 03 Nov 2002 11:48:23 +0200 Subject: Python2.1->2.2 broke my thread/signal code? Message-ID: I have some code starting ogg123 in a new thread, I then send signals (SIGTERM. Clearly the code is "wrong", since it didn't survive the 2.1->2.2 upgrade. What should I change? What am I doing wrong? Here is the code, trimmed down significantly to only the relevant part: #!/usr/bin/env python import signal import os import time import thread class player: playerpid = 0 def skip(self): os.kill(self.playerpid, signal.SIGTERM) def stop(self): os.kill(self.playerpid, signal.SIGSTOP) def play(self): pid = os.fork() if pid == 0: signal.signal(signal.SIGTERM, signal.SIG_DFL) os.setpgrp() # not really sure what the effect of this is try: os.execv("/usr/bin/ogg123", ['/usr/bin/ogg123',"/home/music/stow/owned/STEF_BOS/BESTE_VAN_BOS/07-PAPA.ogg"]) except: os._exit(1) else: self.playerpid = pid os.wait() n = player() thread.start_new_thread(n.play,()) # Not using a thraed results in an ogg123 that can be killed with # "kill" from bash. #n.play() time.sleep(5) n.skip() # This does the job when using 2.1, but not when using 2.2 time.sleep(5) Thanks, Hugo van der Merwe From pearu at cens.ioc.ee Fri Nov 22 11:00:41 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Fri, 22 Nov 2002 18:00:41 +0200 (EET) Subject: Proposal: min(None, x) and max(None, x) return x In-Reply-To: Message-ID: On 22 Nov 2002, Andrew Koenig wrote: > Eric> So I told myself: wouldn't it be great if max(None, x) or > Eric> min(None, x) always simply returned x? > > My first thought was that this was an excellent idea. > > Then I thought again. > > Here's the problem: The notion that max(None, x) and min(None, x) > should both return x is one of three desirable properties that cannot > all be true at once. Here are the other two: > > 1) Whenever x < y, min(x, y) is x and max(x, y) is y. > > 2) < is an order relation over all types. > > The desirability of (1) should be obvious. (2) is more subtle, but > it is necessary for it to be possible to sort a vector of heterogenously > typed objects. > > Now, if max(None, x) and min(None, x) both yield x, and (1) is true, > then x > None and x < None must both be true. If max(None, x) and min(None,x) both yield x, then already (1) cannot be true. For example, take x=None in (1). Then min(None, y) is None and max(None, y) is y But this contraticts the assumption that min(None, x) is x. > But then (2) cannot be true. (2) is never true. Hint: complex numbers. Pearu From Oschler at earthlink.net Thu Nov 7 09:15:25 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Thu, 07 Nov 2002 14:15:25 GMT Subject: [Jython] Pass variable or class reference to PythonInterpreter? References: Message-ID: <1Auy9.45044$Lg2.12386430@news2.news.adelphia.net> "Alex Martelli" wrote in message news:qVpy9.1040$XO.51258 at news2.tin.it... > Robert Oschler wrote: > > > Sure, Jython's PythonInterpreter class gives you methods you > can use for this purpose. interp.set("theString", theString) > for example would add an attribute named "theString" to the > inteprreter's local namespace, with its value set to the Java > value theString. *CHANGING* it is obviously out of the question > (strings are immutable in Java *AND* in Python), but THAT > is clearly a completely different issue. > Alex, Re: String == immutable. Sure, but other types and user classes are OK right? At least that's what the tests I ran indicated. I did discover that a the class of a instance variable passed to the python interpreter via the set() method, must be public if it's going to be accessed by the Python Interpreter, otherwise you get a Java illegal access exception when Jython tries to reflect the class. I would have thought private inner classes, 'inner' to the class whose method created the PythonInterpreter insntance, would have been OK but they're not. thx From Patrick.Carabin at SciencesNaturelles.be Tue Nov 5 03:23:51 2002 From: Patrick.Carabin at SciencesNaturelles.be (Patrick Carabin) Date: Tue, 5 Nov 2002 09:23:51 +0100 Subject: How do I reply to an item in the list ? In-Reply-To: References: Message-ID: <02110509235100.01192@pc20_118> When i try to use groups.google.com, i allways get the message : ? Apache Tomcat/4.0.3 - HTTP Status 500 - No Context configured to process this request type Status report message No Context configured to process this request description The server encountered an internal error (No Context configured to process this request) that prevented it from fulfilling this request. ? What can i do to answer a thread, please ? -- Patrick Carabin. Institut Royal des Sciences Naturelles de Belgique http://www.SciencesNaturelles.be/ Koninklijk Belgisch Instituut voor Natuurwetenschappen http://www.NatuurWetenschappen.be/ ?Het geluk is niet op het einde van de weg, het geluk is de weg.? ?Le bonheur n'est pas au bout du chemin, le bonheur est le chemin.? Dala? Lama. From tjreedy at udel.edu Mon Nov 11 17:15:10 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 11 Nov 2002 17:15:10 -0500 Subject: Is python a good choice for this task? References: Message-ID: "Ron Lau" wrote in message news:pan.2002.11.11.20.29.19.704887.2239 at spongebob.corporate.com... > Hi, > > This IS NOT a request for someone to write a program for me. (But I won't > turn it down :) ). The only programming I ever did was FORTRAN >:P , and short shell > scripts. I'm just looking for advice. > > > I have a CFD program that takes a text file as input (Q1.1). I run it on the > command line as: > > phoe Q1.1 > > which outputs the binary file PH.1 > > > I also have a program that gives me a number as the last line of its > output to the terminal with the command > > pointquerey PH.1 TempK 1 1 1 | tail -1 > > > What I do now is compare the output of the line above to the value I want > it to be, then change a parameter in the Q1.1 file, say T1=500.0 > > I would like to write something that would Goal Seek this for me. > (something simple like a newtonian method) > > So I would need a program to.. > -------------------------- > > run the command "phoe Q1.1" > > then run the command "pointquery PH.1 TempK 1 1 1 | tail -1" > > read the output of the above and compare to the desired value. > > calculate a better value of T1. > > replace T1=oldvalue in the file Q1.1 with the calculated value from > above. > > loop back to the beginning... > > ------------------------- > > > My question is, What language is best suited for this? Perl, Python, or > shell scripts? You can run external programs from Python with os.system('command') (check docs for details). You can easily read, modify, and write a file (check out file() and file objects). The goal seeking logic can be programmed in Python as well as anything else. If the other programs take any sort of time at all, the interpreted speed of the Python part will not matter. This type of glue job is one of the things Python was invented for. Good luck. Terry J. Reedy From woodsplitter at rocketmail.com Mon Nov 25 21:49:15 2002 From: woodsplitter at rocketmail.com (David Rushby) Date: 25 Nov 2002 18:49:15 -0800 Subject: stupid Python/database connection References: <4cce07d5.0211250918.5c97a929@posting.google.com> Message-ID: <7876a8ea.0211251849.3541c7fb@posting.google.com> claird at lairds.com (Cameron Laird) wrote in message news:... > Yet another way: if the Interbase and Oracle interfaces don't already con- > form to , > you could upgrade them, or hire someone to do so on your behalf. This is slightly off topic, since the original poster wasn't asking about *specific* Interbase or Oracle interface modules, but here's the URL of an Interbase (and Firebird) interface that conforms to the Python DB API 2.0: http://kinterbasdb.sourceforge.net/ From bhards at bigpond.net.au Thu Nov 21 17:55:20 2002 From: bhards at bigpond.net.au (Brad Hards) Date: Fri, 22 Nov 2002 09:55:20 +1100 Subject: Popular conceit about learning programming languages In-Reply-To: References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <2259b0e2.0211210838.7647301a@posting.google.com> Message-ID: <200211220955.20993.bhards@bigpond.net.au> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I think that this is a good analogy, and I'd like to take it a bit further, with a couple of examples (and there is a Python link in there, look out for it :-) I was fortunate enough to attend Linux Kongress 2002. I did a bit of touring around in Central Europe before the conference, mainly in Germany. It was a real struggle at first (I am mono-lingual). The people spoke very fast, and very few words were familiar. I had a dictionary, and when I wanted to buy something, or ask a question, I would think about the question (in English), translate it to German (very badly), and then try to pronounce the words (very badly). Normally the response I got was "It's OK, I speak English", in English. At Linux Kongress, I happened to win a copy of the Python Cookbook (thanks to O'Reilly). I read a bit of it on the flights back to Australia, and it looked kind-of interesting, although some of it was very confusing. (especially the meaning of * and ** in def(), which I thought were something like pointers, because I do most of my coding in C). I decided that I'd like to learn more, and bought an intro book, and started on the learning path. I coded a useful script for testing my network driver after about a week of playing around and reading, but I certainly wouldn't even consider myself minimally competent at this stage. I am starting to see solutions in terms of dictionaries, but I still don't understand some things, and most of it is "what is the problem, how would I solve this problem (implicitly, in C), now how do I write that in Python" The big thing I don't yet really get is OO. I don't see solutions in terms of classes yet. In the natural language analogy, this is the equivalent of never come across a tonal language (for those not familiar, this is very roughly where the meaning (in a denotational sense, not just a connotational sense) of a sound varies with how it is pronounced - the same sound with a rising frequency might be a verb, while a flat frequency might be a noun). No OO is a big hole, and while I can program using classes (in C++ and Python) a little bit, I don't really "see the solution" in those terms yet. Also, it clearly helps if the language you are trying to learn is close to the language(s) you already know. A lot of C knowledge translates to Python. (like my earlier Pascal, Fortran and Modula-2 translated into C, but Prolog was more helpful when learning LaTeX). German isn't that different to English. By contrast, I went to Hungary for a couple of days, and it was a huge shock. I think that I could have learned enough German to get by in a few months of immersion. I never felt that I had any grip on Hungarian. Hungarian is probably like the Lisp of European languages :-) [Aside: I did formal language aptitude testing when I worked for Defence, which said I could likely keep up on an intensive French, German or Indonesian course; but would be unlikely to be able to keep up on the other courses. This is better than most of my class.] When I got back, I visited a couple of German speaking friends, one of whom came out to Australia without a lot of English. She explained that she knew she had really learned English when she had her first "all in English" dream. I don't dream in Python yet. And I don't think that even a couple of months of very serious work gives you that level of knowledge, natural or programming. Brad - -- http://linux.conf.au. 22-25Jan2003. Perth, Aust. I'm registered. Are you? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE93WRYW6pHgIdAuOMRApsKAJ4s4srcswhCH6fuTU8+so+TBOA1QwCfRT2G aBkdji7WmbetJZz6y2dtoZU= =np0C -----END PGP SIGNATURE----- From trentm at ActiveState.com Fri Nov 15 15:28:09 2002 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 15 Nov 2002 12:28:09 -0800 Subject: redirecting output from spawned processes In-Reply-To: <3dd53e37.86527109@news.genuity.net>; from jef.mangelschots@iname.com on Fri, Nov 15, 2002 at 06:36:04PM +0000 References: <3dd53e37.86527109@news.genuity.net> Message-ID: <20021115122809.E23552@ActiveState.com> [Jef Mangelschots wrote] > How do I redirect the output of 'someapp' to the file log_file ? > > > log_file = 'c:\output.log' > > os.spawnv(os.P_WAIT, 'some_app', 'p1', 'p2') A couple of ways: os.system("someapp > %s" % log_file) or: # get the output fout = os.popen(someapp) output = fout.read() fout.close() # then write it to your file flog = open(log_file, 'w') flog.write(output) flog.close() I think you want the former though. To redirect stderr as well you need to do a little bit more work: os.system("someapp > %s 2>&1" % log_file) or: ... look at os.popen3() Cheers, Trent -- Trent Mick TrentM at ActiveState.com From skip at pobox.com Tue Nov 5 13:54:09 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 5 Nov 2002 12:54:09 -0600 Subject: How does Python handle probing to see if a file already exists? In-Reply-To: References: Message-ID: <15816.5073.986815.981549@montanaro.dyndns.org> gustavo> Others have talked about the goodness of using try/except, I'll gustavo> say to use os.access(), which is precisely for what you're gustavo> asking, if you can read or write a file. os.access() is almost never what you want. On Unix systems, if you are su'd to another user it tests permissions using the wrong user (real instead of effective). Just try the operation and recover if it throws an exception. -- Skip Montanaro - skip at pobox.com http://www.mojam.com/ http://www.musi-cal.com/ From john.abel at pa.press.net Fri Nov 15 10:01:46 2002 From: john.abel at pa.press.net (John Abel) Date: Fri, 15 Nov 2002 15:01:46 +0000 Subject: Calling A Deconstructor References: Message-ID: <3DD50C5A.3090800@pa.press.net> Thanks very much that. Explains a lot. A lot of the docs I've read, mention the __init__, but not much on the __del__. Thanks again. John sismex01 at hebmex.com wrote: >>From: John Abel [mailto:john.abel at pa.press.net] >>Sent: Friday, November 15, 2002 7:47 AM >> >>Hi, >> >>I have a class, with an __init__, and a main function, basically a >>wrapper around smtplib. I wish to add a __del__ to the class. Two >>questions: Do I need to do it this way? If so, how do I can >>close the instance, so the __del__ is called? The script will be >>permanently resident, so I wanted to make sure that I didn't have >>various connections open to the smtp server. >> >>Thanks >> >>John >> >> >> > >Hmm... interesting conundrum. > >An object is "deleted" automatically when the last reference >to it disappears (goes out of scope, is deleted expl?citly, >etc). BUT, you can't force the __del__ method to be called, >it's an implementation detail that depends on the memory >management scaffolding in place. > >For example. In CPython, memory management is done via >reference counting; when the refcount of an object drops >to zero, it's immediately destructed and deallocated; BUT, >in Jython, memory management is done via Java's machinery, >and there is no assurement of *when*, or *if*, the >destructor is going to be called on the object. > >So, for sanity's sake, use a .close() method, or a .done(), >or something like that, to explicitly close your connection >to your SMTP server, so you won't have to depend on __del__ >doing it for you. > >Python doesn't have the fixed semantics for destructor >invocation that C++ has, so you have to take that into account >when designing your software. > >HTH > >-gustavo > >pd: TGIF! > > -- *John Abel Systems Administrator * PA News Limited www.pa.press.net E-Mail address: john.abel at pa.press.net Telephone Number : 01430 455553 Fax Number : 0870 1240192 Mobile Number : 07971 611356 The Bishop's Manor, Market Place, Howden, DN14 7BL PA News Limited, 292 Vauxhall Bridge Road, London SW1V 1AE. Registered in England No. 3891053. From mwh at python.net Tue Nov 26 12:38:17 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 26 Nov 2002 17:38:17 GMT Subject: Python Tutorial Was: Guido's regrets: filter and map References: <3de39ce9$0$22220$a1866201@newsreader.visi.com> Message-ID: grante at visi.com (Grant Edwards) writes: > In the case of reduce: > > sum = reduce(operator.add, valueList) > > How is that expressed any better with a list comprension? It's not. It's better expressed as a for loop, though. The for loop might well be quicker, too (cue Alex proving me wrong :). Cheers, M. -- In many ways, it's a dull language, borrowing solid old concepts from many other languages & styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it. -- Tim Peters, 16 Sep 93 From skip at pobox.com Tue Nov 12 13:55:25 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 12 Nov 2002 12:55:25 -0600 Subject: Optimisation problem In-Reply-To: <1037125844.10171.14.camel@wintermute.atriaky.sk> References: <7h3heem23ju.fsf@pc150.maths.bris.ac.uk> <1037125844.10171.14.camel@wintermute.atriaky.sk> Message-ID: <15825.20125.371951.589652@montanaro.dyndns.org> gabor> x,y = 2,4 gabor> creates a tuple? gabor> i thought thatr x,y=2,4 is the same as x=2;y=4 Semantically, yes, it's the same, however, it makes an intermediate tuple of the rhs in the process of performing the assignment. The "dis" module is your friend here: >>> import dis >>> def f(a,b): ... c,d = a,b ... >>> dis.dis(f) 2 0 LOAD_FAST 0 (a) 3 LOAD_FAST 1 (b) 6 BUILD_TUPLE 2 9 UNPACK_SEQUENCE 2 12 STORE_FAST 2 (c) 15 STORE_FAST 3 (d) 18 LOAD_CONST 0 (None) 21 RETURN_VALUE -- Skip Montanaro - skip at pobox.com http://www.mojam.com/ http://www.musi-cal.com/ From anton at vredegoor.doge.nl Sat Nov 9 14:25:08 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 09 Nov 2002 20:25:08 +0100 Subject: indexed looping, functional replacement? References: <3fe406f0.0211091037.2795e538@posting.google.com> Message-ID: On 9 Nov 2002 10:37:15 -0800, bushbo at attbi.com (Brian O. Bush) wrote: >I would like a simpler approach to avoid having to manually maintain >an index, maybe functional if possible. [f(a) for f, a in zip([f1, f2, f3], ["bbb", "sdf", "sdw"])] Regards, Anton. From Padraig at Linux.ie Fri Nov 22 09:53:30 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Fri, 22 Nov 2002 14:53:30 GMT Subject: int() shortcoming? References: <3DDE4274.3070902@Linux.ie> Message-ID: Padraig Brady wrote: > Matthew Knepley wrote: > >> Is there a reason I should have to specify the base for a string >> conversion using int() when it is already clear from the form? For >> instance: >> >>>>> oct(15) >>>> >> '017' >> >>>>> int('017') >>>> >> 17 >> >>>>> int('017', 8) >>>> >> 15 >> >> and hexidecimal actually generates an error. > > I agree with you somewhat. > I think int() be default should behave like strtol(nptr, (char **)NULL, 0) > rather than strtol(nptr, (char **)NULL, 10); > However this is not backwards compatible. > I.E. int('017') would give a different answer. > > see also: > http://tardis.redbrick.dcu.ie/391/groups.google.com I should also mention you can also run eval on the string first to get the functionality you want + extra functionality, like: int(eval("1.2")) int(eval("1e3")) int(eval("1L")) P?draig. From max at alcyone.com Fri Nov 1 20:50:59 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 01 Nov 2002 17:50:59 -0800 Subject: Textbooks on Perl/Python References: <87b0ada6.0211011453.1df4d216@posting.google.com> Message-ID: <3DC32F83.8990DEC9@alcyone.com> Jalab wrote: > Any help in finding a university level textbook on the subject of > "Scripting languages" I am mainly looking for a book that covers Perl > and Python only as the 2 main scripting languages and that is written > for students, i.e. chapter summary, exercises, etc. I hate to force my > student to buy and study from two separate books. I doubt you'll find one that will really cover both subjects adequately, since they're totally different languages. The only thing I can think of that comes close is the "little language" books, that give a brief summary of a wide variety of "little," high-level languages. The one I'm familiar with (though I don't own it) is _HPL: Little Languages and Tools_ by Salus (editor). -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Things are as they are because they were as they were. \__/ Thomas Gold Bosskey.net: Return to Wolfenstein / http://www.bosskey.net/rtcw/ A personal guide to Return to Castle Wolfenstein. From cliechti at gmx.net Sat Nov 2 06:06:50 2002 From: cliechti at gmx.net (Chris Liechti) Date: 2 Nov 2002 13:06:50 +0200 Subject: Sending null byte to serial port in Windows using PySerial? References: <49f4e27a.0211010930.56788863@posting.google.com> <49f4e27a.0211020033.6d7b66ac@posting.google.com> Message-ID: sundae1888 at hotmail.com (sundae) wrote in news:49f4e27a.0211020033.6d7b66ac at posting.google.com: >> > com = serial.Serial("COM1", 9600, timeout=1) >> > com.write(chr(0)) > So that *is* the way to send a null byte? I was wondering if I > screwed up there (and/or that WriteFile() doesn't support null byte). yes if you have a longer string with other data you can also insert a null byte with "\0" or "\x00" etc. it's all the same. > Since it's easier to test case (b), my question is, would inWaiting() > detect a byte even if the timeout is too fast? inWaiting() return the number of characters in the buffer that the OS has. characters disapear from the buffer if you read them or if you flush the buffer. so yes, if your read() call would return too fast and characters arrived after that and then you did a inWaiting() it should return a nonzero value. chris -- Chris From gerhard.haering at opus-gmbh.net Wed Nov 13 10:44:16 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 13 Nov 2002 15:44:16 GMT Subject: calendar modules References: Message-ID: In article , Geiger Ho wrote: > Hi all, > > Wondering around the modules, I find that "calendar" does not function > well in MS Windows. When I type "calendar.month(2002,11)", it outputs a > string > > ' November 2002\nMo Tu We Th Fr Sa Su\n 1 2 3\n 4 5 6 > 7 8 9 10\n11 12 13 14 15 16 17\n18 19 20 21 22 23 24\n25 26 27 28 29 > 30\n' > > but rather in proper formating. Try "print calendar.month(2002, 11)" instead of the implicit repr that's called in your case. > This seems calendar module is not platform It is. -- Gerhard H?ring OPUS GmbH M?nchen Tel.: +49 89 - 889 49 7 - 32 http://www.opus-gmbh.net/ From theo345 at hotmail.com Tue Nov 19 04:07:47 2002 From: theo345 at hotmail.com (Theo Brenningerer) Date: Tue, 19 Nov 2002 10:07:47 +0100 Subject: something like apache DBI ? Message-ID: hello is there something like Apache DBI (as for modperl) for Python? I couldn't find anything on the web thanks From max at alcyone.com Sat Nov 23 01:25:33 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 22 Nov 2002 22:25:33 -0800 Subject: int() shortcoming? References: Message-ID: <3DDF1F5D.F4FC9A88@alcyone.com> Matthew Knepley wrote: > Is there a reason I should have to specify the base for a > string > conversion using int() when it is already clear from the form? For > instance: > > >>> oct(15) > '017' > >>> int('017') > 17 > >>> int('017', 8) > 15 > > and hexidecimal actually generates an error. You can pass 0 in as the radix to int and it will automatically determine the base. Clever, huh? >>> int('017', 0) 15 >>> int('0x17', 0) 23 -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ The little I know, I owe to my ignorance. \__/ Sacha Guitry Bosskey.net: Counter-Strike / http://www.bosskey.net/cs/ A personal guide to Counter-Strike. From claird at lairds.com Fri Nov 8 14:14:03 2002 From: claird at lairds.com (Cameron Laird) Date: Fri, 08 Nov 2002 19:14:03 -0000 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <20021108.115059.1034949299.9010@cybermesa.com> Message-ID: In article <20021108.115059.1034949299.9010 at cybermesa.com>, Jay O'Connor wrote: . . . >Yes, I was a Python advocate in a TCL shop for awhile and had a hard >time convincing >people that there was a qualitative difference between. > >set x [lindex [lindex $var 5] 5] > >and > >x = var[5][5] . . . Tcl has definite problems that are close to what this example expresses. Somebody's tilting the idiomatic playing field, though; the experienced Tcl-ers I know would write set x $var(5,5) rather than deal with the monstrosity above. What makes Tcl look bad is set rounded [expr int(a + 0.5)] vs. rounded = int(a + 0.5) -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From markusjais at yahoo.de Thu Nov 21 06:09:05 2002 From: markusjais at yahoo.de (Markus Jais) Date: Thu, 21 Nov 2002 12:09:05 +0100 Subject: gui References: Message-ID: Ryan oberto wrote: > > hey all > > i have just installed my firs python trying to learn it now > is there a gui for it or must i just you the command line Hola one thing you can use is Idle http://www.python.org/idle/ markus From quadric at primenet.com Tue Nov 5 17:33:21 2002 From: quadric at primenet.com (quadric at primenet.com) Date: Tue, 05 Nov 2002 15:33:21 -0700 Subject: ** URGENT ** Obtaining global and local dict's for current interpreter using C API Message-ID: <5.1.1.6.2.20021105150907.01a34c88@pop3.norton.antivirus> Hi, I am new to Python but an experienced C++ programmer familiar with scripting etc..... and very excited about Python. I have successfully embedded/extended it and am attempting to execute Python source from a variety of sources. I have looked through all my Python books for an answers to the following questions and can find none ( at least not yet ). Can someone please help? I'm sure this is incredibly simple, I'm just a bit new at it. I'm using the latest build (2.2.2) and programming using MS Visual C++ 6.0 ( no flame from UNIX/Linux guys please ). Question(s): How , and using which C API functions, do you acquire the PyObject * to the dictionaries ( both local and global) of the current interpreter. I AM NOT looking for the dictionary of an imported module, but rather the dictionary of the current interpreter. You know, the one you get when executing 'dir()' in the interpreter window. The C API docs say to do the following: PyObject * pdict = PyObject_Dir(NULL); and , assuming an execution frame is active, should return the dictionary. 1> What is an execution frame? 2> How do I know if an execution frame is active? 3> I've tried this and only get NULL in return, indicating the absence of an active execution frame, I guess? ----------------------------------------------------------------------------------- My code looks similar to this: PyObject * pres = NULL , * pdict = NULL; int result = 0; Py_Initialize(); pdict = PyObject_Dir(NULL); // Returns a useless NULL pointer if ( pdict != NULL ) { PyRun_SimpleString( "result = 4 + 5" ); pres = PyObject_GetAttrString( pdict , "result" ); PyArg_Parse( pres , "i" , &result); } // decrement any references here Py_Finalize(); -------------------------------------------------------------- The problem is that pdict is always NULL and I cannot retrieve values for variables created within the namespace of the current interpreter by use of the PyRun_xxxx() functions. Any knowledgeable help would be greatly appreciated. Thanks, quadric at primenet.com From stuart.191 at ntlworld.com Fri Nov 1 16:33:41 2002 From: stuart.191 at ntlworld.com (Stuart MacGregor) Date: Fri, 01 Nov 2002 21:33:41 +0000 Subject: Tkinter in RH8.0 Message-ID: I only use Python implicitly - it runs some nice apps like uligo, the go problem program. After installing RH8 the apps find 'from Tkinter import *' does not work. RH 8 ships with python 2.2.1 and I have installed every shipped rpm that might help. Is there some simple action to restore this behaviour - an environment setting perhaps, or do I need to rip out the RH rpm and replace it with a new build? Cheers -- Stuart From mgarcia at cole-switches.com Wed Nov 27 19:29:40 2002 From: mgarcia at cole-switches.com (Manuel M. Garcia) Date: Thu, 28 Nov 2002 00:29:40 GMT Subject: More pythonic way to change an element of a tuple? References: Message-ID: On Wed, 27 Nov 2002 09:58:44 -0800, in comp.lang.python you wrote: (edit) >I frequently have to change a single element of a tuple, and I wind up >doing something like this: Not recommended to have something that is mutable to give a hash value. The internal implementation of the dictionary gets confused if a key changes. class list_with_hash(list): def __hash__(self): return hash(tuple(self)) dict0 = {} dict1 = {} for i in range(10): dict0[list_with_hash([i])] = i dict1[list_with_hash([i])] = 9-i for k in dict1.keys(): k[0] = 9 - k[0] print 'dict0 = %r' % (dict0) print 'dict1 = %r' % (dict1) for k in dict0.keys(): try: v = dict0[k] except KeyError: print 'could not find key %r in dict0' % (k) else: print 'dict0[%r] = %r' % (k,v) for k in dict1.keys(): try: v = dict1[k] except KeyError: print 'could not find key %r in dict1' % (k) else: print 'dict1[%r] = %r' % (k,v) The dictionaries 'dict0' and 'dict1' print out the same, but most of they keys in 'dict1' just cannot be found at all. If you change the 'list_with_hash' class to give the same hash for all elements like this: class list_with_hash(list): def __hash__(self): return 0 you will no longer have the problem of the dictionary not able to find its own keys. But now the performance of the dictionary will be lousy: import time class list_with_hash0(list): def __hash__(self): return hash(tuple(self)) class list_with_hash1(list): def __hash__(self): return 0 t1 = time.clock() dict0 = {} for i in range(5000): dict0[list_with_hash0([i])] = i for i in range(5000): x = dict0[list_with_hash0([i])] t2 = time.clock() print 'time for list_with_hash0: %.3f' % (t2-t1) t1 = time.clock() dict1 = {} for i in range(5000): dict1[list_with_hash1([i])] = i for i in range(5000): x = dict1[list_with_hash1([i])] t2 = time.clock() print 'time for list_with_hash1: %.3f' % (t2-t1) Manuel From andre.hates.spam at ifi.uio.no Mon Nov 25 04:35:08 2002 From: andre.hates.spam at ifi.uio.no (=?ISO-8859-1?Q?Andr=E9_N=E6ss?=) Date: Mon, 25 Nov 2002 09:35:08 +0000 Subject: if : References: Message-ID: David Brown wrote: > > "Andr? N?ss" wrote in message > news:arqm0r$s6f$1 at maud.ifi.uio.no... >> When I started learning Python one of the things that surprised me was > that >> you couldn't do assignments inside the if clause, e.g.: >> >> if myvar = someFunction(): >> >> My question is, what is the rationale for this? Is it a technical issue? > Or >> purely a matter of language design? I'm curious because I'm interested in >> the design og programming languages, not because I want this behavior >> changed in Pyton :) >> > > My guess is that the languages you are most familiar with are C and C++. Java and PHP, actually, but that obviously doesn't make much of a difference :) > The question should not be "why doesn't Python support 'if myvar = > someFunc()'?", but "why *does* C support 'if (myvar = someFunc())' ?" The > answer is that C was designed with the sole aim of reducing keystrokes for > the programmer, regardless of its effect on program readability and > correctness. I've always felt one should use := as the assigment operator, and then = can be used as the equality operator. But having read the thread I found on this subject I at least understood that in Python you will very rarely need this sort of thing, when I ran into this problem it was because I was thinking C-style. Now it's gonna be interesting to see if I ever run into a situation where I'd feel most comfortable doing an if :, knowing that there are usually better ways of solving the problem. Andr? N?ss From jorgencederberg at hotmail.com Fri Nov 1 06:55:31 2002 From: jorgencederberg at hotmail.com (=?iso-8859-1?Q?J=F8rgen_Cederberg?=) Date: Fri, 1 Nov 2002 12:55:31 +0100 Subject: problem with calendar References: Message-ID: "Roman Suzi" wrote in message news:mailman.1036148287.8559.python-list at python.org... > > I have the following problem: > > Python 2.2.2 (#1, Oct 18 2002, 11:40:02) > [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import calendar > >>> calendar.month_abbr > > >>> calendar.month_abbr() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: _localized_month instance has no __call__ method > > What's up? calendar.month_abbr is an instance of a _localized_month class and thus not callable because it does not have a __call__ method as the Traceback states. A dir-command reveals that it has a __getitem__ method. Example: >>> calendar.month_abbr[1] 'Jan' Sincerely yours Jorgen > > Sincerely yours, Roman A.Suzi > -- > - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - > > > > > > > not to mailto:aaro at onego.ru > > From mwh at python.net Wed Nov 6 06:32:34 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 6 Nov 2002 11:32:34 GMT Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DC8623B.88753C16@earthlink.net> <3DC8CDDD.7050103@mindspring.com> Message-ID: <7h33cqf0wd8.fsf@pc150.maths.bris.ac.uk> Andrew Dalke writes: > Some years back, RMS proposed a standard 'scripting' language called > Guile. See, various languages like Tcl, Perl, Python, etc. were > being developed and none of them were 1) developed under the FSF nor > 2) a variation of Scheme. (A simplified and perhaps biased > interpretation of mine.) I've never seen any even perceived advantages of guile other than the FSF thing. I don't get the impression that it is that great even as a scheme implementation. Cheers, M. -- We've had a lot of problems going from glibc 2.0 to glibc 2.1. People claim binary compatibility. Except for functions they don't like. -- Peter Van Eynde, comp.lang.lisp From claird at lairds.com Thu Nov 21 09:11:08 2002 From: claird at lairds.com (Cameron Laird) Date: Thu, 21 Nov 2002 14:11:08 -0000 Subject: gui References: Message-ID: In article , Markus Jais wrote: >Ryan oberto wrote: > >> >> hey all >> >> i have just installed my firs python trying to learn it now >> is there a gui for it or must i just you the command line > >Hola > >one thing you can use is Idle >http://www.python.org/idle/ . . . The original question is ambiguous; in either of its readings, though, the answer is, "Yes". Yes, there are at least a half- dozen worthy IDEs for working with Python, including Idle, and, yes, Python builds in capabilities for development of applica- tions with graphical user interfaces (GUI). Tkinter is the most natural starting point in the latter regard, although, again, there is a variety of choices, each of which enjoys fervent favor among at least some Pythoneers. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From costanza at web.de Sun Nov 24 20:25:15 2002 From: costanza at web.de (Pascal Costanza) Date: Mon, 25 Nov 2002 02:25:15 +0100 Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <2259b0e2.0211210838.7647301a@posting.google.com> <2259b0e2.0211220946.5f61f641@posting.google.com> <3DDE711E.3010005@web.de> <6qyD9.60432$Yw.2729711@news2.tin.it> Message-ID: Alex Martelli wrote: > Pascal Costanza wrote: > ... > >>>>I mean, Python is already more advanced than Java. >>> >>>Oh, I agree with this, but that's not the point. >> >>Er, I have thought that's exactly the point. What do you need a >>backstage language for that is less powerful than the frontstage >>language? > > > The first Lisp interpreter was coded in machine language. The first Python > interpreter was coded in C. Examples could easily be multiplied. The > lower-level, faster language is often used as the "backstage" (not a term > I'm familiar with, but I think I'm interpreting your meaning correctly). I > think (not sure) that the first Prolog interpreter was coded in Lisp, > presumably with similar intentions. So, I'm not quite sure what your > question is meant as -- rhetorical, perhaps? No, my question is not meant as a rhetorical one. I am a little bit confused because I believe I have made it clear what I am talking about - obviously not. Hm. Languages like C and assembler are more powerful than, say, Python because they allow you to circumvent type restrictions and fiddle with the operating system level. Common Lisp is more powerful than Python because it has the code=data feature that allows you to create new language features and some sophisticated and efficient algorithms. Languages like Python, Ruby, Lua and so on make use of C as a "backstage" language in order to expand their possibilities. I believe that they could also benefit from Common Lisp as a backstage language. So my mental model is as follows: Scripting languages allow you to solve, say, 90% of the problems in straightforward and simple ways. However, some problems are complicated or demanding enough that you (or "someone";) needs to revert to the more powerful backstage language. I don't see how Java can play this role for Python because Java neither allows you to fiddle with the machine level nor allows for writing complicated algorithms, at least not when compared to Python. Or is there something I miss? >>(I guess that Jython is useful to take advantage of the Java >>APIs and its platform independence.) > > > That's a typical reason to choose Jython rather than CPython, yes -- being > able to take advantage of existing Java-coded libraries (including the APIs > of the various Java-based standards), and/or of platforms able to run Java > bytecode (including various JVMs). Are there other reasons? Pascal -- Given any rule, however ?fundamental? or ?necessary? for science, there are always circumstances when it is advisable not only to ignore the rule, but to adopt its opposite. - Paul Feyerabend From grante at visi.com Tue Nov 19 20:07:57 2002 From: grante at visi.com (Grant Edwards) Date: 20 Nov 2002 01:07:57 GMT Subject: Bug in Win32file WaitCommEvent ??? References: <3ddaa58d$0$4459$a1866201@newsreader.visi.com> Message-ID: In article , Bengt Richter wrote: >==== from an old win32 help file that may have come with an old version of Delphi ?? ====== > > If the overlapped operation cannot be completed immediately, the function returns FALSE and > the GetLastError function returns ERROR_IO_PENDING, indicating that the operation is executing > in the background. When this happens, the system sets the hEvent member of the OVERLAPPED > structure to the not-signaled state before WaitCommEvent returns, and then it sets it to the > signaled state when one of the specified events or an error occurs. The calling process can > ^^^^^^^^^^^^^^^^^^^^^^^ > use a wait function to determine the event object's state and then use the GetOverlappedResult > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > function to determine the results of the WaitCommEvent operation. GetOverlappedResult reports > ^^^^^^^^^^^^^^^^^^^^^^^^^^^ > the success or failure of the operation, and the variable pointed to by the lpfdwEvtMask > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > parameter is set to indicate the event that occurred. > ^^^^^^^^^^^^^^^^ > > If a process attempts to change the device handle's event mask by using the SetCommMask > function while an overlapped WaitCommEvent operation is in progress, WaitCommEvent returns > immediately. The variable pointed to by the lpfdwEvtMask parameter is set to zero. > >========================================== > > Sounds like the mask location is safe if you don't call > GetOverlappedResult?? I sure don't know. I've found examples that don't call GetOverlappedResult and they expect a "delayed" write to *lpfdwEvtMask happen. And I thought it impossible for me to grow to hate Windows even more... -- Grant Edwards grante Yow! YOW!! Now I at understand advanced visi.com MICROBIOLOGY and th' new TAX REFORM laws!! From jacek.generowicz at cern.ch Mon Nov 11 03:31:26 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 11 Nov 2002 09:31:26 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: Fernando P?rez writes: > Would you care to elaborate a bit? I'm honestly interested. Sure, but I have approximately 0 time at the moment. If you want to me to give any more details than I do, you will probably have to wait a week or so ... > Please keep in mind that I: > > - know next to zero about lisp > - have a pretty solid scientific computing background (I see you're > from CERN, I do lattice qcd). > > So please be gentle on the lisp, which is what I'm interested in > learning about, but don't pull any punches on the numerics. I want > to know _specifically_ what kinds of transformations you were able > to perform to enhance the performance of your numerical code. First of all, let me say that I did nothing that I could not have done by hand, except that given the number of (complicated) functions involved, it would have taken a long time to do it that way, and I would, undoubtedly have made many mistakes along the way. The macro let me do this quickly and confidently ... and if anyone gives me such a bunch of functions again, I can apply the optimization instantly. Here goes ... Mostly, we were interested in "the big function". This was built out of calls to other functions, which were, in turn made up out of calls to other functions etc. Now, it was clear that the "auxiliary" functions were being called very many times, with the same arguments, each time "the big function" was being calculated. Memoizing would have been one obvious approach, but I knew that at least one argument of "the big function" (TBF) was monotonically increasing throughout my run ... so the memo would mostly contain values which I knew I was never going to need again. So I used the following caching scheme. - Get the macro to collect all the names of the functions used in calculating TBF, by extracting them from the function definitions. - Create cache variable names corresponding to those function names (Lisp separates namespaces for values and functions, so these names could be identical to the function names) - Create new functons by replacing all calls to the cached functions with references to the cached variables. - I made the new-cache referencing functons closures over the shared cached values, just to keep the latter from interfering with anything else, but that's a minor detail. As I said, not really profound, but for a quick hack the result was really satisfying. I can imagine that you could put """ """ around your Python definitions, do something similar by processing the resulting string, and then eval it ... but it sounds far too painful to try. > I have a question for you (keeping in mind what I said above about > my background in HEP, moving these days towards algorithm > development). Could you try to outline what things someone like me > would benefit from in Lisp? > I'd very much appreciate an overview of this by you or anyone else > with a good lisp background. I would not consider myself to have a "good lisp background". But I'd be happy to try to make constructive suggestions, and maybe give you some pointers ... but please allow me to postpone this for a week or so, as I would not be able to make a sensible contribution with my current time constraints. Jacek. From tjreedy at udel.edu Thu Nov 28 20:20:57 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 28 Nov 2002 20:20:57 -0500 Subject: Implementation of the global statement References: <8ef9bea6.0211270526.5a1278c5@posting.google.com> <3DE59E73.4040908@something.invalid> Message-ID: "Bengt Richter" wrote in message news:as5ugi$a48$0 at 216.39.172.122... > >>> def foo(x): print x > ... > >>> bar = foo.__get__('Hi via foo') > >>> bar() > Hi via foo This is a new one for me: >>> def f(): pass ... >>> f.__get__ >>> f.__get__.__doc__ 'descr.__get__(obj[, type]) -> value' Seems to be a new, undocumented (?, not in indexes) method producing a new, undocumented (?) internal type. Not something to bank a product on ;-) Terry J. Reedy From costanza at web.de Thu Nov 21 12:03:48 2002 From: costanza at web.de (Pascal Costanza) Date: Thu, 21 Nov 2002 18:03:48 +0100 Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <2259b0e2.0211210838.7647301a@posting.google.com> Message-ID: Michele Simionato wrote: > It is true that you can read the Python tutorial in couple of hours, > "understand" most of it and start immediately programming in Python. [...] > It takes a much longer time to become to *think* in Python. I started > six months ago and I am still in the process of adapting my way of > thinking to the language. This is much harder than adapting the language > to your way of thinking. But eventually you must do it if you really > want to understand the language. Could you try to describe what it means to you to think in Python? What makes it different from thinking in other languages? (This is not a rhetorical question!) > Final thought: different persons have different way of thinking. > Different programming languages have different philosophies. It is not > strange at all that when you find a language that fits you mind, it is > *for you* much easier to learn than other languages. Good point! Pascal -- Given any rule, however ?fundamental? or ?necessary? for science, there are always circumstances when it is advisable not only to ignore the rule, but to adopt its opposite. - Paul Feyerabend From mertz at gnosis.cx Fri Nov 22 14:33:12 2002 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Fri, 22 Nov 2002 14:33:12 -0500 Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <2259b0e2.0211210838.7647301a@posting.google.com> <2259b0e2.0211220946.5f61f641@posting.google.com> <3DDE711E.3010005@web.de> Message-ID: <4Zo39kKkXYZf092yn@gnosis.cx> Pascal Costanza wrote previously: |I would like to know more specifically what features make Python |special to you. As Kenny put it, in what regards is Pythonthink |different from Otherlangthink? I think studying the -Zen of Python- is an excellent start for an answer. And after that, it is an excellent intermediary. One feature that is not directly a single one of the lines in -Zen- is the openness of Python. When I write Python code, I know at every moment that I could "step behind the scenes" if I wanted to. Attributes are not kept away from me, although the underscore conventions make recommendations I usually obey; the magic methods are available to change how objects respond to operators, but I know not to do that most of the time; functions are first class, and basic FP techniques are available, but only to be used when procedural code is not as straightforward; and so on. Python is not at all a bondage-and-discipline language. On the other hand, Python still maintains an obvious distinction (to keep my metaphor) between what is "in the scene" and what is behind it. With a language like CL, I feel overwhelmed by the feeling of having to understand -everything- that I -could- do at every moment I do one particular thing. The S-expressions, for example, make it painfully obvious -exactly- what the program is actually doing. It has no comfortable level of abstraction where I can pretend I'm living in this safe and simple world when I just want to write a loop or a conditional test. At the other end, Assembly--or C too to a large extent--bring me into the world of the machine. I have to think about memory allocation, and stacks, and pointers, and all sorts of low-level details that have nothing to do with the problem *I* want to be solving. You can get behind the scenes easily with these, but they're the wrong scenes... I don't want to poke into the machine, I want to poke into the language. Of course, all of these are in contrast to a monstrosity like Visual Basic. It is bad enough at the language level, where you are handed a set of high-level abstractions that are both clumsy and inflexible. You can't ever step behind these... except in the sense of learning a whole different language (C/C++/C#) and an unwieldy API (WinAPI/COM/NET/...). But the way "programmers" actually work in VB is even worse... drag some widgets around at random, and hope that everything mysteriously works despite the fact you have no idea what it is doing. Yours, Lulu... -- mertz@ _/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: \_\_\_\_ n o gnosis _/_/ Postmodern Enterprises \_\_ .cx _/_/ \_\_ d o _/_/_/ IN A WORLD W/O WALLS, THERE WOULD BE NO GATES \_\_\_ z e From max at alcyone.com Tue Nov 12 16:03:43 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 12 Nov 2002 13:03:43 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCF83B2.2030008@web.de> <3DD0D765.3030907@web.de> Message-ID: <3DD16CAF.41214BBA@alcyone.com> Pascal Costanza wrote: > You're right, but I wanted to avoid to explain the difference between > ' > and #'. These examples are only meant to give a first taste of Lisp. Note that for "first tastes," Scheme is probably a better introduction (if you're only learning Lisp-like languages for their own sake, that is, rather than trying to learn a language skill you want to sell). Scheme doesn't have this distinction between a symbol and the function associated with it, so there's no distinction between ' and #'. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ If a thing is worth doing, then it is worth doing badly. \__/ G.K. Chesterton ZOE / http://www.alcyone.com/pyos/zoe/ A simple Python OpenGL rendering engine. From nospam at bigfoot.com Mon Nov 4 16:50:26 2002 From: nospam at bigfoot.com (Gillou) Date: Mon, 4 Nov 2002 22:50:26 +0100 Subject: MySQLdb and threads References: Message-ID: > >>>>> "Gillou" (G) writes: > > G> Hi, > G> I plan to make SQL queries in different threads of an application using > G> MySQLdb. > G> Can I use the same Connection object in all threads (each thread having its > G> own cursor) for the queries ? Or should I use a different Connection object > G> for each thread ? > > The doc says: > [SNIP] > For threaded applications, try using a connection pool. This can be done > using the Pool module. Many thanks Piet for this enlightenment, Where did you find the Pool module you're writing of ? I didn't find it in the standard Python distro (2.1.3) nor with google. Cheers --Gilles > > -- > Piet van Oostrum > URL: http://www.cs.uu.nl/~piet [PGP] > Private email: P.van.Oostrum at hccnet.nl From detlev at die-offenbachs.de Sun Nov 24 11:15:39 2002 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 24 Nov 2002 17:15:39 +0100 Subject: ANN: Eric 3.0.0-alpha2 released Message-ID: Hi, Eric 3.0.0-alpha2 is available for download via http://www.die-offenbachs.de/detlev/eric3.html What is it? ----------- Eric 3.0.0 (or short eric3) is a Python IDE written using PyQt and QScintilla. It has integrated project management capabilities, it gives you an unlimited number of editors, an integrated Python shell, an integrated debugger and more. Please see for yourself by visiting the a.m. page (it contains a picture of Eric our mascot as well). Please report bugs, feature wishes or code contributions to eric-bugs at die-offenbachs.de Help wanted!! ------------- I would need some support in the area of more translations and user documentation. Any volunteers out there? Just let me know. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From bokr at oz.net Thu Nov 21 12:44:41 2002 From: bokr at oz.net (Bengt Richter) Date: 21 Nov 2002 17:44:41 GMT Subject: Read-only attributes using properties? References: <82c04a2.0211210527.4d1a4393@posting.google.com> Message-ID: On 21 Nov 2002 05:27:55 -0800, wolfoxbr at hotmail.com (Roberto Amorim) wrote: >I was thinking about trying to use the new properties on Python 2.2 to >implement read-only attributes. So I tried the following: > >class MyException(Exception): > pass > >class TProp(object): > def __init__(self): > self.a = 0 > def get_a(self): > return self.a > def set_a(self, v): > raise MyException > a = property(get_a, set_a, None, "Test a") > >t = TProp() >print t.a >t.a = 5 > >I was expecting that the script would fail with an exception on the >"t.a = 5" command. However, I was surprised to see the code fail on >the attribution inside __init__ - that is, there is no "inner class >scope", or direct access within the class itself, and no clear way to >initialize the property. If the property is an alias to the real >internal variable (call it size, for instance), it works, but then if >I try to add a __slots__ list excluding the internal var and only >adding the external reference (__slots__=("a")) it stops working >again. > >Is there any other way to do that? > If by "that" you mean implementing a read-only property, just leave out the "write": >>> class TProp(object): ... def __init__(self): ... self._a = 0 ... def get_a(self): ... return self._a ... a = property(get_a, None, None, "Test a") ... (I.e., just omit set_a and specify None in the corresponding property arg) >>> t = TProp() >>> print t.a 0 >>> t.a = 5 Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute However, Python doesn't shut you out totally: >>> t._a = 5 >>> print t.a 5 You need a separate name for the actual data, because the property action triggers by way of finding the property name as a class attribute when looking it up via an instance. BTW, looking it up directly gets you the property object itself without triggering its action: >>> TProp.a To illustrate further(I think this is ok, but I'm not sure if it's frowned upon): >>> TProp.b = property(lambda self: self._b, None, None, None) >>> t._b = 'aha' >>> t.b 'aha' >>> t.b = 'oho' Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute Regards, Bengt Richter From zhitenev at cs.vsu.ru Fri Nov 15 05:50:17 2002 From: zhitenev at cs.vsu.ru (Lexy Zhitenev) Date: Fri, 15 Nov 2002 13:50:17 +0300 Subject: socket.error __del__ References: Message-ID: > I'm using a TCP threading socket server and I get this error > > Exception socket.error: (10054, 'Connect reset by peer') in method _fileobject.__del__ of 0x0089CED8>> ignored AFAIK, this happens because socket is already closed by your client. When socket object is destroyed, it tries to close the connection, but this operation failes, because your peer - client has already closed the connection, or the client socket has failed (e.g. for power failure, or computer reboot or smth else). From sanzio2001 at hanmail.net Tue Nov 5 23:51:19 2002 From: sanzio2001 at hanmail.net (Kong Hyeog Jun) Date: 5 Nov 2002 20:51:19 -0800 Subject: transmission problem at the requested offset Message-ID: Hi! i had tried to implement the way that the server restarts sending the file's bytes at the requested offset. i wrote the following code. but this code didn't work well. when i typed "a", it didn't perform "Append" operation at the requested offset "rest" but it performed "Overwrite" oeration. that is, Append operation is not implemented. i don't know what should i do. anybody can give me any hints? Thanks. (sorry, i can not write english as well. my mother language is not english) -------------------------------------------------- def do_getFile(self, tar): self.do_size(tar) # it is used to assign the file size of the # given "tar" on local host to "self.file_size" self.ftp.voidcmd("TYPE I") rest = str(os.path.getsize(tar)) while 1: res = string.lower(raw_input("(O)verWrite/(A)ppend/(P)ass ?")) if res == "o": print 2 f = file(tar,"w") conn = self.ftp.transfercmd("RETR "+tar) break elif res == "a": print 1,rest f = file(tar,"a") conn = self.ftp.transfercmd("RETR "+tar, rest) print 3 break elif res == "p": return flen = 0 while 1: block = conn.recv(8192) if len(block) == 0: break flen = flen + len(block) f.write(block) print "\r%s downloading :%10dbytes/%sbytes %5d%%" % (tar,flen , self.file_size,int((flen/float(self.file_size))*100)), print "\r%s : Downloaded :%10dKB/%sKB" % (tar,flen, self.file_size) conn.close() self.ftp.voidresp() self.file_size = 0 -------------------------------------------------- From rmunn at pobox.com Mon Nov 11 02:38:05 2002 From: rmunn at pobox.com (Robin Munn) Date: Mon, 11 Nov 2002 07:38:05 GMT Subject: Question about drawing simple graph in Python? References: <20021108044701.4273.94217.Mailman@mail.python.org> Message-ID: Patrick Surry wrote: > I don't know of a specific module for this, but there's a nice package called > graphviz (google will find it, I'm offline) which includes tools for rendering For the record (and the archives), graphviz can be found at: http://www.research.att.com/sw/tools/graphviz/ and/or: http://www.graphviz.org/ One is the official AT&T research site, the other the development site. Please note that I have nothing to do with this project, so don't ask me any questions about it. I just thought it would be nice if the URL's showed up in the thread for the sake of anyone reading the archives later. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From tjreedy at udel.edu Sat Nov 9 17:58:04 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 9 Nov 2002 17:58:04 -0500 Subject: none - output References: <1036864302.150371@news.liwest.at> Message-ID: "Christian Stockhammer" wrote in message news:1036864302.150371 at news.liwest.at... > Hello List! Hello Christian > I wrote a litte program that will print out the rates of a credit, but i > face some problems. Here is the code: > > schuld = 100000.0 > > zinsfaktor = 5.0 > > tilgung = 20000.0 > > def tilgungsplan(schuld, zinsfaktor, tilgung): Guessing payment plan, principle, interest%, payment > print "Periode Restschuld Zinsen Tilgung" > > for i in range(0,5): > > zinsen = (schuld*zinsfaktor)/100 Divide %interest by 100 once before loop > echtetilgung=tilgung-zinsen > > i = i + 1 This should almost certainly not be here. I is automatically incremented. Perhaps you want range(1,6)? > schuld = schuld - echtetilgung > > print i," "," ", schuld," ", zinsen," ", echtetilgung Just so you know, tabs in newsgroup articles disappear for some readers. If you want everyone to to read your code without guessing, use spaces. > print tilgungsplan(schuld, zinsfaktor, tilgung) This is your problem. If you do not specify return value, Python functions return None (the object named None with value None). Remove 'print ' and all will be better. Or have function return a value > print "Restzahlung: ", schuld > None > My problem is that the "None" (I do not know how to avoid this output!) See above. > and the value for "Restzahlung" (how much is still left to pay) is not correct! Can't say why for sure without seeing your indentation. Try without i=i+1. Terry J. Reedy From mwh at python.net Wed Nov 27 05:35:55 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 27 Nov 2002 10:35:55 GMT Subject: Why not a, b += i, j? (augmented assignment via tuple unpacking) References: Message-ID: <7h3r8d7qp6g.fsf@pc150.maths.bris.ac.uk> Steven Rumbalski writes: > In python I can write: > > a, b = i, j > > but the following is not legal: > > a, b += i, j > > Is there a reason that allowing this would be bad? Well, as others have said it's not totally clear what it does (though I thought it pretty obvious what you meant). > Why does Python forbid this? It would probably be a swine to implement, for one thing... I did the grammar hacks for augmented assignment back in 2000 and allowing this didn't even occur to me. Cheers, M. -- : Giant screaming pieces of excrement, they are. I have a feeling that some of the people in here have a MUCH more exciting time relieving themselves than I do. -- Mike Sphar & Dave Brown, asr From jb at cascade-sys.com Thu Nov 14 23:25:32 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Thu, 14 Nov 2002 20:25:32 -0800 Subject: A really bad idea. References: <4STA9.9987$744.345722@news1.tin.it> <3DD44152.69795B9F@alcyone.com> Message-ID: <3DD4773C.80004@cascade-sys.com> Erik Max Francis wrote: > > I think what's making the difference here is the quality/depth of the > reference guides, not the actual languages. A "C/C++" reference that is > a total of 16 pages simply not comparable to a Python reference that is > 124 pages. C and C++ (two different languages, by the way) are not > about 8 times simpler than Python. Far from it, in fact. I don't disagree with anything you say. A fairer comparison might be the 1.5 Python pocket ref and the one for Perl 5. There it's 74 vs. 48 pages. The Python ref is newer, a LITTLE bit more verbose and arguably covers a LITTLE more library code (though that's unfair to Perl, which includes a lot of what should be library functions in the base language). If you actually look through the two booklets, it is evident that it is not an entirely unfair comparison on a gross level. I view it as circumstantial evidence that Python and Perl5 are comparable in power and capability (though Python is much more easy to learn and understand). In any case, I agree Pocket reference guides are at best a poor metric for comparing language complexity. I only mentioned the others because Mr. Garcia cited it as evidence that Python is "small" and I offered what were intended to be seen as counter examples. My main point was to disagree with the notion that Python itself is "small". I think the deceptive thing is that Python omits the declarative syntax which is standard with static typed languages. Take away the declarative syntax from C++ and compare what's left to what you can do in Python and in Python there's a lot more meat to choose from. Yeah, C++ gives you arrays, 14 flavors of fixed sized integers and 3 or 4 flavors of reals, but BFD. It doesn't have true Longs, complex, lists, dictionaries or even a good string type to speak of, at least not as first-class objects. Each language has roughly the same number of operators, although each has some not available in the other. The control structures in Python are generally more powerful than C++s. The several omissions from C++ (switch, goto, pointer/reference types, expression assignment and ++/--) were all intentional and arguably make the language better, not substantially smaller. Bring back all the declarative syntax and semantics and, yes, C++ is more complicated. BUt take it all back out and I submit that Python has more features -- more tools to apply to your problem. Fred Brooks talks about 'essential' and 'accidental' problems in programming. The essential ones pertain to the key decisions you make about your algorithms, problem solving that has a direct bearing on the solution to your application. The accidental problems are the attendant complexities you have to deal with in your programming environment in order to implement your solution; they unrelated to the solution itself. I submit that Python's strength is that a much greater portion (most?) of it's features go directly to the "essence" of programming, while other languages contribute less (possess fewer 'essential' features) and actually add to the problem. Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From mhammond at skippinet.com.au Sat Nov 23 00:51:47 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 23 Nov 2002 05:51:47 GMT Subject: Bug in Win32file WaitCommEvent ??? In-Reply-To: <3dde5e18$0$22192$a1866201@newsreader.visi.com> References: <3ddaa58d$0$4459$a1866201@newsreader.visi.com> <3DDD711D.2000802@skippinet.com.au> <3dde5012$0$4491$a1866201@newsreader.visi.com> <3dde5e18$0$22192$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: > In article <3dde5012$0$4491$a1866201 at newsreader.visi.com>, Grant Edwards wrote: > >>>I don't have win32all, but don't you need to have the >>>OVERLAPPED struct persist as well? Isn't the event slot there >>>also used asynchronously? >> >>Yes, the OVERLAPPED struct has to be persistent. I've thought >>about using that as storage for the comm event mask value, but >>then we've got to add some sort of accessor function to >>retreive it later. The advantantage of using a 4-byte buffer >>is that the semantics stay more similar to both the Win32 >>usage, and the way that data buffers work for overlapped >>read/write operations: >> >> >> rc,mask = WaitCommEvent(handle,overlapped) >> rc = WaitForSingleObject(overlapped.hevent) >> whatHappened = int(mask) > > > I should have mentioned that in the non-overlapped case, the > returned mask value would be an integer (same as it is now). > That way the only change is to the overlapped usage. Actually, I don't mind the idea of attaching it to the overlapped object. We already have the concept of attaching an object to an overlapped structure, so adding support for a generic "flags" 32 bit value wouldn't hurt, and 2 bytes per Python-allocated overlapped structure wont kill anyone. Might be overkill if this is the only case we come across, but it doesn't change any semantics. ie, the code would look like: rc,mask = WaitCommEvent(handle,overlapped) rc = WaitForSingleObject(overlapped.hevent) whatHappened = overlapped.flags Also much easier for me to code ;) Would only work for overlapped objects created via Python, but I think that is reasonable. If a non Python overlapped structure is used, we pass the address of a static variable to ensure no one ever crashes. Sound reasonable? Mark. From dsavitsk at e-coli.net Sun Nov 3 16:14:14 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Sun, 03 Nov 2002 21:14:14 GMT Subject: Python embedded into C#, how? References: Message-ID: "Brant Harris" wrote in message news:uU6x9.4009$mN6.1306943 at newssrv26.news.prodigy.com... > quote: > ------------------------------------------------------------------------ > ... and I can't seem to actually use the COM object once it's used. > ------------------------------------------------------------------------ > > > Sorry I meant, I can't seem to actually use the COM object once it is > registered. Use it as in, I have to reference it in C# and I can't seem to > find the object in its COM list. I preface this by saying that I know nothing about C#, and I aim to keep it that way. In answer to this narrow question, however, not the larger one about embedding an interpreter, my guess is that you need to use late binding on the COM pobject. A google search turned this up http://www.c-sharpcorner.com/1/call_com.asp -d From cbrown at metservice.com Thu Nov 14 23:17:52 2002 From: cbrown at metservice.com (Colin Brown) Date: Fri, 15 Nov 2002 17:17:52 +1300 Subject: Serial Port References: Message-ID: <3dd47570$1@news.nz.asiaonline.net> Hi Luca Try PySerial - a nice multiplatform solution Colin Brown PyNZ From aleax at aleax.it Thu Nov 14 15:15:46 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 14 Nov 2002 20:15:46 GMT Subject: Variable names on the fly? References: <3dd3f5fd$0$28311$fa0fcedb@lovejoy.zen.co.uk> Message-ID: Gerhard H?ring wrote: ... > OTOH being able to dynamically create class attributes by writing in > the class object's __dict__ or by overriding __getattr__ sometimes > really helps. Another often-helpful way to create attributes with runtime-computed names for any object that support general arbitrary attributes (classes, instances, functions, modules, ...) is built-in function setattr. Alex From robin at jessikat.fsnet.co.uk Thu Nov 21 16:25:48 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 21 Nov 2002 21:25:48 +0000 Subject: need help porting ctypes to Linux References: <8yzp5pgv.fsf@python.net> Message-ID: .... >Now I'm implementing (read hacking) libffi to work under Windows so >that I don't have to use other code here. Using the latest Dev-C++ (mingw32 gcc based) I am able to build a libffi.dll and using M$ LIB I also have an import libffi.lib. I can also build a libffi.a, but I guess that's no good for Thomas' efforts unless he uses mingw32 to build the whole extension. -- Robin Becker From mis6 at pitt.edu Mon Nov 4 15:24:31 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 4 Nov 2002 12:24:31 -0800 Subject: parenthesis Message-ID: <2259b0e2.0211041224.7c24635b@posting.google.com> Suppose I want to parse the following expression: >>> exp='(a*(b+c*(2-x))+d)+f(s1)' I want to extract the first part, i.e. '(a*(b+c*(2-x))+d)'. Now if I use a greedy regular expression >>> import re; greedy=re.compile('\(.*\)') I obtain to much, the full expression: >>> match=greedy.search(exp); match.group() '(a*(b+c*(2-x))+d)+f(s1)' On the other hand, if I use a nongreedy regular expression >>> nongreedy=re.compile('\(.*?\)') I obtain too little: >>> match=nongreedy.search(exp); match.group() '(a*(b+c*(2-x)' Is there a way to specify a clever regular expression able to match the first parenthesized group ? What I did, was to write a routine to extract the first parenthesized group: def parenthesized_group(exp): nesting_level,out=0,[] for c in exp: out.append(c) if c=='(': nesting_level+=1 elif c==')': nesting_level-=1 if nesting_level==0: break return ''.join(out) >>> print parenthesized_group(exp) (a*(b+c*(2-x))+d) Still, this seems to me not the best way to go and I would like to know if this can be done with a regular expression. Notice that I don't need to control all the nesting levels of the parenthesis, for me it is enough to recognize the end of the first parenthesized group. Obiously, I would like a general recipe valid for more complicate expressions: in particular I cannot assume that the first group ends right before a mathematical operator (like '+' in this case) since these expressions are not necessarely mathematical expressions (as the example could wrongly suggest). In general I have expressions of the form ( ... contains nested expressions with parenthesis... )...other stuff where other stuff may contain nested parenthesis. I can assume that there are no errors, i.e. that all the internal open parenthesis are matched by closing parenthesis. Is this a problem which can be tackled with regular expressions ? TIA, -- Michele Simionato - Dept. of Physics and Astronomy 210 Allen Hall Pittsburgh PA 15260 U.S.A. Phone: 001-412-624-9041 Fax: 001-412-624-9163 Home-page: http://www.phyast.pitt.edu/~micheles/ From niemeyer at conectiva.com Sat Nov 30 18:50:50 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Sat, 30 Nov 2002 21:50:50 -0200 Subject: Python and ONC RPC anyone? In-Reply-To: References: Message-ID: <20021130215050.A27015@ibook.distro.conectiva> > > has anyone ever used RPC (Sun RPC/ONC RPC) from Python? How > > did you do it? > > I have not tried it myself, but Demo/rpc in the Python distribution > contains xdr and rpc code, as well as an nfs and mount client. I belive ILU also would do the job, but it's probably an overkill, depending on what what he wants to do. I've read a message from you in some documentation about it. Have you evaluated it? If yes, how do you compare it to CORBA (e.g. omniORB) these days? -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From peter at engcorp.com Wed Nov 27 00:36:15 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 27 Nov 2002 00:36:15 -0500 Subject: CVS References: Message-ID: <3DE459CF.DAA2EC3C@engcorp.com> Ali K wrote: > > What is CVS? Google is your friend: http://www.google.com/search?q=what+is+cvs From newt_e at blueyonder.co.uk Mon Nov 11 16:50:16 2002 From: newt_e at blueyonder.co.uk (Newt) Date: Mon, 11 Nov 2002 21:50:16 GMT Subject: Classes References: Message-ID: "Skip Montanaro" wrote in message news:mailman.1037020816.31691.python-list at python.org... > [ ...snip... ] > No "self" is needed. To create a class which has three explicit parameters, > define it as > > class ClassName: > def __init__(self, one, two, three): > ... > > then instantiate it like so: > > instance = ClassName(a,b,c) > How would I do this if I wanted to get a response back? If for example the screen listed 5 buttons, each with a piece of text. I want the use to click on the button. This would then close the screen, and I'd get my response back, which would tell me which button was pressed or something. > newt> Is the correct way to do this: in the class module, get the > newt> __init__ to do not very much, and then call the do_widgets > newt> routine? > > In all depends. How complex are your screens? How dynamic are they (do > widgets come and go)? What initialization is repeated each time a screen is > displayed? > No, that not that complex. One has a series of buttons, arranged in 4 groups of 5. One is a text only screen (a bit like a help screen). Widgets are fixed, but the name displayed in Labels might change. > -- > Skip Montanaro - skip at pobox.com > http://www.mojam.com/ > http://www.musi-cal.com/ > Newt From cookedm+news at physics.mcmaster.ca Tue Nov 5 00:09:58 2002 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 05 Nov 2002 00:09:58 -0500 Subject: Crash in curses stdscr.getkey? References: <3DC6FA56.74A8D516@alcyone.com> Message-ID: At some point, Erik Max Francis wrote: > I'd receive a report from someone using CAGE (my cellular automata > explorer in Python which uses curses) that he was getting crashes; he > ran SuSE. He fiddled around fond a workaround. If he changed the line > from > > char = self.stdscr.getkey() > > to > > char = self.stdscr.getch() > if 1 <= char <= 255: > char = chr(char) > > he found that the crash went away. I had presumed it was just an > isolated incident (i.e., he had a corrupt curses library on his system > or something similar), but just the other day another user reported the > same crash, and when I sent them the workaround, it went away. > > Both users use Linux; the first used SuSE and the latter used Red Hat. > I use Slackware, and haven't seen any such crash (though both code > fragments work fine). The first was using Python 2.2.1; the latter was > using Python 2.2.2. > > Is this a known problem, or should I try to get the endusers to research > it further to submit bugs to the appropriate parties? (I can't tell > whether it's a curses problem or a Python glue problem.) Looks like it's a problem with the wrapper for stdscr.getkey() -- in no delay mode (according to the docs), it's supposed to throw an exception, but doesn't. Digging further, it looks like _cursesmodule.c has the wrong prototypes for the *getch functions. In particular, it seems keyname(c) segfaults when c < 0. Also looks like the doc's claims of throwing an exception from getch() and getkey() when there is no input in nodelay mode is false. I've gone ahead and submitted a patch (SF #633635). In the meantime, you can get this functionality of getkey() with this: def getkey(stdscr): c = stdscr.getch() if c == -1: raise curses.error, 'no input' return curses.keyname(c) -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From aleax at aleax.it Tue Nov 19 11:12:16 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 19 Nov 2002 16:12:16 GMT Subject: stopping SimpleHTTPServer References: Message-ID: dsavitsk wrote: ... > I think I didn't ask a very clear question. I tried to have a special url > cause a function to be called which kills the server. The problem is that > sys.exit() didn't manage to bring it down ... it gave this traceback > instead In your subclass, you need to override method handle_error, which by default processes all exceptions (including the SystemExit exception raised by sys.exit) by printing a traceback and continuing. Check if the exception is SystemExit and then re-raise it, otherwise delegate to your base-class's handle_error for normal error processing... Alex From knepley at mcs.anl.gov Tue Nov 26 13:54:06 2002 From: knepley at mcs.anl.gov (Matthew Knepley) Date: Tue, 26 Nov 2002 12:54:06 -0600 Subject: Python Tutorial Was: Guido's regrets: filter and map References: <698f09f8.0211261046.582254a5@posting.google.com> Message-ID: >>>>> ">" == Jeremy Fincher writes: >> Thomas Guettler wrote in message >> news:... I never liked filter, map and reduce. >> >> I think it would be good to remove them from the python tutorial. I think the tutorial would be easier for newbies >> it it would be smaller. >> The biggest problem with filter, map, and reduce is that they're functions, not methods. All this discussion about >> list comprehensions versus filter/map ignores one major disadvantage of list comprehensions: that they only work >> with lists. If filter/map/reduce had been *methods* on list objects, then a programmer could implement his own >> container objects (binary trees, subclasses of list, etc.) with their own filter/map/reduce methods to construct >> like containers, and people would be happier. Actually, wouldn't you expect (as in most functional languages) that these methods are polymorphic over the shape of the argument? I think that the functional paradigm is just unfamiliar to a great number of Python programmers. That is not a reason to jettison very useful functions from the language. Many systems have mixed programming paradigms, e.g. Mathematica. Matt >> As far as the tutorial goes, filter/map/reduce could be "discovered" just like the rest of the methods that aren't >> emphasized in the tutorial. >> Jeremy -- "Failure has a thousand explanations. Success doesn't need one" -- Sir Alec Guiness From aahz at pythoncraft.com Fri Nov 15 00:06:23 2002 From: aahz at pythoncraft.com (Aahz) Date: 15 Nov 2002 00:06:23 -0500 Subject: questions about scope/threading References: Message-ID: In article , wrote: >Aahz wrote: >> >> Thing is, while var3 is not a module global, any thread can access that >> name through Class1.var3 -- therefore, the object bound to Class1.var3 >> is a completely global object, and you have to be careful what you do >> with Class1.var3 (or the object bound to it if the object is mutable). >> Tricky stuff. > >I hadn't thought about Python's scoping that way before. So anything not >"hidden" inside a function is present in the global tree of namespaces? >(or class definition. hmmm, any others?) No, *everything* is global. Here's a fun one: import dis def f(): print "Hello, world!" print dir(f) print dir(f.func_code) print "Python bytecode for f:", repr(f.func_code.co_code) print print "Disassembled bytecode for f:" print dis.dis(f) One way or another, every object in Python is reachable using Python code. See also the gc module. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From martti.halminen at kolumbus.fi Sat Nov 9 14:47:34 2002 From: martti.halminen at kolumbus.fi (Martti Halminen) Date: Sat, 09 Nov 2002 21:47:34 +0200 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h31y5uyj81.fsf@pc150.maths.bris.ac.uk> <3DCD6038.7E6EC76B@kolumbus.fi> Message-ID: <3DCD6656.3CCD5E24@kolumbus.fi> Richard Dillingham wrote: > > > > (if (a) > > (if (b) > > (if (c) > > (asdf) > > (zzzz)) > > (foo)) > > (bar)) > > > > Would be the normal way to write this. By the way, your newsreader broke the indentation in your reply :-) > > I know, but I personally find the way I wrote it to be easier to read. > You'll also note that I didn't use the normal C coding standard in the C > examples, and instead used the Java/C# standard (Which I prefer). > > The normal C way to use {}s being: > > if (a) > { > asdf; > } > > etc. One of the C styles: see http://www.tuxedo.org/~esr/jargon/html/entry/indent-style.html - And I seem to remember that Linus prefers a style which isn't strictly none of those... -- From loewis at informatik.hu-berlin.de Sun Nov 3 12:58:59 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 03 Nov 2002 18:58:59 +0100 Subject: Largeint.h References: <3dc55de7$0$239$1b0f2dd5@mercury.nildram.co.uk> Message-ID: "Andrew Wilkinson" writes: > Python 2.2.2 doesn't compile under VS.Net because they've removed > largeint.h from the Platform SDK, the current workaround is to copy > the file from VS6. I don't have VS6, does anyone know where I can > download this file? I'd really like to be able to debug my Python > extensions... You should backport the patch that Mark Hammond has already applied to the Python CVS, or use the Python CVS in the first place. You will find that one can work-around not having largeint.h. Regards, Martin From psimmo60 at hotmail.com Thu Nov 28 09:50:57 2002 From: psimmo60 at hotmail.com (Paul Simmonds) Date: Thu, 28 Nov 2002 14:50:57 +0000 Subject: importing question ? Message-ID: >From: Jonas Geiregat >To: python-list at python.org >Subject: importing question ? >Date: Thu, 28 Nov 2002 15:35:47 +0100 > > >>> import classes > >>> a = veryBigSnake() >Traceback (most recent call last): > File "", line 1, in ? >NameError: name 'veryBigSnake' is not defined > >>> from classes import * > >>> a = veryBigSnake() > >why doesn't the first import work ? >and the second does > >and what is the difference between those two ? They both work, it's just that you are looking in the wrong place. Try: >>>import classes >>>a=classes.veryBigSnake() 'from classes import *' brings all the toplevel objects in classes into your local namespace, so you can access them just through the name. Generally, though, I think this is considered bad practice, as it could create overlaps. For instance: >>>from classes import * >>>from snakes import * >>>a=veryBigSnake() You'll find that a takes its class definition from snakes, not classes, as a single name can only be attached to a single object. But: >>>import classes >>>import snakes >>>a=classes.veryBigSnake() >>>b=snakes.veryBigSnake() a and b take their class definitions from different modules- no namespace overlap- no problem. HTH, Paul >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From newsreply at jtwok.worldonline.co.uk Fri Nov 29 03:48:50 2002 From: newsreply at jtwok.worldonline.co.uk (KrayZee--J) Date: Fri, 29 Nov 2002 08:48:50 -0000 Subject: Regular Expressions? Message-ID: Is the Regular Expressions module really buggy or is it just me? Almost every expression I type in gives an error. Many expressions which I have tested and work in JScript give errors in python. I want to make a RE which will match an IP address. This one works in JScript: (\d{1,3}\.){3}\d{1,3} In python it works but matches only 1 digit for the last octet of th IP ie. 192.168.0.100 becomes 192.168.0.1 Any suggestions would be appreciated. John From goodger at python.org Thu Nov 7 19:31:10 2002 From: goodger at python.org (David Goodger) Date: Fri, 08 Nov 2002 00:31:10 GMT Subject: Optik long help strings In-Reply-To: <3DC9CDAD.91A42BDB@kootenay.com> References: <3DC9CDAD.91A42BDB@kootenay.com> Message-ID: Bob van der Poel wrote: > I'm trying to use the Optik package for parsing command line options. > However, I'm running into a problem overriding its line warping > routines. I'd like the help to print something like: > > options: > -p, --pattern Set pattern > 'xx' use the xx pattern > 'yy' use the yy pattern > ... more list of pattern options > > Seems that optik thinks it knows better where the new lines should go. > Suggestions? It's not really clear what you intend. Either you're using hard tabs or single spaces for indents; in any case, it's very subtle here. Optik isn't currently set up to handle complex option descriptions (where complex means anything other than a single flexible paragraph). I suggest you post to . If this feature is really important to you, delve into the code and submit a patch. -- David Goodger Open-source projects: - Python Docutils: http://docutils.sourceforge.net/ (includes reStructuredText: http://docutils.sf.net/rst.html) - The Go Tools Project: http://gotools.sourceforge.net/ From chris.gonnerman at newcenturycomputers.net Thu Nov 7 19:45:21 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 7 Nov 2002 18:45:21 -0600 Subject: Newbie- how to basics References: <8d3e714e.0211071600.2a98b136@posting.google.com> Message-ID: <006101c286c0$22283b60$ba01010a@local> ----- Original Message ----- From: "Gerhard H?ring" > Tony C wrote in comp.lang.python: > > I've gone through much of the documentation included with Python > > 2.2.2, but can find any kind of reference on how to clear the screen > > from a python script, or at the command line. > > You could just print the escape sequence for that, but I believe that > there are utility modules for this. > > If you need more similar stuff, like posititioning the cursor, > changing colors (or using bold/underline/...) you can use the curses > module instead. > > I'm assuming a Unixish system here. On Windows, the console module > from http://effbot.org/downloads/ might be it. Or my WConio module... it's quite a bit more reliable on 9x versions of Windows than the console module. The effbot didn't work around all the bugs in 9x console handling. Or-you-could-avoid-duct-tape-and-baling-wire-os's-ly your's Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From sorry at this.is.my.work.account.com Tue Nov 12 17:59:57 2002 From: sorry at this.is.my.work.account.com (Pasiphe's Bull) Date: Tue, 12 Nov 2002 22:59:57 GMT Subject: os/stat broken under 2.2 / Linux ? Message-ID: Python 2.2 (#1, Apr 12 2002, 15:29:57) [GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-109)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import stat >>> import os >>> file_mode = os.stat("./foo") >>> if (stat.S_ISDIR(file_mode)): ... print "is dir" ... else: ... print "is NOT dir" ... Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/stat.py", line 46, in S_ISDIR return S_IFMT(mode) == S_IFDIR File "/usr/lib/python2.2/stat.py", line 30, in S_IFMT return mode & 0170000 TypeError: unsupported operand type(s) for &: 'posix.stat_result' and 'int' >>> From kahanpaa at gstar.astro.helsinki.fi Thu Nov 14 09:16:01 2002 From: kahanpaa at gstar.astro.helsinki.fi (Jere Kahanpaa) Date: 14 Nov 2002 14:16:01 GMT Subject: total and utter newbie References: Message-ID: Hi. John Hunter wrote: >>>>>> "rockbox" == rockbox writes: > rockbox> Hi. I hope that this is the right group to post this > rockbox> problem in. If not then I appologise. > Ahh yes, the oldest newbie problem in the book :-) > In current versions of python (as in C and many other programming > languages) an integer divided by an integer returns an integer, so > x = 3/2 #x is 1 > but if either number is a floating point number, then the division you > are expecting is used > x = 3.0/2.0 # x = 1.5 > The trick is to add a decimal point and a 0 to your number unless you > want integer behavior > x = 3.0/2 # this is also 1.5 > This is being phased out of python, and is slated for destruction. > Recent versions of python (2.2?) allow you to use > from __future__ import division A more backwards-portable trick is doing a explicit conversion to a floating point number before division. vat = float(rate)/100*value Jere Kahanp?? -- It's hard to think outside the box when you ARE the box. - unknown, alt.religion.kibology From dodo_imp at hotmail.com Thu Nov 14 16:20:20 2002 From: dodo_imp at hotmail.com (Luca Bruderer) Date: Thu, 14 Nov 2002 22:20:20 +0100 Subject: Serial Port References: Message-ID: And what about a module for the USB port? ----- Original Message ----- From: "John Hunter" To: Sent: Thursday, November 14, 2002 9:48 PM Subject: Re: Serial Port > >>>>> "Luca" == Luca Bruderer writes: > > Luca> Hello How can I read and send information through a serial > Luca> port for a custom keyboard I would like to build. > > You may want to try searching google for > > python serial port > > The first result that came back looks useful > > http://balder.prohosting.com/ibarona/en/python/uspp/uspp_en.html > > Cheers, > John Hunter > > -- > http://mail.python.org/mailman/listinfo/python-list > From ianb at colorstudy.com Tue Nov 19 19:03:24 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 19 Nov 2002 18:03:24 -0600 Subject: Implementing some of 'ls -l" directly in python In-Reply-To: <16iera.t5g1.ln@boundary.tundraware.com> References: <16iera.t5g1.ln@boundary.tundraware.com> Message-ID: <1037750604.542.11.camel@dsl-65-184-205-5.telocity.com> On Tue, 2002-11-19 at 17:50, Tim Daneliuk wrote: > So, I use os.path.getmtime and os.path.getsize for two of the things I > need. I then stat the file to get its UID, GID, and permission bits. > Here's where I get stuck. I cannot seem to find a portable way to > convert the UID/GID into their equivalent string names. Also, it would > be handy if there were a (portable) way to convert the permission value > into the more familiar u/g/o - drwx format. There's the pwd and grp modules, which might give a start. Ian From eric.brunel at pragmadev.com Fri Nov 29 10:23:51 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Fri, 29 Nov 2002 16:23:51 +0100 Subject: Tkinter scrolling canvas questions References: Message-ID: Richard Kuhns wrote: > Would you mind telling me what you used for a reference to find info on > winfo_height() and update()? Did you just install and read through the > Tcl/Tk docs, or is there a particular book you like? I've never had any books about Python or Tkinter or Tk. The only references I ever used are Fredrik Lundh's "An introduction to Tkinter" @ http://www.pythonware.com/library/tkinter/introduction/index.htm and Tcl/Tk online man pages @ http://www.tcl.tk/man/ I used the first quite a lot in the beginning, but now I know how to translate tk commands to Python methods, I tend to use the man pages a lot more, if not exclusively. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From zhitenev at cs.vsu.ru Tue Nov 26 11:51:27 2002 From: zhitenev at cs.vsu.ru (Lexy Zhitenev) Date: Tue, 26 Nov 2002 19:51:27 +0300 Subject: Some good Python tuts ? References: Message-ID: "Bram Wijnands" wrote: news:h5wE9.101$Tl3.2735 at nlnews00.chello.com... > well i'm looking for some good tutorials for python im not a beginning > programmer i know perl/php/vb and basic :P > > anyway got some ideas ? :) > If you are an advanced programmer, you can look into 'Dive into Python' tutorial. It's quite big, but very interesting. From jdhunter at ace.bsd.uchicago.edu Sat Nov 16 17:03:15 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sat, 16 Nov 2002 16:03:15 -0600 Subject: Formatted Output - Floating Point Numbers In-Reply-To: (maximum_hops@yahoo.co.uk's message of "16 Nov 2002 13:21:19 -0800") References: Message-ID: >>>>> "David" == David Marshall writes: David> display.divide(57,7) # I only want 2 decimal places David> returned You need to be careful of integer division. In [16]: 57/7 Out[16]: 8 In [17]: 57.0/7 Out[17]: 8.1428571428571423 If you want to insure floating point division, with recent versions of python do from __future__ import division print 57/7 Otherwise, you can do print float(x)/y To format 2 significant digits of a floating point number, you can do print '%1.2f' % (57.0/7) The man pages of the C function sprintf will tell you a lot about the format possibilities: http://www.rt.com/man/sprintf.3.html John Hunter From aleax at aleax.it Wed Nov 20 09:01:13 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 20 Nov 2002 14:01:13 GMT Subject: Deep XML modification.. References: <3ddb6d4f$0$18869$afc38c87@news.optusnet.com.au> <3DDB79FE.8D1CDC41@hotmail.com> <3ddb9413$0$18869$afc38c87@news.optusnet.com.au> Message-ID: nobody wrote: > Are there any better/more in-depth Python specific tutorials for SAX > and/or DOM, than the ones included in PyXML and on the Python site? Yes, O'Reilly published an excellent one written by Christopher Jones and Fred Drake -- highly advisable to anybody interested in Python and XML. Alex From jkraska at san.rr.com Wed Nov 27 12:33:18 2002 From: jkraska at san.rr.com (Courageous) Date: Wed, 27 Nov 2002 17:33:18 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3de1f902$0$695$edfadb0f@dread12.news.tele.dk> Message-ID: >Not really. It wasn't my experience, but it was pretty close. We jumped >right in with Lisp. So we were learning a new style of programming, >functional programming, which we had to wrap our brains around. Which does Lisp a disservice, in a way. Common Lisp is an OO language amongst other things, and this also so happens to be the predominant way that modern Lisp programmers use Lisp. >For me, what turned me off of Lisp as a student was the fact that I was >simultaneously fighting an unfamiliar editor... One of Lisp's _lethal_ failings is that anyone not using Emacs (or something like Emacs) is a second class citizen. The decision to require a programmer to use a special editor is a fatal one. C// From bwfc10 at aol.com Sun Nov 17 04:20:14 2002 From: bwfc10 at aol.com (Bwfc10) Date: 17 Nov 2002 09:20:14 GMT Subject: quick question References: Message-ID: <20021117042014.04759.00000008@mb-fr.aol.com> fair enough, no i'm just practicing a program to esnure that i can do python for when i do get homework. Thanks From sismex01 at hebmex.com Fri Nov 15 17:39:19 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 15 Nov 2002 16:39:19 -0600 Subject: read n bytes from a binary file Message-ID: > From: Rajarshi Guha [mailto:rajarshi at presidency.com] > Sent: Friday, November 15, 2002 4:32 PM > > Hi, > I have a simple question, but I cant seem to find the function to do > it! > How can I read N bytes from a file opened in binary mode. > Basically I'm trying to check that a PDF file is indeed a PDF file > > thanks, > too simple... >>> f = file("BTB.zip","rb") >>> f.read(8) 'PK\x03\x04\x14\x00\x02\x00' >>> HTH! -gustavo From lamco333 at yahoo.com Fri Nov 8 20:40:53 2002 From: lamco333 at yahoo.com (LamCo) Date: 8 Nov 2002 17:40:53 -0800 Subject: where can I get dl-dld-1.1.tar.Z? Message-ID: dear every programmer, How's your life there? I'm trying to install Python with dl-dld module --with-dl-dld: then from the README file I need to get a tar ball from both ftp (ftp://ftp.cwi.nl/pub/dynload/dl-dld-1.1.tar.Z) ftp://ftp.cwi.nl/pub/dynload/dld-3.2.3.tar.Z). but I cant reach the ftp above. Is there any site to get both dl-dld-1.1.tar.Z balls? p/s: I've get dld-3.3.tar.gz from http://sapi.vlsm.org/gnu/dld/ many thanks... YiHua From justin at iago.org Tue Nov 12 13:02:31 2002 From: justin at iago.org (Justin Sheehy) Date: Tue, 12 Nov 2002 13:02:31 -0500 Subject: Is python a good choice for this task? In-Reply-To: (claird@lairds.com's message of "Mon, 11 Nov 2002 21:41:09 -0000") References: Message-ID: claird at lairds.com (Cameron Laird) writes: > I think Tcl's sub- process spawning is perceptibly easier than the > {popen,popen2, popen3} we most often recommend to newcomers. For running a simple command, I agree that Tcl's subprocess spawning is easier for a newcomer to understand than popen and friends. So why not recommend the "commands" module instead of popen for those uses? -Justin From CousinStanley at HotMail.com Wed Nov 13 18:58:03 2002 From: CousinStanley at HotMail.com (Cousin Stanley) Date: Wed, 13 Nov 2002 16:58:03 -0700 Subject: Presenting Data neatly... how :) References: <3dd2dd57$0$28316$fa0fcedb@lovejoy.zen.co.uk> Message-ID: || ... || Is there anyway to format it like this: || || Dell 45 40% || Microsoft 60 56% || IBM 4 5% || ... e-tones ... Something like this seems to work ... vList = [ ( 'Dell' , 45 , 40 ) , ( 'Microsoft' , 60 , 56 ) , ( 'IBM' , 4 , 5 ) ] for xTup in vList : print ' %-12s %3d %3d%% ' % ( xTup[ 0 ] , xTup[ 1 ] , xTup[ 2 ] ) Cousin Stanley From martin at v.loewis.de Tue Nov 12 16:51:49 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 12 Nov 2002 22:51:49 +0100 Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> <87y98f566d.fsf@zamazal.org> Message-ID: DaveP writes: > > http://tinyurl.com/2mhm [...] > That appears to insist on maintaining a solution to a problem? I can't understand that comment. What is "That", and how does that insist on maintaining what solution to what problem? I'm telling that the Python documentation uses Python-specific markup, which is needed in formatting. > I'm curious what the problem being solved is, and whether docbook > and its xml toolset could resolve it? As a DocBook user, I can tell you that DocBook and its xml toolset could not resolve that. > is \seerfc an external reference to an rfc? It is used in pairs. First, you write \rfc{1521} then you write \seerfc{1521}{MIME (Multipurpose Internet Mail Extensions) Part One: Mechanisms for Specifying and Describing the Format of Internet Message Bodies}{Section 5.2, ``Base64 Content-Transfer-Encoding,'' provides the definition of the base64 encoding.} You can see the resulting HTML at http://www.python.org/doc/current/lib/module-base64.html > .... appears to provide the same > functionality if that is the case. Yes, but the documentation author has to fill in the URL. In Python documentation, the RFC URL provided at formatting time; currently, it points to www.faqs.org. So yes, this could be converted, but only with a loss of information. Regards, Martin From chrisw at nipltd.com Tue Nov 19 15:32:16 2002 From: chrisw at nipltd.com (Chris Withers) Date: Tue, 19 Nov 2002 20:32:16 +0000 Subject: Strip-o-Gram 1.2 Released! Message-ID: <3DDA9FD0.2080304@nipltd.com> Strip-o-Gram is an HTML Conversion Library implemented as a Python package that can convert HTML to Plain Text and strip specified tags and Javascript from HTML. See http://www.zope.org/Members/chrisw/StripOGram for more details. This release includes more documentation and allows the methods to be used from Zope's Script (Python)'s. cheers, Chris From usenet at jasoegaard.dk Sat Nov 9 07:14:46 2002 From: usenet at jasoegaard.dk (=?ISO-8859-1?Q?Jens_Axel_S=F8gaard?=) Date: Sat, 09 Nov 2002 13:14:46 +0100 Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DC8623B.88753C16@earthlink.net> <3DC8CDDD.7050103@mindspring.com> Message-ID: <3dccfcbb$0$200$edfadb0f@dread11.news.tele.dk> A.M. Kuchling wrote: > There's also the problem of motivation: who's going to write those > translators? ... > Guile programmers? If they're Guile programmers, they must like > programming in Scheme. Why would they work on translators for languages > they'll never use? And Guile programmrs is the right choice of words. Most Scheme programmers does not use Guile. In most cases there are better alternatives such as DrScheme and Bigloo. From aleax at aleax.it Wed Nov 20 18:25:55 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 20 Nov 2002 23:25:55 GMT Subject: matching multiple regexs to a single line... References: Message-ID: <7SUC9.34440$744.1277405@news1.tin.it> maney at pobox.com wrote: ... > I can somewhat agree with Alexander, and I think you're overlooking the > way that this approach does force the regexps and their associated > handler code apart in the source code. Most of his objections, yes, So did the approach in the post I was replying to -- there was a list of pairs, each made up of an identifier and a compiled re object, and the code was elsewhere. Personally I like this approach, which is why I accepted it as posted and built on it -- so I don't see why you're claiming that this is a differentiator between Alexander's aproach and mine. >> In some other cases client code may not only need to have no >> constraints against using groups in the RE patterns, but also >> want "the match-object" as an argument to the action code. In > > This is one point on which I agree with Alexander: it seems to me to be > the usual case that the regexp both identifies and parses the target. It's one case, but it's very far from being the only one. > If it isn't being used in that dual mode, then the whole issue > addressed here (and in at least two other threads during the past week) > doesn't exist. Why doesn't it? Alexander's post to which I was replying had no groups at all in the regex patterns -- are you claiming he was utterly missing the point of the thread, and his example totally irrelevant? Alex From kemu at sdf-eu.org Sat Nov 23 09:17:30 2002 From: kemu at sdf-eu.org (Jonas Geiregat) Date: Sat, 23 Nov 2002 15:17:30 +0100 Subject: wxPython probleme Message-ID: <3ddf8d82$0$194$ba620e4c@news.skynet.be> I have 2 questions 1.the lines I've commented out don't work and I don't see the probleme 2.I want to create a function so I can save what I typed in in a file I know how to write to a file but I don't know what variable the wxTextCtrl uses in other words what var do I have to write to the file ? here is the code: import sys, os from wxPython.wx import * ID_OPEN = 101 ID_SAVE = 102 ID_EXIT = 103 class main_window(wxFrame): def __init__(self, parent, id, title): wxFrame.__init__(self, parent, -1, title, size = (500,500),style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) self.CreateStatusBar() self.SetStatusText("small editor") M_file = wxMenu() M_file.Append(ID_OPEN,"&Open","Open a file") M_file.Append(ID_SAVE,"&Save","Save a file") M_file.Append(ID_EXIT,"&Quit","Quit this small editor") menuBar = wxMenuBar() menuBar.Append(M_file,"&File") self.SetMenuBar(menuBar) self.control = wxTextCtrl(self, -1, style=wxTE_MULTILINE) self.Show(true) # EVT_MENU(self, ID_EXIT, self.TimeToQuit) # # def TimeToQuit(self, event): # self.Close(true) class App(wxApp): def OnInit(self): frame = main_window(None, -1, "wxPython: (A Demonstration)") frame.Show(true) self.SetTopWindow(frame) return true app = App(0) app.MainLoop() From aleax at aleax.it Wed Nov 6 10:14:39 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 06 Nov 2002 15:14:39 GMT Subject: regex puzzle References: <3dc91095$1_1@omega.dimensional.com> <3dc92dad$1_1@omega.dimensional.com> Message-ID: Mike Brown wrote: ... > seems to give me what I want: r'\A(?!\n)(.+)?\Z' ... thanks for getting > me on the right track! (.+)? is basically the same thing as (.*) right? > I'm not sure I understand the difference between ^$ and \A\Z, but the \A is always start-of-string and nothing else, \Z always end-of-string and nothing else. ^ and $, depending on the setting of re.M or not, may also match around a \n; $ I believe always matches just before a trailing \n in particular, with or without re.M. > (?!\n) makes sense. Yes, negative-lookahead is quite handy sometimes. Alex From roy at panix.com Wed Nov 20 22:46:47 2002 From: roy at panix.com (Roy Smith) Date: Wed, 20 Nov 2002 22:46:47 -0500 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <3DDBB8BD.6020806@web.de> <3DDBE406.6030803@nyc.rr.com> Message-ID: Courageous wrote: > Even if Python and Ruby have or will have the _capabilities_ that > Lisp has, (Python (will (never (be (lisp))))). Um, shouldn't that be __capabilities__? :-) From nw_moriarty at yahoo.com Thu Nov 14 19:34:01 2002 From: nw_moriarty at yahoo.com (Nigel Moriarty) Date: 14 Nov 2002 16:34:01 -0800 Subject: socket.error __del__ Message-ID: I'm using a TCP threading socket server and I get this error Exception socket.error: (10054, 'Connect reset by peer') in > ignored The program continues (I think because of the threading server) but it would be wonderful if I could stop this error being printed (without redirecting stdout as I'm doing other things with that). Nigel From uwe.schmitt at procoders.net Thu Nov 21 08:44:50 2002 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 21 Nov 2002 13:44:50 GMT Subject: py2exe/numpy/com-server problem References: Message-ID: Uwe Schmitt wrote: > Thomas Heller wrote: >> Uwe Schmitt writes: >> Maybe a missing numeric dll? Neither py2exe nor installer get them >> all, I think. If I remember correctly, multiarray.pyd dynloads >> _numpy.pyd (in C code), or something like that. >> You should try copying all the Numeric dlls (pyds). Does this help? > Thanks for your answer. I tried it, but the program still crashes. I found the reason: I forgot to copy on .pyd into the dist directory, now it works. Greetings, Uwe -- Dr. rer. nat. Uwe Schmitt Computer science is no more about Computers, uwe.schmitt at num.uni-sb.de than astronomy is about telescopes. (Dijkstra) http://www.procoders.net From lyle at users.sourceforge.net Mon Nov 18 15:11:52 2002 From: lyle at users.sourceforge.net (Lyle Johnson) Date: Mon, 18 Nov 2002 14:11:52 -0600 Subject: Debugging python with C++ extensions References: <3DD921E0.2000605@elemtech.com> Message-ID: <3DD94988.6050901@users.sourceforge.net> Karl G. Merkley wrote: > I am looking using python as a framework for some C++ components. > However, I am concerned about debugging across the python/C++ interface. > How do people currently debug python with C++ extensions. Every C++ > component will have it's own unit test; however, it seems inevitable that > there will be times when it would be helpful to step from the python > code into the C++ component. This recipe from the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66510 may give you something to work with. Hope this helps, Lyle From martian_bob at portalofevil.com Thu Nov 28 16:37:47 2002 From: martian_bob at portalofevil.com (R. Arens) Date: 28 Nov 2002 13:37:47 -0800 Subject: Problem opening files while using os.path.walk Message-ID: <4f5748b4.0211281337.5597a4ac@posting.google.com> Hi. I'm writing what should be a simple function that will walk a directory structure, opening and joining all files within the directory tree into a single huge file. I'm using os.path.walk and testing the list of files returned to the function specified in walk to make sure that each file is actually a file as opposed to another directory - herein lies the problem. The function isn't seeing _anything_ as a file, and is just skipping it. This one has me quite perplexed, and I'd appreciate any help anyone can offer. Thanks! Code follows.... import os, sys def walkJoin(out, dirname, names): print "Current directory: " + dirname names.sort() for name in names: if os.path.isfile(name): file = open(name, 'r') lines = file.readlines() for line in lines: out.writeline(line) file.close() else: print "Keep walking" os.path.walk(name, walkJoin, out) print "Done with directory ", name def main(): out = open('out.txt', 'w') directory = raw_input("Enter the name of the directory: ") print "Root directory " + directory os.path.walk(directory, walkJoin, out) out.close() From jepler at unpythonic.net Wed Nov 13 16:47:42 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 13 Nov 2002 15:47:42 -0600 Subject: Help with searching a list In-Reply-To: References: <8d3e714e.0211111913.2e0964c3@posting.google.com> Message-ID: <20021113214741.GB13513@unpythonic.net> # Replace this with a more sophisticated test if you prefer def flattenable(o): return type(o) == list def flatten(x, b = None): if b is None: b = [] for i in x: if flattenable(i): flatten(i, b) else: b.append(i) return b def flatten_generator(x): for i in x: if flattenable(i): for j in flatten(i): yield j else: yield i Jeff From dfan at dfan.org Tue Nov 12 23:41:25 2002 From: dfan at dfan.org (Dan Schmidt) Date: 12 Nov 2002 23:41:25 -0500 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3dce5e2f$0$35917$edfadb0f@dread13.news.tele.dk> Message-ID: Martin Maney writes: | So the typical processing loop is conceptually simple in a language very | similar to Python: | | for l in file.readlines(): | if (m = re1.match(l)): | (first, second, ...) = m.groups() | process type 1 record ... | elif (m = re2.match(l)): | ... | ... | | Now, I don't use indents as small as that in real code, and the processing | itself typically added a few levels. So the straightforward translation of | the simple concept into Python would go marching steadily off towards the | right side of the screen. Very annoying, and so unnecessary. Yeah, this is the main thing that annoys me about not being able to use assignments as expression. | But in this case there was a beautiful, only mildly hazardous | solution. | | I wrapped the compiled regexps in a class that saved the results of | applying the regex to a string, of course. | | Notationally, this is very nice. The code now looks like | | for l in file.readlines(): | if re1.match(l): | (first,second ...) = re1.groups() # typically | process type 1 record ... | elif re2.match(l): | ... | ... I've done this too for simple scripts. If you're writing reusable code, one thing you do have to worry about with this approach is thread safety. Another alternative, which is often possible because this stuff tends to happen inside line-processing loops, is: for l in file.readlines(): m = re1.match(l) if m: (first, second, ...) = m.groups() process type 1 record ... continue m = re2.match(l) if m: ... ... Dan -- http://www.dfan.org From mgarcia at cole-switches.com Sat Nov 16 13:54:20 2002 From: mgarcia at cole-switches.com (Manuel M. Garcia) Date: Sat, 16 Nov 2002 18:54:20 GMT Subject: quick question References: <20021116120631.08993.00000062@mb-fo.aol.com> <3DD685B6.DF1C65FF@engcorp.com> Message-ID: On Sat, 16 Nov 2002 12:51:50 -0500, Peter Hansen wrote: (edit) >Of course, this group being what it is, someone will >almost always post a fully functional solution with >annotated source without even questioning whether that >will hurt you more than it will help. ;-) > >I actually find that a little sad, personally... It is the curse of Python. It is so much fun to code in Python, and so easy, most of us cannot stop our fingers. Of course, all your points are correct. I was thinking just a few days ago about how this group will change as Python gets more popular for teaching programming. Manuel From shti at attbi.com Fri Nov 15 15:47:31 2002 From: shti at attbi.com (Yuri Shtil) Date: Fri, 15 Nov 2002 20:47:31 GMT Subject: pdb misbehaves in emacs-21.2.1 References: <3DD5528C.5090608@attbi.com> Message-ID: <3DD55C9B.3070707@attbi.com> Correction: Yuri Shtil wrote: > Hi > > I have installed RH 8.0 and got emacs-21.2.1 with it. > > I noticed that pdb (python debugging package) no longer tracks the > source code. It displays line numbers in the debugger window instead. > The statement that it works after I moved gud.el is NOT correct. Something is fishy there. I THOUGHT it worked, but I cannot see it working anymore. > It works well with emacs-21.1.1. When I moved the file gud.el to the new > emacs and byte-recompiled it, the correct behavour appeared. > > I concluded that the changes to the gud.el introduced in 21-2.1 broke > the pdb (or maybe some other supported debuggers). > > Any clues anyone ? > > Yuri. > From donn at drizzle.com Sun Nov 24 13:36:16 2002 From: donn at drizzle.com (Donn Cave) Date: Sun, 24 Nov 2002 18:36:16 -0000 Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <2259b0e2.0211210838.7647301a@posting.google.com> <093kra.3n3.ln@beastie.ix.netcom.com> Message-ID: <1038162975.415777@yasure> Quoth Alexander Schmolck : | "Donn Cave" writes: | | > If there's one thing that makes Python a bad choice for me, that's it. | > During development, static type systems save me a lot of trouble. | | Have you tried pychecker? I'm not sure what sort of troubles static type | systems save you from, but at least for the relatively trivial but common | cases like typos, pychecker seems to do quite a good job. In the context where I've been making my typos lately, pychecker has been out of its depth. Lots of stuff it can't follow for one reason or another, functions too long to analyse, etc. This is not all my own code, I hasten to point out. Most of the problems are just limitations in pychecker that could be overcome with more development effort. But this same software is full of every kind of introspective hack you can think of, importing modules determined at run time and that kind of thing. | On the whole, I think compulsory static typing is a bad idea. It invariably | seems to lead to spurious warnings and unnecessary code (partly because | typecheckers are usually quite daft and complain about correct code and partly | because it causes less flexible code) and longer development times. | | It would seem to me that most or all of the benfits of static typing can be | obtained from tools. It can't. In places where the program itself is determined by run time inputs - like in the case of the module that's imported that way - your tool is of no use. That's an extreme case, but in general, Python isn't typable, be it compulsory or optional. As per another followup's observation, it does not come as a surprise to find that static type checking is not popular on comp.lang.python, and it probably isn't worth while to take it up here. I will only say that there are many languages that have some degree of static typing, and the quality and usefulness differs a lot from one to another. OK, and I guess I will say, if you don't count bugs that turn up in a program months after you thought it was finished, I think you are underestimating your Python development time. But forget the way other languages do it, we're all Python users here and we're talking about how experts program in Python, and guess what - we're responsible for doing the work that the static type checking language would have supposedly done during compilation. We have to reason about the correctness of programs - so - we have to write programs that people can reason about with decent odds of success. Python's most frequently touted advantage is probably its readability, and of course that's the same thing, and of course it isn't achieved just by selecting Python as your implementation language. I would like to propose, for example, that a simple 'if/elif/else' block might be better than mounds of OO code with objects that register themselves in tables at run time, if it means that you can tell at a glance how the code works. I would like to propose that an expert Python programmer is one who knows all the introspective tricks in the book, and knows better than to use them. Donn Cave, donn at drizzle.com From robin at jessikat.fsnet.co.uk Thu Nov 14 08:06:54 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 14 Nov 2002 13:06:54 +0000 Subject: windll event loop leaks References: Message-ID: In article , Thomas Heller writes ....... > >Sounds like a leak in calldll? > >So the only advice is to build a debug version and run it with a >debugging build of Python to either use > I also suspected the calldll stuff, but when I try just a simple looping pair eg from dynwin import windll testdll = windll.module('testdll') print 'start', for i in xrange(1000000): testdll.setrecord(i) testdll.getrecord() print 'finished' then I don't see any memory leakage. This dll is one of my old tcldllcaller things and so uses standard C linkage. /*testdll*/ int record=0 int getrecord(void) { return record; } void setrecord(int i) { record = i; } One thought that occurs is that the system API linkage might be different. Any thoughts on that? If that were the case I would assume leakage in the stack. >- the (undoumented) sys.getobjects() function to find leaking objects. >- or step through calldll's code with the MSVC debugger. > >You should be able to find some messages on python-dev were Tim Peters >explains what getobjects() does. Thanks for that. > >Another approach ;-) would be to give up calldll/windll and try the >ctypes module - this way you would have me debugging the thing (in >case it leaks). > >Thomas Well it's only a few days old according to the announcement I just found :) I will certainly give this a whirl. It doesn't provide a callback generatr, but I suppose I can still use Sam's gencb. Does ctypes use the FFI library for accessing external DLLs? That way it would map to other platforms fairly easily. -- Robin Becker From aleax at aleax.it Mon Nov 18 06:04:36 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 18 Nov 2002 11:04:36 GMT Subject: gobbling (was Re: What is the best way to merge two lists?) References: <3DD71094.2030606@attglobal.net> <3DD7F1D4.4090201@attglobal.net> Message-ID: <8P3C9.29956$Yw.1496221@news2.tin.it> Gon?alo Rodrigues wrote: ... > I believe it has also been made stable-sort. The con is that it gobbles > up more memory. Here's a first attempt to quantify that "gobbling": import sys import random # memsize -- theoretically-portable version import resource pagesize = float(resource.getpagesize()) mega = 1024 * 1024.0 def megs(x): return '%.2f' % (x*pagesize / mega) def vmegs(): res = resource.getrusage(resource.RUSAGE_SELF) return res[4] # Linux-only hack pagesize = 1 def vmegs(): mstr = open('/proc/self/stat').read().split()[22] return int(mstr) maxmem = 0 def memsnap(): global maxmem mem = vmegs() if mem>maxmem: maxmem=mem def cmp_and_snap(x, y): memsnap() return cmp(x, y) random.seed(234876) N = 5000 if len(sys.argv)>1: N = int(sys.argv[1]) data = range(N) random.shuffle(data) startmem = megs(vmegs()) data.sort(cmp_and_snap) print "%s -- %d: %s -> %s" % (sys.version, N, startmem, megs(maxmem)) [alex at lancelot alex]$ python2.2 some.py 20000 2.2.2 (#1, Oct 24 2002, 11:43:01) [GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] -- 20000: 3.10 -> 3.10 [alex at lancelot alex]$ python2.3 some.py 20000 2.3a0 (#4, Nov 6 2002, 09:18:17) [GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] -- 20000: 3.55 -> 3.61 [alex at lancelot alex]$ python2.2 some.py 100000 2.2.2 (#1, Oct 24 2002, 11:43:01) [GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] -- 100000: 4.33 -> 4.33 [alex at lancelot alex]$ python2.3 some.py 100000 2.3a0 (#4, Nov 6 2002, 09:18:17) [GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] -- 100000: 4.78 -> 4.97 [alex at lancelot alex]$ A first assessment: 2.3 takes up more memory than 2.2 -- about 0.45 MB more independently of the tasks involved. 2.3 also takes up extra memory for its sort operation -- here, about 0.06 MB more when sorting a 20,000 items list, about 0.19 MB more when sorting a 100,000 items list. There MAY be limit-cases where this extra memory consumption does hit performance -- cases where 2.2 was just on the verge of VM thrashing and the small extra memory requested by 2.3 pushes the process just above the edge -- but only if the working set is also increasing, which I do not yet _know_ (the above is only meeasuring the overall memory footprint, not the working set); and they should be rare cases. Tentative conclusion: for now, I wouldn't particularly worry about the extra memory consumption, pending of course more investigation. Alex From gerhard.haering at opus-gmbh.net Wed Nov 6 20:56:39 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 7 Nov 2002 01:56:39 GMT Subject: question on select References: Message-ID: In article , Gon?alo Rodrigues wrote: > Hi, > > I know that select does not work on file objects in the Windows > platform. But does select work on sys.stdin? On the Windows platform, > that is. Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> type(sys.stdin) >>> sys.stdin.fileno() 0 >>> Does that answer your question? ;-) stdin/stdout/stderr *are* file objects. -- Gerhard H?ring OPUS GmbH M?nchen Tel.: +49 89 - 889 49 7 - 32 http://www.opus-gmbh.net/ From imbosol at vt.edu Tue Nov 26 03:40:09 2002 From: imbosol at vt.edu (Carl Banks) Date: Tue, 26 Nov 2002 03:40:09 -0500 Subject: if : References: Message-ID: "Simon Wittber (Maptek)" wrote: > I remember in my TurboC++ 2.0 days, the compiler would spit out > 'Ambiguous assignment' or something like that anyway. 'Possibly incorrect assignment' > I always found the construct if(x = func()) rather confusing, and > *never* used it, even though it was available and acceptable to do > so. Same here. -- CARL BANKS From aleax at aleax.it Mon Nov 18 05:03:30 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 18 Nov 2002 10:03:30 GMT Subject: Calling local functions from the C API References: Message-ID: Jon Parise wrote: ... >> In Python, you could write >> >> d = {} >> exec sourcecode in d >> func = d['SomeFunction'] >> func() >> >> Now just do the same in C. Which of the four steps is unclear to you? > > Thinks makes sense, I think (although I may have more questions when I > work on my actual implementation). > > The one thing I note, however, is that I just can't execute arbitrary > blocks of code via PyRun_SimpleString() and expect to be able to > execute a function defined in one of those blocks of code again. > Instead, it looks like I'll need to use Py_CompileString() or similar > to maintain a code object. > > Is that correct? Not really. When an arbitrary block of source code contains a def statement, you want to EXECUTE that block of code, specifically to execute that def statement, which creates the function object that you can later call (not sure what you mean by "again" here). If you just COMPILE the block to bytecode, the function object will not be created until the def statement is executed. Maybe the key tidbit you need to keep in mind is: def is a statement just like any other -- when the def statement EXECUTES, it creates a function object and binds that object to a name. So, def is quite similar to an assignment statement "name = expr", where the expr part creates an object and the assignment binds that object to the name. Sometimes programmers with experience in other languages have a hard time grasping the simple fact that def is a statement, and the consequences thereof, because they may be thinking in terms of "declarations" (which other languages have but Python doesn't). Alex From timr at probo.com Tue Nov 26 02:04:26 2002 From: timr at probo.com (Tim Roberts) Date: Mon, 25 Nov 2002 23:04:26 -0800 Subject: Python for website size References: Message-ID: <0476uugl13jgrkh3dvm3vortdogb5cem4h@4ax.com> "Shawn Zeng" wrote: > >Is there any python program or libray can be used to obtain the total size >of a website and its individual pages as well? Do you mean remotely? As in, a web site on another computer? If so, then the answer is no, this information is not learnable without fetching each and every link and image on every page and adding up the sizes yourself. On your own web site, you can use the 'du' command as suggested by another poster, but many sites put icons and images in separate directory trees, so even that is not entirely reliable. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mis6 at pitt.edu Sat Nov 16 10:43:20 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 16 Nov 2002 07:43:20 -0800 Subject: Web Programming in Python Message-ID: <2259b0e2.0211160743.eb01a55@posting.google.com> I was browsing in Amazon.com for Python books and I have found Web Programming in Python: Techniques for Integrating Linux, Apache and MySQL by George K. Thiruvathukal, Thomas W. Christopher, John P. Shafaee used at $4.00 (original price $44.99). I bought it; it arrived in a week and it is in perfect conditions, like new. I thought people could be interested. Michele P.S. I have checked today and the price has lowered !? From wurmy at earthlink.net Wed Nov 13 01:15:10 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Wed, 13 Nov 2002 06:15:10 GMT Subject: __getattr__ and others References: Message-ID: <3DD1EF79.8070509@earthlink.net> Grzegorz Dostatni wrote: > Hi. > > I want to create an object that (at runtime) is called with an arbitrary > function with arbitrary number of arguments. Haveing this call it will > forward it through xml-rpc to the server, execute it and return the > results. > > I am missing something simple - here is what I have: > > def calling(self, method="", *args, **kwargs): > print "calling method ", method > print "With arguments", args, kwargs > > def __getattr__(self, name): > return lambda s=self, m=name, *args, **kwargs: apply(s.calling, > (m, ) + args, kwargs > > This works as expected for (o is the instance of the object) > > 1. o.hello = OK. Returns the lambda function. > 2. o.hello(keyword="Argument") = OK. that works. > 3. o.hello(3, keyword="Argument") = This does not work. > 4. o.hello(3) = This does not work again. > > I have to do something like o.hello(o, "hello", 3) to get what I want. That's because if you do o.hello(3), s gets the value 3: lambda s=self, ... rather than 'self'. Next you try to call s.calling, and since s is an integer now, it doesn't have a method 'calling'... This does not occur with the keyword arguments, since they go to the **kwargs dict rather than overriding the s or m arguments. > Does anyone have an idea how to make it more consistent with normal > calling style? This might work: def __getattr__(self, name): def temp(*args, **kwargs): self.calling(name, *args, **kwargs) return temp HTH, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ Kaa:: http://www.awaretek.com/nowak/kaa.html From dwelch91 at nospam.attbi.com Sat Nov 23 13:05:29 2002 From: dwelch91 at nospam.attbi.com (djw) Date: Sat, 23 Nov 2002 18:05:29 GMT Subject: reliable tcp server holding multiple connections References: <3DDFAEB4.1040506@nospam.attbi.com> Message-ID: <3DDFC36D.4090906@nospam.attbi.com> Wojtek Walczak wrote: > Dnia Sat, 23 Nov 2002 16:37:07 GMT, djw napisa?(a): > >>Do you know about Medusa? > > Yes, but Medusa it a little bit large. I want to create small code, > proof of concept. An educational example, nothing more. > I would take a look at Steve Holden's "Python Web Programming". I think it has examples of what you are after. /d/ From fperez528 at yahoo.com Wed Nov 6 02:04:47 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 06 Nov 2002 00:04:47 -0700 Subject: ** URGENT ** Obtaining global and local dict's for current interpreter using C API References: Message-ID: quadric at primenet.com wrote: > Hi, > > I am new to Python but an experienced C++ programmer familiar with > scripting etc..... and > very excited about Python. I have successfully embedded/extended it and am [snip] A friendly suggestion: repost your question removing the '** URGENT**'. Not only does it sound a bit rude to many, I bet you most of those who might have given you a good answer (your question is valid and interesting) probably didn't even read your message. These days, I know that I blindly hit 'd' whenever I see '***ANYTHING IN CAPS***blah', since it tends to be related to some very interesting financial transaction involving some African country. So welcome to c.l.p, and I bet you a repost without the spam-triggering ALLCAPS will get you some good answers. Cheers, f. From nw_moriarty at yahoo.com Fri Nov 8 19:29:26 2002 From: nw_moriarty at yahoo.com (Nigel Moriarty) Date: 8 Nov 2002 16:29:26 -0800 Subject: pickle-ing two instances of the same class on MSW Message-ID: Folks I have a list of two instances of the same class in a list which I can pickle on LINUX but it fails on MSW with this error. cPickle.PicklingError: Can't pickle two.Task: its not the same object as two.Task which is stating the obvious. Any help Nigel From wlfraed at ix.netcom.com Mon Nov 25 14:06:12 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 25 Nov 2002 11:06:12 -0800 Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <1038199757.350382@yasure> Message-ID: <5bstra.no3.ln@beastie.ix.netcom.com> Donn Cave fed this fish to the penguins on Sunday 24 November 2002 08:49 pm: > Quoth Pascal Costanza : > | > | Message passing means that there are several entities that > | communicate by sending messages between them. The main points are > | that these entities are autonomous and that there is no central > | "main" program that controls the behavior of these entitities. > > But that's somewhat circular. Message passing means that there are > entities that pass messages, eh? But what would a message be, > precisely? What are the semantics of passing, for the sender and the > recipient? > How is it different from calling a subroutine? Is multi-threaded > execution necessary for this model? If there is no main program, > where does the program begin? Can Python programs be written this > way, and if so how would you tell the difference? > Pure message passing tends to imply threading at the minimum (and fully separate processes at the extreme -- AmigaOS was one such). I don't think P.C. said there wasn't a main that initiated the system, but that the main didn't control the processing once started. Main could have been a shell script starting five or six programs as background tasks, and the tasks then use IPC to pass messages. A Python program written for this scheme, in purest form, probably creates n-Queues (one for each of the n-entities), then starts each of the entities as a distinct thread; after which the main program just waits for everyone to complete. Message passing would be handled by the sender process putting an entry onto the destination's Queue (to identify the source, I'd expect the message format to be a tuple of (return-thread's Queue, message data) ). The main difference, in my mind, is that subroutine/method calls are synchronous -- the caller is frozen until the method completes and returns. Message passing allows both to continue. -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From bokr at oz.net Sun Nov 24 17:25:00 2002 From: bokr at oz.net (Bengt Richter) Date: 24 Nov 2002 22:25:00 GMT Subject: if : References: <3DE14A0C.E0CDBC16@alcyone.com> Message-ID: On Sun, 24 Nov 2002 13:52:12 -0800, Erik Max Francis wrote: >Andr? N?ss wrote: > >> if myvar = someFunction(): >> >> My question is, what is the rationale for this? Is it a technical >> issue? Or >> purely a matter of language design? I'm curious because I'm interested >> in >> the design og programming languages, not because I want this behavior >> changed in Pyton :) > >It's a language design feature, intended to avoid the confusion between >when people write (say, in C): > > if (a = b) ... > >but mean > > if (a == b) ... > >Instead in Python assignments are treated as statements, not >expressions, so they cannot appear in an if clause. > except in perverse ways (and this is not the only one): >>> a Traceback (most recent call last): File "", line 1, in ? NameError: name 'a' is not defined >>> b=123 >>> if [a for a in [b]][0] == 123: print 'aha' ... aha >>> a 123 BTW, are list comprehensions going to get their own local namespace sometime or is this the way it's going to be forever? Regards, Bengt Richter From clspence at one.net Tue Nov 5 15:13:26 2002 From: clspence at one.net (Chris Spencer) Date: 5 Nov 2002 14:13:26 -0600 Subject: help() function References: <0h2esukvqtolp17lt0hdg72ua9t038k18v@4ax.com> Message-ID: Wow, thanks! This is perfect for my needs. :) Chris. On 5 Nov 2002 01:03:58 GMT, bokr at oz.net (Bengt Richter) wrote: >On 4 Nov 2002 18:05:19 -0600, Chris Spencer wrote: > >> The documentation makes it clear that the help() function is only used >>in interactive mode. However, I see it as a really neato-way of generating >>standalone .txt files from docstrings in modules. However, as it currently >>stands, it looks like help() can ONLY be used in interactive mode, which means I >>can't capture the output to a file. >> Is there any way to get the same docstring formatting that help() uses, >>but be able to capture it to a variable or a file handle? >> Inquiring minds want to know. > python D:\Python22\Lib\pydoc.py > a_file.txt > >as extension-triggered program output is not always redirectable. > >Regards, >Bengt Richter From spammers.do.not.bother at void.bogus Fri Nov 22 16:00:21 2002 From: spammers.do.not.bother at void.bogus (Magnus) Date: Fri, 22 Nov 2002 21:00:21 GMT Subject: Python and gd library References: Message-ID: Antonio.P wrote: > Hi to all > Is there some integration in Python of the GD graphics library? > http://www.boutell.com/gd/ > > Python instructions produce very poor quality images.. :-( Perhaps you would like to try: http://www.nullcube.com/software/pygdchart.html Regards, Magnus From shalehperry at attbi.com Sun Nov 10 02:20:20 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sat, 9 Nov 2002 23:20:20 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? In-Reply-To: References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: <200211092320.20597.shalehperry@attbi.com> On Saturday 09 November 2002 17:46, Pascal Costanza wrote: > > The core is extremely simple: > > This is a piece of program in Lisp: (gethash "key" table) > This is some data in Lisp, a list: '(gethash "key" table) > > In the first example, we have a call of the function gethash with > arguments "key" and table. In the second example, we have a list with > the three elements gethash, "key" and table. > > (BTW, this is exactly the reason why Lisp has this seemingly strange > syntax - you can easily switch between program representation and data > representation. On the conceptual level, Lisp makes no difference > between data and programs.) > I have picked up lisp a few times and put it back down each time. As I become a better programmer I find lisp makes more sense. The prefix thing no longer bothers me because I just parse it as a function call and not algebra like I learned in school. What always bothers me though is the quote syntax. '(this text) is different from (this text). I find that when reading code it is very, very easy to miss that silly quote. Sure you just learn to look for it but it is still what irks me most. From wlfraed at ix.netcom.com Tue Nov 26 21:14:11 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 26 Nov 2002 18:14:11 -0800 Subject: if : References: Message-ID: Dave Brueck fed this fish to the penguins on Tuesday 26 November 2002 08:33 am: > Ugh! Shame on any aspect of a language that burdens the developer this > way. The fact that such strategies as the above have cropped up is, > IMO, proof that the language is broken in that area. We don't say, "Is > Tuesday today?" or "Is 5 your age?", either. :) > Well, not in normal English, at least I've seen too many novels that try to indicate "foreigner" by using a hacked germanic structure... Not alone Yoda is... 5 your age is... Tuesday today is... {besides Yoda, there is the Weaponsmaster in Lackey's Valdemar novels, the orientation supervisor in McCaffrey's Crystal Singer novels, and the agent(s) in some of Modesitt's Ecolitan novels} -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From maney at pobox.com Wed Nov 27 01:12:17 2002 From: maney at pobox.com (maney at pobox.com) Date: Wed, 27 Nov 2002 06:12:17 +0000 (UTC) Subject: if : References: Message-ID: Delaney, Timothy wrote: > Most studies after all do have a specific agenda in mind ;) The price of getting funding, alas. From imbosol at vt.edu Fri Nov 15 15:40:30 2002 From: imbosol at vt.edu (Carl Banks) Date: Fri, 15 Nov 2002 15:40:30 -0500 Subject: wrapping all class methods References: Message-ID: Robin Becker wrote: > In a partially successful attempt at wrapping all methods in a > module I used the appended code. It does add a traceback wrapper to > each method, but the tracebacks don't continue back very far ie I > typically see something like > > [Application.__getattr__] > Traceback (most recent call last): > File "", line 3, in __getattr__ > File "C:\Python\devel\anygui\lib\anygui\Attribs.py", line 67, in __getattr__ > raise AttributeError, name > AttributeError: wrapper Can't tell what's going on here. My best guess is there's a bug in your exec'd string, and it is trying to call an method that doesn't exist. > ie the traceback seems to get stuck in the wrapper method. What's > the 'proper' pythonic way to do this kind of global wrapping? Metaclasses. What else? :-) Ok, it looks like you want to do this on the fly, and I don't think you can set a class's type after it's been defined. (Maybe you can assign to it's __class__ attribute, but I recall that assigning to __class__ is being phased out.) > ##### attempt at wrapping all methods > n = 0 > from inspect import isclass, ismethod, getmembers > def makeTBWrap(C,methodname): > import new > global n > oldmethodname = '_%d_tbWrap_%s' % (n,methodname) > oldmethod = getattr(C,methodname) > S = [] > s = S.append > s('def %s(self,*A,**K):' % methodname) > s('\ttry:') > s('\t\treturn self.%s(*A,**K)' % oldmethodname) > s('\texcept:') > s('\t\timport traceback') > s('\t\tprint \'[%s.%s]\'' % (C.__name__,methodname)) > s('\t\ttraceback.print_exc()') > s('\t\traise') > s('setattr(C,oldmethodname,oldmethod)') > s('setattr(C,methodname,new.instancemethod(%s,None,C))' % methodname) > exec '\n'.join(S) + '\n' in locals() > n += 1 Mega-Ugh. Using exec for stuff like this is hella-uncool. That's is what nested scopes are for: def makeTBWrap(C,methodname): oldmethod = getattr(C,methodname) def wrapper(self,*A,**K): try: return oldmethod(self,*A,**K) except: import traceback print "[%s.%s]" % (C.__name__,methodname) traceback.print_exc() raise setattr(C,methodname,wrapper) Maybe you're using a version where there are no nested scopes. And in this case, you can't use a callable class, because we're replacing a method. You can set C, oldmethod, and methodname as optional arguments to wrapper, using odd names that you hope will never be arguments to the method you're wrapping--the risk of variable capture is probably worth it to avoid having to use exec. Also, note that you don't have to set the oldmethod as an attribute of the class to call it. You can call a method simply by calling it with the instance as the first argument, as I did. This is why class.method(instance,args) is equivalent to instance.method(args). -- CARL BANKS From ktilton at nyc.rr.com Sat Nov 23 15:47:42 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Sat, 23 Nov 2002 20:47:42 GMT Subject: Newbie w IDE Issues (win32) Message-ID: <3DDFE9D1.4000608@nyc.rr.com> I am trying to settle on the best way to work on multi-module projects in Python. In other IDEs for C and CL, after editing any number of separate text files I can with one keystroke: save all open files recompile all and only changed files run the project With IDLE (hopefully needlessly): for each changed file other than the 'main' one: save it run it (^F5) [side question below] find the module I consider main save it run it 1. main question: is there a better way with IDLE? Or.. I saw the various IDEs in the vaults, any recommendations? Oddly, after /years/ of doing Lisp I still have not gotten into emacs, and want to defer that a while longer. 2. side question: IIANM, I cannot just save a module. I guess the import picks up the old .pyc? FWIW, all in all, IDLE is serving nicely. -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From jan at jandecaluwe.com Wed Nov 27 15:40:26 2002 From: jan at jandecaluwe.com (Jan Decaluwe) Date: Wed, 27 Nov 2002 21:40:26 +0100 Subject: Issue with new-style classes and operators References: <3DE215D1.D9A3FEF9@jandecaluwe.com> <5ApE9.52343$744.1917235@news1.tin.it> <3DE2893A.CCB631D6@jandecaluwe.com> <3DE449BD.1040503@something.invalid> <3DE48ECC.8FC9AE53@jandecaluwe.com> Message-ID: <3DE52DBA.27A072AF@jandecaluwe.com> Terry Reedy wrote: > > "Jan Decaluwe" wrote in message > news:3DE48ECC.8FC9AE53 at jandecaluwe.com... > > Ok, let me explain better. Suppose - for the sake of the > > argument - that I have a legitimate need for mutable numbers. > > To me, the concept 'mutable number' doesn't 'compute' very well. > > A label or pointer that is attached to or points to different > (eternally existing) numbers at different times (a 'variable') make > sense, and we have such. > > A container whose number contents change also make sense, and we also > have that. > > One could regard a count as a (changeable) collection of units, but > that is similar to the above and can be modeled either with list or > set/dict. > > So what do you mean by mutable number, such that it could be needed > but not available today? Too long to explain here - really. I promise I will though (in another thread, at another time). I propose to concentrate on the main point here: whether Python works as promised or not. At this moment - and with your help - I believe I can show it doesn't. Regards, jan -- Jan Decaluwe mailto:jan at jandecaluwe.com From max at alcyone.com Thu Nov 14 14:05:12 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 14 Nov 2002 11:05:12 -0800 Subject: PEP #99484663 References: <418ab5dd.0211141031.48b7f0bf@posting.google.com> Message-ID: <3DD3F3E8.3D083FA6@alcyone.com> bboman at research.panasonic.com wrote: > I could go into a long explanation as to why block delimiters are > useful but I will just say that when you cut and paste a block of code > from one nested block loop into another block at a different > indentation level it is much nicer and much less error prone to just > tell emacs to re-indent the entire function than to manually adjust > each line. If you're already using emacs, it's far easier to just do block indents and unindents with C-c > and C-c <. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ History is a bucket of ashes. \__/ Carl Sandburg EmPy / http://www.alcyone.com/pyos/empy/ A system for embedding arbitrary Python in template text as markup. From fgeiger at datec.at Wed Nov 13 14:05:15 2002 From: fgeiger at datec.at (F. GEIGER) Date: Wed, 13 Nov 2002 20:05:15 +0100 Subject: [regexp] Where's the error in this ini-file reading regexp? Message-ID: <3dd2a254@news.swissonline.ch> Dear all, I have to parse a string which contains data in ini-file-format, i.e.: s = \ ''' [Section 1] Key11=Value11 Key12=Value12 Key13=Value13 [Section 2] Key21=Value21 Key22=Value22 Key23=Value23 ''' I decided to try a solution using re (yes, ConfigParser or simple string splitting would be an other way to do it), because the structure really is regular: Sections, which contain key/value pairs. I'm sure there's only a tiny step left to succeed. I tried: rex = re.compile(r"(\s*(\[.+\])(\s*((.+)=(.+)))+?)", re.MULTILINE|re.IGNORECASE) L = rex.findall(s) where s is the string already shown above. What I get is: [('\n[Section 1]\nKey11=Value11', '[Section 1]', '\nKey11=Value11', \ 'Key11=Value11', 'Key11', 'Value11'), ('\n[Section 2]\nKey21=Value21', \ '[Section 2]', '\nKey21=Value21', 'Key21=Value21', 'Key21', 'Value21')] So L[0][1] contains the string 'Section1', L[0][4] the string 'Key11', L[0][5] the string 'Value11'. Section2 is also there and is contained by L[1]. So what I have is both sections, but only one (i.e. the first one) key/value pair for each of those two sections. When I remove the last '?' in ...(.+=.+))+?)" then the last key/value pair instead of the first one is the result. So this must have to do with greediness/non-greediness. What I wonder is, why do I not get all three key/value pairs? How can I tell the re engine "gimme *all* groups having key=value form", when a '+' delivers only the last, and '+?' only the first of those pairs? Many thanks in advance Franz GEIGER P.S.: You guess it, I use regular expressions only from time to time. Therefore I almost always run into troubles like this. Would Friedl's Mastering Regular Expression be an option for people like me? Anyone's owning it? Does it have a cookbook section too? Any other pointers except to those "if you want to parse a telephone number..."-examples? From edream at tds.net Wed Nov 6 10:31:29 2002 From: edream at tds.net (Edward K. Ream) Date: Wed, 06 Nov 2002 15:31:29 GMT Subject: Guilty secret: globals baffle me References: <3U9y9.19300$ko1.2872530@kent.svc.tds.net> Message-ID: > You can share globals across modules by means of import. If you want > to assign to the global, make sure you don't use from-import, but > import the module, then assign via module.globalname = value. Thanks for this reminder. - Edward From christian.stockhammer at students.uni-linz.ac.at Fri Nov 8 10:17:02 2002 From: christian.stockhammer at students.uni-linz.ac.at (Christian Stockhammer) Date: Fri, 8 Nov 2002 16:17:02 +0100 Subject: java to python Message-ID: <1036768161.439599@news.liwest.at> Hello List! I've got homework I have to solve in python but i just know a little bit java and i got my homework to run in java. Is there anybody who can help me to translate that code to python? Here it is: public class Tilgung{ public static void main(String [] args){ tilgungsplan(100000.0,5.0,20000.0); } static void tilgungsplan(double schuld,double zinsfaktor,double tilgung){ double zinsen; double echteTilgung; System.out.println("Periode Restschuld Zinsen Tilgung"); for(int i=0;i<5;i++){ zinsen=(schuld*zinsfaktor)/100; echteTilgung=tilgung-zinsen; System.out.println(" "+i+" "+schuld+" "+zinsen+" "+echteTilgung); schuld=schuld-echteTilgung; } System.out.println(" Restzahlung: "+schuld); } } This is what it produces: (it is a calculator for paying back a credit)!!! Periode Restschuld Zinsen Tilgung 0 100000.00 5000.00 15000.00 1 85000.00 4250.00 15750.00 2 69250.00 3462.50 16537.50 3 52712.50 2635.63 17364.38 4 35348.13 1767.41 18232.59 Restzahlung: 17115.53 Is there anybody who is willing to help me. I really appreciate any suggestions Cheers Christian From gerhard.haering at opus-gmbh.net Wed Nov 27 06:55:08 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 27 Nov 2002 11:55:08 GMT Subject: what does is ? References: <3de4a6dd$0$86531$ba620e4c@news.skynet.be> Message-ID: Jonas Geiregat wrote: > I saw something > import string > string._StringType is str > what does this specially that IS The "is" operator compares object *identity*, rather than equality, which the "==" operator does. > or in 2.2.2 string._StringTypes is str I'd assume the check "types.StringType is str" will check if you have a Python implementation (CPython or Jython) with class-type unification: In pre-2.2 versions of CPython, str was a built-in function, while in 2.2+, it is a new-style class: C:\>c:\Python21\python.exe Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> import types >>> str, types.StringType (, ) >>> C:\>c:\Python22\python.exe Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import types >>> str, types.StringType (, ) >>> str is types.StringType 1 -- Gerhard H?ring OPUS GmbH M?nchen Tel.: +49 89 - 889 49 7 - 32 http://www.opus-gmbh.net/ From max at alcyone.com Tue Nov 5 01:28:50 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 04 Nov 2002 22:28:50 -0800 Subject: Crash in curses stdscr.getkey? References: <3DC6FA56.74A8D516@alcyone.com> Message-ID: <3DC76522.54375641@alcyone.com> "David M. Cooke" wrote: > I've gone ahead and submitted a patch (SF #633635). Ah, excellent, thanks for looking into it. I figured it was far more likely it was in the Python glue layer than in curses itself, but really had no way of researching it directly (the crash doesn't happen on my machines). I've already released an updated version with the workaround, which is good enough for my users; just wanted to pass the word along about a potential problem. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Society attacks early when the individual is helpless. \__/ B.F. Skinner Bosskey.net: Return to Wolfenstein / http://www.bosskey.net/rtcw/ A personal guide to Return to Castle Wolfenstein. From aleax at aleax.it Sun Nov 24 18:20:41 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 24 Nov 2002 23:20:41 GMT Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <2259b0e2.0211210838.7647301a@posting.google.com> <2259b0e2.0211220946.5f61f641@posting.google.com> <3DDE711E.3010005@web.de> <6qyD9.60432$Yw.2729711@news2.tin.it> Message-ID: Pascal Costanza wrote: ... >>>I mean, Python is already more advanced than Java. >> >> Oh, I agree with this, but that's not the point. > > Er, I have thought that's exactly the point. What do you need a > backstage language for that is less powerful than the frontstage > language? The first Lisp interpreter was coded in machine language. The first Python interpreter was coded in C. Examples could easily be multiplied. The lower-level, faster language is often used as the "backstage" (not a term I'm familiar with, but I think I'm interpreting your meaning correctly). I think (not sure) that the first Prolog interpreter was coded in Lisp, presumably with similar intentions. So, I'm not quite sure what your question is meant as -- rhetorical, perhaps? > (I guess that Jython is useful to take advantage of the Java > APIs and its platform independence.) That's a typical reason to choose Jython rather than CPython, yes -- being able to take advantage of existing Java-coded libraries (including the APIs of the various Java-based standards), and/or of platforms able to run Java bytecode (including various JVMs). Alex From gminick at hacker.pl Sat Nov 16 09:53:28 2002 From: gminick at hacker.pl (Wojtek Walczak) Date: Sat, 16 Nov 2002 14:53:28 +0000 (UTC) Subject: Get Stdout from external script startet through python References: Message-ID: Dnia Sat, 16 Nov 2002 12:40:30 +0100, Christian Rapp napisa?(a): > I need to start an external script from inside python. This works just fine. > The called script produces some output on StandardOut, that I need within > the python-script. How do I get this Output into python? >>> import os >>> print os.popen.__doc__ popen(command [, mode='r' [, bufsize]]) -> pipe Open a pipe to/from a command returning a file object. >>> a = os.popen("/bin/date") >>> print a.read(), Sat Nov 16 19:42:59 CET 2002 >>> a.close() Is that what you wanted ? -- [ Wojtek gminick Walczak ][ http://gminick.linuxsecurity.pl/ ] [ gminick (at) hacker.pl ][ gminick (at) underground.org.pl ] From m.faassen at vet.uu.nl Fri Nov 22 16:55:46 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 22 Nov 2002 21:55:46 GMT Subject: Popular conceit about learning programming languages References: Message-ID: Matt Gerrans wrote: > I disagree. I've learned a number of languages and Python was by far the > fastest. This was probably due to the fact that it is not just easy to > learn, but also fun. But that might indicate Python was not your first programming language. Python is very easy to pick up if you have some experience with programming languages already; I can attest to that too. But if you're new to programming altogether it will take longer to assimilate all kinds of concepts. When I learned Python I knew about objects and references and garbage collection and functions and arguments and local and global variables and naming conventions and design patterns and module separation and namespaces already. If you have to learn all of that and everything I didn't mention to boot, you're going to take a while. Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From mgarcia at cole-switches.com Thu Nov 21 15:22:05 2002 From: mgarcia at cole-switches.com (Manuel M. Garcia) Date: Thu, 21 Nov 2002 20:22:05 GMT Subject: Popular conceit about learning programming languages References: <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <2259b0e2.0211210838.7647301a@posting.google.com> Message-ID: On Thu, 21 Nov 2002 14:00:47 -0500, mertz at gnosis.cx (David Mertz) wrote: (edit) >But even given that, a comparative linguist who "learns" Tlingit doesn't >really learn to carry on conversations with Tlingit speakers (edit) >When programmers optimistically "learn" a language in a couple days, it >is a similar thing. Good point. It "felt" like I learned Python in just a few hours, but I still have some of that early code on my hard drive, and looking at it makes me sick. Around the time I was learning Python, I was doing a lot of coding in Visual Basic, so I know why my early code makes me sick. Python, compared to other languages, does very little to stand in your way in being productive. Nothing outlandish, no maddening omissions, no strange operators, very few special cases, code can be translated into Python from other languages quickly without a very deep knowledge of Python. So it can "feel" like one can learn it very quickly. Manuel From rjones at ekit-inc.com Fri Nov 15 04:09:51 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Fri, 15 Nov 2002 20:09:51 +1100 Subject: rm -rf in python? In-Reply-To: <200211150508.VAA12921@mail.arc.nasa.gov> References: <3DD478CD.2080608@verio.net> <200211150508.VAA12921@mail.arc.nasa.gov> Message-ID: <200211152009.51211.rjones@ekit-inc.com> On Fri, 15 Nov 2002 4:08 pm, Chad Netzer wrote: > On Thursday 14 November 2002 20:32, VanL wrote: > > I suppose that I could recurse > > down through, deleteing as I went, but it seems that there must be an > > easier way. > > Nope, there isn't. (At least, not a portable way) Yes there is, os.rmtree() Richard From piet at cs.uu.nl Tue Nov 5 10:00:43 2002 From: piet at cs.uu.nl (Piet van Oostrum) Date: 05 Nov 2002 16:00:43 +0100 Subject: MySQLdb and threads References: Message-ID: >>>>> "Gillou" (G) writes: >> >>>>> "Gillou" (G) writes: >> G> Hi, G> I plan to make SQL queries in different threads of an application using G> MySQLdb. G> Can I use the same Connection object in all threads (each thread having G> its G> own cursor) for the queries ? Or should I use a different Connection G> object G> for each thread ? >> >> The doc says: >> G> [SNIP] >> For threaded applications, try using a connection pool. This can be done >> using the Pool module. G> Many thanks Piet for this enlightenment, G> Where did you find the Pool module you're writing of ? I just copied the doc. G> I didn't find it in the standard Python distro (2.1.3) nor with google. Google gives me: http://dustman.net/andy/python/Pool -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From blakeg at metalink.net Wed Nov 13 19:26:49 2002 From: blakeg at metalink.net (Blake Garretson) Date: Wed, 13 Nov 2002 19:26:49 -0500 Subject: wxPython program failing after upgrade Message-ID: I upgraded to wxPython 2.3.3.1 using the precompiled win32 binary, and now my wx program won't work. (I previously used 2.3.2.1) I'm using a DC client to draw some graphics, and it fails when it goes to refresh the screen. Here's the error that shows up in a popup dialog: """ c:\projects\wx\src\msw\dcclient.cpp(216): assert "wxFalse" failed: wxPaintDC may be created only in EVT_PAINT handler! Do you want to stop the program? """ (By the way, that path doesn't exist on my machine!) Then another error gets printed to stderr: """ File "C:\Python222\Lib\site-packages\wxPython\gdi.py", line 607, in DrawText val = apply(gdic.wxDC_DrawText,(self,) + _args, _kwargs) OverflowError: long int too large to convert to int """ I haven't changed the program at all. Just to be sure, I reinstalled Python 2.2.2 and then wxPython, and still no luck. I even tried the Unicode and ANSI versions! Any ideas what's going on here? Thanks, Blake Garretson From tonygreen at techie.com Fri Nov 8 08:19:09 2002 From: tonygreen at techie.com (Tony) Date: Fri, 8 Nov 2002 13:19:09 -0000 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: <9ROy9.7069$8P5.4238@news-binary.blueyonder.co.uk> My guess is that Lisp appeals to people who like predicate logic and Python appeals to people who like to deliver software. Lisp has been the mainstay of a lot of traditional AI courses for donkeys years, Python has been picked up by a lot of the new generation of programmers who learnt their trade on scripted web applications and needed something quick, clear and flexible to get the job done as quickly and painlessly as possible. I'm not at all familiar with Scheme. "Oleg" wrote in message news:3d5b5ad8.0211080454.50bc6128 at posting.google.com... > Hi > > I don't know much about Python, but I looked at this comparison > between Python and Common Lisp ( > http://www.norvig.com/python-lisp.html ), and I couldn't help but > wonder why Python is popular, while Common Lisp and Scheme aren't? > > Oleg From gustav at morpheus.demon.co.uk Mon Nov 11 15:46:20 2002 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: Mon, 11 Nov 2002 20:46:20 +0000 Subject: Efficient scanning of mbox files References: Message-ID: <3cq7q1gj.fsf@morpheus.demon.co.uk> Martin Franklin writes: > I ran the above example on my Python folder (7000+ messages...) > it took 12 seconds to process. Then I changed the > if FROM_RE.match(line): > > to > > if line.startswith("From "): Trouble is, I can't do this, as the mbox files I've got *don't* reliably have lines starting with "From" in the message body quoted with an initial ">" :-( > Then I slurped the file into a cStringIO.StringIO object and got it down > to 5 seconds..... I'll have a look at slurping, though. I was worrying because I have a mix of CRLF and LF line endings (some files have one, some the other). I wasn't sure what effect that would have - but thinking about it, as long as I read files in binary mode, seek offsets should be the same as byte positions in the in-memory string, so things should be OK. Thanks for the suggestions, Paul -- This signature intentionally left blank From piet at cs.uu.nl Tue Nov 19 09:13:24 2002 From: piet at cs.uu.nl (Piet van Oostrum) Date: 19 Nov 2002 15:13:24 +0100 Subject: installing mysqldb module in os x In-Reply-To: References: Message-ID: >>>>> "Stephen Aichele" (SA) writes: SA> Howdy. SA> I've installed mySQL v.3.23.52 on a system running mac os x 10.2, & SA> python 2.2. SA> I'm now trying to install the python module for interfacing with SA> mysql (mysqldb), but on 'python setup.py build', I keep getting the SA> following error: SA> 'can't locate file for: lmysqlclient-r' ... Before I go commenting SA> out lines in the setup file (I'm assuming that I actually DO have the SA> threadsafe libraries installed), I wanted to check if anyone else has SA> run into (and solved) this problem. If you installed the mySQL installer package then you don't have the threadsafe library. You should compile it yourself (or ask me for a copy). That's how I did it. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From a.schmolck at gmx.net Wed Nov 27 17:44:33 2002 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 27 Nov 2002 22:44:33 +0000 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <3DDBD838.10406@nyc.rr.com> <3DDC5851.5060001@nyc.rr.com> <3DE040DF.EACC7D3A@kolumbus.fi> <3DE2AEFE.BF188406@kolumbus.fi> Message-ID: Martti Halminen writes: > Alexander Schmolck wrote: > > > Sure, loop isn't the only iteration construct, but that doesn't really make it > > any better, does it? Especially given that all suffer from the fact that they > > only work on a quite small number of containers. > > Given that every "container" in the language has sufficient iteration > constructs to handle them, I don't see this as a problem. I really have difficulties understanding why you think this lack of polymorphism isn't (at least potentially) a problem. That's why I brought the ocaml example as an analogy: in ocaml you can't just do "1.0 + 1.0", although "1 + 1" works fine. That's because you have to use different operators for floats and ints. As there are however "sufficient constructs" for every number type "in the language", I guess you wouldn't see a problem with that either? > Steele's book "Common Lisp: the Language" was published in 1984; the > biggest missing piece was CLOS. And decent error handling, if I remember right? > The second edition, in 1990 contained most of the stuff that ended in > the standard. And some stuff that didn't (like series). But anyway, you conviently ignored my question why the fact that lisp (including pre-ansi CL) was around before python, perl etc. should have been a *disadvantage*. According to the logic of your argument (fast computers that mamke HLL viable are a relatively recent development), CL should in fact have had a major competetive advantage (when perl came out, there were already lisps that could rival fortran for numeric code). There are of course also plenty of other reasons why being an (I suspect you'd assume inferior) latecomer like python should be detrimental. > Nothing you have written has shown an "iteration class" as anything > desirable, either. OK, let me try a real example. One quite powerful corollary of having a generalized iteration protocol is that you can iterate over things that generate items on the fly (especially useful now that python also sports generators). This simple example, closely based on something I used not too long ago illustrates many of the nice features of iteration in python: colors = "rgbkcmy" styles = (":", "-:", "-", ".") for line, fill, color in zip(matrix, *map(xcycle, (colors, styles))): plot(line, fill + color) # append color to fill xcycle is a self-defined utility function that forever loops over some iterable: def xcycle(seq): while 1: for item in seq: yield item This will plot the rows of a matrix as lines with different color and fill combinations. Note that in this non-contrived example, there are 5 (!) different kinds of containers (or iterables): a matrix object, a string, a tuple, a list and a generator. The list returned by map is admittedly a bit gratuitous, since for only 2 arguments I might as well have written "...xcylce(colors), xcylce(styles)", but it provided a nice opportunity to bring in the nice *-syntax as a shorthand for apply (which of course also works on any iterable (and is much more readable than "apply(zip, [matrix] + map(...))")). The only thing I dislike is of the use of "+" to append stuff :) How would you write the same in CL? Of course this example is quite trivial (note however, that it handles different containers for "lines", such as arrays, matrix'es etc. which happen to be different classes), but I hope it helps to illustrate the point (if not I guess I could show you some others). > > > But that is besides the point. The python ``x = cont[indx]`` will likely > > continue to work even if I choose to replace ``cont`` with some other > > container type later. Same for ``for i in cont: ...`` etc. This is a fairly > > important abstraction barrier. > > If I didn't misunderstand the Python Reference Manual, that would > require stuff like __len__, __getitem__, __setitem__, __delitem__, > __iter__ to be written by you for it to work. Yes, if you wrote something that would act like a container type but instead of naming the relevant methods __iter__, __getitem__ etc. you'd idiotically call them , say 'frblbar' and 'qrtfds' etc., then your 'container' wouldn't support the iteration protocol and so forth. But what are you trying to say? > > > OTOH ``(let ((x (gethash key hash)) won't. T Sure, I could go along and define > > my own generic accesor functions (CL is powerful enough for that) > > (defmethod gethash (key (hash my-hash-table-type)) > ... whatever needed for my own stuff) > > (defmethod gethash (key hash) > (cl:gethash key hash));; default to normal > > If that was difficult in your opinion, we have different definitions for > difficulty. The point was not difficulty. The reason scheme sucks so bad is not because doing things is inherently difficult. It sucks because important fundamentals have no standardized expression. > It is a risk for your own code, but as you would be defining the > semantics, however underspecified you like, that is your problem. The I know that would not affect the core language, but that alone isn't good enough. > system continues to run its built-in version for its internals > regardless of what you do in your own code (assuming you did that in > your own package, which is the only sensible way unless you actually > know what you are doing.) Are there any cases where you'd know what you're doing (I thought messing with cl: => undefined behavior, according to the standard)? > > > > complex already for most people. > > > > Well yes, but not sufficiently general. The for loop in python is not complex, > > but more general in that it takes an infinite variety of container classes > > (including lazy ones, which obviously adds expressiveness). And I should > > suspect that people would actually like to extend loop if it weren't such a > > nightmare (also note that e.g. emacs's (cl) LOOP *is* extended). > > If you like the Python looping constructs better, it is possible to > implement those in CL. Feel free. Actually, I'd be tempted, if I were to do quite a bit of CL coding. That, of course wouldn't make the problem go away (just as the fact that you can define (various, incompatible) module and OO systems in scheme doesn't make the problem that scheme doesn't have a module system go away). It would also not mean that the myriad of builtin functions that work on lists or sequences (count-if, some, etc.) or other people's code would magically start to accept all kind of container types. Before we run into some misunderstanding again, there is of course little magic about 'for' as such, the nice thing about it (and 'map' and 'filter' etc.) is just that it works for everything that support python's iteration protocol (an ersatz of which I'd have to implement). > > Hey, we agree on something! :-) Oh, well we might agree on more that you're thinking :) > > > Unified item access, setting and deletion OTOH is an abstraction and thus > > helps to produce better code. If you disagree, try replacing all instances of > > SETF in your code with SETQ. > Given that they do quite different things, I fail to see the meaning of > this. For that matter, I prefer SETQ when handling symbols: it is less > dangerous. What are different things (not SETF and SETQ, I assume, since the former is pretty much a superset of the latter and PAIP, e.g. never uses SETQ)? If you mean setf and python's "cont[FOO] = x" etc. then I'd like to know what makes you think so? > > > Now what tools did Python have to define your own control flow > > > constructs ? :-) > > > Well, for some cases where lispers think you'd need macros the iteration > > protocol and generators are actually enough (and, I guess, also better). Of > > course there are quite a few things you can conveniently do with macros that > > are awkward in python and CL has many cool things python hasn't -- but I > > really think iteration and containers are better done in python. > > That may be if you are happy with just that. Quite often in Lisp > programming the datastructures are trees, graphs etc where a > single-dimensional iteration is not what is needed, so it is not such a > holy grail as you make it to be. It is of course possible that usage patterns differ, so that this kind of iteration indeed doesn't occur that often (the number of CL builtins that follow this pattern makes me doubt that, though). Why it shouldn't be useful to iterate through all the leaves of e.g. a tree, however, is really beyond me. BTW, I guess the ability to deep and shallow-copying unknown containers is also not useful? > > At one level it is a question of stylistical freedom: in Python you > program in a language which looks like Guido likes it to be. In CL you > can program in a language that looks like anything you want it to be, > assuming you consider the effort worthwhile. Not all do. Sure, I'm explicitly acknowledging the neatness of a proper (unlike, say cpp) macro system above. However I also happen to think that CL's macros are not good enough for python (in a non-derogatory way; doing them better is not trivial), so I don't think it is not purely a difference in stylistic freedom Guido is willing to grant. alex From bokr at oz.net Fri Nov 29 14:33:11 2002 From: bokr at oz.net (Bengt Richter) Date: 29 Nov 2002 19:33:11 GMT Subject: Implementation of the global statement References: <8ef9bea6.0211270526.5a1278c5@posting.google.com> <3DE59E73.4040908@something.invalid> Message-ID: On Thu, 28 Nov 2002 20:20:57 -0500, "Terry Reedy" wrote: > >"Bengt Richter" wrote in message >news:as5ugi$a48$0 at 216.39.172.122... >> >>> def foo(x): print x >> ... >> >>> bar = foo.__get__('Hi via foo') >> >>> bar() >> Hi via foo > >This is a new one for me: > >>>> def f(): pass >... >>>> f.__get__ > >>>> f.__get__.__doc__ >'descr.__get__(obj[, type]) -> value' > >Seems to be a new, undocumented (?, not in indexes) method producing a >new, undocumented (?) internal type. Not something to bank a product >on ;-) > I was reading http://www.python.org/2.2/descrintro.html and PEP 252 http://www.python.org/peps/pep-0252.html and trying stuff ;^P when I noticed that dir(foo) showed __get__, so one thing let to another ;-) but while that stuff is really interesting, what I was reflecting on was whether internals docs ought *all* to have some kind of predictable footnoting saying what's off limits for ordinary use. Or should one assume that it's all obviously off limits? It may not be so obvious to newbies sometimes -- and remember, we're all newbies, just on different subjects ;-) (to paraphrase Will Rogers). Regards, Bengt Richter From mikael at isy.liu.se Wed Nov 27 10:00:22 2002 From: mikael at isy.liu.se (Mikael Olofsson) Date: Wed, 27 Nov 2002 16:00:22 +0100 Subject: Implementation of the global statement In-Reply-To: <8ef9bea6.0211270526.5a1278c5@posting.google.com> References: <8ef9bea6.0211270526.5a1278c5@posting.google.com> Message-ID: <20021127160022.4871392e.mikael@isy.liu.se> Hi all! On 27 Nov 2002 05:26:33 -0800 hungjunglu at yahoo.com (Hung Jung Lu) wrote: > The global statement as in > > def f(x): > global y > ... > > is a directive to the parser. Internally the parser must keep a list > of the "locally-globalled" names. Yes, you guessed right, out of pure > curiosity: is this list accessible from Python? If not, why not? :) I have a few related questions. Assume that we have defined f as above in one global namespace, A say, and assume that f (re)binds y. Then we place f in another global namespace, B say. What happens when we execute f in B is that y in A is rebound. I would have guessed that a variable y in B would have been created or rebound. Now to my questions: Why is that so? Is that behaviour intended? Is it likely to stay that way? Please understand me correcly. I'm not complaining. I'm just curious. Actually, in my application, the described behaviour is what I'm after. I could also imagine that there are situations where someone would prefer y in B to be affected, and not y in A, which brings me to my last question: Is there an obvous way to have f (still defined in A) manipulate objects in B when executed in B? Greetings /Mikael ----------------------------------------------------------------------- E-Mail: mikael at isy.liu.se WWW: http://www.dtr.isy.liu.se/dtr/staff/mikael Phone: +46 - (0)13 - 28 1343 Telefax: +46 - (0)13 - 28 1339 /"\ \ / ASCII Ribbon Campaign X Against HTML Mail / \ This message was sent by Sylpheed. ----------------------------------------------------------------------- Link?pings kammark?r: www.kammarkoren.com From pruebauno at latinmail.com Tue Nov 12 12:59:13 2002 From: pruebauno at latinmail.com (nnes) Date: 12 Nov 2002 09:59:13 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: oleg_inconnu at myrealbox.com (Oleg) wrote in message news:<3d5b5ad8.0211080454.50bc6128 at posting.google.com>... > http://www.norvig.com/python-lisp.html ), and I couldn't help but > wonder why Python is popular, while Common Lisp and Scheme aren't? Maybe because of this???? Newbie: I want to add 2+2 ... c.l.xx go take some BASIC programming course first kid c.l.p. type [2] [+] [2] [Enter] bozo huh? ========================================= Newbie: how do I read an xml file? c.l.xx I am selling this library you might be interested in ... c.l.p. copy and paste the following code budy import xml ... bozo isn't xml standard in all computers? =============================================== Newbie: I need to store some data in (Postgresql, Mysql)... c.l.xx Postgresql is open source. Write your own driver ... c.l.p. copy and paste the code of page x of the documentation provided with (PG, M) bozo buy (Oracle, DB2). It probably has a driver for xx language ================================================= Newbie: I want to run my neat windows GUI thingy on a *nix machine c.l.xx graphical interfaces are for sissies c.l.p. install python on that *nix machine bozo I heard Java is "the" thing =================================================== Newbie: I have application in language yy I want to use c.l.xx yy is evil rewrite everything in xx c.l.p. import it, call it, send textfiles ... we will find some way to push, pull information into that thing bozo labor from elbonia will handle this for cheap money P.S.: Don't take this too seriously :-) From rodrigobamboo at hotmail.com Wed Nov 20 07:23:47 2002 From: rodrigobamboo at hotmail.com (Rodrigo B. de Oliveira) Date: 20 Nov 2002 04:23:47 -0800 Subject: Python embedding question: how to expose a new "builtin"? References: Message-ID: > > > > > > PyObject* __builtin__ = PyImport_ImportModule("__builtin__"); > > PyObject_SetAttrString(__builtin__, "application", > > (PyObject*)_pyapplication); Py_DECREF(__builtin__); > > > > > > This looks to me like the correct way to do what you ask. > Thanks. > > > Notes: > > * _pyapplication is an instance of a C new style class > > What IS "a C new style class"...? Sorry. I meant a class defined in C instead of a class defined in python. Too much going on here ;-) > > > The problem is: the modules can see the name "application" but > > dir(application) returns [] and if I try to access any of application's > > attributes I get an AttributeError. > > > > Thoughts? > > Looks to me like the problem is with the _pyapplication object > rather than with the exposing of it in the built-ins module. What happens > if you architect another way to let Python code get at that same object? > Does "is" show the two ways give the same object, and what are the > symptoms on e.g. dir for each? I think you should get the same > results, confirming the problem is with the object and not with > the way you're choosing to expose it. You are right. I tried that and the results were the same. I don't have the source code here at the office I'll take a deeper look at the _pyapplication type definition again tonite and probably will be bothering you again soon ;-) Thank you very much. Rodrigo From grahamd at dscpl.com.au Fri Nov 8 22:11:17 2002 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 8 Nov 2002 19:11:17 -0800 Subject: Building Python 2.2.2 with aqua Tk support on MacOS X 10.2 -- instructions References: Message-ID: "Russell E. Owen" wrote in message news:... > Instructions for building Python 2.2.2 with aqua Tk support (plus > readlines and XML parsing) are available at > . Thanks to the many people > (credited in the document) who helped me figure out how to do it. > > There are still a few minor glitches, but no show stoppers. I may update > the file over time if any answers come in for the glitches. The > procedure should be simpler for building Python 2.3, when that comes out. > > -- Russell One very minor issue. When giving instructions on how to create a pythonw shell script, you say to put in it: #!/bin/sh exec /Applications/Python.app/Contents/MacOS/python $@ You might want to use: #!/bin/sh exec /Applications/Python.app/Contents/MacOS/python "$@" If you don't have double quotes around $@, if you have an argument to the script which has a space in it, that argument will get separated into more than one argument when passed to the actual python executable. Ie., with script as you originally suggest it should be: bash-2.05a$ pythonw test.py "a b" original argc=4 original argv[0] = "/Applications/Python.app/Contents/MacOS/python" original argv[1] = "test.py" original argv[2] = "a" original argv[3] = "b" modified argc=4 modified argv[0] = "/Applications/Python.app/Contents/MacOS/python" modified argv[1] = "test.py" modified argv[2] = "a" modified argv[3] = "b" and with quotes: bash-2.05a$ pythonw test.py "a b" original argc=3 original argv[0] = "/Applications/Python.app/Contents/MacOS/python" original argv[1] = "test.py" original argv[2] = "a b" modified argc=3 modified argv[0] = "/Applications/Python.app/Contents/MacOS/python" modified argv[1] = "test.py" modified argv[2] = "a b" From mwh at python.net Thu Nov 21 08:29:35 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 21 Nov 2002 13:29:35 GMT Subject: Does Python (or psyco) already do this optimisation? References: Message-ID: <7h3r8dft5pi.fsf@pc150.maths.bris.ac.uk> "Mike C. Fletcher" writes: > Okay. That answers whether base Python (non-psyco) currently does > this. Thank-you for confirming what I'd assumed regarding the current > operation. > > Any idea (anyone) whether the outlined approach has been attempted for > global-variable access optimisation? i.e. is this an explored and > deemed-dead path, or something new? Neither :) There are some patches that do roughly what you're talking about on sf -- I think, I'd have to admit I haven't read any of the proposals especially closely -- but noones working on them actively right now. If you have time, picking one of them up and working it into being ready for inclusion would be appreciated, I think. Though it might be getting a bit late for 2.3. Cheers, M. -- Remember - if all you have is an axe, every problem looks like hours of fun. -- Frossie -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From gerhard.haering at gmx.de Thu Nov 7 17:54:02 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 7 Nov 2002 22:54:02 GMT Subject: default argument depending on another argumen? References: Message-ID: Marco Herrn wrote in comp.lang.python: > Hi, > > I want to define a function like this: > > def foo(self, bar, x= bar.x): > .... > pass > > Now I have the problem that 'bar' isn't really known when defining this > function. > So how can I achieve this behaviour? There's a FAQ entry o this, too IIRC :-) The workaround looks like this: def foo(self, bar, x=None): if x is None: x = bar.x ... -- Gerhard From fredrik at pythonware.com Wed Nov 6 13:35:24 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 06 Nov 2002 18:35:24 GMT Subject: Subclassing the min() build-in function? References: <18eef4ae.0211060911.2c0a7731@posting.google.com> Message-ID: Eddie Corns wrote: > The last example shows that you might want to check whether 'a' is a sequence > if that's ever likely to happen. Using __builtins__.min is easier than making > a local copy of the standard min which could have been done by: never use __builtins__ -- it's an implementation detail. to make sure you get the right builtins, import __builtin__ (no plural s) and access the functions via that module. From robin at jessikat.fsnet.co.uk Thu Nov 14 06:26:57 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 14 Nov 2002 11:26:57 +0000 Subject: windll event loop leaks Message-ID: Hi, I'm trying to implement a calldll/windll backend for the anygui project. I have working code, but it leaks so I'm looking for assistance with how one should program/debug such a loop. My test prog is a simple blank window. Using process explorer I can see that the working memory increases when I just move the mouse around over the window. For comparison I tried Sam Rushing's dynwin/button.py and lo and behold it also leaks. The pythonwin backend which has a similar structure doesn't leak. The loop I use is just while user32.GetMessage(msg, 0, 0, 0): try: user32.TranslateMessage(msg) user32.DispatchMessage(msg) except: logTraceback(None) and my test seems to just end up calling the default window procedure using user32.DefWindowProc(hwnd, msg, wParam, lParam). Any help gratefully received. FWIW I'm using Python-2.2.2 Win2K sp2 -- Robin Becker From mgarcia at cole-switches.com Thu Nov 14 16:41:49 2002 From: mgarcia at cole-switches.com (Manuel M. Garcia) Date: Thu, 14 Nov 2002 21:41:49 GMT Subject: A really bad idea. References: <4STA9.9987$744.345722@news1.tin.it> Message-ID: On Thu, 14 Nov 2002 20:39:28 GMT, Alex Martelli wrote: (edit) >Python has a few dozen built-in functions. I wouldn't _expect_ MOST of >them to be "immediately obvious" to somebody who has not even bothered >glancing at the docs, or trying e.g help(zip) at the prompt in an >interactive session. A good point. Python is pretty darn small. O'Reilly's Python Pocket Reference for Python 2 is 124 pages, and only because the major modules are referenced starting at page 65. And the language is pretty well covered in those 64 pages, it is rare I need any documentation beyond the Pocket Reference, even when doing thing that would be considered tricky in other languages, like handling attribute access on an object programmatically. Manuel From simon at callan.demon.co.uk Thu Nov 7 14:45:02 2002 From: simon at callan.demon.co.uk (Simon Callan) Date: Thu, 07 Nov 2002 19:45:02 GMT Subject: Making a better textbook (was Re: The Deitel book) References: Message-ID: <3b7ccd914b.simon@satin.callan.demon.co.uk> In message Dave Brueck wrote: > On Wed, 6 Nov 2002, Dave Reed wrote: > > > I've been using Python for my own projects (from short scripts to > > 25,000 line apps) for almost three years now and can't imagine > > using anything else right for anything that wasn't extremely > > computationally expensive. After attending the panel, I talked my > > other colleagues into using it for our CS 1 course this fall. The > > only thing that bothers me about Python for teaching is the lack > > of enforced private members for classes. As an experienced > > programmer, I can live with that because I know better, but I > > don't know whether the students will believe me when I tell them > > it's a bad idea to directly access them outside of classes :-) > > Who cares if they believe you though, and why should they anyway? > Part of becoming a good programmer is getting bit by taking > shortcuts (over doing it the "right" way), learning from it, and > moving on - and it's a great thing to learn through experience that > the prof might actually know what he's talking about! :) If you are feeling cruel, you could give them a library that has both exposed internals, and proper interface functions, and then halfway through the course, change the library so that anyone who doesn't use the correct interface finds that subtle bugs have been introduced into their code. Simon From gerhard.haering at opus-gmbh.net Tue Nov 19 11:24:38 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 19 Nov 2002 16:24:38 GMT Subject: converting python scripts to exe References: Message-ID: In article , asdfasd asdfasdf wrote: > hi Hi "asdfasd asdfasdf", > i have a python script and this script calls another program by using > os.system() function. This program needs a configuration file as input. > i converted this python script to exe using py2exe utility and removed > the configuration file as this configuration file contains passwords and > such... Why don't you simply convert your configuration file into a Python module with the appropriate constants? -- Gerhard H?ring OPUS GmbH M?nchen Tel.: +49 89 - 889 49 7 - 32 http://www.opus-gmbh.net/ From wasjaja at gmx.de Sat Nov 16 06:40:30 2002 From: wasjaja at gmx.de (Christian Rapp) Date: Sat, 16 Nov 2002 12:40:30 +0100 Subject: Get Stdout from external script startet through python Message-ID: Hello, I need to start an external script from inside python. This works just fine. The called script produces some output on StandardOut, that I need within the python-script. How do I get this Output into python? Any suggestions? Please answer! Greets Christian Rapp -- "We build software like cathedrals! First we build them; then we pray!" (Author unknown) From imbosol at vt.edu Sun Nov 10 17:44:43 2002 From: imbosol at vt.edu (Carl Banks) Date: Sun, 10 Nov 2002 17:44:43 -0500 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: Jacek Generowicz wrote: > Carl Banks writes: > >> As cool as Lisp is, it is too low-level, > > This must be some usage of the term "low-level" with which I was not > previously familiar. I mean close to the compiler. >> The real problem is that, while Python makes a significant effort to >> accomodate human thinking (i.e., Python lets programmers think like >> humans instead of machines a lot of the time), Lisp doesn't put a high >> priority on this. > > Funny, I find that Lisp offers me great help in concentrating on what > I want to do, rather than the details of how I am going to make the > machine do it. Of course it does, but that is not exactly what I was saying. I'm very familiar with how Lisp allows you to write embedded languages that let you approach human thinking as close as you want. But to write macro, you have to think at a level closer to the machine. You have to think about expressions as objects. That is thinking like a machine (like software, not like hardware) as opposed to thinking like a human. You can say, "I won't use the advanced stuff that requires me to think like a machine," but then Lisp is pointless, because then it's nothing but a hard to read, complicated, and faster Python. >> Python uses infix notation for math. Most humans were brought up to >> understand infix. > > So download an infix notation macro ... As if anyone really does this. (Shut up, I know they do.) >> Python is more like C than Lisp at all levels. > > ? > [snip] You misunderstood (because I stated it ambiguously): Python is more like C than Lisp is like C at all levels. I hope you won't try to argue that point by point. ("They both are native compilers," ok that's one thing.) >> There are many, many factors that determine the poularity of a >> langauge. In this case, I think the main factor is that Python just >> thinks more like we do than Lisp. > > I would say that the biggst ones (in no particular order) are > > - Python is simpler than Lisp. Entry is easier. Well, see, I think that's because it's closer to human thinking. I'm a step ahead of you. > - Most people _know_ that Lisp is a slow, arcane language with the > list as the only data type (and other such lies). Such lies get > repeated, and as a consequence most people don't bother to give Lisp > a single look. Python does not suffer from this. Well, people say Python is slow, and that isn't a lie. :-) I'm sure the lies have something to do with it. > - Batteries included: Python's library of packages is larger and more > rapidly growing. I definitely agree this is a very big factor. -- CARL BANKS From mwh at python.net Fri Nov 15 06:25:27 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 15 Nov 2002 11:25:27 GMT Subject: A really bad idea. References: Message-ID: <7h3d6p7xelx.fsf@pc150.maths.bris.ac.uk> Andrew Koenig writes: > Simon> I doubt that the C / C++ reference includes examples on slicing > Simon> lists and using dictionaries, whereas the Python reference > Simon> would *have* to, as these constructs are integral to the > Simon> language. > > You might be surprised what you would find in the C++ standard library... This is the hoary old language/library thing isn't it? Not that C++ gets to be called "simple" or "small" on either count. C without it's library would get a rating of "useless"... guess this is true for most languages, but C more than most. Cheers, M. -- languages shape the way we think, or don't. -- Erik Naggum, comp.lang.lisp From gmuller at worldonline.nl Wed Nov 27 14:39:52 2002 From: gmuller at worldonline.nl (GerritM) Date: Wed, 27 Nov 2002 20:39:52 +0100 Subject: Problem with paths on Win 9x References: Message-ID: "John Roth" schreef in bericht news:uu7ov1nva2gf07 at news.supernews.com... > > "John Roth" wrote in message > news:uu4pbuofg1dhb8 at news.supernews.com... > > > While I still haven't figured out why it isn't working as written, > it does work with a full path name in quotes, starting with c:\. > No relative path works. > > Is it possible that Python doesn't use the Python path for > parameters to the Python command? > > John Roth > I did not read your original problem. However I can tell you that you can make sure that your path is included in the Python path by making a very small .pth file, with the full pathname as text in the file. This small file should be in your main Python directory. regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From aleax at aleax.it Mon Nov 18 04:55:12 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 18 Nov 2002 09:55:12 GMT Subject: My (late) beef with Simple Generator syntax (PEP 255) References: <3DD3A563.B781BE58@hotmail.com> <3DD850D3.8030207@something.invalid> Message-ID: <4O2C9.22714$744.832177@news1.tin.it> Greg Ewing wrote: > Alan Kennedy wrote: > >> class emptyGenerator: >> >> def __init__(self): >> raise StopIteration() >> >> def emptyGen(): >> yield emptyGenerator() > > This is quite nice, but it's misnamed slightly. > Something called xxxGenerator should be returning > an iterator when you call it, but this isn't. > > It would be nicer if it were called Nothing. > Then you could write > > def emptyGen(): > yield Nothing() > It seems to me that there's no real usefulness in making Nothing a class -- it just takes an extra statement or so to come to the key raise statement. So why not use a function instead: def Nothing(): raise StopIteration def emptyGen(): yield Nothing() Alex From jorgencederberg at hotmail.com Tue Nov 5 08:26:01 2002 From: jorgencederberg at hotmail.com (=?iso-8859-1?Q?J=F8rgen_Cederberg?=) Date: Tue, 5 Nov 2002 14:26:01 +0100 Subject: bug report w\o registering References: Message-ID: "Anton Vredegoor" wrote in message news:aq8cmh$gcq$1 at news.hccnet.nl... > On Tue, 5 Nov 2002 15:49:20 +1100, "Delaney, Timothy" > wrote: > > >> From: anton at vredegoor.doge.nl [mailto:anton at vredegoor.doge.nl] > >> > >> Here's a bug report. I don't want to register at SourceForge now > >> (browser settings etc.). Sorry for the inconvenience. > > > >If you do not submit to sourceforge, the bug report *will* be lost. > > If you do not read the traceback you will not detect the bug. > Hi, Please see section 6.8 in the Library reference ( http://www.python.org/doc/current/lib/module-popen2.html ), it clearly states how popen2.popen2 should be called. Example >>> import os, popen2 >>> infile, outfile = os.popen2("dir", "b", -1) >>> outfile, infile = popen2.popen2("dir", -1, "b") >>> Regards Jorgen From imbosol at vt.edu Fri Nov 15 00:08:25 2002 From: imbosol at vt.edu (Carl Banks) Date: Fri, 15 Nov 2002 00:08:25 -0500 Subject: A really bad idea. References: Message-ID: Paul Foley wrote: > On Thu, 14 Nov 2002 15:33:33 -0800, Russell E Owen wrote: > >> On the other hand, I like zip just fine (though I lament the lack of an >> unzip counterpart). > > Eh? Zip is its own inverse! Sure? >>> a = [(1,2,3,4),(5,6,7,8)] >>> zip(zip(a)) [(((1, 2, 3, 4),),), (((5, 6, 7, 8),),)] -- CARL BANKS From owen at nospam.invalid Thu Nov 14 18:33:33 2002 From: owen at nospam.invalid (Russell E. Owen) Date: Thu, 14 Nov 2002 15:33:33 -0800 Subject: A really bad idea. References: Message-ID: In article , marvelan at hotmail.com (M) wrote: >The new enumerate or zip function. If you look at the code using this function >it is not at all obvious what the code does...Generators >are another thing that are just horrible. They just don't work in a way >that one would expect from previous experience. I agree with some of this and am always glad to see discussions like this. I hope you don't get too many dismissive replies -- they often seem to surface when one discusses warts. I think generators were done rather poorly in that there is no special statement to indicate a generator (something many of us lobbied for at the time). As a result you have to look through the code to see whether it's a function or a generator, looking for that magic "yield" statement -- which can be quite buried, especially in a long function (or is that a generator? damn!). As a concept, I feel generators and iterators are well worth learning and using. I make pretty heavy use of them and am glad to be saving myself the code I'd otherwise have to write. On the other hand: - There is some area of all this I still find confusing. it's hard to put my finger on, but I'm not always sure whether I should be obtaining an iterator and then using it in a for loop or defining __iter__ (or is it iter?) and using my object directly in a for loop. Also, I'm not always sure about iterators or generators that call iterators or generators. - Iterators have some nasty pitfalls. For instance on a file you cannot reliably do this: # read some data for line in file: # process the data, break partway through # read more data: for line in file: (or maybe that works but file.readline() will not) You will often lose data--the first "for" loop reads ahead for efficiency and the later read misses all that data. Map, reduce and their ilk are quite specialized. I usually (but not always) find that using them makes my code harder to understand, probably due to the need to pass in a function. I suspect a big reason they're in the language is they're so much faster than doing the same jobs with other constructs. On the other hand, I like zip just fine (though I lament the lack of an unzip counterpart). I find it simple and straightforward, though it's not something I use every day. Another wart, in my mind, is that map and zip (which are closely related) handle a set of lists of nonequal lengths in different ways. I'd much rather have seen consistency between them, and preferably a way to specify a modifier to get the other behavior (for lists of unequal lengths). The lack of consistency is all the more surprising to me because zip was introduced fairly recently, long after map was well established. How do you feel about list comprehensions? To me they look a bit like line noise, but I love them and use them heavily. them. I find myself wshing there was a similar construct for creating dictionaries. -- Russell From jef.mangelschots at iname.com Fri Nov 15 13:36:04 2002 From: jef.mangelschots at iname.com (Jef Mangelschots) Date: Fri, 15 Nov 2002 18:36:04 GMT Subject: redirecting output from spawned processes Message-ID: <3dd53e37.86527109@news.genuity.net> How do I redirect the output of 'someapp' to the file log_file ? log_file = 'c:\output.log' os.spawnv(os.P_WAIT, 'some_app', 'p1', 'p2') From Oschler at earthlink.net Wed Nov 6 22:36:58 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Thu, 07 Nov 2002 03:36:58 GMT Subject: [Jython] Pass variable or class reference to PythonInterpreter? Message-ID: I know I can compile a Jython class and then have it accessible as a true Java class to other java code. But I'm wondering if I can pass a variable or class reference to an instance of PythonInterpreter? For example: private void CallInterpreter() { String theString = "Hello"; PythonInterpreter interp = new PythonInterpreter(); // Here I enter a loop receiving python commands and passing them to "interp.exec()" // So how could I give "interp" access to "theString" so commands passed to "exec()" // can see it, print it, change it, etc? } Is there a way to do this? thx From sismex01 at hebmex.com Tue Nov 12 13:30:23 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 12 Nov 2002 12:30:23 -0600 Subject: Optimisation problem Message-ID: > From: gabor [mailto:gabor at realtime.sk] > > On Tue, 2002-11-12 at 16:50, Michael Hudson wrote: > > anton at vredegoor.doge.nl (Anton Vredegoor) writes: > > > m,x,y,z = self.matrix,self.x,self.y,self.z > > > > > > This is faster > > > > Don't be so sure: this creates a tuple. > > > > > this is interesting.... > > you're saying that for example > > x,y = 2,4 > > creates a tuple? > > i thought thatr x,y=2,4 is the same as x=2;y=4 > > bye, > gabor Nope; when declaring tuples, unless stated otherwise, using parenthesis is optional; so you are in fact creating a tuple on both sides of the assignment, and unpacking it into variables on the left side. HTH (Handle This Harefully) -gustavo From robin at jessikat.fsnet.co.uk Wed Nov 6 11:35:00 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 6 Nov 2002 16:35:00 +0000 Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DC8623B.88753C16@earthlink.net> <3DC8CDDD.7050103@mindspring.com> <3pE8dhAtvNy9EwoQ@jessikat.fsnet.co.uk> Message-ID: In article , Carel Fellinger writes >On Wed, Nov 06, 2002 at 09:07:57AM +0000, Robin Becker wrote: >... >> Isn't it a commonplace that the n x m translation problem is best solved >> by having a common intermediate? This seems more efficient when > >Yep, it is a commonplace, but that doesn't make it true:) > >You see, for the common constructs this might be true, but each >language has it weird corners and for those you'll end up with >language pair specific translations inside the intermediate language, >i.e. if there *is* such a translation. There will always be some left >overs that can't be (easily) translated. e.g. suppose one of the >languages support continuations, but the others don't, bad luck. ....yes I understand that .NET and Python have some disputes about universality :) -- Robin Becker From sismex01 at hebmex.com Mon Nov 11 10:39:05 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 11 Nov 2002 09:39:05 -0600 Subject: writing from file into dictionary Message-ID: > From: Alex Martelli [mailto:aleax at aleax.it] > > On Monday 11 November 2002 01:15 pm, Brad Hards wrote: > > On Mon, 11 Nov 2002 22:16, Alex Martelli wrote: > > > > > > > Assuming the trailing colon at the end of the 'rewrite' part > > > (and anything following it, such as the comment in the last > > > line) is to be removed; and that corresponding to each head > > > you want a list of the possible rewrites for that head; > > > > Can I try an explanation? > > Yes. Python 1.5.2 idioms equivalent to this statement include: > > if not grammardict.has_key(head): > grammardict[head] = [] > grammardict[head].append(rewrite) > > I feel a better way than the previous snip would be: try: grammardict[head].append(rewrite) except KeyError: grammardict[head] = [ rewrite ] This would have the advantage of only indexing 'head' twice in the worst case --when it's not present in the dictionary--, and only one time, once it's been inserted. I haven't done any timing, anybody has? It just "feels" cleaner. *sigh* Python's made me actually *seek* exception handlers, so much for staying away from then, back in my c++ days. Good luck y'all. OK OK OK OK OK Do I did a bit of trivial timing on a few functions which implement checking/adding to a dictionary using setdefault, has_key or try/except, and the results surprise me somewhat. I'm using Py 2.2, just in case things have changed. The functions take two lists as arguments: the list of dictionary keys, and a list of items which are appended to lists which are inserted in the dictionary at those keys. It's just two for loops, the outer iterating over the keys, the inner loop over the items. Using keys=range(100), items=range(10): test_setdefault() --> 8.562000 ms/call test_haskey() --> 6.700000 ms/call test_except() --> 8.592000 ms/call huh! says me. I thought setdefault() was more efficient than this. Maybe it's the keys/items ratio, let's check: Using keys=range(1000), items=range(1): test_setdefault() --> 13.259000 ms/call test_haskey() --> 13.509000 ms/call test_except() --> 41.190000 ms/call ouch, again. Let's switch the ratio over to the other side: Using keys=range(10), items=range(1000) test_setdefault() --> 8.201000 ms/call test_haskey() --> 6.029000 ms/call test_except() --> 4.587000 ms/call Ah! Vindicated! Let's make it a bit more extreme: Using keys=range(2), items=range(500): test_setdefault() --> 8.752000 ms/call test_haskey() --> 6.259000 ms/call test_except() --> 4.557000 ms/call Interesting; I hope this clears things up a bit, it did for me, a lot :-) -gustavo pd: Have a nice monday :-) From martin at v.loewis.de Fri Nov 1 17:08:36 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 01 Nov 2002 23:08:36 +0100 Subject: Abort in garbage collector in 2.2.2 References: <871c2723.0211011234.6d807ec0@posting.google.com> Message-ID: x0phe at netscape.net (Christophe) writes: > Any idea what could cause this? Are you using any additional C modules, beyond what the standard distribution provides? It would be interesting to see the value of gc_refs for the object for which the assertion fails, i.e. the value of unreachable->gc.gc_next->gc.gc_refs As an assertion, it is supposed to never happen. If it happens anyway, the most likely reason is that some buggy code has stomped over the gc data structures. It would be also interesting to see whether the object itself is meaningful, i.e. what is its ob_refcnt field, and its ob_type->tp_name field? Regards, Martin From bokr at oz.net Tue Nov 5 19:59:56 2002 From: bokr at oz.net (Bengt Richter) Date: 6 Nov 2002 00:59:56 GMT Subject: parenthesis References: <2259b0e2.0211041224.7c24635b@posting.google.com> <2259b0e2.0211050956.5da2c074@posting.google.com> Message-ID: On 5 Nov 2002 09:56:54 -0800, mis6 at pitt.edu (Michele Simionato) wrote: >bokr at oz.net (Bengt Richter) wrote in message news:... >> Well, they don't count, so if you want to count you have to throw in >> something extra. E.g., you could do this, to insert a delimiter after >> a closing right paren, and then split on the delimiter. Probably not ^^^^^^^^^^^^ >> wonderfully efficient, and I am just duplicating what you did, except ^^^^^^^^^^^^^^^^^^^^^-[1] >> the regex separates the chunks for me. >> >> >>> import re >> >>> rx = re.compile(r'([()]|[^()]*)') >> >>> class Addelim: >> ... def __init__(self): self.parens=0 >> ... def __call__(self, m): >> ... s = m.group(1) >> ... if s=='(': self.parens+=1 >> ... if self.parens==1 and s==')': >> ... self.parens=0 >> ... return s+'\x00' >> ... if s==')': self.parens -=1 >> ... return s >> ... >> >>> for e in rx.sub(Addelim(),exp).split('\x00'): print e >> ... >> (a*(b+c*(2-x))+d) >> +f(s1) >> >> Where exp was >> >>> exp >> '(a*(b+c*(2-x))+d)+f(s1)' >> >> Regards, >> Bengt Richter > >Very interesting approach. But it is even more interesting to compare Yes, I had just learned from a post of Alex M that sub can take a function, so I thought it would be interesting to use it ;-) >its >speed with the simple minded approach. I thought your algorithm was >going to >be the fastest, since you do not split the initial string chars by I didn't think so [1] ;-) >chars in Python, but let the regular expression do the job. Well, doing a job that doesn't really need to be done never increases speed ;-) I.e., for your original problem, there is no need to create an alternative string with delimiters after expressions, never mind to split that string again to get at just the first item. All that's needed is to look at the input string and count to find out where the first expression ends. The question then becomes, what is the fastest way to look for parentheses and make sure you've counted some before detecting balanced count. If parentheses were separated by thousands of characters, I would expect that a regex search or finditer for [()] would go faster than a simple s[i] indexed scan, but for short expressions such as the example, there's probably a crossover point. Certainly '(x)' can be scanned brute force faster than you can get results from a regex object method. For speed, I think it might be faster to count position but not use it to get the characters, e.g., >>> def get_1st(exp): ... parens=i=0 ... for c in exp: ... i += 1 ... if c=='(': parens+=1 ... elif c==')': ... parens -=1 ... if not parens: return exp[:i] ... >>> exp = '(a*(b+c*(2-x))+d)+f(s1)' >>> get_1st(exp) '(a*(b+c*(2-x))+d)' This is a little different from Lee Harr's post (which BTW looks to me like it depends on the first char being '('). I'd expect the above to run a little faster. >However a simple benchmark (not subtracting the overhead times) gives: > >parenthesized_group: 130-140 microseconds >Addelim: 620-640 microseconds Yes, Addelim has calling overhead for one, and is creating a new string by substitution for another, so it's doing a lot of un-needed work. > >The simple minded approach is more than four-five times faster! > >I think this is rather instructive. Addelim is particular inefficient >for >long expressions, since it analizes the full expression whereas >parenthesized_group stops at the end of the first parenthesized group. Sure. The cost of generalizing requirements instead of sticking to specs ;-) >For fun I run Addelim on exp*100 (i.e. the 100 times the original >string): it takes more than 50000 microseconds whereas >parenthesized_group >is still on 140 microseconds. Not exactly unanticipated, I'm sure ;-) > >It is good to have yet another proof of the dangers involved with >regular >expressions ! There are dangers in drawing too general conclusions from particular examples too ;-) Regards, Bengt Richter From rmunn at pobox.com Tue Nov 26 18:36:35 2002 From: rmunn at pobox.com (Robin Munn) Date: Tue, 26 Nov 2002 23:36:35 GMT Subject: Python IRC dictatorship References: <29304.91T434T13743504threeseas@earthlink.net> Message-ID: Cliff Wells wrote: > > --=-FK+OtUyvyIb2iy15XR3T > Content-Type: text/plain > Content-Transfer-Encoding: quoted-printable > > On Mon, 2002-11-25 at 14:50, Robin Munn wrote: >> Timothy Rue wrote: >> [Snip a large IRC log] >> > ThreeSeas I'm a genius... If I can't answer your question I will try an= > d make >> ^^^^^^^^^^^^^^^ >> > out that you don't know what you are talking about..... but are there r= > eally >> > 120 users here that hail to ...... dash >>=20 >> A free piece of advice for you. It's been my experience, along with the >> experience of many others, that anybody who claims publicly to be a >> genius: >>=20 >> a) Almost certainly has an ego problem, and >>=20 >> b) Usually isn't worth listening to. > > I would shorten the second to > > b) Usually isn't. Except that they usually are, at least by the definition of "Genius: someone with IQ >= N" (where N, IIRC, is something around 130). Of course, we know how utterly meaningless IQ tests are when it comes to measuring "intelligence" -- but the kind of person who will publicly proclaim (him|her)self a genius is also the kind of person who will stubbornly argue for hours about dictionary definitions, completely ignoring the point about the usefulness of IQ tests. So I decided to bypass that fruitless argument by not questioning his claim to be a genius. > > It's odd how someone who purports to be a genius can be so stupid when > it comes to dealing with people. Since he seems to be incapable of > communicating with anyone on any level, I wonder how he is able to > compare his own intelligence with that of others. By IQ test results, of course. How else? Yes, I know IQ test results aren't worth the paper they're printed on when it comes to measuring any kind of "real" intelligence level (by which I mean the ability to actually achieve complex tasks). And I know that comparing IQ "scores" is nothing more than an empty bragging contest. But it wasn't worth getting in that argument with him. The only reason I posted any response to Mr. Rue was, basically, that I feel sorry for him. He appears to be the kind of person whose overinflated ego will ultimately bring them nothing but suffering. And yes, the chances of getting through to him and helping deflate his ego are only slightly greater than a snowflake's chance on the surface of the Sun. But every now and then, someone ought to try. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From SBrunning at trisystems.co.uk Tue Nov 12 04:43:25 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Tue, 12 Nov 2002 09:43:25 -0000 Subject: [Jython] out of memory during jythonc compilation Message-ID: <31575A892FF6D1118F5800600846864DCBDAEB@intrepid> > From: Robert Oschler [SMTP:Oschler at earthlink.net] > > I've had similar problems quite a while ago when Jython was called > > JPython and had version numbers less than two. Increasing the heap size > > helped, but you may want to try something more substantial than 50 MB. > > Give it everything your machine has. I managed to compile everything > > when the heapsize was at least 256 MB. A fast machine comes handy, too > :-) > > Yikes! Ok, will do. Unfortunately all I have is 256MB and unfortunately > Dell saw fit to only put two DIMM slots in the system. Guess I'll have to > replace the 2 128's with 256's. Always a good idea to upgrade - Java *loves* lots of memory. But using the -mx switch changes the *maximum* heap size - it will only use what it needs. (The default value is 64MB.) And if it needs more than you have, then it will just go to swap. It won't fail, just run slowly. Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From theller at python.net Thu Nov 14 08:40:35 2002 From: theller at python.net (Thomas Heller) Date: 14 Nov 2002 14:40:35 +0100 Subject: windll event loop leaks References: Message-ID: > >Sounds like a leak in calldll? > > > One thought that occurs is that the system API linkage might be > different. Any thoughts on that? If that were the case I would assume > leakage in the stack. Just did a quick test with a system function with __stdcall linkage, and this doesn't seem to have problems: from dynwin import windll kernel32 = windll.module("kernel32") while 1: kernel32.GetModuleHandle(0) > > > >Another approach ;-) would be to give up calldll/windll and try the > >ctypes module - this way you would have me debugging the thing (in > >case it leaks). > > > >Thomas > Well it's only a few days old according to the announcement I just found > :) The announcement and the distribution is only a few days old, ctypes is much older, and in active use for quite some time (by me). OTOH, I wouldn't be too surprised if there are stiill bugs in it. > > I will certainly give this a whirl. It doesn't provide a callback > generatr, but I suppose I can still use Sam's gencb. Sure does it! It's just not yet documented, although I believe there are examples in the test directory. Paul Moore posted even a nice example for a callback here http://aspn.activestate.com/ASPN/Mail/Message/python-list/1425385 > > Does ctypes use the FFI library for accessing external DLLs? That way it > would map to other platforms fairly easily. No. It uses very old code of mine to call these functions, but I'm already looking into more portable ways to do it. Anthony Green's libffi is my favorite currently. Thomas From jjl at pobox.com Wed Nov 20 14:30:03 2002 From: jjl at pobox.com (John J Lee) Date: 20 Nov 2002 11:30:03 -0800 Subject: timeoutsocket & sendall / Python 2.1 References: Message-ID: Dave Brueck wrote in message news:... > On 19 Nov 2002, John J Lee wrote: [...] > > > I'm surprised that nobody has bumped into this before, which is > > > why I'm posting it here -- I have a feeling I must be missing > > > something. [...] > Yeah, it looks like timeoutsocket should get a sendall wrapper too - why > don't you submit a patch to the module's author. Thanks, Dave. This is one of those 'so simple I must have made a mistake' things, so I'm glad to have somebody else check it. I sent the patch to the author, but no answer, so I assume he's not maintaining it any more. > Perhaps the reason that nobody has raised this concern has to do with the > facts that sendall is relatively new, Not *that* new -- 2.1 and 2.2 have been out for a while now. > lots of socket code is non-blocking (and thus wouldn't use timeoutsocket), And lots of code isn't. > and in Python 2.3 sockets have timeout functionality built in? But of course 2.3 isn't even officially out yet. John From s at hotmail.com Tue Nov 26 10:14:23 2002 From: s at hotmail.com (Stephan) Date: Tue, 26 Nov 2002 16:14:23 +0100 Subject: building database form-applications References: Message-ID: What are 'SQL aware widgets'? Phil Thompson wrote: > On Tuesday 26 November 2002 2:19 pm, Stephan wrote: > >>Hi, >> >>I want to evaluate tools for building Python-based form-applications for >>database interaction. So far I have looked into Boa Constructor and >>Black Adder which both seem to be promising. But what other tools can be >>recommended? And which is best equipped for rapid GUI development? > > > If you want develop GUIs with SQL aware widgets then look at the combination > of PyQt, the eric IDE and Qt Designer. > > Although BlackAdder is built on the same technology it does not yet support > the SQL aware widgets in it's form designer, nor does it include support for > Qt's SQL classes in its version of PyQt. However, depending on what platform > you want to support, and whether you wish to sell your applications, > BlackAdder may be a better bet - and stick with "dumb" forms. > > Phil > From uwe.schmitt at procoders.net Tue Nov 12 07:52:10 2002 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 12 Nov 2002 12:52:10 GMT Subject: How to create and interactive, distributable program? References: <3dcfa0e3.921157@news.jaring.my> Message-ID: Kenneth Gomez wrote: > Hello all, > To do all of this, my questions are , can Python handle the > mathematics, e.g. does Python have a subroutine to inverse a matrix, > or find the modulus of a number,....? Or, is it like C, where I have > to write the subroutine myself? Have a look at NumPy http://numpy.sf.net It includes matrix/vector handling (like MatLab, sometimes even better :-) and some linear algebra. But don't take the new version "numarray", it's still under development. But: these routines do not handle sparse matrices in an efficient way, afaik you'll have to use full matrices. Modulus is a function in the python core. > Second, will I be able to create the GUI explained above within 3 > months? Take wxPython. > Third, can I make the GUI into an executable file so that I can run it > off the laptop/workstation that will be used for the presentation? Take py2exe > Cheers, > Kenneth Gomez. Greetings, Uwe -- Dr. rer. nat. Uwe Schmitt Computer science is no more about Computers, uwe.schmitt at num.uni-sb.de than astronomy is about telescopes. (Dijkstra) http://www.procoders.net From peter at engcorp.com Sun Nov 3 15:34:24 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 03 Nov 2002 15:34:24 -0500 Subject: Parsing & question about usages off classes! References: <0efx9.175905$Mf5.8592441@Flipper> Message-ID: <3dc58868@news.sentex.net> Frans wrote: > I want to create several new list. The name off the new lists will come > from another list. That way I can create several lists, depending on the > data received from logfiles. Is that possible ? > > Or isnt that a good idea either ? :) Correct, this is also not a good idea. > So basicly: > my_list['some','data'] > variable = my_list[0] > variable = list > > Now this doesnt work, but the result I want is a new list with the name > 'some'. Now why would you want that? You would have to write code in advance that uses the variable name, even before you know what the variable name is going to be? Rethink the approach: you can't get where you want to be from here. Can you explain why you think you want a new list with the name "some"? If you can dig down to your real requirements and express them here, we can probably show you how to approach the problem in a more workable fashion. -Peter From john.abel at pa.press.net Mon Nov 25 08:42:09 2002 From: john.abel at pa.press.net (John Abel) Date: Mon, 25 Nov 2002 13:42:09 +0000 Subject: Multi Recipients With smtplib? Message-ID: <3DE228B1.1060802@pa.press.net> Hi, I am trying to send a mail, to multiple recipients, without much success. A single mail address works fine, but when I add another, using a comma to separate the addresses, the second address fails to receive the mail. Any ideas? Here's the code I am using: mailMessage = "From: %s \r\nTo: %s\r\n" % (self.mailFrom, self.mailTo) mailMessage += "Subject: %s\r\n%s" % (mailSubject, mailBody) try: self.MailConn.sendmail( self.mailFrom, self.mailTo, mailMessage) except (smtplib.SMTPRecipientsRefused, smtplib.SMTPSenderRefused), ErrorMsg: print "There Was A Problem Sending The Mail. Reason: %s" % ErrorMsg Any help would be appreciated, as this is driving me mad! Thanks John From jdhunter at ace.bsd.uchicago.edu Wed Nov 27 15:38:34 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 27 Nov 2002 14:38:34 -0600 Subject: do you guys help newbies?? In-Reply-To: (malik m's message of "Wed, 27 Nov 2002 19:47:47 GMT") References: Message-ID: >>>>> "malik" == malik m writes: malik> i didnt to import that yet but i will try even tho i think malik> the program did what i want it to:) What do you think your mpg is if you drive 3 miles on a tank that holds 2 gallons? What does your program tell you it is ..... John Hunter From maney at pobox.com Sun Nov 24 19:06:41 2002 From: maney at pobox.com (maney at pobox.com) Date: Mon, 25 Nov 2002 00:06:41 +0000 (UTC) Subject: if : References: Message-ID: Mel Wilson wrote: > We've just been there. groups.google.com can bring it all > back, although I don't offhand remember the subject. Which of three in the last ten days do you want? :-) > Basically, assignments aren't possible within > expressions. More fundamentally, because assignment is a statement, not an operator, in Python. > One good reason for this is list packing/unpacking in > assignments: > > a, b = 5, 8 > > As it stands, this is an assignment which effectively makes > two 2-tuples equivalent, associating `a` with the value 5, > and `b` with the value 8. > > If `b=5` were an allowable expression, then the statement > above would change into a 3-tuple, and a useful piece of > semantics would be a tad more awkward. You are also assuming that operator= would have higher precedence than the comma. Offhand, that seems like a mistake that could be avoided, although it may well not be the only such complication that would arise if operator= were to be added. > You could think of making an exception for `if` > statements, but beyond an uncertain point, exceptions are > bad for a language Right. If it were to be done, t'would best be done consistently. In theory, that point is between "none" and "any"; in practice, well, in practice it's a little different than in theory. :-/ From bboman at research.panasonic.com Thu Nov 14 13:31:01 2002 From: bboman at research.panasonic.com (bboman at research.panasonic.com) Date: 14 Nov 2002 10:31:01 -0800 Subject: PEP #99484663 References: Message-ID: <418ab5dd.0211141031.48b7f0bf@posting.google.com> Russell Nelson wrote in message news:... > Suggested PEP: > > Treat { and } when encountered at the end of a statement like this: > > When you see a {, generate an error if the next statement is not > indented more than the previous statement. When you see }, generate > an error if the next statement is not indented less than the previous > statement. > > In this manner, people who are unable to wean themselves from silly > syntactic block structure tokens will be happy with Python, rather > than continually whinging about how horrible it is that indentation is > meaningful to the program. I also would like to see *OPTIONAL* block delimiters, but I wouldn't do it with {}. It turns out that there are several keywords in Python like "return" "raise", "break", "continue" and "pass" that pretty much have to end a block. Technically "pass" doesn't have to end a block but there is no point in putting "pass" anywhere except at a block end. All you need to do to implement block delimiters is to have a option to check that each block ends with one of these statements and that these statements do not appear anywhere except at the end of a block. Now you have full block delimiters and complete compatibility with normal python code! It turns out that the python mode for emacs assumes that these keyword end blocks and if you code this way emacs can completely recover the indentation from the keywords. I could go into a long explanation as to why block delimiters are useful but I will just say that when you cut and paste a block of code from one nested block loop into another block at a different indentation level it is much nicer and much less error prone to just tell emacs to re-indent the entire function than to manually adjust each line. From jdhunter at ace.bsd.uchicago.edu Sat Nov 23 14:16:58 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sat, 23 Nov 2002 13:16:58 -0600 Subject: Newbie : desperately need help on "import MySQLdb" In-Reply-To: <3ddfc208$0$11853$626a54ce@news.free.fr> ("Michel COMBE"'s message of "Sat, 23 Nov 2002 18:58:17 +0100") References: <3ddfa321$0$18230$626a54ce@news.free.fr> <3ddfc208$0$11853$626a54ce@news.free.fr> Message-ID: >>>>> "Michel" == Michel COMBE writes: Michel> I downloaded the tar version of MySQLdb and made the build Michel> (not the install as I feared a version problem). I copied Michel> _mysql.so in /usr/lib/python2.2/site-packages et Voila ! Michel> Now I can start working :-) Congrats! My advice is that you are more likely to get into versioning problems by using the rpm for part of the package and the src for another. Take the plunge (back up site-packages first if you like) /usr/bin/python2.2 setup.py install You'll never go back to rpm. JDH From gerhard.haering at gmx.de Sun Nov 3 11:04:58 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 3 Nov 2002 16:04:58 GMT Subject: how to use smtp starttls() encryption? References: <8f41cfd.0210101719.ad47c7@posting.google.com> <8f41cfd.0210120805.6ced204a@posting.google.com> <8f41cfd.0210162236.3e5c970a@posting.google.com> <8f41cfd.0210211030.33365530@posting.google.com> <8f41cfd.0210312325.7ab7969f@posting.google.com> <8f41cfd.0211011737.383e2c2@posting.google.com> Message-ID: Xu, C.S. wrote in comp.lang.python: > Gerhard, > > You saved me! Why don't I need s.login(fromEmail, password) > to identify myself after s.starttls() ? Because the smtp server is configured in a way that you don't? :) > Earlier when our mail server don't require TLS, it need check mail > before sending out, or use s.login(fromEmail, password) to identify > myself. 'Sending out' is configured differently than receiving mail. Note that in my example, I sent mail to your domain, using your smtp server, which is thus already the 'final destination'. No relaying involved here. The main point of SMTP auth is to prevent unauthorized relaying, and therefore you require it only for mail to domains other than yours. For interoperability with the rest of the world, you cannot even do otherwise, because then you could receive no more mail. > What the hell s.starttls() is doing? There just no slightest clue > in python lib reference. There is. Be sure to read in the Python 2.2.x docs, as this feature didn't exist in earlier versions. -- Gerhard From grante at visi.com Tue Nov 26 13:57:59 2002 From: grante at visi.com (Grant Edwards) Date: 26 Nov 2002 18:57:59 GMT Subject: Python Tutorial Was: Guido's regrets: filter and map References: <3de39ce9$0$22220$a1866201@newsreader.visi.com> Message-ID: <3de3c437$0$22225$a1866201@newsreader.visi.com> In article , Michael Hudson wrote: > grante at visi.com (Grant Edwards) writes: > >> In the case of reduce: >> >> sum = reduce(operator.add, valueList) >> >> How is that expressed any better with a list comprension? > > It's not. It's better expressed as a for loop, though. sum = 0 for v in valueList: sum += v I think the former is more obvious, but I guess it's a matter of taste. > The for loop > might well be quicker, too (cue Alex proving me wrong :). -- Grant Edwards grante Yow! Mary Tyler Moore's at SEVENTH HUSBAND is wearing visi.com my DACRON TANK TOP in a cheap hotel in HONOLULU! From bh at intevation.de Wed Nov 27 05:19:29 2002 From: bh at intevation.de (Bernhard Herzog) Date: 27 Nov 2002 11:19:29 +0100 Subject: Python Tutorial Was: Guido's regrets: filter and map References: <3de39ce9$0$22220$a1866201@newsreader.visi.com> <3DE44D27.3030904@something.invalid> <6GH59kKkXIpD092yn@gnosis.cx> Message-ID: <6q4ra3nwlq.fsf@salmakis.intevation.de> Lulu of the Lotus-Eaters writes: > Actually... here's an... ummm... "improved" version: > > reduce = lambda func, seq, init=None:\ > [(l.append(func(l[i],seq[i])),l[-1]) > for l in [[init or seq[0]]] > for i in range(len(seq))][-1][1] It doesn't work correctly: >>> import operator >>> reduce(operator.add, [1,2]) 4 That should have been 3. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From see_reply_address at something.invalid Sun Nov 3 17:57:33 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Mon, 04 Nov 2002 11:57:33 +1300 Subject: Parsing & question about usages off classes! References: <0efx9.175905$Mf5.8592441@Flipper> <3dc58868@news.sentex.net> <2lgx9.177762$Mf5.8693527@Flipper> Message-ID: <3DC5A9DD.6090902@something.invalid> Frans wrote: > > So I thought I would do the following: > > short=['D','H','W'] > long=['DAILY','HOURLY','WEEKLY'] > > information = string.split(logline,'\t') > > DAILY.append(information) Use a dictionary indexed by the first field in the log line. For example: log_dict = {} # Create an empty dictionary log_dict['D'] = [] # Initialise with 3 new empty lists log_dict['H'] = [] log_dict['W'] = [] ... # for each log line: information = string.split(logline,'\t') log_dict[information[0]].append(information) Then log_dict['D'] will contain a list of all the log entries beginning with 'D', etc. If you really want them in separate variables, you could then do DAILY = log_dict['D'] HOURLY = log_dict['H'] WEEKLY = log_dict['W'] -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From fperez528 at yahoo.com Sat Nov 9 13:55:27 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Sat, 09 Nov 2002 11:55:27 -0700 Subject: [OT] Cameras (was Re: Why is Python popular, while Lisp and Scheme aren't?) References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h3wunmx4j7.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson wrote: > Totally off-topic, but hey... Indeed :) >> If you just want convenience for 4x6 prints from negative, a P&S is >> fine. But even a basic SLR like a Canon Rebel is about as easy to >> use as a P&S, while allowing you to 'go manual' when you feel like >> it. > > What strikes me is that with modern, decent print film, going manual > -- at least wrt. exposure -- makes next to now difference. I don't > know enough about the area to say what's going on, but I was > surprised. It's the exposure latitude. Modern print films have about 5 stops of exposure latitude, so you can really get away with murder. On the other hand, with slide film a half stop off is already noticeable. I shoot mostly slides, and occasionally need to use a P&S, which can get a bit tricky :) But with a bit of luck and good optics, you can get nice shots in situations where pulling an SLR out might not be practical. For this shot (http://www-hep.colorado.edu/~fperez/photo/Cotopaxi99/7.html) I simply couldn't stop to get my SLR out of my bag, but I had my trusty Stylus Epic in a jacket pocket. I took the shot without barely stopping at all, and it turned out nicer than all others in that climb, including the ones where I did pull out my SLR. As they say, it's the moment, not the equipment :) Cheers, f. From tjreedy at udel.edu Sun Nov 10 02:41:25 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 10 Nov 2002 02:41:25 -0500 Subject: Image merging within python - based tool (maybe OT) References: <8ed56b42.0211092045.1e833602@posting.google.com> Message-ID: "R. Charles Henry" wrote in message news:8ed56b42.0211092045.1e833602 at posting.google.com... > I'd like to ask the group's advice. > > My situation: I have two separate document images, both of the same > format .png, .bmp, .jpg, or .tif. They are otherwise identical in size > and file characteristics, having been produced from a larger-than-A4 > document using an A4 flatbed scanner. Each image contains a region of > 'overlap' with the other. > > I need to find an open-source 'mosaicking' or 'blending' codebase, > which will be capable of accepting both input images, and merging them > to reproduce an image of the original larger-than-A4 document. > > This code is to be used within a tool I am creating using python, & > I'd like to avoid the neccessity of having to manually set reference > points on the input images. The code itself that I'm searching for > doesn't need to be python, just accessible from it. > > Since the input images are 'flat', I don't require such features as > projection adjustment etc, I just need some form of basic automatic > 'merging'. > > Would anyone have any suggestions? Any pointers at all would be very > gratefully received. Semi-random thoughts. First, convert to bitmap. Then minimize misfit as function of x,y offset of centers or whatever. Details depend on nature of images. With black/white documents, misfit is % mismatch. You should standardize scanning process so proper offset is approximately known and search for best fit within circumscribed region. Entirely different approach is to apply OCR to images and then match text. TJR From bokr at oz.net Thu Nov 28 12:37:27 2002 From: bokr at oz.net (Bengt Richter) Date: 28 Nov 2002 17:37:27 GMT Subject: if : References: <3DE4102D.7D4291F4@alcyone.com> <3DE58723.5040306@something.invalid> Message-ID: On Thu, 28 Nov 2002 16:01:55 +1300, Greg Ewing wrote: >Erik Max Francis wrote: > >> >> I think the severity of the =/== confusion problem in C has been >> severely overrepresented in this thread. In my opinon, in the real >> world, among competent software eengineers, it is a tiny issue. > > >I think it's too simplistic to regard the =/== confusion problem >as the only reason to be wary of assignments in expressions. >It also hurts readability to have expressions with assignments >buried in them. > >This is a special case of the general principle that it's >usually clearer if expressions don't have side effects. > OTOH, an expression is a (normally) limited programming context, and no one seems to have a big problem with the temporary bindings created inside list comprehensions -- even though they are *not* temporary, and therefore *are* side effects (which IMO is a wart) ;-) ISTM it's a question of whether making it syntactically easier is more likely to encourage bad usage than facilitate and clarify legitimate uses. BTW, is there anything written on what the BDFL may have in mind for ':=' and '?' and '@' etc for? I'm sure he wouldn't want to squander them on something trivial, but I wonder if there's some indication. Similarly for words like "on", "when", "whenever", "before", "after", "initially", "finally", etc, etc. (is there a don't-use-in-case-this-becomes-special list? Seems like I saw something like that somewhere). HTG ;-) Regards, Bengt Richter From s at hotmail.com Tue Nov 26 09:19:24 2002 From: s at hotmail.com (Stephan) Date: Tue, 26 Nov 2002 15:19:24 +0100 Subject: building database form-applications Message-ID: Hi, I want to evaluate tools for building Python-based form-applications for database interaction. So far I have looked into Boa Constructor and Black Adder which both seem to be promising. But what other tools can be recommended? And which is best equipped for rapid GUI development? Thanks for feedback, stephan From bokr at oz.net Wed Nov 27 16:02:11 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Nov 2002 21:02:11 GMT Subject: re.DOTALL References: Message-ID: On Wed, 27 Nov 2002 13:46:56 -0500, Irina Szabo wrote: > >I need to remove all tags from HTML files. > >matchstr = re.compile(r'''<.*?>''',re.DOTALL|re.MULTILINE) >print matchstr.sub(" ", str ) ^^^--- BTW, using builtin names for variables is not a good idea ;-) > >The program works well for tags located on one line, >but dosn't delete tags if the brackets <> are on different lines, like > > > >What is wrong? > If you had posted what you actually did (noodge ;-), it would probably have been clear, but ... ====< interactive snip >======= >>> aString = """ ... something, followed by your html comment: ... ... followed by this line. ... """ >>> import re >>> matchstr = re.compile(r'''<.*?>''',re.DOTALL|re.MULTILINE) >>> print matchstr.sub(" ", aString) something, followed by your html comment: followed by this line. =============================== ... works, so you must have done something else. Regards, Bengt Richter From pyth at devel.trillke.net Mon Nov 18 08:20:09 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 18 Nov 2002 14:20:09 +0100 Subject: pythonic way to optimize access to imported value? In-Reply-To: <20021118064744.A4002@unpythonic.net>; from jepler@unpythonic.net on Mon, Nov 18, 2002 at 06:47:54AM -0600 References: <3DD85526.6020606@something.invalid> <20021118064744.A4002@unpythonic.net> Message-ID: <20021118142009.F30315@prim.han.de> Jeff Epler wrote: > On Mon, Nov 18, 2002 at 04:03:30AM +0000, Bengt Richter wrote: > > IOW, IMO there ought to be a way to do a temporary global-side-effect-free > > import and delete all traces of its having been done -- without restarting > > the interpreter or invoking a second interpreter instance. > > Let us know when you've implemented it. yes bengt, go for it :-) > Some of the problems: > > Modules need not be side-effect-free. For instance, the following is a > (very harmful) legal Python module: > from os import system > system("rm -rf /") sure, removing modules can only be as side effect free as the modules itself is. You can't even reverse print 'hello world'. I am sure there are uses for removing module objects. I'd recommend going for an 'try_remove_module' function which tries to achieve module unloading. It's probably neccessary to assert that there are no references to any objects in that to-be-removed module. So you might be able to say: import somemodule # do stuff with somemodule but don't permanently bind to any # of its objects try_remove_module(somemodule) del somemodule # or do a hack inside try_remove_module # somemodule should now be removed from memory, unless it's # a C-module or other special cases to be determined :-) On a side note, yesterday i talked to a perl hacker and he said that mod_perl suffers a lot from interpreter bloat because it's very hard to unload something plus perl has memory allocation problems with its mutable strings (memory usage always stays at the maximum size that string ever had). python doesn't have the latter problem because its strings are immutable. Don't know about how lists and dicts are handled, though. So I think that e.g. apps with mod_python could benefit from beeing able to unload some modules which are only temporarily used as helpers. regards, holger From mgerrans at mindspring.com Mon Nov 11 12:12:28 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Mon, 11 Nov 2002 09:12:28 -0800 Subject: Can python find fibonacci series in a single line of code? References: Message-ID: "Jeff Epler" wrote: > import zlib,base64;exec zlib.decompress(base64.decodestring('eNpLtE2yNeQqz8jMSVUwtOJSSNRJsk3STtRJ5FI oKMrMK1FI5AIAsOwJ0A==')) > > it's as unreadable as the best Perl code IMO Nah, nice try, but I think the Perl is still more unreadable. From bokr at oz.net Tue Nov 26 11:21:57 2002 From: bokr at oz.net (Bengt Richter) Date: 26 Nov 2002 16:21:57 GMT Subject: Python Tutorial Was: Guido's regrets: filter and map References: <20021126043142.4323.25612.Mailman@mail.python.org> Message-ID: On Mon, 25 Nov 2002 23:19:46 -0800, Terry Hancock wrote: [...] > >map(), filter(), and reduce() do not represent all of the uses for filter, >and thus, they can't all be replaced by list comps (BTW, I never used >reduce, never understood what it was good for, and don't immediately >see how it can be done using list-comps -- would be genuinely interested >in seeing a couple of example if anyone's willing). > I guess I'll bite: >>> def lcreduce(fn, seq, init=None): ... return [first ... for first, rest in [ init is None and ... (list(seq[:1]), list(seq[1:])+[id]) or ... ([init], list(seq)+[id])] ... for y in rest if y is id or first.append(fn(first.pop(), y))][0][0] ... >>> seq = range(10) >>> lcreduce(int.__add__,seq) 45 >>> lcreduce(int.__add__,seq,5) 50 >>> seq = (1,2) >>> lcreduce(int.__add__,seq) 3 >>> lcreduce(int.__add__,seq,5) 8 >>> seq = [3] >>> lcreduce(int.__add__,seq) 3 >>> lcreduce(int.__add__,seq,5) 8 >>> seq = () >>> lcreduce(int.__add__,seq,5) 5 >>> lcreduce(int.__add__,seq) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in lcreduce IndexError: list index out of range But that last is ok: >>> reduce(int.__add__,seq) Traceback (most recent call last): File "", line 1, in ? TypeError: reduce() of empty sequence with no initial value I suspect reduce is a little faster than lcreduce ;-) Regards, Bengt Richter From dvass at felis.uni-freiburg.de Thu Nov 14 09:37:01 2002 From: dvass at felis.uni-freiburg.de (Joerg Woelke) Date: Thu, 14 Nov 2002 15:37:01 +0100 Subject: os.system and wget References: <7d728336.0211130756.3e39a748@posting.google.com> Message-ID: <3DD3B50D.C6A6BA8B@felis.uni-freiburg.de> Hi! John Hunter wrote: [ snip ] > zunbeltz> os.system('wget -q -O foo.txt http://foo.html') [ snip ] > h = os.popen('wget -q -O foo1.txt http://foo.html') > h.close() What for, if you don't do anything (read/write) with the pipe? That's what os.system is for. [ snip ] > John Hunter Confused, J"o! -- sigfault From mhammond at skippinet.com.au Mon Nov 18 16:53:57 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 18 Nov 2002 21:53:57 GMT Subject: Will python binaries compiled on vs.net? In-Reply-To: References: Message-ID: Tim Peters wrote: > I don't foresee PythonLabs getting into the VC7 business anytime soon: > there are monetary and human costs we can't afford. Perhaps ActiveState > will, and/or the Python Business Forum will fund a VC7 effort, but I don't > know. I simply like the VC6 UI better. I have a full VC7 installed here, but never use it. Mark. From tweedgeezer at hotmail.com Wed Nov 27 04:55:03 2002 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 27 Nov 2002 01:55:03 -0800 Subject: Python Tutorial Was: Guido's regrets: filter and map References: <698f09f8.0211261046.582254a5@posting.google.com> Message-ID: <698f09f8.0211270155.207f81e@posting.google.com> "John Roth" wrote in message news:... > I could see filter and reduce as methods. Since map is a function across > a number of input lists, I have a somewhat harder time seeing it that > way - it looks a bit assymetric to me. What's asymmetric is that filter and map operate over any sequence but only return lists; if, instead, they had been methods on lists, then implementations of other container data structures (dictionaries, binary trees, strings, etc.) could provide their own filter and map methods that returned values of the same type. Reduce (which I so wish was called foldl, leaving the oppurtunity open for a symmetric foldr) is really the only of the three (map/filter/reduce) that makes sense as a function (rather than as a method) since it's defined over sequences in general, and sequences don't by nature make an appearance in its return value. Jeremy From soufle at yahoo.com Thu Nov 7 17:41:34 2002 From: soufle at yahoo.com (noyb) Date: Thu, 07 Nov 2002 22:41:34 GMT Subject: Complex numbers, abs results in mag, what results in phase? Message-ID: <071120021741272463%soufle@yahoo.com> I am trying to find out how to get the phase or angle of a complex number in Python 2.2. Yes, I have Numpy installed. I have found how to get the magnitude of a complex number, use "abs". I have also found how to get the real and imaginary parts but am stumped by the angle. I am using something like: my_complex_variable = (a +bj) and I can do abs(my_complex_variable) to get the magnitude. I realize the angle is atan(b,a) but I need to use my_complex_variable as input and not a,b. Hope someone knows of a comand I am missing. David From eric.brunel at pragmadev.com Thu Nov 14 03:54:00 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 14 Nov 2002 09:54:00 +0100 Subject: Tkinter+CORBA+threads, two main-loops. Problems? References: Message-ID: L Ekman wrote: > Hello, > > I am trying to make a program that contains a CORBA server > implemented with orbit-python-0.3.1 and a GUI implemented with > Tkinter. > > The problem is that both orbit-python-0.3.1 and Tkinter has > "main-loops", and can not find a way to implement this in a > single threaded program. I once used the fnorb ORB (http://www.fnorb.org) and problem was solved in the ORB itself. See http://www.fnorb.org/docs/1.2/Fnorb-Guide/node50.html It may be a solution if you can change your ORB. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From gminick at hacker.pl Sat Nov 23 11:13:18 2002 From: gminick at hacker.pl (Wojtek Walczak) Date: Sat, 23 Nov 2002 16:13:18 +0000 (UTC) Subject: reliable tcp server holding multiple connections Message-ID: Hi, I'm trying to write a skeleton of a TCP server able to hold multiple connections. The code is here: It works nice, but I'm sure, there're dozens of small, hard to see and to think about bugs, and I want you to help me in tracing them ;) Why I'm doing this? Since it's hard to find such an example in c.u.py archives. In howtos and documentation you'll find nothing but some simple single server examples. I want to create a point of reference to well-written TCP server (holding multiple connections), but it's almost impossible without your participation :) ps. I know about SocketServer ;) -- [ ] gminick (at) underground.org.pl http://gminick.linuxsecurity.pl/ [ ] [ "Po prostu lubie poranna samotnosc, bo wtedy kawa smakuje najlepiej." ] From maney at pobox.com Thu Nov 14 23:39:13 2002 From: maney at pobox.com (maney at pobox.com) Date: Fri, 15 Nov 2002 04:39:13 +0000 (UTC) Subject: questions about scope/threading References: Message-ID: Aahz wrote: > Thing is, while var3 is not a module global, any thread can access that > name through Class1.var3 -- therefore, the object bound to Class1.var3 > is a completely global object, and you have to be careful what you do > with Class1.var3 (or the object bound to it if the object is mutable). > Tricky stuff. I hadn't thought about Python's scoping that way before. So anything not "hidden" inside a function is present in the global tree of namespaces? (or class definition. hmmm, any others?) Of course I knew that, and have used it to access modules, but somehow this feels like a new point of view. Interesting. From kowk at earthlink.net Mon Nov 18 23:31:53 2002 From: kowk at earthlink.net (Kow K) Date: Mon, 18 Nov 2002 20:31:53 -0800 Subject: classifier systems re-coded in Python? Message-ID: On Monday, November 18, 2002, at 07:11 , Terry Reedy wrote: >> I'm just wondering if anybody has re-coded David Goldberg's Pascal >> implementation of John Holland's (learning) classifier system in > Python. >> >> Any pointer will be appreciated. > > try: > google('Holland learning classifier Python') Yes, I did a Google search before posting here, but I didn't get really relevant threads. Kow From mwh at python.net Mon Nov 4 08:46:18 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 4 Nov 2002 13:46:18 GMT Subject: PyGTK question References: Message-ID: Tom writes: > In article , Michael Hudson > wrote: > > > Tom writes: > > > > > Thanks for your help. If I compile it from source (pygtk2-1.99.10-1), > > > wouldn't it check for a version of python that is compatible when > > > running the ./configure script? > > > > God knows. You'd have thought so, but it doesn't look like it. > > > > The problem you're having is that the gtk DSO seems to be looking for > > a wide unicoode build of Python whereas the Python you're running is > > built for narrow unicode. > > > > How many versions of Python do you have on your machine? > > I have two at the moment...1.5 and 2.2. However, I have recently > downloaded (but not yet installed) 2.1 to see if I get different > results. It's possible the pygtk configure script is finding Python 1.5, not 2.2. Or it found 2.2 but you're trying to use it with 1.5. Cheers, M. -- 40. There are two ways to write error-free programs; only the third one works. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From Andreas.Leitgeb at siemens.at Tue Nov 12 10:24:14 2002 From: Andreas.Leitgeb at siemens.at (Andreas Leitgeb) Date: Tue, 12 Nov 2002 15:24:14 +0000 (UTC) Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCFDE7A.8010404@web.de> Message-ID: Pascal Costanza wrote: >> I quote one function from AisleRiot (game Kansas): >> " (define (button-pressed slot-id card-list) >> " (and (not (= (length card-list) 0)) >> " (is-visible? (car card-list)) >> " (or (= slot-id 1) >> " (> slot-id 5)))) > If you are used to this kind of syntax, it's very simple. I don't know > enough Python (yet) in order to translate this, but in Java it would > look as follows. > 1 boolean buttonPressed (int slotId, Vector cardList) { > 2 return !(cardList.size() == 0) && > 3 cardList.get(0).isVisible() && > 4 ((slotId == 1) || (slotId > 5)); > 5 } I'd have rewritten it differently (to show the point I was trying to make by calling the scheme-snippet ugly): 2 if (cardList.size() == 0) return false; 3 else if (!cardList.get(0).isVisible()) return false; 4 else return ((slotId == 1) || (slotId > 5)); Now this doesn't make a big difference here, but it makes a lot of a difference, once, things get longer and deeper nested. > My basic message here is that you might like Common Lisp more than > Scheme. *nudge, nudge* I'm not sure if I can really see the difference yet (beyond some differently named predefined symbols/keywords). Since almost every modern language (worth mentioning) has the concept of short cutting boolean evaluation, one could write Lisp/Scheme style everywhere; Nevertheless I'm glad it's not so common anywhere else. From sundae1888 at hotmail.com Fri Nov 1 12:30:17 2002 From: sundae1888 at hotmail.com (sundae) Date: 1 Nov 2002 09:30:17 -0800 Subject: Sending null byte to serial port in Windows using PySerial? Message-ID: <49f4e27a.0211010930.56788863@posting.google.com> Hi all, I'm having troubles sending the null byte (0x00) to the serial port in Windows using PySerial on ActivePython 2.2.1 build 222. Currently I'm doing something like this: com = serial.Serial("COM1", 9600, timeout=1) -- -- com.write(chr(0)) The device should reply a single byte upon receiving this byte, but I never got anything in reply. I looked at PySerial's code, which calls win32file.WriteFile() to write to the serial port. I also checked out USPP, which unfortunately threw an exception when I called read(). I suppose it wouldn't make a huge difference anyway, since USPP uses win32file for the underlying communication as well. Have I missed anything? Should I use some other method to write the null byte to the serial port? Thank you very much for you help! From sismex01 at hebmex.com Tue Nov 26 11:22:08 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 26 Nov 2002 10:22:08 -0600 Subject: Python Tutorial Was: Guido's regrets: filter and map Message-ID: > From: grante at visi.com [mailto:grante at visi.com] > Sent: Tuesday, November 26, 2002 10:10 AM > > In article , > sismex01 at hebmex.com wrote: > > > Anyway, to each it's own. But I do concurr with those who > > say that with the acquisition of list comprehensions, map(), > > reduce(), filter(), lambda() et-al, should be on the road > > to deprecation and eventual elimination, being the black > > un-pythonic sheep of the family. > > I see how you use list comprehensions to replace map and > filter, but I don't understand why list comprehensions are > touted as a replacement for reduce and lambda. I use lamba > almost exclusively to generate anonymous functions that are > passed to GUI widgets. How does a list comprehension solve > that problem? > > In the case of reduce: > > sum = reduce(operator.add, valueList) > > How is that expressed any better with a list comprension? > Indeed it's a difficult question; let's ponder it for a sec... (or ten). :-) -gustavo From aleax at aleax.it Thu Nov 14 15:39:28 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 14 Nov 2002 20:39:28 GMT Subject: A really bad idea. References: Message-ID: <4STA9.9987$744.345722@news1.tin.it> M wrote: ... > But I see a disturbing trend. "trend"? > The new enumerate or zip function. If you look at the code using this "new"? _zip_...? It was introduced in Python 2.0... > function it is not at all obvious what the code does. Let say a programmer Are you claiming the pre-2.0 code (without zip) doing the rough equivalent of today's e.g. x = zip(onething, another) namely x = map(None, onething, another) WAS more obvious...?! I don't see how you can claim a TREND unless you ARE claiming that "map(None, ..." was indeed "obvious" in a way that zip isn't. And that is so totally and utterly absurd a claim that I wouldn't know what to make of it. Python has a few dozen built-in functions. I wouldn't _expect_ MOST of them to be "immediately obvious" to somebody who has not even bothered glancing at the docs, or trying e.g help(zip) at the prompt in an interactive session. And I don't see any "trend" in that, since e.g. the time of Python 1.5.2, which is where I came in. > I hope this is not a start of adding powerfull and hard to understand > features to Python. I dispute that "not immediately obvious unless one bothers to read the docs or try calling help" is equivalent to "hard to understand". In any case, you cannot possibly be seeing "the start" of adding a few powerful built-in functions to Python, since most of them were already in 1.5.2 -- thus, "the start" must have been much older. Alex From wlfraed at ix.netcom.com Sun Nov 24 18:15:36 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sun, 24 Nov 2002 15:15:36 -0800 Subject: using del() to 'unimport' References: <918bc22f.0211240425.68b8c282@posting.google.com> Message-ID: Donnal Walter fed this fish to the penguins on Sunday 24 November 2002 04:25 am: > When the the following module is imported, I want only 'MyClass' (NOT > 'Useful' and 'Mixin1') to be publicly accessible. > > ======= mymodule.py ================== > from utilities import Useful, Mixin1 > > class MyClass(Useful, Mixin1): pass > ====================================== > Don't use "from...import..." What happens if you use: import utilities class MyClass(utilities.Useful, utilities.Mixin1): pass -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From des.small at bristol.ac.uk Wed Nov 20 11:39:53 2002 From: des.small at bristol.ac.uk (Des Small) Date: Wed, 20 Nov 2002 16:39:53 GMT Subject: Teaching numerics with Python References: Message-ID: Antti Rasila writes: > 1) ..someone has experience on this kind of usage of Python numerical > mathematics? We would be happy to hear from your experiences. I work as a Scientific Programmer in a University maths department, and Python is my main language. The advantages for me are essentially those you note: * short development times * interactive code development (I can't work without this, anymore) * it's not FORTRAN * convenient bindings to Tk for guis, VTK for 3D visualisation stuff (typically both get used together). * it's not C++ * Numeric extensions have much of the power attributed to MATLAB for array-bashing * it's a Real Language * you can recode bottlenecks in C if the mood takes you (it usually doesn't in my case, but that's because I care more about my time than the computer's) Plus you can get people from a FORTRAN background to try it (if this wasn't a constraint I might have gone with Lisp) although I'd prefer not to look at any more of the resulting code. > 2) ..if some course material and ready program files are available, > which we could use as building blocks of our course? We don't have any. I don't teach, but the computing curriculum here is being reconsidered, and it may be that Python figures in undergraduate life in the future, so I'd be interested in this too. How you teach this stuff probably depends on whether you can assume prior knowledge of programming in general. > 3) ..you have seen a book such as Scientific Computing with Python No, but if someone writes one, I'll buy it. > Links: > > Spring 2002 course homepage: > http://www.math.helsinki.fi/~arasila/nrc02/ Des -- Des Small, Scientific Programmer, School of Mathematics, University of Bristol, UK. From bokr at oz.net Wed Nov 6 12:21:46 2002 From: bokr at oz.net (Bengt Richter) Date: 6 Nov 2002 17:21:46 GMT Subject: Guilty secret: globals baffle me References: <3U9y9.19300$ko1.2872530@kent.svc.tds.net> <82ay9.98000$TD1.4405986@news2.tin.it> Message-ID: On Wed, 06 Nov 2002 14:53:56 GMT, Alex Martelli wrote: >Edward K. Ream wrote: > ... >> 1. How many globals are there? Is there just one, or does each module >> define its own? > >The latter. Each module has its own globals-dictionary. > > >> 2. It seems that: >> >> global foo >> foo = x >> ... >> global >> print foo >> >> only works if the two parts are within the same module, so I think maybe >> globals() returns module specific stuff, but then why call it globals? > >It seems that you haven't noticed the existence of functions (and >their namespaces, particularly their crucial local namespace). > >The global statement only makes sense inside a function: it tells the >Python compiler that certain names, that the function binds, rebinds >or unbinds, are NOT (as is the normal case) local to the function, but >rather refer to names in the module's globals-dictionary. > >Outside of any function, all names refer to the module's globals- >dictionary, therefore the global statement is redundant -- useless, >although technically innocuous. > >Given that names that only exist within a function are commonly >called "local names" or "local variables" of that function, how >else would you call names that AREN'T local, but rather global >to all functions within the module? Calling them "module names" >would IMHO be far more confusing than calling them "global >names" -- I think of module names as the names of modules; and >the local/global distinction would become quite confused. > I agree. But BTW, don't forget in-between variables such as x in >>> def foo(): ... x=1 ... def bar(): ... print x ... bar() ... x=2 ... bar() ... >>> foo() 1 2 which isn't local to bar but isn't global either. I have an uncomfortable feeling there is unfinished business in the way names in nested scopes and otherwise related namespaces work. The global/local dichotomy doesn't fully express the possibilities any more. IMO it would be nice to have full access to accessible namespaces without magically determined access mode restrictions based on full-function lookahead. I.e., we have a de facto hierarchy of name spaces defined by the ability to nest functions. Why not have an access mechanism that allows rebinding as desired? E.g., you could let locals take a depth argument, so locals() is equivalent to locals(0), and locals(1) is the enclosing name space, so locals(1)['x'] = 3 in bar above would rebind the x local to foo. For notational convenience, you could make locals an object with a __getitem__ that would return the name space as an object with attributes, so you could write locals[1].x = 3 instead. Globals would be at the end of the list at locals[-1]. In conjuction with this, I wonder if the PostScript way of pushing and popping dictionaries onto/from a stack of dictionaries has something that could be used by python. Temporarily getting unqualified-name access to a chosen namespace shadowing others by being on top seems like a useful thing. Sort of like entering the local namespace of a function without leaving the calling code context. Thus pushing a dictionary would make it temporarily local[0] and the previous local[0] would be local[1], so you could still get at it explicitly if a name was shadowed and/or you wanted to rebind there. Lots of things would become possible. You could push a reference to another module's global space temporarily, for unqualified name access, or you could do it with kwargs, meaning just a reference push instead of the update trick, and many other possibilities. push_dir(local(1)) would give you transparent access to the enclosing scope for read/rebind as if it were your own local space. push_dir(vars(obj)) would let you write x = 1 and have the effect of obj.x = 1. pop_dir() would revert to the previous unqualified name space. Regards, Bengt Richter From djc at object-craft.com.au Thu Nov 7 21:04:03 2002 From: djc at object-craft.com.au (Dave Cole) Date: 08 Nov 2002 13:04:03 +1100 Subject: csv module 1.0pre1 released Message-ID: WHAT IS IT: The CSV module provides a fast CSV parser which can split and join CSV records which have been produced by Microsoft products such as Access and Excel. NOTES: The most important change for this release is that the basic quote handling has been modified to exactly match the observed behaviour of Excel. A comprehensive test suite has been added to test this observed behaviour. If the module does not conform to Excel behaviour we consider this to be a bug. The pre designation on the release is due to the slight change in quote handling. CHANGES SINCE 0.5: * Moved to standard BSD template license. * Now using distutils to create source distribution. * Parser's handling of unusual quoting styles was found to be at odds with Excel. In particular, Excel only treats the quote character as special if it appears as the first character in a field, whereas our parser honoured them anywhere. We now produce the same result as Excel - quotes within a field appear in the output. * Introduced Parser.quote_char attribute to replace the hard coded " (double quote). You can now disable quoting by setting quote_char to 0 or None. * Introduced Parser.escape_char attribute which is used to escape special characters when quote_char is specified is disabled. * Introduced Parser.strict attribute which controls whether the parser will raise an exception on malformed fields rather than attempting to guess the right behaviour. * Introduced a suite of unit tests. -- http://www.object-craft.com.au From neal at metaslash.com Sat Nov 9 10:11:52 2002 From: neal at metaslash.com (Neal Norwitz) Date: Sat, 09 Nov 2002 10:11:52 -0500 Subject: Dynamic loading of modules in AIX References: Message-ID: On Fri, 08 Nov 2002 01:13:03 -0500, Stuart D. Gathman wrote: > On Thu, 07 Nov 2002 22:04:23 -0500, Neal Norwitz wrote: > >> I'm trying to get python to load dynamic modules. But after loading the >> module, when code inside the module calls back into the main program, >> it seg faults. More details below. > > You need to use ld_so_aix, which imports the symbols for the main > program into the loadable modules. Otherwise, those symbols are > unresolved giving a coredump when called. Stuart, thanks for your reply. Actually, it is using ld_so_aix. I cut it out for brevity. Sorry for the confusion. I am using the standard make process. ./configure && make > You can find my RPM spec file for python-2.2 at > http://www.bmsi.com/aix/python-2.2.spec > > (along with binary RPMs and a tar of rpm itself. RPM needs LANG=C on > some AIX versions.) > > Even if you don't use RPM on AIX, the spec file will tell you how to > build python. Look at the %build section. I looked at your spec file. I tried setting LANG=C. It didn't help. I tried using xlc and -brtl -bdynamic. That also didn't help. I noticed that gcc was compiled with --disabled-shared. I don't know if that's a problem. I suspect not, since xlc also fails. The python.exp file appears to be created correctly. The API which causes the core dump is in python.exp file. This file is imported when trying to make the .so. I'm not sure how the machines are configured. So it's possible there's a configuration problem. I checked my limits (ulimit) and those seemed fine. Any other ideas? Thanks, Neal From ianb at colorstudy.com Sat Nov 16 15:25:54 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 16 Nov 2002 14:25:54 -0600 Subject: Python instead of php In-Reply-To: References: Message-ID: <1037478354.3335.44.camel@dsl-65-184-205-5.telocity.com> Look to: http://www.python.org/cgi-bin/moinmoin/WebProgramming There are several frameworks, some of which are very similar to PHP and some of which are not. PSP (in Webware) and Spyce are probably the most like PHP -- there's quite a few small Python-embedded-in-HTML programs out there as well. Other frameworks have different ways of mixing HTML and code. On Sat, 2002-11-16 at 06:25, Marten Bauer wrote: > Hello to ya all, > > i use python for programming a database (postgresql) project. > The Systeminterfaces are written in python and the Userinterface > (web based) is written in html/php. > > Is it possible to use python like php as script language to writte > the Userinterfaces also in html and python? > > Is modpython for apache or Twisted from Tweak Labroratory a possible > way? > > > Thanks for helping > Marten -- Ian Bicking From martin at v.loewis.de Wed Nov 13 16:18:30 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 13 Nov 2002 22:18:30 +0100 Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> Message-ID: DaveP writes: > > However, it is not clear to what the value would be of completing the > > circle, given that the XML is of no use. > > Martin, your prejudice is showing; very badly :-) That might be the case. However, as a question, I meant it seriously: What do I gain from converting the Python documentation to XML? I'm convinced that there would be immediate gain; this is not a prejudice but a fact. Longer-term, I have been considering that using XML might help translating the Python documentation to French and German, but I'm certain that nobody else has that usage in mind. So I'm wondering what other people expect from this, apart from buzzword compliance. Regards, Martin From gerhard.haering at gmx.de Mon Nov 4 21:18:39 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Tue, 5 Nov 2002 03:18:39 +0100 Subject: python2.2 and wxPythonGTK problem In-Reply-To: <88bc63c6.0211041724.17cff049@posting.google.com> References: <88bc63c6.0211041724.17cff049@posting.google.com> Message-ID: <20021105021839.GA1283@lilith.ghaering.test> * Doug Farrell [2002-11-04 17:24 -0800]: > [splitter problems after switch versions] You'll have much better chances of receiving a useful answer by posting this question to the wxPython-users mailing list. -- Gerhard From gerhard.haering at gmx.de Sat Nov 9 10:34:28 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sat, 9 Nov 2002 16:34:28 +0100 Subject: Determining Presence Of GUI Support In-Reply-To: <42aiqa.jp82.ln@boundary.tundraware.com> References: <42aiqa.jp82.ln@boundary.tundraware.com> Message-ID: <20021109153428.GA13991@lilith.ghaering.test> * Tim Daneliuk [2002-11-09 06:40 +0000]: > Is there a portable method of determining whether the current runtime > environment supports a GUI or text-based interface? I would like to > write a single program which autosenses the presentation environment > and works accordingly. You can obtain wether or not you're running under X11 by checking for the existence of the "DISPLAY" environment variable: >>> import os >>> "DISPLAY" in os.environ 1 -- Gerhard From m.faassen at vet.uu.nl Fri Nov 22 17:19:58 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 22 Nov 2002 22:19:58 GMT Subject: PSU Space Time Continuum Warning Message-ID: SECRET SECRET SECRET FOR PSU MEMBERS ONLY SECRET SECRET This Python Secret Underground Space Time Continuum Warning is SECRET. Do not distribute on punishment of removal from the space time continuum in ALL timelines. Some of you may have been wondering why the Python Journal claims Guido van Rossum developed Python in Italy: http://pythonjournal.cognizor.com/template/PyJdescr.html """ Python is a forefront language for web communication and general computing. Download it for free from python.org, with lots of goodies. You can see how programs work in python because it's legible and clear: It was originated as a first programming language by Guido van Rossum in Italy, now in US. """ You may even feel inclined to point out that no, Guido is Dutch, and he developed it in the Netherlands, not Italy. This is a MISTAKE. Your memories will adjust shortly. Guido van Rossum is of course from Italy. This has always been the case. Your memories are just a temporal remnant caused by inductive failure in the crosstime bands. Python was developed in Italy with the sage help and advice of Alex Martelli, aka the Martellibot. The Martellibot is an acausal construct caused by an feedback loop in timeline 14A, as is well known. This doctoring of the timeline is necessary to prevent the cataclysm of 2514. This cataclysm, an intense irregular expression confluxion in the Earth's Tentative Core, would otherwise have prevented the foundation of the first Dawn Federation. It is expected that further doctoring of the timeline is necessary. If the Python Journal claims next that Guido is really from Japan and that there was an early schism with Ruby (about indentation, of course) from an ur-language that he and Matz were designing, then do not be surprised. From Oschler at earthlink.net Sat Nov 2 14:36:27 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sat, 02 Nov 2002 19:36:27 GMT Subject: Jython 2.1 requires JDK 1.2? Message-ID: <%OVw9.41490$Lg2.11093045@news2.news.adelphia.net> I thought Jython 2.1 could run with JDK 1.1 or above. However, when I try to compile a Jython project, it's looking for the ReferenceQueue class which is from JDK 1.2 . I thought I saw a 'release note' item mentioning the removal of JDK 1.2 dependencies. I checked the JVM compatibility link: http://www.jython.org/platform.html But it mostly talks about JVM versions and not JDK versions. thx From jbublitzNO at SPAMnwinternet.com Tue Nov 5 15:53:06 2002 From: jbublitzNO at SPAMnwinternet.com (Jim) Date: Tue, 05 Nov 2002 20:53:06 GMT Subject: pyqt table References: <3dc7f35b$0$11674@echo-01.iinet.net.au> Message-ID: <3DC82F93.9090603@SPAMnwinternet.com> Rob Hall wrote: > I have created a qt table fine. I want to be able to colour the background > of individual cells but I cant find a setBackground method fot QTableItem. > How do I colour the background of a cell? I haven't done this in quite a while, but it looks like you need to subclass QTableItem and overload the paint method: class CustomTableItem (QTableItem): def __init__ (self, table, et, text): QTableItem.__init__ (self, table, et, text) def paint (self, p, cg, cr, selected): if new_cg = else: new_cg = cg QTableItem.paint (self, p, new_cg, cr, selected) Each QTableItem holds row/col properties, so you can use those to determine the row being painted. (see QTableItem.row (), for example) See the Qt docs for QTableItem::paint and QColorGroup. There's also some example C++ code linked at QTableItem.paint in the Qt docs. Jim From tchur at optushome.com.au Thu Nov 14 14:24:12 2002 From: tchur at optushome.com.au (Tim Churches) Date: Fri, 15 Nov 2002 06:24:12 +1100 Subject: decision tree by python References: <_xTA9.30934$QZ.6707@sccrnsc02> Message-ID: <3DD3F85C.8E691E0B@optushome.com.au> Laurence Gonsalves wrote: > > On Wed, 6 Nov 2002 16:06:14 -0500, > Chermside, Michael wrote: > > > i am trying to construct a decision and classifiy a set > > > of data using GINI index. > > > Is there any references? > > > > I'm really not quite sure what you're asking for. The phrase > > "construct a decision" suggests that you're trying to build > > some object... but I'm not sure what a "decision object" would > > be. Alternatively, you may simply not be a native English > > speaker and you simply meant you wanted to "make a decision". > > That's fine, but without SOME SORT of description of WHAT > > decision, it's hard to find a resource. > > Or maybe they made typo. :-) > > The subject says "decision tree", so I'm guessing they want to construct > a decision tree for classifying data using the GINI index. > > The ID3 decision tree learning algorithm is described on this page: > > http://www.cs.tufts.edu/g/150ML/slides/id3.html > > Converting it to Python isn't too difficult. Orange might be worth a look (see http://magix.fri.uni-lj.si/orange/ ) - it implements some elementary classifiers as well as a wrapper for C4.5, which is a further development of ID3 (and also freely available, unlike the proprietary C5.0 algorithm). Peter Christen at ANU has also written a very nice Pythonic C-level interface to the C4.5 code, but I'm not sure whether he has released it - see http://cap.anu.edu.au/cap/projects/KDDMemPerf/ for more details. Tim C From mwilson at the-wire.com Sun Nov 24 11:11:43 2002 From: mwilson at the-wire.com (Mel Wilson) Date: Sun, 24 Nov 2002 11:11:43 -0500 Subject: if : References: Message-ID: In article , =?ISO-8859-1?Q?Andr=E9_N=E6ss?= wrote: >When I started learning Python one of the things that surprised me was that >you couldn't do assignments inside the if clause, e.g.: > >if myvar = someFunction(): > >My question is, what is the rationale for this? Is it a technical issue? Or >purely a matter of language design? I'm curious because I'm interested in >the design og programming languages, not because I want this behavior >changed in Pyton :) We've just been there. groups.google.com can bring it all back, although I don't offhand remember the subject. Basically, assignments aren't possible within expressions. One good reason for this is list packing/unpacking in assignments: a, b = 5, 8 As it stands, this is an assignment which effectively makes two 2-tuples equivalent, associating `a` with the value 5, and `b` with the value 8. If `b=5` were an allowable expression, then the statement above would change into a 3-tuple, and a useful piece of semantics would be a tad more awkward. (Reading that thread, I was surprised to find that I'd uncritically been associating `()` with tuples the way `[]` are actually associated with lists. 'Tain't so.) You could think of making an exception for `if` statements, but beyond an uncertain point, exceptions are bad for a language; Gerald M.Weinberg's _The Psychology of Computer Programming_ contains a discussion. I don't know where that point is, at most I might claim to know cases where languages haven't passed it and cases where they have. Regards. Mel. From irmen at NOSPAM-REMOVETHIS-xs4all.nl Thu Nov 28 14:44:42 2002 From: irmen at NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 28 Nov 2002 20:44:42 +0100 Subject: LAN communication under windows In-Reply-To: <3de60530.10377734@news.easynews.net> References: <3de60530.10377734@news.easynews.net> Message-ID: <3de67227$0$11752$e4fe514c@news.xs4all.nl> If you have no idea where to start, I strongly suggest you skip the socket programming altogether, and have a look at PYRO. http://pyro.sourceforge.net Pyro provides remotely callable objects without having to program a single line of networking code. Irmen From eric.brunel at pragmadev.com Mon Nov 4 04:06:46 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 4 Nov 2002 10:06:46 +0100 Subject: Field in SGML file References: Message-ID: Peter Flynn wrote: [snip] > I don't know how you call external binaries from within Python, but you > need to issue the command string > > nsgmls -cCATALOG [sgml-dec] filename >From within Python: nsgmlsOutput = os.popen("nsgmls -cCATALOG [sgml-dec] filename") will do the trick. Use nsgmlsOutput just like a file opened for reading. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From fgeiger at datec.at Thu Nov 21 13:24:40 2002 From: fgeiger at datec.at (F. GEIGER) Date: Thu, 21 Nov 2002 19:24:40 +0100 Subject: [wxPython] I'd like to catch mouse click events within a text control Message-ID: <3ddd24d9@news.swissonline.ch> I'd like to catch mouse click events within a text control and then read the mouse pointer position. Alas, the only events I found in the dox are, EVT_TEXT, EVT_TEXT_ENTER, EVT_TEXT_URL, EVT_TEXT_MAXLEN. Is this possible at all? Do I have to catch the click event from an other control, which receives the click event? Which one could it be? Many thanks in advance and kind regards Franz GEIGER P.S.: Platform is AP 2.1.3, wxPython 2.3.2.1. From theller at python.net Fri Nov 15 07:14:19 2002 From: theller at python.net (Thomas Heller) Date: 15 Nov 2002 13:14:19 +0100 Subject: A really bad idea. References: <7h3d6p7xelx.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson writes: > C without it's library would get a rating of "useless"... guess this > is true for most languages, but C more than most. > Not at all, imo. You just have to write the library yourself, and you *can* do it in C. Thomas From bokr at oz.net Sun Nov 10 08:36:51 2002 From: bokr at oz.net (Bengt Richter) Date: 10 Nov 2002 13:36:51 GMT Subject: RE - non-greedy - some greediness - complete greediness References: Message-ID: On Sun, 10 Nov 2002 09:57:28 +0100 (MET), Doru-Catalin Togea wrote: >Hi! > >I am working on a little project where i need REs with a self-defined >level of greediness. > >I am processing text in a Latex like manner, for those of you who are >familiar with it. > >I want to be able to recognize Latex-like commands within my text. A >command starts with a character, say '\' followed by the command's name >and followed by the text on which the command applies enclosed in curly >brackets. Examples: > > \footnote{some text} > \cite{some referance} > \section{some title} > >Recognizing such patterns and retriving the name of the command and the >text on which the command applies is not so difficult to achieve. Things >get complicated though when one encounters nested commands. > This comes up with some regularity ;-) >Say I have the following string: > > "abcd \footnote{efgh \cite{myRef1} ijkl} mnop \footnote{hello there}" > ^ ^ ^ > closing bracket of nested \cite | | | > closing bracket of first \footnote | | > closing bracket of second \footnote | > >By using non-greedy REs, I would get recognized the following footnotes: > 1) \footnote{efgh \cite{myRef1} > 2) \footnote{hello there} > >The first matching is wrong because the first '}' encountered belongs to >the nested \cite command. The second matching is correct. > >By using greedy REs, I would get recognized the following pattern: > 1) \footnote{efgh \cite{myRef1} ijkl} mnop \footnote{hello there} > >This is wrong because a) there are two \footnote commands in my string, so >I should get two matchings, and b) the first \footnote command should be >applied only to the "efgh \cite{myRef1} ijkl" substring. > >In other words I need to be able to specify the level of greediness my REs >should have. Is it possible? If yes, how? > >I have an idea of how to solve my problem without REs, by counting the >opening and closing curly brackets and reasoning algorithmically about >where within my text each nested command begins and ends. The question is >can the above stated problem be solved elegantly by means of REs? > Since re's can't count without external help, and tricking it into using external help is not very efficient, it is probably best either to do it all without re or just use re to split the input into pieces that are easier for your subsequent processing to identify and deal with. E.g. (I added escaped backslash and curly brackets without knowing if/how that's actually done in Latex, and also assumed commands are lower case [a-z]+ Adjust to suit): >>> import re >>> s = r"abcd \footnote{efgh \cite{myRef1} ijkl} mnop \\not-cmd \{no curl\} \footnote{hello there}" >>> rx = re.compile(r'(\\[\\{}]|\\[a-z]+|[{}])') >>> ss = rx.split(s) >>> ss ['abcd ', '\\footnote', '', '{', 'efgh ', '\\cite', '', '{', 'myRef1', '}', ' ijkl', '}', ' mnop ', '\\\\', 'not-cmd ', '\\{', 'no curl', '\\}', ' ', '\\footnote', '', '{', 'hello there', '}', ''] >>> for x in ss: print `x` ... 'abcd ' '\\footnote' '' '{' 'efgh ' '\\cite' '' '{' 'myRef1' '}' ' ijkl' '}' ' mnop ' '\\\\' 'not-cmd ' '\\{' 'no curl' '\\}' ' ' '\\footnote' '' '{' 'hello there' '}' '' Thus each element in the list will be r'\\' or r'\{' or r'\}' or r'\command' or '{' or '}' or plain text, which are easy to tell apart. You could then process the list recursively or in a loop. BTW, you can get rid of the null strings with filter, e.g., ss = filter(None, rx.split(s)) if you don't want to use the fact that they serve to put matches with the split expression at the odd indices in the list and plain text (which will be null if matches are adjacent) at the even indices. I.e., note: >>> [ss[i] for i in range(1,len(ss),2)] ['\\footnote', '{', '\\cite', '{', '}', '}', '\\\\', '\\{', '\\}', '\\footnote', '{', '}'] and >>> [ss[i] for i in range(0,len(ss),2)] ['abcd ', '', 'efgh ', '', 'myRef1', ' ijkl', ' mnop ', 'not-cmd ', 'no curl', ' ', '', 'hello there', ''] My question would be how outer functions are applied to the results of inner ones. Are some inner results marked for passing through the outer and others marked for modification, and then all finally put together? Regards, Bengt Richter From mwh at python.net Fri Nov 29 07:11:46 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 29 Nov 2002 12:11:46 GMT Subject: Implementation of the global statement References: <8ef9bea6.0211270526.5a1278c5@posting.google.com> <3DE59E73.4040908@something.invalid> Message-ID: <7h3smxko9ry.fsf@pc150.maths.bris.ac.uk> "Terry Reedy" writes: > "Bengt Richter" wrote in message > news:as5ugi$a48$0 at 216.39.172.122... > > >>> def foo(x): print x > > ... > > >>> bar = foo.__get__('Hi via foo') > > >>> bar() > > Hi via foo > > This is a new one for me: > > >>> def f(): pass > ... > >>> f.__get__ > > >>> f.__get__.__doc__ > 'descr.__get__(obj[, type]) -> value' > > Seems to be a new, undocumented (?, not in indexes) method producing a > new, undocumented (?) internal type. Not something to bank a product > on ;-) Curiouser and curiouser: >>> def f(arg): ... print arg ... >>> f.__get__("e") >>> f.__get__("e")() e >>> def g(a,b): ... print a, b ... >>> g.__get__("f")("e") f e >>> g.__get__("f","e") >>> g.__get__("f","e")() Traceback (most recent call last): File "", line 1, in ? TypeError: g() takes exactly 2 arguments (1 given) >>> g.__get__("f","e")("d") f d Boggle :) Actually, I think I have some faint idea what is going on here: When you go instance.attr the translates, roughly, so long as 'attr' isn't a key in the instance's __dict__, into instance.__class__.__dict__['attr'].__get__(instance) so if instance.__class__.__dict__['attr'] is a regular function, the behaviour above is what produces the bound method. Hmm, actually, the translation might be: instance.__class__.__dict__['attr'].__get__(instance, instance.__class__) That whirring sound you can hear is my brain on its spin cycle :) Cheers, M. -- The "of course, while I have no problem with this at all, it's surely too much for a lesser being" flavor of argument always rings hollow to me. -- Tim Peters, 29 Apr 1998 From mgarcia at cole-switches.com Fri Nov 15 21:53:09 2002 From: mgarcia at cole-switches.com (Manuel M. Garcia) Date: Sat, 16 Nov 2002 02:53:09 GMT Subject: list.reverse() References: Message-ID: On Fri, 15 Nov 2002 20:16:30 -0600, Mike Dean wrote: >I think I recall seeing a reasonable explanation for this earlier >(probably referring actually to list.sort()), but I'm wondering - what >was the rationale for making list.reverse() reverse a list in-place >rather than return a new, reversed list? I'm sure there's a good >reason, but what might that be? list.reverse() is implemented as a very efficient, very tight C loop, because it is just swapping a bunch of pointers to internal Python objects. It requires much less time than having to make a copy, especially since a Python object can have unlimited size and unlimited levels of nesting of objects inside of objects. Manuel From jdhunter at nitace.bsd.uchicago.edu Sat Nov 16 09:52:42 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Sat, 16 Nov 2002 08:52:42 -0600 Subject: quick question In-Reply-To: <20021116051220.01520.00000047@mb-bk.aol.com> (bwfc10@aol.com's message of "16 Nov 2002 10:12:20 GMT") References: <20021116051220.01520.00000047@mb-bk.aol.com> Message-ID: >>>>> "Bwfc10" == Bwfc10 writes: Bwfc10> If you were writing a program aking about peoples Bwfc10> favourite flavour of ice cream and you input the number of Bwfc10> votes for 5 flavours, how do you get your program to Bwfc10> display the most popular (the one with the most votes). Bwfc10> This may be easy to most of you but i am new to python. This isn't homework, is it :-)? Python has a number of data structures to make your life easier. Let's start with the end result, and then I'll show you how to get there. Suppose you had a list of tuples, each tuple was a pair of vote tallies and icecreams votes = [ (12, 'vanilla'), (53, 'chocolate'), (1003, 'rocky road'), (1, 'rasberry sorbet'), ] python lists have an in place sort method, which for lists of tuples will sort on the first element of the tuple, which is what we want since vote counts are the first element of each tuple, If you want to display the winners first, you can reverse the list votes.sort() votes.reverse() # winners first! for (count, flavor) in votes: print '%s got %d votes' % (flavor, count) Now, all that remains to be done is generate the list in the first place. This depends on how you collect your data, but a good structure to use is a dictionary that maps flavors to counts. Suppose you had a long text file, where every row was the favorite flavor of somebody, eg chocolate vanilla chocolate rocky road vanilla rasberry sorbet ... and so on... You can loop over that file and create a dictionary mapping flavors to counts like so: favorites = {} for flavor in file('votes.dat'): flavor = flavor.strip() # remove leading or trailing white space favorites[flavor] = favorites.get(flavor,0) + 1 This last line is a common idiom for dictionaries. get returns the value of flavor if it exists, otherwise it returns the default value of 0. favorites looks like {'rocky road': 1, 'rasberry sorbet': 1, 'vanilla': 2, 'chocolate': 2} Now were almost done. We just need to get that dictionary into the list of tuples used above. votes = [(count, flavor) for (flavor, count) in m.items()] Here then, is the complete program: favorites = {} for flavor in file('votes.dat'): flavor = flavor.strip() # remove leading or trailing white space favorites[flavor] = favorites.get(flavor,0) + 1 votes = [(count, flavor) for (flavor, count) in favorites.items()] votes.sort() votes.reverse() # winners first! for (count, flavor) in votes: print '%s got %d votes' % (flavor, count) There is a chapter on sorting in The Python Cookbook that you should read if you get your hands on it. John Hunter From mwh at python.net Thu Nov 7 06:06:14 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 7 Nov 2002 11:06:14 GMT Subject: A vision for Parrot References: <3DC8623B.88753C16@earthlink.net> <3DC8CDDD.7050103@mindspring.com> <3pE8dhAtvNy9EwoQ@jessikat.fsnet.co.uk> <3DC943CF.84A68F32@san.rr.com> <20021106184401.X30315@prim.han.de> Message-ID: <7h3u1itzlot.fsf@pc150.maths.bris.ac.uk> holger krekel writes: > > I think that python allows any reference to change type dynamically. > > There are some restrictions especially with new-style classes. But *references* can still change type! I don't know whether SSA or something would help compiling Python. Maybe. Cheers, M. -- My hat is lined with tinfoil for protection in the unlikely event that the droid gets his PowerPoint presentation working. -- Alan W. Frame, alt.sysadmin.recovery From klaatu at evertek.net Tue Nov 19 21:08:00 2002 From: klaatu at evertek.net (Mike Dean) Date: Tue, 19 Nov 2002 20:08:00 -0600 Subject: static variables? References: <2259b0e2.0211190937.217dc25d@posting.google.com> Message-ID: On Tuesday 19 November 2002 11:37 am, Michele Simionato wrote in comp.lang.python: > > A simple trick to simulate static variables by passing an optional > mutable object is the following: > > def f(x,i=[0]): # i[0] is the "static" variable > i[0]+=1 > return x+i[0] > > print f(0),f(0),f(0) #--> 1,2,3 I've seen this trick a time or two before and always wondered - why does it work? Why does Python remember the changed list as the function's default value, rather than reverting back to the list that was specified when the function was defined? At first glance it seems a bit non-intuitive. Thanks, Michael From jason at tishler.net Wed Nov 27 07:43:59 2002 From: jason at tishler.net (Jason Tishler) Date: Wed, 27 Nov 2002 07:43:59 -0500 Subject: Python - Boost - Cygwin linker error In-Reply-To: References: Message-ID: <20021127124358.GB2100@tishler.net> Dave, On Tue, Nov 26, 2002 at 07:06:37PM -0500, David Abrahams wrote: > Jason Tishler writes: > > On Sat, Nov 23, 2002 at 07:42:28PM -0800, St?phane Vaxelaire wrote: > >> I get an error at link time that appears to occur between Boost code > >> and python lib. Here is the output : > > > > > [snip] > > > > Note that this occurs automatically for Distutils built shared > > extensions. If Boost.Python is built using a different mechanism, > > then -DUSE_DL_IMPORT will have to be specified manually. > > Naw, Boost.Python's own build mechanism (Boost.Build) also adds > -DUSE_DL_IMPORT automatically for Cygwin. Thanks for the clarification -- I was hoping that you would chime in. > This only happened because St?phane decided to build things > ``manually'' in the first place ;-) Ah. I knew that I was going to get myself into "trouble" with the loose wording above -- sorry, for the misinformation. 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 berkowit at silcom.com Fri Nov 29 15:46:09 2002 From: berkowit at silcom.com (Paul Berkowitz) Date: Fri, 29 Nov 2002 12:46:09 -0800 Subject: Can't find user module despite setting PYTHONPATH References: Message-ID: On 11/29/02 12:30 PM, in article BA0D0E7D.2749B%berkowit at silcom.com, "Paul Berkowitz" wrote: > OK. I discovered I'm not supposed to include the .py extension. So I removed > it. It still doesn't work: > >>>> import module1 > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named module1 > > > But it's there, in my ~/Library/Scripts/Python/ directory. There must be > something wrong with my PYTHONPATH? > > setenv PYTHONPATH > .:/usr/lib/python2.2/:/Users/berkowit/Library/Scripts/Python/:/usr/lib/pytho > n2.2/plat-darwin/ # all one line > > What? Yes. If I cd to '/Users/berkowit/Library/Scripts/', then I can import the module without problem. But otherwise PYTHONPATH doesn't seem to find that directory. Does anyone know why not? (Mac OS 10.2.2, using tcsh in Terminal to set PYTHONPATH). -- Paul Berkowitz From aahz at pythoncraft.com Wed Nov 27 13:41:40 2002 From: aahz at pythoncraft.com (Aahz) Date: 27 Nov 2002 13:41:40 -0500 Subject: if : References: Message-ID: In article , wrote: >David Brown wrote: >> >> correctness. This particular "feature" is a huge source of bugs and >> frustration in C programming - mixing up "=" and "==" in conditions is >> probably the biggest single cause of C program bugs. Python, on the other > >Are you speaking from experience, or is this as well-founded as the >hysterical wails about how Python's use of indentation is just wrong? >It certainly isn't remotely near my own experience (which covers a bit >more than two decades, during much of which C was used more than >anything else). Well, I regularly get syntax errors from the Python compiler because I typed "=" instead of "==". Maybe I should proof my own code more thoroughly... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From max at alcyone.com Wed Nov 20 18:19:16 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 20 Nov 2002 15:19:16 -0800 Subject: static variables? References: <3DDAFA97.92B70465@alcyone.com> <3DDB3373.2578CEC0@alcyone.com> Message-ID: <3DDC1874.F72E2B35@alcyone.com> Terry Reedy wrote: > If I understand this, you are proposing that if a default is > 'mutable', then extra magic be added to re-initialized (somehow) on > every call. I am doing no such thing. I am simply stating that there is no a priori reason why it _couldn't_ have been done that way. It wasn't done that way, and I am not suggesting it be changed, just justifying my position that the way it's done right now is an arbitrary choice (simply because it is the easiest to implement). Whether the way it's currently done is a good idea is another question; it seems from the constant confusion that this issue causes, it doesn't seem so to me: It causes confusion for newbies, and I can't think of any circumstances in which you'd actually use that "feature" to your own advantage that wouldn't be better expressed in clearer ways. > > [For those about to mention the "But what if you really want x to be > > None?" objection, one can simply use a private sentinel object.] > > Ugh. None *is* a (public, global) sentinel object. Making it do some > automagical special-case switcheroo behind the scenes in one > particular context would complexify the language. Making people do > something more complex to get an obvious simple result strikes me as a > wrong direction to go. My parenthetical (well, bracketed) comment was simply to offset the obvious complaint, "Well, what if I really did want to pass a None?" If you wanted to call f(None), you'd get the defaulting behavior, which might not what be what you had wanted. It would not have put the onus on the program to use the private sentinel object in any way. (It was a minor point anyway; and since None isn't mutable, it was really an irrelevant comment anyway.) -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Most men do not mature, they simply grow taller. \__/ Leo Rosten Alcyone Systems' CatCam / http://www.catcam.com/ What do your pets do all day while you're at work? Find out. From herrn at gmx.net Wed Nov 27 17:37:05 2002 From: herrn at gmx.net (Marco Herrn) Date: 27 Nov 2002 22:37:05 GMT Subject: redirecting stdout Message-ID: Hi, I am redirecting my output to a file via: sys.stderr= open('out.txt','a', 0) All exceptions are handled like this: try: ... except Exception, detail: print detail That works. But I am missing the line numbers. How can I get to the line numbers in exceptions? And is there a good documentation of exception handling in python availabe? I just found very short ones. Thanks in advance Marco -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From imbosol at vt.edu Wed Nov 13 15:33:18 2002 From: imbosol at vt.edu (Carl Banks) Date: Wed, 13 Nov 2002 15:33:18 -0500 Subject: simple metaclass question References: <3DD08DC1.A4CFE557@irl.cri.nz> <6NrA9.4123$744.137981@news1.tin.it> <7h3k7jhz3ti.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson wrote: > Carl Banks writes: > >> Thanks. I was thinking at the C level, where objects that serve as >> types have to have a certain fixed structure. To create a metatype in >> Python (not C), it would have to be an instance of a class that >> subtypes type, right? > > I don't know whether type(type(ob)) is always a subtype of type -- I > think so -- but certainly the thing you write > > class Bob: > __metaclass__ = ...<---- here > > doesn't have to be a subtype of type. Of course not. It might be useful and/or in bad style to do this: def makedict(name,bases,dict): return dict class whatever: __metaclass__ = makedict a = 1 b = 2 ... just to create a large, built-in dictionary a little bit easier than with the dict constructor. > It can be handy to have a > function here, for instance -- but if this function doesn't return a > subtype of type, inheriting from the resulting class gets totally > bewildering (or at least, I managed to totally bewilder myself along > these lines). Ok, I think a lot the difficulty is linguistic. We're used to taking shortcuts like saying "a is an integer," but when talking about metaclasses, it leads to utter confusion. We need to be explicit: "a is an instance of integer." (Even that is a shortcut for "a is bound to an instance of integer," but it probably won't cause confusion for this discussion.) Now, obviously, the callable object given by __metaclass__ can return any sort of object it wants, but only certain objects can serve as a class in the normal way we think of them. If I do this: class A(base): __metaclass__ = metafunction a = 1 b = 2 c = A(*args) what's not clear to me is, what conditions does the object returned by metafunction (which becomes bound to A) have to satisfy for c's type to be A? It seems to me that A would have to be either an instance of type, or an instance of a subclass of type (and be callable, and return instances of itself when called). Now, let's assume, as is typical in metaclass programming, that metafunction is, in fact, a class object. Class objects, when called, (are supposed to) return instances of themselves. Therefore, if the above statement is true, then the metaclass would have to be a subtype of type, In other words, metaclasses written in Python have to subclass type. But, I don't think that's true of metaclasses written in C. Since C has control over the low-level structure of an object, C types can create instances that have the same low-level structure as type objects, without actually having to include "type" in it's bases. But this opens up the possibility that a Python class could subclass *that* object, and it needn't subclass type. So I think the final statement becomes: "Metaclasses written in Python have to be a subclass of another metatype." Ok, I think I'm clear with that, and it seems a little obvious now that I've typed it (no pun intended :). After taking a few hours to fit it into my head every day, it might even become natural. -- CARL BANKS From dvass at felis.uni-freiburg.de Thu Nov 21 20:06:39 2002 From: dvass at felis.uni-freiburg.de (Joerg Woelke) Date: Fri, 22 Nov 2002 02:06:39 +0100 Subject: [Boost.Python] Printed documentation available? References: <6152d0a0.0211211547.2afdb8df@posting.google.com> Message-ID: <3DDD831F.91EFE7E0@felis.uni-freiburg.de> Hi! Tom Hanks wrote: Ahm... > Unfortunately for me the available documentation is not > printer-friendly. Instead it is browser-friendly, organised > into an html tree 3-4 pages deep. wget is your tool. "http://www.gnu.org/software/wget/wget.html" > Tom Hanks. HTH, J"o! -- $ make LOVE $ Don't know how to make LOVE. Stop. $ From Janssen at rz.uni-frankfurt.de Sat Nov 9 01:32:40 2002 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Sat, 09 Nov 2002 07:32:40 +0100 Subject: field names from MySQLdb References: <653cf871.0211081429.2b8c69c8@posting.google.com> Message-ID: <3dccac08@nntp.server.uni-frankfurt.de> les wrote: > Hi, > how do i get field names for a table in MySQLdb? > thanks > (i looked into pydoc MySQLdb but did not find it there) you need any mysql-docs: show fields from ; From pan-newsreader at thomas-guettler.de Wed Nov 20 11:08:46 2002 From: pan-newsreader at thomas-guettler.de (Thomas Guettler) Date: Wed, 20 Nov 2002 17:08:46 +0100 Subject: Mirror of Python Cookbook Message-ID: Hi! Is there a mirror of the python cookbook? It has a lot of great recipes, I don't want to miss them if the sever is down. thomas -- Thomas Guettler http://www.thomas-guettler.de From tjreedy at udel.edu Wed Nov 13 13:56:07 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 13 Nov 2002 13:56:07 -0500 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCF83B2.2030008@web.de> <3DD0D765.3030907@web.de> <3DD16CAF.41214BBA@alcyone.com> <3dd1ffd7$0$63936$edfadb0f@dread15.news.tele.dk> Message-ID: "Jens Axel S?gaard" wrote in message news:3dd1ffd7$0$63936$edfadb0f at dread15.news.tele.dk... > Beating > > http://www.htdp.org Thanks. I'll learn a few things from this. However, apropos to the thread topic, I am somewhat flabbergasted that anyone could think that Scheme's (sort (cons 1297.04 (cons 20000.00 (cons -505.25 empty)))) ;; expected value: (cons 20000.00 (cons 1297.04 (cons -505.25 empty))) (section 12.2) is a sensible list notation to inflict on anyone, let alone newcomers, in preference to anything like Python's [1297.04, 2000.00, -505.25], etc. I understand that there is a pedagogical point in using such notation to explain list construction and destruction, but the above comes well beyond that part ot the book. > and > > http://www-mitpress.mit.edu/sicp/ I read the hard copy a few years ago due to recommendations of Python posters. Also good. > are hard though. Terry J. Reedy From mhammond at skippinet.com.au Mon Nov 11 05:30:23 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 11 Nov 2002 10:30:23 GMT Subject: NEWBIE: Extending Python with C In-Reply-To: References: <3dcc7e2c.3568851@news.earthlink.net> <3dcd6aee.7793165@news.earthlink.net> <3dceb920.8008485@news.earthlink.net> Message-ID: <3FLz9.13073$eX.32901@news-server.bigpond.net.au> Dennis Lee Bieber wrote: > Need speed, and some access to a posix thread system... Any Python portable thread system. > IMO, I'm going to present some bad news... > > From what you've said, I'd almost think you were coming at it from the > wrong direction. > > /I/ think what you'll end up with is a C/C++ application with an > embedded Python interpreter for your scripting, and maybe for part of > the graphical part of the user-interface... But the rest of the > application strongly sounds like it needs to be ported to a different > OS (drop the MS-DOS mode for Windows or Linux) and cleaned up -- > remaining in C or rewritten in C++. I don't agree. I think the approach he outlined is correct. I believe a common mistake is to think "app with embedded Python", when what you really mean, and ended up with, is "python with embedded app". To the OP: Creating a Python extension is quite trivial. The Python source tree has at least one example extension module in PC\example_nt, and others should be simple to find - indeed mine and Andy's book has such an example. So I'm really not sure what the question boils down to ;) Mark. From SBrunning at trisystems.co.uk Thu Nov 7 11:48:17 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Thu, 7 Nov 2002 16:48:17 -0000 Subject: IBM MQ Series Message-ID: <31575A892FF6D1118F5800600846864DCBDAB8@intrepid> > From: Daniel Klein [SMTP:danielk at aracnet.com] > Is there a Python interface for this, such that I can connect to a MQ > server and send/recv messages? Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From Psyco at mailme.dk Mon Nov 11 15:34:38 2002 From: Psyco at mailme.dk (Mads Sejersen) Date: 11 Nov 2002 20:34:38 GMT Subject: Can python find fibonacci series in a single line of code? References: Message-ID: <3dd0145e$0$75431$edfadb0f@dread15.news.tele.dk> > My Perl-addicted friend shows me that he can find fibanicci series in > a single line of code. > > perl -le '$b=1; print $a+=$b while print $b+=$a' > > can python do something like this? Goto http://www.python.org/cgi-bin/faqw.py and search for lambda From stuart at bmsi.com Fri Nov 8 01:13:03 2002 From: stuart at bmsi.com (Stuart D. Gathman) Date: Fri, 08 Nov 2002 06:13:03 GMT Subject: Dynamic loading of modules in AIX References: Message-ID: On Thu, 07 Nov 2002 22:04:23 -0500, Neal Norwitz wrote: > I'm trying to get python to load dynamic modules. But after loading the > module, when code inside the module calls back into the main program, it > seg faults. More details below. You need to use ld_so_aix, which imports the symbols for the main program into the loadable modules. Otherwise, those symbols are unresolved giving a coredump when called. You can find my RPM spec file for python-2.2 at http://www.bmsi.com/aix/python-2.2.spec (along with binary RPMs and a tar of rpm itself. RPM needs LANG=C on some AIX versions.) Even if you don't use RPM on AIX, the spec file will tell you how to build python. Look at the %build section. -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From loewis at informatik.hu-berlin.de Tue Nov 5 07:24:45 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 05 Nov 2002 13:24:45 +0100 Subject: Regex: Matching characters, but not digits References: Message-ID: Thomas Guettler writes: > \w matches characters and digits. But, > how can I match only characters? > > This should work for unicode, too This is currently not supported, directly. SRE should be able to support Posix regex categories, such as [:alpha:], and Unicode categories, such as [:Ll:], but at the moment, it doesn't. Patches in this area are welcome. Your best bet is to generate a character class yourself. For Unicode, you can use alphaclass = [u"["] for i in range(32, sys.maxunicode): c = unichr(i) if c.isalpha(): alphaclass.append(c) alphaclass.append(u"]") alphaclass = "".join(alphaclass) Compiling this particular regular expression will be expensive, but matching it won't: it is compiled into a bitmap internally, with a constant-time test. Regards, Martin From zopestoller at thomas-guettler.de Tue Nov 5 07:06:23 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Tue, 05 Nov 2002 13:06:23 +0100 Subject: Regex: Matching characters, but not digits Message-ID: Hi! \w matches characters and digits. But, how can I match only characters? This should work for unicode, too thomas From steve410 at blaze.cs.jhu.edu Tue Nov 26 14:04:57 2002 From: steve410 at blaze.cs.jhu.edu (Steve Rifkin) Date: Tue, 26 Nov 2002 14:04:57 -0500 Subject: Please help! Getting python errors running mailman after an apache install. Message-ID: <3DE3C5D8.ECE85757@blaze.cs.jhu.edu> Hi! We've recently upgraded Apache on our webserver to version 1.3.27. Since then, our web interface to mailman (2.08) has stopped running. The current error we're seeing is python related (we're running python 2.2.2 -- we rebuilt python again just to make sure there wasn't a problem with python). The errors from mailman are below. The main error is: admin(7162): ImportError: ld.so.1: /usr/local/bin/python: fatal: /usr/local/lib/python2.2/lib-dynload/_socket.so: bad ELF flags value: 256 And I have no idea what that python-related error is. Note that things worked before the apache upgrade, but now mailman is complaining about python. If anyone has any info regarding this error (or the errors below), can you please e-mail me directly in addition to your post on this newsgroup? Thanks so much in advance! Steve steve410 at cs.jhu.edu Mailman 2.08's python 2.2.2 errors (when accessing mailman web interfaces): ==================================== admin(7153): DOCUMENT_ROOT: /users/httpd/htdocs Nov 26 11:19:04 2002 admin(7162): @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ admin(7162): [----- Mailman Version: 2.0.8 -----] admin(7162): [----- Traceback ------] admin(7162): Traceback (most recent call last): admin(7162): File "/home/mailman/scripts/driver", line 80, in run_main admin(7162): import Mailman.pythonlib.cgi admin(7162): File "../Mailman/pythonlib/cgi.py", line 31, in ? admin(7162): import urllib admin(7162): File "/usr/local/lib/python2.2/urllib.py", line 26, in ? admin(7162): import socket admin(7162): File "/usr/local/lib/python2.2/socket.py", line 41, in ? admin(7162): from _socket import * admin(7162): ImportError: ld.so.1: /usr/local/bin/python: fatal: /usr/local/lib/python2.2/lib-dynload/_socket.so: bad ELF flags value: 256 admin(7162): [----- Python Information -----] admin(7162): sys.version = 2.2.2 (#1, Nov 25 2002, 15:28:57) [GCC 2.95.2 19991024 (release)] admin(7162): sys.executable = /usr/local/bin/python admin(7162): sys.prefix = /usr/local admin(7162): sys.exec_prefix= /usr/local admin(7162): sys.path = /usr/local admin(7162): sys.platform = sunos5 admin(7162): [----- Environment Variables -----] admin(7162): HTTP_PRAGMA: no-cache admin(7162): PYTHONPATH: /home/mailman admin(7162): SERVER_SOFTWARE: Apache/1.3.27 (Unix) PHP/4.2.3 mod_perl/1.27 admin(7162): SCRIPT_FILENAME: /home/mailman/cgi-bin/admin admin(7162): SERVER_ADMIN: webmaster at cs.jhu.edu admin(7162): SCRIPT_NAME: /mailman/admin admin(7162): SCRIPT_URI: http://www.cs.jhu.edu/mailman/admin admin(7162): SERVER_SIGNATURE:
Apache/1.3.27 Server at www.cs.jhu.edu Port 80
admin(7162): REQUEST_METHOD: GET admin(7162): HTTP_HOST: www.cs.jhu.edu admin(7162): SCRIPT_URL: /mailman/admin admin(7162): SERVER_PROTOCOL: HTTP/1.0 admin(7162): QUERY_STRING: admin(7162): HTTP_CONNECTION: Keep-Alive admin(7162): REQUEST_URI: /mailman/admin admin(7162): HTTP_ACCEPT: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */* admin(7162): HTTP_ACCEPT_CHARSET: iso-8859-1,*,utf-8 admin(7162): HTTP_USER_AGENT: Mozilla/4.7 [en] (X11; U; SunOS 5.6 sun4u) admin(7162): TZ: US/Eastern admin(7162): SERVER_NAME: www.cs.jhu.edu admin(7162): REMOTE_ADDR: 128.220.13.39 admin(7162): REMOTE_PORT: 35634 admin(7162): HTTP_ACCEPT_LANGUAGE: en admin(7162): SERVER_PORT: 80 admin(7162): GATEWAY_INTERFACE: CGI/1.1 admin(7162): HTTP_ACCEPT_ENCODING: gzip admin(7162): SERVER_ADDR: 128.220.13.101 admin(7162): DOCUMENT_ROOT: /users/httpd/htdocs -- Steve steve410 at cs.jhu.edu From tom at bigpier.com Wed Nov 13 01:09:05 2002 From: tom at bigpier.com (Tom Nunamaker) Date: Wed, 13 Nov 2002 00:09:05 -0600 Subject: Problems having Python read from SQL server Message-ID: I'm a Python newbie. I need to connect from a Win2K Python script to a MS SQL server database on another computer. I've tried several methods. The DSN is setup as a system DSN and it has the UID/PWD in the DSN setup. Other programs can connect fine with the DSN. The common error I'm getting with Python scripts is: "[Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user '(null)'. Reason: Not associated with a trusted SQL Server connection." How can I create a trusted connection? The SQL server is on a shared ISP's box and I don't have the sa login for it. Any other suggestions to connect python to this DB? Thanks Tom From jjl at pobox.com Tue Nov 19 14:35:05 2002 From: jjl at pobox.com (John J Lee) Date: 19 Nov 2002 11:35:05 -0800 Subject: Generic lazily seekable file-like object wrapper? Message-ID: Does anybody have a (free) file-like object wrapper that adds a seek method and allows lazily read()ing from the wrapped file-like object? ie.: fh = urlopen("http://foo.bar.com/") # any old file-like object assert hasattr(fh, "read") or hasattr(fh, "readline") assert not hasattr(fh, "seek") sfh = LazilySeekableFile(fh) # doesn't call fh.read do_something(sfh.read(100)) # calls fh.read sfh.seek(0) # doesn't call fh.seek print sfh.read(100) # doesn't call fh.read or fh.readline John From rmunn at pobox.com Fri Nov 8 20:19:00 2002 From: rmunn at pobox.com (Robin Munn) Date: Sat, 09 Nov 2002 01:19:00 GMT Subject: Newbie-list-problem: how to supress constraining 2 lists - a=b ? References: <813cfe33.0211080235.5d4b8c9e@posting.google.com> Message-ID: On Fri, 08 Nov 2002 at 10:35 GMT, HugOnline wrote: > Hello, > > I'm a Python - newbie and I can not solve the following problem: > >>>>a=[8,7,6,5,4] # set this list to a >>>>b=a # I' want to have two same lists: a and b >>>>b.sort() # b should be sorted >>>>print b # it's ok > [4,5,6,7,8] >>>>print a > [4,5,6,7,8] # but a is sorted, too !!! > > How can I suppress the constraining of a and b? I want to have in the > result two list - a unsorted and b sorted. Is there a switch to supress > it? You're confusing the name of the thing with the thing itself. In Python, names of objects are separate from the actual objects. With your first line, you created a list of five integers and made the name 'a' point to that list. With your second line, you made the name 'b' point to the same object as the name 'a'. If you want to copy the list, use something like slice notation: b = a[:] This creates a copy of the list pointed to by 'a' and makes 'b' point to that copy. That will do what you were expecting. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From mfranklin1 at gatwick.westerngeco.slb.com Tue Nov 12 10:17:48 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 12 Nov 2002 15:17:48 +0000 Subject: [Fwd: Re: Tk extension for python] Message-ID: <1037114269.18235.0.camel@m-franklin> Sorry Martin!!! new mail client! -----Forwarded Message----- > From: Martin Franklin > To: Martin v. Loewis > Subject: Re: Tk extension for python > Date: 12 Nov 2002 13:54:13 +0000 > > On Tue, 2002-11-12 at 13:38, Martin v. Loewis wrote: > > 1327055037 Anatol Sukhomlyn writes: > > > > > How i can add Tktable extension to python? > > > I think it is very good package into Tcl/Tk > > > > If you tell me how you add it to Tcl, I will tell you how to add it to > > Tkinter. > > > > Once again google is you friend.... search for TkTable python Tix > and you should end up with :- > > > http://tix.sourceforge.net/Tixapps/src/Python/ > > > (I think this is the second time this month) > > > From kennethg at pd.jaring.my Mon Nov 11 07:24:14 2002 From: kennethg at pd.jaring.my (Kenneth Gomez) Date: Mon, 11 Nov 2002 12:24:14 GMT Subject: How to create and interactive, distributable program? Message-ID: <3dcfa0e3.921157@news.jaring.my> Hello all, In my course, I am asked to develop a basic finite element analysis program. It is basically a program for engineers to evaluate the stresses and strains in any given structure, e.g. beams, cars, ships and so forth. The program would need to have a GUI. The main characteristics of any commercial FEA package is that it has to be mouse drive, i.e. a user clicks the rectangle button from a widget and then proceeds to click 4 points on the drawing window, and the program then draws a rectangle using those 4 points. After which, the program would have to calculate the area of the rectangle and then proceed to divide the rectangle into many small rectangles, which length would be given by the user. In FEA, this would be known as meshing. To do all of this, my questions are , can Python handle the mathematics, e.g. does Python have a subroutine to inverse a matrix, or find the modulus of a number,....? Or, is it like C, where I have to write the subroutine myself? Second, will I be able to create the GUI explained above within 3 months? Third, can I make the GUI into an executable file so that I can run it off the laptop/workstation that will be used for the presentation? Thanking you in advance for your advise. Cheers, Kenneth Gomez. From mhuening at zedat.fu-berlin.de Tue Nov 5 15:13:57 2002 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 5 Nov 2002 20:13:57 GMT Subject: SSH/SCP References: <2259b0e2.0211050833.7367bf5f@posting.google.com> Message-ID: mis6 at pitt.edu (Michele Simionato) wrote in news:2259b0e2.0211050833.7367bf5f at posting.google.com: > the simplest way to do is to download > (for free) putty and use something like > Okay, I tried your solution (using PSCP). Works fine. I think I'll stick to it, because there seems to be no usable Python module which would do the job without external support. Thanks, Matthias From wks000 at t-online.de Sun Nov 10 09:11:27 2002 From: wks000 at t-online.de (Wolfgang Strobl) Date: Sun, 10 Nov 2002 15:11:27 +0100 Subject: Determining Presence Of GUI Support References: <42aiqa.jp82.ln@boundary.tundraware.com> Message-ID: bokr at oz.net (Bengt Richter): >On 09 Nov 2002 17:40:11 GMT, Tim Daneliuk wrote: >[...] >> >>Years ago, in the transition from MS-DOS to Windows, there used to be >>a way to lay a DOS binary into the Windows executable file. That way, >I suspect there still is, normally used for the code that tells you >"This program cannot be run in DOS mode." ;-) Correct, there still is. Adding /stub: as a linker option uses instead of the buildin stub. -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From 2002 at weholt.org Mon Nov 4 07:46:09 2002 From: 2002 at weholt.org (Thomas Weholt) Date: Mon, 04 Nov 2002 12:46:09 GMT Subject: Extending distutils ?? References: Message-ID: I think I got an idea on how to solve some of the things I mentioned. I'll give it a shot and post an announcement if the effort produces any useful results. Thomas "Martin v. Loewis" wrote in message news:m3d6pm456m.fsf at mira.informatik.hu-berlin.de... > "Thomas Weholt" <2002 at weholt.org> writes: > > > Distutils is great, but adding a few features would make it almost perfect. > > Since we allready got a documentation package in the standard distro why > > can't Distutils generate documentation using pydoc in the process of > > generating a package for distribution? > > All distutils questions have a simple answer: Nobody contributes anything. > You can make a difference (actually, a context diff would do :-) > > Regards, > Martin From eppstein at ics.uci.edu Wed Nov 13 17:16:36 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 13 Nov 2002 14:16:36 -0800 Subject: My (late) beef with Simple Generator syntax (PEP 255) In-Reply-To: <8087437.1037225519862.JavaMail.camhorn@mac.com> References: <8087437.1037225519862.JavaMail.camhorn@mac.com> Message-ID: <2147483647.1037196996@dhcp31-169.ics.uci.edu> On 11/13/02 2:11 PM -0800 Cameron Horn wrote: >> What I wonder is, why does it need to be a generator? What's wrong with >> def foo(): return ( ) >> ? > > You're right if it's a one-time thing. However, if I've got a > scaffolding like this, then it matters. > > def process_generator(function): > for x in function(): > print x How does the function foo() I defined above fail to work in this scaffolding? -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From lac at strakt.com Fri Nov 29 17:03:06 2002 From: lac at strakt.com (Laura Creighton) Date: Fri, 29 Nov 2002 23:03:06 +0100 Subject: Anybody using vtk and Python out there? In-Reply-To: Message from stojek@part-gmbh.de (Marcus Stojek) of "Fri, 29 Nov 2002 18:36:22 GMT." <3de7b230.19875609@news.easynews.net> References: <3de7b230.19875609@news.easynews.net> Message-ID: <200211292203.gATM36en013279@ratthing-b246.strakt.com> > Hi, > > I have to visualize huge amount of data and I would like to use Python > and vtk. So far I have seen only two methods to get data into the vtk > structure. > 1. Using a vtkReader (e.g. vtkUnstructuredGridReader) > > 2 Generating Cell one by one:. > P=vtkPoints() > P.InsertPoint(..) > C=vtkCellArray() > C.InsertNextCell.... and so on > > The first method is not flexible enough and the second is very slow. > Does anybody know another way? > Thanks > marcus > -- MayaVi http://mayavi.sourceforge.net/ uses Python to script VTK. The mailing list mayavi-users at lists.sf.net may also be of interest. Laura Creighton From mertz at gnosis.cx Tue Nov 19 20:44:21 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Tue, 19 Nov 2002 20:44:21 -0500 Subject: yield: implementation details and other technica References: Message-ID: <1ju29kKkXQcR092yn@gnosis.cx> I have a technical problem for which grabbing the context of a generator and *throwing* it up the stack would be preferable to the current implementation... What I want is a giant coroutine between a bunch of objects and a master scheduler that I control....For one, certain high level methods are called that imply a yield in a higher context. "Raymond Hettinger" wrote previously: |Joe, try looking at: |http://gnosis.cx/publish/programming/charming_python_b7.txt |The article shows how to use generators with a master scheduler. His |example shows how to implement co-routines, but it is general purpose. |Used this way, the scheduler has the ability to resume any process, |in effect deciding the current continuation. The article Raymond suggest is indeed probably the most on topic. It also follows on a related one. The HTML versions of both are at: http://gnosis.cx/publish/programming/charming_python_b5.html http://gnosis.cx/publish/programming/charming_python_b7.html Moreover, for some more fleshed out examples of scheduling generators, take a look at the SimPy project. The authors of that use a bit of the framework I suggested in those articles, but in a much more fleshed out form. The also handle some data passing in a nice way. But it's not hard to yield some "cargo" along with a state target, in any case. One thing I regret in my first article on this is that I used string names for targets rather than the callable objects themselves. I think the latter article fixed that, and I believe SimPy does to. Generators are even more cool that you might think at first brush. Yours, David... -- mertz@ _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i gnosis _/_/ Postmodern Enterprises _/_/ s r .cx _/_/ MAKERS OF CHAOS.... _/_/ i u _/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/ g s From martin at v.loewis.de Mon Nov 4 12:05:58 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 04 Nov 2002 18:05:58 +0100 Subject: file iterators and codecs, a bug? References: Message-ID: Greg Aumann writes: > Is this definitely a bug, or is it an undocumented > 'feature' of the codecs module? Sounds like a bug to me; please submit a report to SF. Better yet, create a patch (which shouldn't be too difficult to do). Regards, Martin From shadowlord13_1 at yahoo.com Mon Nov 18 17:59:04 2002 From: shadowlord13_1 at yahoo.com (Richard Dillingham) Date: Mon, 18 Nov 2002 22:59:04 GMT Subject: Hmm... An idea: if a,b==c,d: References: Message-ID: It doesn't have ()s, so it ain't two tuples. Easy enough, da? "Carl Banks" wrote in message news:arbqp2$rkb$1 at solaris.cc.vt.edu... > Richard Dillingham wrote: > > Kind of like we have multiple assignments in a line (oldx,oldy=x,y), what do > > you think of the ability to have multiple tests in an if statement with only > > one == or >=. > > > > This would mean that lines like the following: > > if posx>=coords[0] and posy>=coords[1] and posx<=coords[2] and > > posy<=coords[3]: > > > > Could be rewritten like so: > > if posx,posy>=coords[0],coords[1] and posx,posy<=coords[2],coords[3] > > How would you disambiguate that from a comparison of two tuples? > > > -- > CARL BANKS From s802645999 at yahoo.com Thu Nov 28 04:41:52 2002 From: s802645999 at yahoo.com (ghostdog) Date: Thu, 28 Nov 2002 01:41:52 -0800 (PST) Subject: Sybase modules In-Reply-To: <20021128053600.23289.20158.Mailman@mail.python.org> Message-ID: <20021128094152.7367.qmail@web14507.mail.yahoo.com> hi i wanted to install Sybase database module on windows ..which C compiler should i use?? thanks --------------------------------- Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now -------------- next part -------------- An HTML attachment was scrubbed... URL: From jepler at unpythonic.net Tue Nov 12 14:33:49 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 12 Nov 2002 13:33:49 -0600 Subject: Optimisation problem In-Reply-To: References: Message-ID: <20021112193348.GB1756@unpythonic.net> On Tue, Nov 12, 2002 at 12:43:28PM -0600, sismex01 at hebmex.com wrote: > In this case which is quite simple, yes, it's the > same result; but others might enlighten us on other > cases where the "obvious" result isn't the one we'd > get. > > Any suspects, anyone? a, b = b, a ? This is bytecompiled to 6 LOAD_NAME 0 (b) 9 LOAD_NAME 1 (a) 12 BUILD_TUPLE 2 15 UNPACK_SEQUENCE 2 18 STORE_NAME 1 (a) 21 STORE_NAME 0 (b) A creative individual could possibly write a peephole optimizer to get rid of BUILD_TUPLE/UNPACK_SEQUENCE, but it means either reversing the order of calculation or the order of assignment as well. This approach can't always work, given statements like a, b = d or (b, a) 6 LOAD_NAME 0 (d) 9 JUMP_IF_TRUE 10 (to 22) 12 POP_TOP 13 LOAD_NAME 1 (b) 16 LOAD_NAME 2 (a) 19 BUILD_TUPLE 2 >> 22 UNPACK_SEQUENCE 2 25 STORE_NAME 2 (a) 28 STORE_NAME 1 (b) Jeff From see_reply_address at something.invalid Sun Nov 17 21:26:34 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Mon, 18 Nov 2002 15:26:34 +1300 Subject: Pythoncal, anyone? (My (late) beef with Simple Generator syntax (PEP 255)) References: Message-ID: <3DD84FDA.3010708@something.invalid> I have an idea: Suppose there were a "don't" statement that could be put in front of another statement to, effectively, comment it out, e.g. def foo(): # This function does nothing don't print "Hello" Then an empty generator could be written def g(): don't yield None Now, since this isn't going to do anything, it should be permissible to omit any expressions that would otherwise be required in a statement covered by a "don't", leaving just def g(): don't yield -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bdesth at nospam.free.fr Mon Nov 18 21:32:36 2002 From: bdesth at nospam.free.fr (laotseu) Date: Mon, 18 Nov 2002 21:32:36 -0500 Subject: Create DLL in Python ? References: <1b318b70.0211111607.74ace07@posting.google.com> Message-ID: <3DD9A2C4.2070203@nospam.free.fr> Chris Tavares wrote: > "Georges Bernier" wrote in message > news:1b318b70.0211111607.74ace07 at posting.google.com... > >>Hello, >> >>We have a legacy application at work written in Visual C which makes >>use of a DLL for specific communication functions. Now I have to >>replace this DLL (whose API is well documented) with an enhanced >>version which will make use of TCP/IP instead of older protocols >>without changing the original C application (or at least changing the >>minimum possible). >> >>Naturally I was thinking of using Python (as it has great network >>libraries and would simplify the development) but after much googling >>haven't found a clear answer on how to generate standalone DLLs from >>Python (i.e. DLLs which are not Python extensions). >> >>So does anybody have experience in such a thing, is it a bad idea (as >>I'm starting to think is is) and would it better be done in C/C++ ? >>I would appreciate comments from the Python community on this. >> >>Thanks ! >> >>Georges Bernier >> > > > You can't avoid coding in C completely, but you can cut down on the amount > of work tremendously. > > What you need to do is write a C DLL. The DLL will implement your API. > Inside the implementation, use the Python API to call from the DLL into your > python code. Essentially embed Python into your DLL. The original app will > just call the DLL and not know that python's involved at all, and you can > write your actual logic in Python. > > -Chris > > > Well.. this might be a solution, but loading a DLL to launch a virtual machine to execute some instructions might also be a bit heavy. As anyone tested such a solution around here ? and with what result ? Laotseu From tjreedy at udel.edu Sun Nov 17 11:57:25 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 17 Nov 2002 11:57:25 -0500 Subject: Possibly a stupid question regarding Python Classes References: <3dd7c140$1_6@nopics.sjc> Message-ID: "Adonis" wrote in message news:3dd7c140$1_6 at nopics.sjc... > Is this even possible: > > class Foo: > def Bar(self): > print 'Foo' > > class Fib(Foo): > def Bar(self): > # do the original Foo.Bar() go ahead and do it... Foo.Bar(self) > # NOTE: w/o needing to instantiate Foo the instance of Fib effectively *is* an instance of Foo > # then do: > print 'Bar' Terry J. Reedy From bokr at oz.net Fri Nov 1 18:59:39 2002 From: bokr at oz.net (Bengt Richter) Date: 1 Nov 2002 23:59:39 GMT Subject: Regex recursion error example. References: <88caaeda.0211010713.5d3b1e05@posting.google.com> Message-ID: On 1 Nov 2002 07:13:20 -0800, yin_12180 at yahoo.com (Yin) wrote: >After tinkering with this issue for a day or so, I've decided to use >xmllib to solve the problem. But for future reference, I've attached >the piece of text that is failing and the two approaches that I've >tried to make the match. > >Of course there are other approaches to doing this parse, but I am >interested in understanding the regex approach I am trying and its >limitations. > >If there are no solutions using regex, I would be interested in seeing >a reference to articles or books that discuss overcoming particularly >long string matches. > >Approach 1: >pattern=re.compile('<PubMedArticle>(.*?)</PubMedArticle>', >re.DOTALL) >self.citationlist = re.findall(pattern, allinput) > >Approach 2: >comppat=re.compile(r'<PubMedArticle>((?:(?!<PubMedArticle>).)*)</PubMedArticle>', >re.DOTALL) >self.citationlist = re.findall(pattern, allinput) > >There are three matching to make in this body of text. The above code >has been failing on the second of the third. This problem has only >been occuring on linux python and Windows python (the stack in Windows >is just larger enough to accomadate the matches. >Text to match: > >http://160.129.203.97/1998_xmltest.html > Here's a little different approach you could try: >>> import re >>> import urllib >>> allinput = urllib.urlopen('http://160.129.203.97/1998_xmltest.html').read() >>> len(allinput) 29714 >>> pattern=re.compile('(</?PubMedArticle>)',re.DOTALL) >>> allsplit = pattern.split(allinput) In the following, allsplit[i] is the (.*?) text you wanted, I think, but it's a bit long, so I just printed the first and last 80 chars and bracketed with <...> ([w]hat [y]ou [w]ant ;-): >>> for i in range(2,len(allsplit),4): print '%s\n<...>\n%s\n' % ( ... allsplit[i][:80],allsplit[i][-80:]) ... <MedlineCitation Status="Completed"> <MedlineID>99071918& <...> quot;>99071918</ArticleId> </ArticleIdList> </PubmedData> <MedlineCitation Status="Completed"> <MedlineID>99071917& <...> quot;>99071917</ArticleId> </ArticleIdList> </PubmedData> <MedlineCitation Status="Completed"> <MedlineID>99071916& <...> quot;>99071916</ArticleId> </ArticleIdList> </PubmedData> Of course, this depends on there being no missing tags for .. and no alternative forms of those tags. Regards, Bengt Richter From teaandbikkie at aol.com Fri Nov 8 18:49:33 2002 From: teaandbikkie at aol.com (TeaAndBikkie) Date: 08 Nov 2002 23:49:33 GMT Subject: socket.py and 2.2.1 References: Message-ID: <20021108184933.23310.00000020@mb-mt.aol.com> >From: susan at provis.com (Susan Williams) > >Hello, > >We're finally getting around to upgrading from 1.5.2 to 2.2.1... ;-) >and I'm having a problem (Solaris 5.7). > >I've got the simple (no SSL) socketmodule in my python, and >when I try to import the socket module I get the following error: > >>python >Python 2.2.1 (#6, May 24 2002, 16:38:14) [C] on sunos5 >Type "help", "copyright", "credits" or "license" for more information. >>>> import socket >Traceback (most recent call last): > File "", line 1, in ? > File "/usr/local/lib/python2.2/socket.py", line 47, in ? > __all__.extend(os._get_exports_list(_socket)) >AttributeError: 'module' object has no attribute '_get_exports_list' >>>> > >Yup, the source line is there all right, and socket.py and the os >module seem to be on different planets. Anyone got a clue what >is hosed up here? Perhaps you have an old version of socket.pyc in your Lib directory? Try deleting (or renaming) socket.pyc and see if the error disappears. Kind regards, Misha From newt_e at blueyonder.co.uk Mon Nov 4 18:01:05 2002 From: newt_e at blueyonder.co.uk (Newt) Date: Mon, 04 Nov 2002 23:01:05 GMT Subject: Str and instance concatanation error Message-ID: I keep getting the following error when trying to write to a file. Traceback (most recent call last): File "C:\Python22\lib\lib-tk\Tkinter.py", line 1292, in __call__ return apply(self.func, args) File "D:\py_stuff\curry.py", line 14, in __call__ return self.fun(*(self.pending + args), **kw) File "D:\py_stuff\chaz.py", line 144, in savefile gv.save_char() File "D:\py_stuff\globals.py", line 96, in save_char file.write('' + self.creator + '') TypeError: cannot concatenate 'str' and 'instance' objects This occurs in a class module (called globals.py). This is used to hold all my global variables, and also has a method (called save_char) to write these to a file. self.creator is initialised in the __init__ as "". Should I create it as a stringVar instead, or am I doing something incredibly stupid. TIA Newt From SBrunning at trisystems.co.uk Mon Nov 4 10:55:08 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Mon, 4 Nov 2002 15:55:08 -0000 Subject: problem's with strings Message-ID: <31575A892FF6D1118F5800600846864DCBDA9C@intrepid> > From: Richard Mertens [SMTP:richard.mertens at wolfi.org] > I'd like to convert a text-file von unix to windows and vice versa > > Do you know a solution for this > > > When the python script is reading the text-file i have always the Nextline > - > Character on the end. How do you I remove it? crlf.py in the tools/scripts directory of your Python installation converts from Windows to Unix. You should be able to take it from there. ;-) Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From rnd at onego.ru Sat Nov 2 12:26:22 2002 From: rnd at onego.ru (Roman Suzi) Date: Sat, 2 Nov 2002 20:26:22 +0300 (MSK) Subject: Python rulez In-Reply-To: <3dc1b6c5$1@news.sentex.net> Message-ID: On Thu, 31 Oct 2002, Peter Hansen wrote: >Alessandro Bottoni wrote: >> Alle 08:50, venerd? 25 ottobre 2002, Roman Suzi ha scritto: >> >>>Well... this is kinda test message (i'm checking if >>>Python maillist is reaching my mailbox). >> >> >> Welcome to the Python community! > >Heh heh... Roman's been here rather a while already. He >should be saying that to *you*. :-) Well, I just wanted to know why my traffic dropped so drastically ;-) It seems, that I am among the rare one using mail-list rather than newsgroup. Anyway, thanks for welcoming me! >-Peter Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by Linux RedHat 7.3 From ajw126NO at SPAMyork.ac.uk Sun Nov 3 12:33:27 2002 From: ajw126NO at SPAMyork.ac.uk (Andrew Wilkinson) Date: Sun, 3 Nov 2002 17:33:27 -0000 Subject: Largeint.h Message-ID: <3dc55de7$0$239$1b0f2dd5@mercury.nildram.co.uk> Hi, Python 2.2.2 doesn't compile under VS.Net because they've removed largeint.h from the Platform SDK, the current workaround is to copy the file from VS6. I don't have VS6, does anyone know where I can download this file? I'd really like to be able to debug my Python extensions... Regards, Andrew Wilkinson --- Quiet! You'll miss the humorous conclusion From gerhard.haering at gmx.de Fri Nov 22 18:37:21 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 22 Nov 2002 23:37:21 GMT Subject: secure sockets References: Message-ID: adrian wrote: > hi, > > i need to use use urllib with an https url i.e. using secure sockets. > I'm on win32 with version 2 python. apparently i need to build python > with the secure socket option turned on but i can't find out how i > turn this option on. also do i have to build the whole of python or > just the socket dll? or is there an easier way to do this using a > third party dll? > > any help very much appreciated. I used to offer a SSL-aware socket.pyd for Windows on my homepage. But it went offline and I don't have new webspace, yet. So for the meantime, I've put the really interesting pieces on the site of one Sourceforge project I'm involved in. The page you'll be interested in is http://pypgsql.sourceforge.net/misc/python-ssl.html Do as described there and HTTPS urls will just work with urllib, urllib2, etc. -- Gerhard From brian at sweetapp.com Tue Nov 19 19:28:24 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 19 Nov 2002 16:28:24 -0800 Subject: urllib slow on FreeBSD 4.7? In-Reply-To: <6cBC9.1422$Kw6.870449@newssrv26.news.prodigy.com> Message-ID: <008b01c2902b$bcd5b1f0$21795418@dell1700> dsavitsk wrote: > >>> f = open('somefile') > >>> u = urllib.urlopen('http://site/index.asp?file=somefile') > >>> f.write(u.read()) > > to get a 5 meg file takes about 1 to 2 seconds on a 500mhz windows > computer and nearly 2 minutes on a 150mhz freebsd computer. > (redhat 8 on a PII350 is also fast) both client computers and the > server are on the same network. any ideas? any other ways to get the > file? Could you try retrieving the file using wget/curl/etc on FreeBSD to verify that it is not a network problem? Cheers, Brian From tjreedy at udel.edu Wed Nov 27 13:20:23 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 27 Nov 2002 13:20:23 -0500 Subject: Issue with new-style classes and operators References: <3DE215D1.D9A3FEF9@jandecaluwe.com> <5ApE9.52343$744.1917235@news1.tin.it> <3DE2893A.CCB631D6@jandecaluwe.com> <3DE449BD.1040503@something.invalid> <3DE48ECC.8FC9AE53@jandecaluwe.com> Message-ID: "Jan Decaluwe" wrote in message news:3DE48ECC.8FC9AE53 at jandecaluwe.com... > Ok, let me explain better. Suppose - for the sake of the > argument - that I have a legitimate need for mutable numbers. To me, the concept 'mutable number' doesn't 'compute' very well. A label or pointer that is attached to or points to different (eternally existing) numbers at different times (a 'variable') make sense, and we have such. A container whose number contents change also make sense, and we also have that. One could regard a count as a (changeable) collection of units, but that is similar to the above and can be modeled either with list or set/dict. So what do you mean by mutable number, such that it could be needed but not available today? Terry J. Reedy From nicholas.y at NOSPAM.immersivetechnologies.com Fri Nov 1 03:50:41 2002 From: nicholas.y at NOSPAM.immersivetechnologies.com (Nicholas Yue) Date: Fri, 1 Nov 2002 16:50:41 +0800 Subject: urllib2 network access denied Message-ID: <3dc2406b$0$6041@echo-01.iinet.net.au> Hi, OS: WindowsXP Professional ActiveState Python 2.2 I am running a schedule task which includes a python script for retrieving daily report from an external web server. My machine sits behind a firewall and a proxy server. When I am login, I am able to run the script but once I logout, the schedule task runs the script on my behalf (I have provided the require Windows credential to run the script), it fails to have access to the internet saying that: File "C:\Python22\lib\urllib2.py", line 400, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 502: Proxy Error ( The specified network name is no longer available. ) Is this a firewall related problem? Can I setup the firewall stuff (login etc) using Python? Cheers From theller at python.net Fri Nov 22 04:57:17 2002 From: theller at python.net (Thomas Heller) Date: 22 Nov 2002 10:57:17 +0100 Subject: With what module can Python handel *.tar.gz file? References: Message-ID: "Wang Hanbo" writes: > Hi, > Buddies, I have a file named ***.tar.gz, and I want to gunzip > it with Python. > With which modules can I accomplish this task? And how to? > I can really recommend Lars Gustaebel's tarfile module: http://www.gustaebel.de/lars/tarfile/ Thomas From nthomas at cise.ufl.edu Mon Nov 11 18:44:29 2002 From: nthomas at cise.ufl.edu (N. Thomas) Date: Mon, 11 Nov 2002 23:44:29 +0000 (UTC) Subject: return values for exceptions Message-ID: I notice that user defined Python exceptions always return a value of 1 to the shell. I'd like to return different values in my program, depending on the exception, is there any way to do this? I suppose that I could trap the exception, and then return a value based on that, but I'm not too sure if that is the right way to go about doing it. thanks, thomas From tweedgeezer at hotmail.com Tue Nov 26 13:46:35 2002 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 26 Nov 2002 10:46:35 -0800 Subject: Python Tutorial Was: Guido's regrets: filter and map References: Message-ID: <698f09f8.0211261046.582254a5@posting.google.com> Thomas Guettler wrote in message news:... > I never liked filter, map and reduce. > > I think it would be good to remove them from the python tutorial. > I think the tutorial would be easier for newbies it > it would be smaller. The biggest problem with filter, map, and reduce is that they're functions, not methods. All this discussion about list comprehensions versus filter/map ignores one major disadvantage of list comprehensions: that they only work with lists. If filter/map/reduce had been *methods* on list objects, then a programmer could implement his own container objects (binary trees, subclasses of list, etc.) with their own filter/map/reduce methods to construct like containers, and people would be happier. As far as the tutorial goes, filter/map/reduce could be "discovered" just like the rest of the methods that aren't emphasized in the tutorial. Jeremy From hancock at anansispaceworks.com Thu Nov 21 01:19:43 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 20 Nov 2002 22:19:43 -0800 Subject: "properties" idiom Message-ID: I could swear I saw a conversation about this on list, but I'm having trouble finding anything relevant. Let's say I have a class that exposes an attribute x as part of it's public API: class spam: def __init__(self, x): self.x = x Due to later development, however, it's clear (hypothetically) that setting or getting the value of x, requires a method call (to update a database, for example). Is there a standard idiom for calling that method when an outside caller does something like: spaminstance.x = 42 or y = spaminstance.x (i.e. when we see this, my class actually calls an internal method, spaminstance.__set_x(42)). If so, I'd have the same flexibility as if I had used get_x()/set_x() accessor methods, but my code would be simpler for the most common case. Can you do this with Python today? I was thinking there might be a way using __getattr__ and __setattr__, but it initially looks very complex -- is there a preferred way to do it? I'm defining an interface now, and I'm wondering whether I should go with attributes or accessor-methods. I've been using accessor methods, but it bloats the interface quite a bit, and I'm wondering if I can make the interface simpler this way. Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From shadowlord13_1 at yahoo.com Mon Nov 18 18:19:29 2002 From: shadowlord13_1 at yahoo.com (Richard Dillingham) Date: Mon, 18 Nov 2002 23:19:29 GMT Subject: System Administration with Python -- documentation? References: Message-ID: <5AeC9.17354$0U1.1669384@news2.east.cox.net> > The information in this email is confidential and may be legally privileged. > It is intended solely for the addressee. Access to this email by anyone else > is unauthorised. If you are not the intended recipient, any disclosure, > copying, distribution, or any action taken or omitted to be taken in > reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot > accept liability for statements made which are clearly the senders own. *scratches head* *thinks to himself* Yeah. Uh. And I can't accept liability for reading your newsgroup post. Maybe I should make myself a sig like so: The information contained in this newsgroup post, message board post, or email, (hereafter referred to as 'this post', 'it', or 'WTF?') is governed by Terms of Use which are detailed below. If you do not hold the copyright for this post, reading it constitutes acceptance of the Terms of Use of this post. Said Terms of Use are: 1) You agree never to give all your worldly possessions to charity, because they don't want the stuff that's living in your fridge. 2) You agree to steal a nuclear bomb and drop it on Saddam Hussein's head just to see what will happen. If you cannot get near enough to him to drop the nuke on his head, you agree to blow him to smithereens with the nuke and pretend you dropped the nuke on his head. Nobody will be able to tell you didn't. 3) You agree to ignore any bullets or other objects which Saddam's security forces throw at you. They're irrelevant. Just set off the fricking nuke and blow him to kingdom come. 4) You agree to pretend that you have lost the ability to read or write for a period or time not less than 1 mercurian day, and not to exceed 2 mercurian days. You agree to calculate exactly how long a mercurian day is in order to fulfill these Terms of Use, without reading or writing, because you are pretending you can't, remember? 5) You agree to Have a Nice Day. From anton at vredegoor.doge.nl Tue Nov 26 05:47:59 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 26 Nov 2002 11:47:59 +0100 Subject: Python Tutorial Was: Guido's regrets: filter and map References: <20021126043142.4323.25612.Mailman@mail.python.org> Message-ID: On Mon, 25 Nov 2002 23:19:46 -0800, Terry Hancock wrote: >map(), filter(), and reduce() do not represent all of the uses for filter, >and thus, they can't all be replaced by list comps (BTW, I never used >reduce, never understood what it was good for, and don't immediately >see how it can be done using list-comps -- would be genuinely interested >in seeing a couple of example if anyone's willing). from operator import mul def fac(n): #faculty of n return reduce(mul,range(2,n+1),1L) Regards, Anton. --- 2658271574788448768043625811014615890319638528000000000L From bokr at oz.net Mon Nov 4 20:03:58 2002 From: bokr at oz.net (Bengt Richter) Date: 5 Nov 2002 01:03:58 GMT Subject: help() function References: <0h2esukvqtolp17lt0hdg72ua9t038k18v@4ax.com> Message-ID: On 4 Nov 2002 18:05:19 -0600, Chris Spencer wrote: > The documentation makes it clear that the help() function is only used >in interactive mode. However, I see it as a really neato-way of generating >standalone .txt files from docstrings in modules. However, as it currently >stands, it looks like help() can ONLY be used in interactive mode, which means I >can't capture the output to a file. > Is there any way to get the same docstring formatting that help() uses, >but be able to capture it to a variable or a file handle? > Inquiring minds want to know. > YPMV (Your Path May Vary) but just type [17:01] C:\pywk>D:\Python22\Lib\pydoc.py pydoc - the Python documentation tool D:\Python22\Lib\pydoc.py ... Show text documentation on something. may be the name of a function, module, or package, or a dotted reference to a class or function within a module or module in a package. If contains a '\', it is used as the path to a Python source file to document. D:\Python22\Lib\pydoc.py -k Search for a keyword in the synopsis lines of all available modules. D:\Python22\Lib\pydoc.py -p Start an HTTP server on the given port on the local machine. D:\Python22\Lib\pydoc.py -g Pop up a graphical interface for finding and serving documentation. D:\Python22\Lib\pydoc.py -w ... Write out the HTML documentation for a module to a file in the current directory. If contains a '\', it is treated as a filename; if it names a directory, documentation is written for all the contents. If you are on windows and want to capture output, don't forget to run it explicitly with python D:\Python22\Lib\pydoc.py > a_file.txt as extension-triggered program output is not always redirectable. Regards, Bengt Richter From NadavH at envision.co.il Tue Nov 26 11:05:38 2002 From: NadavH at envision.co.il (Nadav Horesh) Date: Tue, 26 Nov 2002 18:05:38 +0200 Subject: How to generate libpython2.2.so ? Message-ID: <3DE39BD2.5070700@envision.co.il> I compiled python 2.2.2 under RedHat 8.0 with gcc 3.2.1 using the simple ./configure; make combination. It all went smoothly and seems to work well, but it does not generate libpython2.2.so, although other shared libraries were generated. I looked at the README and the configure --help option but found no hints. Any ideas? Thanks, Nadav. From tjreedy at udel.edu Sat Nov 23 20:25:07 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 23 Nov 2002 20:25:07 -0500 Subject: ~~~ Python Use Question ~~~ References: <2a001b6.0211230739.13aaf7c5@posting.google.com> Message-ID: "Roy Smith" wrote in message news:roy-A43C5B.20103423112002 at reader1.panix.com... > "Terry Reedy" wrote: > > I think GPG, for instance, blew it when they designed > > and implemented yet another scripting language for Dungeon Siege > > instead of using Python (and putting more work into the game itself). > > I've been involved with a few projects where the designers felt the need > to invent their own language. Invariably, it's ended up being a > mistake. Which language you pick (Python, Perl, and TCL are all > plausable choices) is a far less important decision than the core > decision not to try inventing your own. Of course. I meant both 'for instance, Python' but also Python specifically since what they came up with could be seen as a cross between (for instance) C and Python. I forgot to add that a custom language also needs documentation and tutorials if buyers are to make any use of it. This is very easy to short-change and deliver late (as GPG did) or never. Terry J. Reedy From mwh at python.net Thu Nov 14 06:13:23 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 14 Nov 2002 11:13:23 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCF83B2.2030008@web.de> <3DD0D765.3030907@web.de> <3DD16CAF.41214BBA@alcyone.com> <3DD1DE6A.1BBEFE5A@alcyone.com> <3DD2 Message-ID: <7h3bs4sz9tw.fsf@pc150.maths.bris.ac.uk> Erik Max Francis writes: > > [What do you mean by "Lisp-like language" anyway? Python seems pretty > > Lisp-like to me...] > > Languages that look and act like Lisp. One might argue that Logo > qualifies (as a once-removed cousin), but I don't see how you can really > argue that Python looks and acts like Lisp. Looks like, no. Acts like, yes -- dynamic nature, manifest types, everything's an object (in some sense, not the Smalltalk one). > If Python is Lisp-like then what isn't? C++? Cheers, M. -- Lisp does badly because we refuse to lie. When people ask us if we can solve insoluble problems we say that we can't, and because they expect us to lie to them, they find some other language where the truth is less respected. -- Tim Bradshaw, comp.lang.lisp From jan at jandecaluwe.com Mon Nov 25 15:34:02 2002 From: jan at jandecaluwe.com (Jan Decaluwe) Date: Mon, 25 Nov 2002 21:34:02 +0100 Subject: Issue with new-style classes and operators References: <3DE215D1.D9A3FEF9@jandecaluwe.com> <5ApE9.52343$744.1917235@news1.tin.it> Message-ID: <3DE2893A.CCB631D6@jandecaluwe.com> Alex Martelli wrote: > > So, to wrap an arbitrary object X in such a way that X's special > methods will be used by any operator, you need to ensure you do > the wrapping with a _class_ that exposes said special methods. > That's generally easiest to do with a factory function with a > nested class that uses inheritance, but you have many other choices > depending on what exactly you're trying to accomplish. Mm, I think I see, thanks for that. (I'll try again to understand this from the documentation.) However, if I use inheritance from an immutable type, the subtype is automatically immutable also, right? So I wanted mutability, I'm back to delegation ... and apparently stuck with new-style classes ??? Jan -- Jan Decaluwe mailto:jan at jandecaluwe.com From fredrik at pythonware.com Wed Nov 6 15:58:23 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 06 Nov 2002 20:58:23 GMT Subject: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up References: Message-ID: Tim Peters wrote: > > What am I supposed to do to make the warning go away? Rewrite 0x80000000 > > as 0x40000000 * 2 ? ;-) > > Write it in a platform-independent way. If you *intended* this literal to > mean "a 1 bit followed by 31 zero bits", then stick an L on the end of the > literal. ...and remove it again when you get to Python 2.5. From animeshk at yahoo.com Sat Nov 9 10:38:02 2002 From: animeshk at yahoo.com (animeshk) Date: 9 Nov 2002 07:38:02 -0800 Subject: Odd problem with Wing IDE & PythonForDelphi extensions Message-ID: <4cce07d5.0211090738.370f3c2c@posting.google.com> I am encountering an oddity with the Wing IDE and Delphi extensions written using PythonForDelphi. These problems do not happen when running in a Python command prompt, and they do not happen with running within PythonWin. Basically, I took the PythonForDelphi example where you create a new Python data type (a "Point", created with a "CreatePoint" function in the Delphi DLL). I put this code in a DLL, and wrote the appropriate "init" function for Python. Cool. It worked at the command line. However, if I ran this within the Wing IDE, I get a "Debugging Stopped Unexpectedly" error: "Error: The debug connection closed unexpectedly while waiting for reply type 0x1011 after message type 0x70001: Runtime failure details: Exception: socket.error Value = (10054, 'winsock error') Of course, I'm not using winsock at all. I also encountered this same error when I used the PythonForDelphi example for accessing the database from a DLL. I've seen this in both Delphi 7 and Delphi 6. I realize that this isn't enough information: if anyone would like the source for the DLL, for testing, let me know. Does anyone know what this might mean? Is this a Wing IDE bug? Thanks! From martin at v.loewis.de Thu Nov 14 02:22:56 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 14 Nov 2002 08:22:56 +0100 Subject: xml.dom.minidom.parse(fname).save() still complains about UnicodeError... References: <6acfe44e.0211132209.2f07dd2f@posting.google.com> Message-ID: juha.o.ylitalo at kolumbus.fi (juha.o.ylitalo at kolumbus.fi) writes: > >>> print d.toxml() > > Traceback (most recent call last): > File "", line 1, in ? > UnicodeError: ASCII encoding error: ordinal not in range(128) Here, .toxml() returns a unicode object. It is the attempt to print this Unicode object that fails. Try print d.toxml().encode("utf-8") Regards, Martin From tracy at reinventnow.com Sat Nov 23 00:39:10 2002 From: tracy at reinventnow.com (Tracy Ruggles) Date: 22 Nov 2002 21:39:10 -0800 Subject: help interpreting a gdb traceback Message-ID: Hi, Not knowing a whole lot about c code, I'm trying to track down a rare bug that's happening. The code below is the 'bt' command from using gdb on the core that's being dumped. My current interpretation is that 1) a thread is being started, 2) "eval" code is being called somewhere and 3) the system dies during garbage collection. My hypothesis is that bad things happen when eval is called in a thread (at least on my system --> '2.2.1 (#5, Aug 21 2002, 03:45:02) \n[GCC 2.95.3 20010315 (release) [FreeBSD]]') So, to test my hypothesis, I'm changing the one or two places in my code where eval is being used and sit back and watch what happens. In the mean time, does anyone else have any insight on what this traceback has hidden in it? Thanks --Tracy ---------- START TRACEBACK ---------- (gdb) bt #0 _PyObject_GC_New (tp=0x80f08e0) at Modules/gcmodule.c:864 #1 0x80c1cab in PyDict_New () at Objects/dictobject.c:161 #2 0x80a9361 in PyInstance_NewRaw (klass=0x811800c, dict=0x0) at Objects/classobject.c:508 #3 0x80a9439 in PyInstance_New (klass=0x811800c, arg=0x9c479ec, kw=0x0) at Objects/classobject.c:539 #4 0x80a6404 in PyObject_Call (func=0x811800c, arg=0x9c479ec, kw=0x0) at Objects/abstract.c:1684 #5 0x8076f71 in PyEval_CallObjectWithKeywords (func=0x811800c, arg=0x9c479ec, kw=0x0) at Python/ceval.c:3049 #6 0x80859c2 in PyErr_NormalizeException (exc=0xbfa989e8, val=0xbfa989ec, tb=0xbfa989f0) at Python/errors.c:173 #7 0x8075f0f in eval_frame (f=0x839180c) at Python/ceval.c:2281 #8 0x80767a8 in PyEval_EvalCodeEx (co=0x8173180, globals=0x8171d0c, locals=0x0, args=0x8396498, argcount=1, kws=0x839a0d0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2585 #9 0x80b6cb0 in function_call (func=0x82d638c, arg=0x839648c, kw=0x829250c) at Objects/funcobject.c:374 #10 0x80a6404 in PyObject_Call (func=0x82d638c, arg=0x839648c, kw=0x829250c) at Objects/abstract.c:1684 #11 0x80abb1c in instancemethod_call (func=0x82d638c, arg=0x80fb10c, kw=0x829250c) at Objects/classobject.c:2276 #12 0x80a6404 in PyObject_Call (func=0x838cccc, arg=0x80fb10c, kw=0x829250c) at Objects/abstract.c:1684 #13 0x8076f71 in PyEval_CallObjectWithKeywords (func=0x838cccc, arg=0x80fb10c, kw=0x829250c) at Python/ceval.c:3049 #14 0x80c40dd in builtin_apply (self=0x0, args=0x838cecc) at Python/bltinmodule.c:95 #15 0x80c2785 in PyCFunction_Call (func=0x810c0a0, arg=0x838cecc, kw=0x0) at Objects/methodobject.c:80 #16 0x80757b3 in eval_frame (f=0x837240c) at Python/ceval.c:2004 #17 0x80767a8 in PyEval_EvalCodeEx (co=0x8296c00, globals=0x829880c, locals=0x0, args=0x8372360, argcount=1, kws=0x8372364, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2585 #18 0x80787b4 in fast_function (func=0x82c0d8c, pp_stack=0xbfa98e04, n=1, na=1, nk=0) at Python/ceval.c:3161 #19 0x8075855 in eval_frame (f=0x837220c) at Python/ceval.c:2024 #20 0x80767a8 in PyEval_EvalCodeEx (co=0x8296cc0, globals=0x829880c, locals=0x0, args=0x83964d8, argcount=1, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2585 #21 0x80b6cb0 in function_call (func=0x82c0dcc, arg=0x83964cc, kw=0x0) at Objects/funcobject.c:374 #22 0x80a6404 in PyObject_Call (func=0x82c0dcc, arg=0x83964cc, kw=0x0) at Objects/abstract.c:1684 #23 0x80abb1c in instancemethod_call (func=0x82c0dcc, arg=0x80fb10c, kw=0x0) at Objects/classobject.c:2276 #24 0x80a6404 in PyObject_Call (func=0x838cdcc, arg=0x80fb10c, kw=0x0) at Objects/abstract.c:1684 #25 0x8076f71 in PyEval_CallObjectWithKeywords (func=0x838cdcc, arg=0x80fb10c, kw=0x0) at Python/ceval.c:3049 #26 0x8097d4d in t_bootstrap (boot_raw=0x839a0b0) at ./Modules/threadmodule.c:190 #27 0x2810fe9b in _thread_start () from /usr/lib/libc_r.so.4 #28 0x0 in ?? () (gdb) From robin at jessikat.fsnet.co.uk Fri Nov 15 13:28:46 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 15 Nov 2002 18:28:46 +0000 Subject: wrapping all class methods References: Message-ID: ..... it seems I was asking a question that Python cannot answer as traceback.print_exc() will only print a traceback back to the point at which it's caught. The stack frames are there and can be listed further, but I don't think that the line number information is always good beyond the traceback. ############# traceback.py def tracebackAdvice(origMethod, methodName): def wrap_traceback_method(*args, **kwargs): inst = args[0] try: origMethod(*args, **kwargs) except: print '[%s.%s]' % (inst.__class__.__name__, methodName) from traceback import print_exc print_exc() print 'stack info' import sys f = sys._getframe(1) while f: co = f.f_code print 'name:%s file:%s co_lno:%d lasti:%d f_lno:%d' % (co.co_name, co.co_filename, co.co_firstlineno, f.f_lasti, f.f_lineno) f = f.f_back return wrap_traceback_method def _allMethods(C): from inspect import ismethod, getmembers M = [] m = M.append for methodname,method in getmembers(C): if ismethod(method): m(methodname) return tuple(M) def tracebackWrap(C, *M): for m in M or _allMethods(C): setattr(C, m, tracebackAdvice(getattr(C, m), m)) if __name__=='__main__': class A(object): def f(self, x): assert x>=0 print "real f", x tracebackWrap(A, "f") def L2(): a = A() a.f(1) a.f(-1) def L1(): L2() def L0(): L1() L0() ################################# C:\Python\devel\anygui\lib\anygui\backends>tbwrap.py real f 1 [A.f] Traceback (most recent call last): File "C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py", line 5, in wrap_traceback_method origMethod(*args, **kwargs) File "C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py", line 35, in f assert x>=0 AssertionError stack info name:L2 file:C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py co_lno:38 lasti:43 f_lno:41 name:L1 file:C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py co_lno:42 lasti:9 f_lno:43 name:L0 file:C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py co_lno:44 lasti:9 f_lno:45 name:? file:C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py co_lno:1 lasti:138 f_lno:46 C:\Python\devel\anygui\lib\anygui\backends> -- Robin Becker From TOGLIMIcuni at programmazione.it Thu Nov 14 18:23:58 2002 From: TOGLIMIcuni at programmazione.it (Antonio Cuni) Date: Thu, 14 Nov 2002 23:23:58 +0000 Subject: property problems References: <46a101c28bb2$6f2d1420$7635bcc3@blueyonder.net> <1wOA9.85898$MGm1.48783@news02.bloor.is.net.cable.rogers.com> Message-ID: Alex Martelli wrote: > What really determines if x is a new-style class is x's metaclass, > and rather than inheriting it from x's base (which is the normal > way to do it) you may alternatively choose to assert it explicitly > by a __metaclass__ attribute in class scope (or a global variable > __metaclass__ in module scope if x has no bases). x is new-style > iff x's metaclass is the built-in type object named 'type'. uhm... type inherit from object, but object's metaclass is type: isn't there a recursion problem? ciao Anto PS & OT: what's the english for "circolo vizioso"? -- "Computer science is not about computers any more than astronomy is about telescopes." -- EW Dijkstra From trentm at ActiveState.com Tue Nov 19 14:40:55 2002 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 19 Nov 2002 11:40:55 -0800 Subject: popen / batchfile / environment variables In-Reply-To: ; from achim.domma@syynx.de on Tue, Nov 19, 2002 at 07:37:52PM +0100 References: Message-ID: <20021119114055.C30986@ActiveState.com> [Achim Domma wrote] > Hello, > > I want to write a python script with automaticaly builds a VC.Net solution. > To make VS.Net usable from commandline, I first have to execute a batchfile > which sets the required environment variables. In a Dos-Box I would do > something like this: > > path_to\vcvars32.bat > devenv solution_file.sln /rebuild "Release" > > If I use popen or system to do the same, every call runs in his own > environment, so the changes made by the .bat file do not change the settings > for the second call. > > Any idea how to do that in python? 1. run this: path_to\vcvars32.bat && devenv solution_file.sln /rebuild "Release" 2. create a wrapper batch file with those two lines and run the new batch file: ---- temp.bat ------- path_to\vcvars32.bat devenv solution_file.sln /rebuild "Release" --------------------- fout = os.popen('temp.bat') Cheers, Trent -- Trent Mick TrentM at ActiveState.com From Simon.Wittber at perth.maptek.com.au Wed Nov 20 19:41:13 2002 From: Simon.Wittber at perth.maptek.com.au (Simon Wittber (Maptek)) Date: Thu, 21 Nov 2002 08:41:13 +0800 Subject: PyOpenGL install issues.... Message-ID: <10F0E58C0018054484E329DC494C4D7F01ADD2@mexper1.maptek.net.au> Hi Bryan, I too had lots of difficulty installing PyOpenGL on RH8. I can't tell exactly what your problem is, however it does look similar to the error messages I was getting. I solved the problem by installing Numeric, OpenGL, GLUT, then PyOpenGL. I have an nvidia card, which came with its own set of OpenGL drivers, but did not come with GLUT. I then had to change the PyOpenGL configuration file to use -lGL -lGLU -lGlut instead of the mesa libs. I suggest you make sure you have all the required libs, then try and build PyOpenGL again. Its worth the trouble, PyOpenGL is great!; Esp. when used with pygame (SDL). -----Original Message----- From: Bryan [mailto:bryan at akanta.com] Sent: Thursday, 21 November 2002 3:46 AM To: python-list at python.org Subject: PyOpenGL install issues.... Hi, I am trying to install PyOpenGL for the first time on a Redhat 8.0 system. I am getting errors though, anyone have any ideas? Thanks, Bryan From slash at peereboom.us Mon Nov 4 08:55:51 2002 From: slash at peereboom.us (Marco Peereboom) Date: Mon, 4 Nov 2002 07:55:51 -0600 Subject: Is there a good checksum system for OPENBSD? References: Message-ID: <019701c28409$e310db20$6400a8c0@slashmarco> The other day there was an article in onlamp about this very question. See: http://www.onlamp.com/pub/a/bsd/2002/10/31/ssn_openbsd.html?page=2 ----- Original Message ----- From: "John D." To: Cc: ; Sent: Monday, November 04, 2002 00:27 Subject: Is there a good checksum system for OPENBSD? > I'm looking for a Program that compares md5 file checksums in a file against actual files and reports discrepancies. A commercial program like "Tripwire" does this, but isn't there an Open Source program that can do this. > > It would be a good thing to use for files in the /bin directories, and other places where one would not expect files to be changed, but would easily identify trojans, and other changes to executeable files and binaries. > > I suppose it wouldn't be that hard to write this in Python or Perl. But how long would it take to checksum thousands of files? > > John > > From mertz at gnosis.cx Fri Nov 22 15:38:30 2002 From: mertz at gnosis.cx (David Mertz) Date: Fri, 22 Nov 2002 15:38:30 -0500 Subject: Python order warts (and others) References: Message-ID: Alex Martelli wrote previously: [...'<' used to be an order relation, but isn't now...] |Why comparing string 'plak' with the number 23 is OK, but comparing it |with 23j isn't, kind of escapes me -- but apparently property (2) was |deemed less desirable than the ability to forbid e.g. comparing 23j with |42j. To the point of changing Python's previous behavior, no less:-(. I think this change is the worst wart that has been added to Python since I've been using it (about 4 years). I think--as Alex does--that the "print >> FILE" form was a mistake. But it is just ugly syntax, and I've even found myself using it occassionally. Likewise, I think that the syntax whereby you create a generator by using the 'yield' statment somewhere deeply buried inside a function is a bad choice. I would much rather see that feature right in the function declaration, perhaps by using the word "gen" or the like in place of "def". Actually, it would not break anything (much) to add the pseudo-keyword 'gen' as an alternative word. In this case, presumably, using the 'gen' keyword would -require- you to also put a 'yield' inside the body (or raise an exception). This would not break existing code, but would provide a path to improving future code by encouraging explicit 'gen' declarations. But those warts are only matters of syntax. I might have spelled those things differently, but there is no deep semantic issue. The "incommensurability of complex numbers" is a much worse semantic problem. I used to be able to sort lists, now I cannot. Or at least without first checking all the contents of the lists before I try to sort (or maybe catching errors and recovering somehow). It's ugly. In my book, I suggest a bit of a workaround for readers. It's not wholly fleshed out, but it points in a possible direction. Take a look at: http://gnosis.cx/TPiP/chap1.txt Jump to the discussion of: BUILTIN -- complex : New-style base class for complex numbers I would welcome better or more complete solutions, of course. Yours, David... -- _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/ _/_/ ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~ _/_/ _/_/ The opinions expressed here must be those of my employer... _/_/ _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/ From theller at python.net Fri Nov 15 02:33:54 2002 From: theller at python.net (Thomas Heller) Date: 15 Nov 2002 08:33:54 +0100 Subject: Supporting older Python versions in py2exe? References: <3DD48D9E.245E5891@engcorp.com> Message-ID: Thanks for all the comments, Kevin, Gerhard, Peter. So I will release a last version compatible with all the older stuff which supports early COM binding (this is already in CVS), and then move on to 'officially' only support Python 2.2 (or 2.1?) and later. Thomas Peter Hansen writes: From ark at research.att.com Tue Nov 12 13:52:41 2002 From: ark at research.att.com (Andrew Koenig) Date: Tue, 12 Nov 2002 13:52:41 -0500 (EST) Subject: pitfall for your amusement In-Reply-To: <20021112164933.A29726@ibook.distro.conectiva> (message from Gustavo Niemeyer on Tue, 12 Nov 2002 16:49:33 -0200) References: <20021112164933.A29726@ibook.distro.conectiva> Message-ID: <200211121852.gACIqfU24763@europa.research.att.com> >> >>> x = (1, 2, 3) >> >>> x += (4, 5, 6) Gustavo> Hey, shouldn't this raise an exception? Perhaps it should, but it doesn't: If x is a tuple, x += y is equivalent to x = x + y which creates a brand-new object and (re)binds x to it. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From nbatada1 at yahoo.com Sun Nov 24 21:41:01 2002 From: nbatada1 at yahoo.com (Nizar Batada) Date: 24 Nov 2002 18:41:01 -0800 Subject: index of items in a List in sorted order Message-ID: <75e086cd.0211241841.72e35ecf@posting.google.com> I am posting a code to get index of sorted list for future reference. if you can make this code faster, i'll appreciate your input nizar ########################################################3 #!/usr/bin/python def ind_of_sorted(L): ''' return index of items in sorted order ''' k = len(L) d = {} # take care of repeated values [ d.setdefault(L[i],[]).append(i) for i in range(k)] auxL = d.keys() auxL.sort() inds = [] [inds.extend( d[x] ) for x in auxL] return auxL,inds if __name__ == '__main__': L=['r','g','a','f','r','j'] Lsort,Lsort_I=ind_of_sorted(L) print L print Lsort print Lsort_I From rhymes at myself.com Mon Nov 11 12:56:42 2002 From: rhymes at myself.com (Lawrence Oluyede) Date: Mon, 11 Nov 2002 17:56:42 +0000 (UTC) Subject: Python 2.2.2 doc in CHM format Message-ID: I've changed the hosting site, please update your links http://digilander.iol.it/rhymes/html-help-222.zip -- Lawrence Oluyede -- Posted via Mailgate.ORG Server - http://www.Mailgate.ORG From greenbeard400 at yahoo.com Thu Nov 21 23:37:54 2002 From: greenbeard400 at yahoo.com (greenbeard) Date: Fri, 22 Nov 2002 04:37:54 GMT Subject: SMTP Relaying References: <3DDC02A5.2090003@yahoo.com> Message-ID: Chris Gonnerman wrote: > ----- Original Message ----- > From: "greenbeard" > > >>Hello all, >> >>I am having trouble getting some mail through to certain addresses. I >>get an SMTPRecipientsRefused {to_address, 550 '5.7.1 >>...relaying denied. >> >>So I am pretty sure that it is due to the target address blocking the >>relay - my machine -> my SMTP on another machine -> corporate SMTP - as >>most non-corporate address have no problem receiving. So think I am >>hitting the RFC2505 wall here but I cant quite seem to figure out what >>fields or combination of values to load to let the mail arrive ok. >> >>All advice appreciated. > > > I hope you aren't SPAMMING 'cause then we have to > send the DOGS after you... > > SERIOUSLY, if the to_address isn't on the server > you are connecting to, and they aren't enabled > to relay to that domain, then nothing you can do > will change that. > > One of the following: > > -- You are connecting to the target mailserver > directly: you must have screwed up the to_address. > > -- You are using your ISP's relay: It's mis- > configured? Dunno. Maybe they don't like your > face :-) > > -- You are using a third party relay without > permission: SPAMMER, GET THEE BEHIND ME! > > I really hope it's the first. > > Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net > http://newcenturycomputers.net > > No spamming here! I have a program sends me files on a timer from my remote machine at home to where I work. (Good for surfing at work - although no images) Now the place I am at during the day uses the Message Labs Virus Scanning Service so the email is definately being forwarded. Anyway. I have no problem sending to other servers it is only the @work one. My guess is that it checks the headers and sees that it originated from my local machine, routed through my webserver , and assumes that it is spam and therefore blocks it. Guess I will have to keep smackin' the code. gb From engsol at teleport.com Fri Nov 8 22:48:35 2002 From: engsol at teleport.com (engsol at teleport.com) Date: Sat, 09 Nov 2002 03:48:35 GMT Subject: NEWBIE: Extending Python with C Message-ID: <3dcc7e2c.3568851@news.earthlink.net> I've read the books, tried some code, and I still just don't get it. If some kind soul can explain the (high level) process, I can figure out the details, I think. What I want to do is call (or invoke) a C exe from Python, and return the results to Python. Or pass values of some sort to the C exe, and again have Python trap the returned results. I'm a long way from the concept of shared variables. The first stumbling block is that the books offer examples of C code which don't seem to have a main(). My compilers don't care for that too much. I took a quick look at SWIG, but to be honest, I didn't understand how to use it. Again, I need the high level concept. The second problem is the concept of translating PyObjects to C and vice versa. As I say, I just don't get it yet. The third problem is that the books spend one paragraph on the Python/C code, usually for Linux, then three pages on reference counts. Do I really have to worry about them, or not? I'm using Python 222 on NT. If I understood how to do "Hello world" (in C, called from Python), I might be able to go from there. In case you're interested, the reason I need to learn this is that my company is in dire need of a new software test tool. I'm convinced that Python is the right scripting language for the testers, and will be best in terms of maintainabilty and enhancement, no matter if the platform is NT/2000/Linux. We have a huge library of legacy C code which we can re-use as is, assuming I can learn to marry Python and C. BTW, I'm a diehard Python convert! (But my family doesn't know yet, so keep it under your hat please) Thanks.....Norm From michel.l.combe at free.fr Sat Nov 23 10:46:18 2002 From: michel.l.combe at free.fr (Michel COMBE) Date: Sat, 23 Nov 2002 16:46:18 +0100 Subject: Newbie : desperately need help on "import MySQLdb" Message-ID: <3ddfa321$0$18230$626a54ce@news.free.fr> I'm trying to use MySQLdb in a python program. System is Linux Mandrake 8.2, Python is installed from rpm in /usr/bin MySQLdb is installed from rpm in /usr/lib/python2.2/site-packages MySQL version 2.23.53a is installed in /var/lib If I type import "MySQLdb", I receive the message File "/usr/lib/python2.2/site-packages/MySQLdb/__init__.py" line 27 ImportError: No module named _mysql I spent more than 2 days on this. Can someone please help before I give up ? Thanks Michel Combe From grante at visi.com Tue Nov 26 11:10:17 2002 From: grante at visi.com (Grant Edwards) Date: 26 Nov 2002 16:10:17 GMT Subject: Python Tutorial Was: Guido's regrets: filter and map References: Message-ID: <3de39ce9$0$22220$a1866201@newsreader.visi.com> In article , sismex01 at hebmex.com wrote: > Anyway, to each it's own. But I do concurr with those who > say that with the acquisition of list comprehensions, map(), > reduce(), filter(), lambda() et-al, should be on the road > to deprecation and eventual elimination, being the black > un-pythonic sheep of the family. I see how you use list comprehensions to replace map and filter, but I don't understand why list comprehensions are touted as a replacement for reduce and lambda. I use lamba almost exclusively to generate anonymous functions that are passed to GUI widgets. How does a list comprehension solve that problem? In the case of reduce: sum = reduce(operator.add, valueList) How is that expressed any better with a list comprension? -- Grant Edwards grante Yow! I'm also against at BODY-SURFING!! visi.com From pinard at iro.umontreal.ca Wed Nov 13 19:47:23 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 13 Nov 2002 19:47:23 -0500 Subject: My (late) beef with Simple Generator syntax (PEP 255) In-Reply-To: <6435449.1037227105210.JavaMail.camhorn@mac.com> References: <6435449.1037227105210.JavaMail.camhorn@mac.com> Message-ID: [Cameron Horn] > >def foo(): return iter(tuple()) > Which is the obvious, clear and consistent way to create a generator that > doesn't do anything. I was to suggest: def foo(): return iter([]) but using a tuple is probably tinily faster. No need to call tuple(), however, just write an empty tuple constant: def foo(): return iter(()) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From jdhunter at ace.bsd.uchicago.edu Mon Nov 25 19:54:49 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 25 Nov 2002 18:54:49 -0600 Subject: Python IRC dictatorship In-Reply-To: <1038264655.1697.137.camel@software1.logiplex.internal> (Cliff Wells's message of "25 Nov 2002 14:50:56 -0800") References: <29304.91T434T13743504threeseas@earthlink.net> <1038264655.1697.137.camel@software1.logiplex.internal> Message-ID: >>>>> "Cliff" == Cliff Wells writes: Cliff> Perhaps the Ruebot should be considered for honorary Cliff> "Village Idiot" status on c.l.py. The subject line on all Cliff> of his posts could be prefixed with "[Comedy Relief]" to Cliff> help avoid misunderstandings. At least he's in good company. I only knew of 3: bots = ['effbot', 'martellibot', 'timbot'] bots.append('ruebot') I hope he feels honored. John Hunter From R.Brodie at rl.ac.uk Mon Nov 25 10:40:49 2002 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Mon, 25 Nov 2002 15:40:49 -0000 Subject: Eric 3.0.0-alpha2 released References: Message-ID: "Detlev Offenbach" wrote in message news:bvtqra-lfh.ln at majestix.gallien.de... > Eric 3.0.0 (or short eric3) is a Python IDE written using PyQt and QScintilla. So it's a replacement for IDLE then ;) From senux at senux.com Sat Nov 23 00:36:33 2002 From: senux at senux.com (Brian Lee) Date: Sat, 23 Nov 2002 14:36:33 +0900 Subject: ARP request/reply by Python? Message-ID: <20021123053633.GA22332@mercury.senux.com> Can I read and write ARP packets by Python? I found that type number for IP datagram is 0x0800 and 0x0806 for ARP request/reply in ethernet frame header. How can I set type number(0x0806) to ethernet frame header in Python socket? Any site link on this? -- Brian Lee - http://www.senux.com/en/ From rmunn at pobox.com Wed Nov 27 17:50:01 2002 From: rmunn at pobox.com (Robin Munn) Date: Wed, 27 Nov 2002 22:50:01 GMT Subject: Database Programming References: <3875fcac.0211260752.60e2e457@posting.google.com> <3de3ac09$0$9474$79c14f64@nan-newsreader-01.noos.net> Message-ID: Jonathan P. wrote: > > Note that the more than half of the Python dev't time involved > the creation, from scratch, of some fairly sophisticated > curses-based text widgets (now I know why they call it curses) Any chance of sharing these widgets, or was your code closed-source? -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From berkowit at silcom.com Fri Nov 29 16:28:29 2002 From: berkowit at silcom.com (Paul Berkowitz) Date: Fri, 29 Nov 2002 13:28:29 -0800 Subject: Can't find user module despite setting PYTHONPATH References: Message-ID: On 11/29/02 12:46 PM, in article BA0D1211.274A2%berkowit at silcom.com, "Paul Berkowitz" wrote: >>>>> import module1 >> Traceback (most recent call last): >> File "", line 1, in ? >> ImportError: No module named module1 >> >> >> But it's there, in my ~/Library/Scripts/Python/ directory. There must be >> something wrong with my PYTHONPATH? >> >> setenv PYTHONPATH >> .:/usr/lib/python2.2/:/Users/berkowit/Library/Scripts/Python/:/usr/lib/pytho >> n2.2/plat-darwin/ # all one line >> >> What? > > Yes. If I cd to '/Users/berkowit/Library/Scripts/', then I can import the > module without problem. But otherwise PYTHONPATH doesn't seem to find that > directory. Does anyone know why not? (Mac OS 10.2.2, using tcsh in Terminal > to set PYTHONPATH). I came upon the other way to do this, within the Python interactive interpreter: >>> import sys >>> sys.path.append('/Users/berkowit/Library/Scripts/Python') >>> import module1 Hello module world! and that works within a particular session, but is not retained. When I quit Python and restart the interactive interpreter, I'm back where I started, and might as well just cd to this directory. When I >>> print sys.path it doesn't include the new directory I've added to PYTHONPATH. Ever. Is there anyone here with Mac OS 10.2? Do you know how to get Python to recognize PYTHONPATH, as the shell does. Or else what is the right way to modify sys.path to it is retained between sessions? -- Paul Berkowitz From tjreedy at udel.edu Fri Nov 22 13:06:04 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 22 Nov 2002 13:06:04 -0500 Subject: [OT] Reciprocal function? References: Message-ID: "Anton Vredegoor" wrote in message news:aril5k$e07$1 at news.hccnet.nl... > def rowinc(x,base): > i,j = 0,1 > while i <= x: > j = j * base > i = i + j > return j Odd and misleading name. Somewhat odd function. For x < 0 (which your problem specification may exclude), rowinc==1. Otherwise, it return the largest power of base, base**n, such that sum(k=1..n-1; base**k) <= x. For x>=0, this is at least base**1. When base=2 and hence base-1==1, this is the largest power of 2 in x+2. Which is to say, n is the index of the high order 1-bit in the binary expression of x+2. This could be done more simply with shifts, but this does not generalize very well to other bases. > def concat(a,b,base): > f = rowinc(b,base) > return f*(a+1)+b This multiply-add (which characterization is the key to your problem) has nothing obvious to do with concat-enation. You implicitly assume below that a and b are counts (non-negative ints). It would be less confusing if you did not add 1 to a, so a is the actual multiplier rather than 1 less, and instead required input to be positive rather than just non-negative. > And, for the moment, lets assume "base" is fixed to the value 2. > > Then concat(9,5,2) will return 45. > But concat(3,13,2) will also return 45. > > In fact if the number that concat returns is known, and the "base" > argument is also known, the function below can be used to calculate > how many other tuples (a,b) will have the same result: > > def seqlen(x,base): > i,j,k = 0,1,0 > while i <= x: > j = j * base > i = i + j > k = k + 1 > return k This version of rowinc returns n instead of base**n. > So seqlen(45,2) returns 5. The number of possible tuples (a,b) that > make concat(a,b,2) return 45 is seqlen(45,2)-1 which is 4. Only because you exclude concat(-1,45,2) = 45. > For (a,b) in [(0, 29), (3, 13), (9, 5), (21, 1)], concat(a,b,2) > returns 45 and there are no other tuples (a,b) that return 45 for > concat(a,b,2). Only with the unstated condition. > > Now I need a function that looks a bit like this: > > def splitat(i,a,base): > """ > returns the i'th tuple (x,y) out of the set of possible > tuples that make concat(x,y,base) return a > """ > return x,y > > Any pointers appreciated. Overloading a as both a param of concat and its result is poor. I will call the result cc instead. Defining i'th tuple depends on the ordering. Sorting on b instead of a makes problem slightly easier. In any case, the 'inverse' of multiply-add is divmod(), possibly adjusted. Because of the rowinc condition linking b, base, and power of base, there is (definitely for base 2 and perhaps for others - not sure) one possible value of a,b for each possible value of rowinc, each of which is a positive power of base. So generate the list of tuples by looping thru powers of base. Example for cc=45 and base=2 to generate pairs (a+1,b) (I'll let you do subtraction of 1 from a+1): divmod(45,2) = (22,1) #OK since rowinc(1,2)=2 divmod(45,4) = (10,5) # OK since rowinc(5,2) = 4 divmode(45,8) = (5,5) # not OK # adjust a down and b up to maintain product-sum of 45 adjust to 4,13(=5+8) # OK since rowinc(13,2)=8 divmod(45,16) = (2,13) # not OK adjust to 1,29(=13+16) #OK since rowinc(29,2)=16 divmod(45,32) = (1,13) # not OK adjust to 0.45 #stop because a+1<1 not allowed return list of 4 tuples With other bases, you might have to adjust more than once. If doing a lot of calculations with one base, it would be worthwhile to calculate a vector of rowinc results. Terry J. Reedy From francois.lepoutre at seriatim.com Fri Nov 15 04:01:32 2002 From: francois.lepoutre at seriatim.com (François Lepoutrre) Date: Fri, 15 Nov 2002 10:01:32 +0100 Subject: some sort of threadsafe locale support Message-ID: We have a modpython delivering fully dynamic content over the wire that uses "locale.format" to deliver fully formatted numerics. The application is now supposed to go "intl" and deliver numeric amounts formatted according to the user locale. That looked pretty simple... We change locale ("locale.setlocale()") on the fly and got comic results as french people would, at times, receive us-formatted amounts and vice-versa... As clearly stated in python documentation, locale services are not threadsafe and possibly costly. Definitely not a good idea. Any threadsafe alternative to format numeric output is welcome :) Of course we could do it the dummy way writing our own formatting stuff. Any clever alternative to "wheel-reinventing" for this simple but irritating issue? Francois From jacek.generowicz at cern.ch Mon Nov 25 08:50:01 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 25 Nov 2002 14:50:01 +0100 Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <2259b0e2.0211210838.7647301a@posting.google.com> <093kra.3n3.ln@beastie.ix.netcom.com> <1038199757.350382@yasure> Message-ID: "Donn Cave" writes: > |> Perhaps I could be, if message passing were clearer to me! > | > | Message passing means that there are several entities that > | communicate by sending messages between them. The main points are > | that these entities are autonomous and that there is no central > | "main" program that controls the behavior of these entitities. > > But what would a message be, precisely? [...] > What are the semantics of passing, for the sender and the recipient? [...] > Can Python programs be written this way ? Yes ... class foo: def bar(self): print 'This is an object of type "foo" responding to the message "bar"' class zot: def bar(self): print 'This is an object of type "zot" responding to the message "bar"' f = foo() z = zot() # Pass message "bar" to the object f. f.bar() # Pass message "bar" to the object z. z.bar() > How is it different from calling a subroutine? When you call a subroutine, you are calling a specific piece of code. The caller decides what will be executed. When you pass a message, the decision as to which exact code should be executed is made elsewhere (some form of dispatch). But it looks as if my understanding of message passing is different from Pascal's. From aleax at aleax.it Fri Nov 1 03:57:35 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 01 Nov 2002 08:57:35 GMT Subject: Protect Python Source References: Message-ID: <3mrw9.71925$TD1.3188780@news2.tin.it> hope wrote: > Hi, > > If i am to develop a full fledge commercial application using Python : > > a. Can i compile my python source into binary ? I have read about py2exe > for windows. Is there one for Linux ? Yes, you can use McMillan's "installer" for both Windows and Linux, see: http://www.mcmillan-inc.com/install1.html > b. Can I distribute the bytecode only (.pyo, .pyd) and not the source Yes, except that .pyd is not an extension used for bytecode but rather for dynamically lodaed libraries used as Python extensions on Windows (you may be thinking of .pyc, which IS the extension used for bytecode that is not optimized, while .pyo indicates bytecode that IS optimized). > (.py) ? Can the bytecode be 'de-compiled' to source ? Of course! It's even easier than "dis-assembling" machine code back into readable symbolic assembly languages, which is something that 'crackers' do for fun -- visit any 'warez' site to see how abundant are the `cracks` available for all sorts of machine-coded commercial programs. Module dis in the Python standard library lets you disassemble bytecode back to readable form. Recovering actual Python sources is harder (just as it is if, say, you code in C, to recover actual C sources rather than disassembled machine code) -- have a look at decompyle, which you can find with Google, but it's not in "production" state nor, I think usable with the latest releases of Python. > Please advice. It is conceptually impossible to stop a halfway-competent 'cracker' from disassembling any compiled form of your program if they have any interest at all in it (or even if they don't: they DO do it just for fun even for programs they have no earthly use for), as long as you distribute your program in a fully executable form for general purpose computers. If the GP computer can get at your program, as it must to be able to execute it, so can the cracker. In some cases you may be able to achieve a measure of protection if your program can only execute when connected to some Internet site: in that kind of scenario, you may be able to check that connections only come from validly registered sites. But in general, you should rely on the law to protect your programs against unauthorized use, not on illusory "protection". "Security through obscurity isn't". Alex From maney at pobox.com Mon Nov 25 15:28:55 2002 From: maney at pobox.com (maney at pobox.com) Date: Mon, 25 Nov 2002 20:28:55 +0000 (UTC) Subject: if : References: Message-ID: Steve Holden wrote: > Interesting that none of the responders referenced a FAQ article ... though > since it refers to 2.0 as a future release it's clearly in some need of > updating! I'll plead that I probably read that back when I was in the process of deciding whether to jump into Python or PHP but have since forgotten it, obviously. I was ultimately swayed by the reputation PHP had as the cool web scripting language, and while I wouldn't say that I wasted the year or so I was working with it (mostly on stolen time, concurrently learning more than pidgin SQL and HTML and so forth), I'm happy that I came back to Python. It's a much better match for the sort of web apps I'm working on. Anyway, that FAQ item: I'm not sure I agree with this bit. An interesting phenomenon is that most experienced Python programmers recognize the "while 1" idiom and don't seem to be missing the assignment in expression construct much; it's only the newcomers who express a strong desire to add this to the language. I am a relative newcomer to Python, but my problem is not that I fail to *recognize* the various work-arounds such as the 'while 1' idiom that's specifically being discussed. Having implemented a service tracking and management system in a dialect of Basic that lacked all but the crudest of facilities (well, in the flow control department), I know all about such workarounds, and recognize them; what I lack with respect to the most experienced Pythoneers (in this regard) seems to be only a *liking* for such workarounds. As long as I'm talking about that FAQ item, I think it praises the other kluge presented at the very bottom with insufficently strong damns. Was it Dijkstra who said that when you've said the same thing twice [in a program] then you have very likely contradicted yourself? IME with C, that has been a larger source of errors than has operator=. From imbosol at vt.edu Sun Nov 10 22:09:21 2002 From: imbosol at vt.edu (Carl Banks) Date: Sun, 10 Nov 2002 22:09:21 -0500 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: Brad Hards wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On Sat, 9 Nov 2002 11:53, Carl Banks wrote: >> Oleg wrote: >> > Hi >> > >> > I don't know much about Python, but I looked at this comparison >> > between Python and Common Lisp ( >> > http://www.norvig.com/python-lisp.html ), and I couldn't help but >> > wonder why Python is popular, while Common Lisp and Scheme aren't? >> >> As cool as Lisp is, it is too low-level, too hard to learn, too >> weird-looking, and way too different from C (at all levels) to gain >> much popularity. > I don't think that this is it. > > If "low-level", "hard to learn" and "too weird looking" were real problems, > then C wouldn't be popular. Well, I apparently misused the word "low-level." I referred to being close to the inner working of the compiler, as opposed to the most common use of low-level, close to the operating system. And if C is weird looking, what is Lisp? -- CARL BANKS From mcfletch at rogers.com Thu Nov 21 01:35:45 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 21 Nov 2002 01:35:45 -0500 Subject: "properties" idiom References: Message-ID: <3DDC7EC1.7080406@rogers.com> Yes, there is such an API, but it really only becomes full-fledged with Python 2.2.2 (where it is called the "descriptors" API). You can read all about it in Guido's Python 2.2.x introduction. http://www.python.org/2.2.2/descrintro.html You can use the standard self.x stuff until you need properties, then switch to properties when you need them. My own basicproperty project extends the concept somewhat, but it doesn't sound like you need that. Enjoy, Mike Terry Hancock wrote: >I could swear I saw a conversation about this on list, but I'm having >trouble finding anything relevant. > >Let's say I have a class that exposes an attribute x as part of it's public >API: > >class spam: > def __init__(self, x): > self.x = x > >Due to later development, however, it's clear (hypothetically) >that setting or getting the value of x, requires a method call >(to update a database, for example). > >Is there a standard idiom for calling that method when an outside >caller does something like: > >spaminstance.x = 42 > >or > >y = spaminstance.x > >(i.e. when we see this, my class actually calls an internal method, >spaminstance.__set_x(42)). If so, I'd have the same flexibility as if I >had used get_x()/set_x() accessor methods, but my code would >be simpler for the most common case. Can you do this with Python >today? I was thinking there might be a way using __getattr__ and >__setattr__, but it initially looks very complex -- is there a preferred >way to do it? > >I'm defining an interface now, and I'm wondering whether I should >go with attributes or accessor-methods. I've been using accessor >methods, but it bloats the interface quite a bit, and I'm wondering if I >can make the interface simpler this way. > >Terry > >-- >Terry Hancock ( hancock at anansispaceworks.com ) >Anansi Spaceworks http://www.anansispaceworks.com > > > -- _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From benc1 at today.com.au Fri Nov 1 01:26:12 2002 From: benc1 at today.com.au (Ben C) Date: 31 Oct 2002 22:26:12 -0800 Subject: Wrapping a .dll under windows with SWIG Message-ID: <8beb91f5.0210312226.7eb08c08@posting.google.com> Hi there, I want to wrap a .dll under windows and have access to it's functions etc. The problem is that all I have is the .dll and header file ... no source ... and as all the examples that I have seen for swig seem to need the original source ... I was wondering if it is still possible to get access to the functions stored in the dll? Would anyone be able to point me in the write direction, docs examples etc if this can be done at all? thanks in advance Ben C From wilk-spamout at flibuste.net Wed Nov 13 07:49:51 2002 From: wilk-spamout at flibuste.net (William) Date: 13 Nov 2002 13:49:51 +0100 Subject: perl2python Message-ID: <87y97xmy6o.fsf@flibuste.net> hi, I want to convert a little perl script to python, is there a tools for that ? or a little doc to learn the minimum of perl for python users ? This script is to convert XpressTag to HTML... maybe somebody else is interested ? bye -- William Dode - http://flibuste.net From aleax at aleax.it Thu Nov 7 03:56:54 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 07 Nov 2002 08:56:54 GMT Subject: [Jython] Pass variable or class reference to PythonInterpreter? References: Message-ID: Robert Oschler wrote: > I know I can compile a Jython class and then have it accessible as a true > Java class to other java code. But I'm wondering if I can pass a variable > or > class reference to an instance of PythonInterpreter? For example: > > private void CallInterpreter() > { > String theString = "Hello"; > > PythonInterpreter interp = new PythonInterpreter(); > > // Here I enter a loop receiving python commands and passing them > to > "interp.exec()" > // So how could I give "interp" access to "theString" so commands > passed to "exec()" > // can see it, print it, change it, etc? > } > > Is there a way to do this? > > thx Sure, Jython's PythonInterpreter class gives you methods you can use for this purpose. interp.set("theString", theString) for example would add an attribute named "theString" to the inteprreter's local namespace, with its value set to the Java value theString. *CHANGING* it is obviously out of the question (strings are immutable in Java *AND* in Python), but THAT is clearly a completely different issue. Alex From brian at sweetapp.com Mon Nov 18 04:04:43 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 18 Nov 2002 01:04:43 -0800 Subject: pythonic way to optimize access to imported value? In-Reply-To: Message-ID: <001f01c28ee1$88e88200$21795418@dell1700> Bengt wrote: > IOW, IMO there ought to be a way to do a temporary global-side-effect-free > import and delete all traces of its having been done -- without restarting > the interpreter or invoking a second interpreter instance. Does that involve unloading a dynamically imported library? If so, you will have to figure out how to do that in a cross-platform manner and without breaking existing Python extensions. Here are some other issues: 1. What happens if two "throwaway" imports of the same module happen at once? 2. What happens if the extension module modifies global state? 3. What happens if the extension module causes external entities to hold references to its objects? Cheers, Brian From nospam at nospam.com Mon Nov 18 19:53:26 2002 From: nospam at nospam.com (C42) Date: Mon, 18 Nov 2002 19:53:26 -0500 Subject: Access to Python/SQL Message-ID: <24vitu0d93ksc5biv4re3gr3d1ocntpqli@4ax.com> I currently have several Microsoft Access databases. My long term goal is to move the data to an SQL server and create web-based front-ends using Python to access them. Does anyone have any recommendations? Is there a framework and/or web app server that would make this easy? Thanks for your help! From anton.wilson at camotion.com Tue Nov 5 16:39:44 2002 From: anton.wilson at camotion.com (anton wilson) Date: Tue, 5 Nov 2002 16:39:44 -0500 Subject: power TypeErrors In-Reply-To: <200211060810.28875.bhards@bigpond.net.au> References: <200211052054.PAA05238@nealtech.net> <200211060810.28875.bhards@bigpond.net.au> Message-ID: <200211052132.QAA07582@nealtech.net> On Tuesday 05 November 2002 04:10 pm, Brad Hards wrote: > On Wed, 6 Nov 2002 08:02, anton wilson wrote: > > I'm trying to understand the possible type errors for ** > > > > The language reference states that > > > > > > The power operator has the same semantics as the built-in pow() function, > > when called with two arguments: it yields its left argument raised to the > > power of its right argument. The numeric arguments are first converted to > > a common type. The result type is that of the arguments after coercion; > > if the result is not expressible in that type (as in raising an integer > > to a negative power, or a negative floating point number to a broken > > power), a TypeError exception is raised. > > Looks like the docs are outdated. I'm not sure about the "broken power" > bit. > It actually causes an error from a source file, only if i use a variable argument to **. so this fails: x = -1 x ** 0.5 but -1 ** -0.5 doesn't. > [bradh at localhost USB-guide-head]$ python > Python 1.5.2 (#1, Jul 5 2001, 03:02:19) [GCC 2.96 20000731 (Red Hat Linux > 7.1 2 on linux-i386 > Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam > > >>> 1**-2 > > Traceback (innermost last): > File "", line 1, in ? > ValueError: integer to the negative power > > >>> -1.2**0.5 > > -1.09544511501 > > bradh at squirt python $ python > Python 2.2.1 (#1, Oct 4 2002, 09:50:49) > [GCC 2.95.3 20010315 (release)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > > >>> 1**-2 > > 1.0 > > >>> -1.2 ** 0.5 > > -1.0954451150103321 > > Brad From max at alcyone.com Sat Nov 23 01:12:11 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 22 Nov 2002 22:12:11 -0800 Subject: Python as first language (Re: static variables?) References: <3DDAFA97.92B70465@alcyone.com> <3DDB3373.2578CEC0@alcyone.com> <8ef9bea6.0211201119.2f846d0c@posting.google.com> <8ef9bea6.0211220601.4c92d43e@posting.google.com> Message-ID: <3DDF1C3B.46BE47BC@alcyone.com> Hung Jung Lu wrote: > It is OK to fantasize the easiness that beginners can understand how > Python work. But it is also good to keep a reality check. People have > faces and names. That's why I selected an example from a start. Please > look over Mr. Erik Max Francis' comments again (and trace to the > original thread.) And tell me why he made the comments he made. (Of > course I am not saying he is right, in fact, anyone who knows Python > well won't agree with his comments. I am simply keeping a reality > check.) The only thing I can conclude from this comment is that you didn't understand the point I was making. Maybe you should try tracing back the original thread yourself. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ The little I know, I owe to my ignorance. \__/ Sacha Guitry Bosskey.net: Counter-Strike / http://www.bosskey.net/cs/ A personal guide to Counter-Strike. From see_reply_address at something.invalid Tue Nov 12 00:31:46 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Tue, 12 Nov 2002 18:31:46 +1300 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCE003C.9080505@mindspring.com> <7h3lm402zq5.fsf@pc150.maths.bris.ac.uk> Message-ID: <3DD09242.9010103@something.invalid> Michael Hudson wrote: > I think the d in cdr stands (stood) for decrement, not data. But the > web seems confused on the issue. It just means "second half of cons > cell" to me... I gather there were also two 3-bit fields interspringled with those, and Lisp originally had functions for accessing those, too... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From dave at boost-consulting.com Fri Nov 8 08:48:19 2002 From: dave at boost-consulting.com (David Abrahams) Date: Fri, 08 Nov 2002 08:48:19 -0500 Subject: Approach to Python extension with C++ References: <3dcb261e$0$15742@echo-01.iinet.net.au> Message-ID: "Nicholas Yue" writes: > I have a need to write Python interfaces to some commercial libraries that > are available on Windows and Linux. > > I have read about the steps to do that in Mark Hammond's Python Programming > book and have also read the extending Python in the Python Essential > Reference (first version). > > I am attempting to write the interface in a cross platform manner, is the > use of Setup.in and compile.py the way to go. > > I am using ActiveState Python 2.2.2 on Windows and probably 2.0/2.1/2.2 on > Linux. > I am writing the interface code in C++. > > What is your advice? Try Boost.Python: http://www.boost.org/libs/python -- David Abrahams dave at boost-consulting.com * http://www.boost-consulting.com Boost support, enhancements, training, and commercial distribution From jepler at unpythonic.net Wed Nov 13 19:57:43 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 13 Nov 2002 18:57:43 -0600 Subject: geometry problem with Tkinter In-Reply-To: References: Message-ID: <20021113185742.A3241@unpythonic.net> On Wed, Nov 13, 2002 at 04:11:32PM -0800, Russell E. Owen wrote: > I've run into a problem displaying a fairly simple geometry; > it displays, but goes into an infinite loop trying to grid everything > (on my display the scroll bar shimmies back and forth a bit and the CPU > usage is high). Dragging the window to a new size stops it. No lockup here. Python 2.3a0 (#1, Jul 13 2002, 09:27:09) >>> root.tk.call("package", "require", "Tk") '8.3' Jeff From uwe.schmitt at procoders.net Thu Nov 21 06:07:41 2002 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 21 Nov 2002 11:07:41 GMT Subject: py2exe/numpy/com-server problem References: Message-ID: Thomas Heller wrote: > Uwe Schmitt writes: >> Hi, >> >> I implemented a COM-Server for a class using NumericalPython (numarray). >> >> If I install the server by 'python server.py --register' everything is fine. >> If I use py2exe or the McMillan installer and call the generated .exe >> in order to (un-)register the COM server, the program crashes. >> >> I use Win2K, Python 2.2 (from Activestate, including win32com), >> and numarray 0.36. >> >> Is this a known bug ? google did not help me. > Maybe a missing numeric dll? Neither py2exe nor installer get them > all, I think. If I remember correctly, multiarray.pyd dynloads > _numpy.pyd (in C code), or something like that. > You should try copying all the Numeric dlls (pyds). Does this help? Thanks for your answer. I tried it, but the program still crashes. Greetings, Uwe. -- Dr. rer. nat. Uwe Schmitt Computer science is no more about Computers, uwe.schmitt at num.uni-sb.de than astronomy is about telescopes. (Dijkstra) http://www.procoders.net From bjornkn at online.no Sat Nov 23 04:36:25 2002 From: bjornkn at online.no (=?ISO-8859-1?Q?Bj=F8rn_K_Nilssen?=) Date: Sat, 23 Nov 2002 10:36:25 +0100 Subject: Confusing list& Test Message-ID: <3DDF5A29.4932.48CE780@localhost> This is just a test to see if I've come to the right place. This list is quite confusing. I first found it on yahoogroups, where I subscribed. Unfortunately I could only get the diget from there (I hate digests..). When I started rceiving those digests I noticed that the Reply-To field was to python-list at cwi.nl, but checking around there, sending mail to python-list- request at cwi.nl with 'help' in the body. After a little web search I found yet anotherr python-list at python.org, which seems to be the same list, and another hit (from 99) said that the cwi.nl list had been moved to python.org. Isn't it about time to get the Reply-To field changed to the correct address? What exactly is that yahoogroups list doing in all this? -- Bjorn K. Nilssen // http://bjornkn.home.online.no/ old 3D stuff// Jegergata 6 N-4616 Kristiansand NORWAY From mwilson at the-wire.com Tue Nov 12 17:31:14 2002 From: mwilson at the-wire.com (Mel Wilson) Date: Tue, 12 Nov 2002 17:31:14 -0500 Subject: pitfall for your amusement References: Message-ID: In article , "Russell E. Owen" wrote: > [ ... ] >If you are collecting pitfalls, here's my least favorite: "never use a >mutable object as a default value". A classic example: > >def badfunc(alist=[]): > ... > >The default value of alist will not stay [] (an empty list) but instead >is affected by whatever you pass in for "alist". Very tricky and >unpleasant. I'm not finding that. Am I misunderstanding something? See below .. Regards. Mel. Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> def f2(dflt=[]): ... return dflt ... >>> f2() [] >>> f2(3) 3 >>> f2() [] >>> f2([1,2]) [1, 2] >>> f2() [] >>> From max at alcyone.com Mon Nov 18 18:31:15 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 18 Nov 2002 15:31:15 -0800 Subject: python lists? References: Message-ID: <3DD97843.5634EFB3@alcyone.com> Dan Stromberg wrote: > So are python lists real lists in the algorithmic sense, or something > more? They're implemented as vectors. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Who's not sat tense before his own heart's curtain? \__/ Rainer Maria Rilke Maths reference / http://www.alcyone.com/max/reference/maths/ A mathematics reference. From robloche at fr.st Wed Nov 20 18:52:44 2002 From: robloche at fr.st (Rodolphe) Date: 20 Nov 2002 23:52:44 GMT Subject: string encoding problem References: Message-ID: >> Could someone help me out with this simple problem ? > > Tk is returning a Unicode object to you. If you want to write that > Unicode object to a byte stream, you need to encode it, e.g. with > > print str.encode("cp1252") > > Regards, > Martin Thanks. Someone pointed me this useful link : http://www.reportlab.com/i18n/python_unicode_tutorial.html I found out the answer to my problem there. Now, when Tk returns a string, say s, I use s.encode('latin-1') to take care of the accents. Thanks to all of you ! -- Rodolphe From ktilton at nyc.rr.com Sat Nov 23 03:26:57 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Sat, 23 Nov 2002 08:26:57 GMT Subject: Newbie Q on searching lists References: <3DDF1673.4020203@nyc.rr.com> Message-ID: <3DDF3C32.4060205@nyc.rr.com> Sean 'Shaleh' Perry wrote: > On Friday 22 November 2002 21:45, Kenny Tilton wrote: > >>I see the index method on lists throws an error if the element sought is >>not found. I was hoping it would return None. >> >>The semantics I am coding happen to throw an error if a certain element >>is found in a list, so i want to code: >> >> if calculators.index[thisCalculator]: >> raise CircularDependency, thisCalculator >> >>1. Am I missing something? >> > > > if calculators.count(thisCalculator): # returns zero if not found > raise CircularDependency, thisCalculator oops :) thx! -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From janto_d at hotmail.com Sun Nov 17 07:58:51 2002 From: janto_d at hotmail.com (Janto Dreijer) Date: 17 Nov 2002 04:58:51 -0800 Subject: popkey() method for dictionaries? References: Message-ID: http://python.org/dev/doc/devel/whatsnew/node12.html Is this what you're looking for? I love that time machine :-) From larrye2000 at hotmail.com Fri Nov 8 18:48:59 2002 From: larrye2000 at hotmail.com (larry) Date: 8 Nov 2002 15:48:59 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: <7b8f89d6.0211081548.f91b468@posting.google.com> oleg_inconnu at myrealbox.com (Oleg) wrote in message news:<3d5b5ad8.0211080454.50bc6128 at posting.google.com>... > Hi > > I don't know much about Python, but I looked at this comparison > between Python and Common Lisp ( > http://www.norvig.com/python-lisp.html ), and I couldn't help but > wonder why Python is popular, while Common Lisp and Scheme aren't? > > Oleg I think the same could be asked about Perl vs Python: Why is Perl so much more popular than Python? Another question that could be asked about Lisp is: Most people it seems have nothing good to say about lisp:"it's hard to read,it's slow, nobody uses it, it's hard to learn etc, etc". Lisp is constantly being bashed and yet Lisp has survived for over 40 years and several companies (Franz, Xanalys, Digitool) seem to make a profit selling lisp compilers. SOMEBODY is using Lisp. If lisp is such a crummy language why has it survived at all for so long? Why do SOME people think Lisp is a fantastic programming langugae? Are we missing something? From david at no.westcontrol.spam.com Fri Nov 1 08:15:34 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Fri, 1 Nov 2002 14:15:34 +0100 Subject: Protect Python Source References: Message-ID: "TuxTrax" wrote in message > > Your comments reveal a thoughtful and curious approach that is quite healthy. > It also reveals a world view that has in large part been shaped by the > philosophies of proprietary software companies. > > Is a python compiler available for linux? I don't know. I do know that no > Linux users I know would even consider using one. It would never cross our > minds to make our source closed to others. This is where the whole open source > software movement takes a completely different world view. In open source > software, you retain the right to make a profit from your work, while still > granting others the right to copy, distribute, modify and view the source > code. Just a year ago, this whole concept was horrifying to me. I could > not concieve of allowing others to have free access to my source code. As > a Long time windows user, I had some un-learning to do. But unlearn I did. > I started thinking in terms of the advantages of open source. First, it keeps > you honest; you write your best code because you know that your peers are > going to be seeing it all over the world. Second, with open source, once > you release it, other programmers may modify it helping it to become more > than you ever could have made it on your own (unless you choose to forbid > the modification of your code, but that's another subject). Third, the > distribution of your product using the open source community, has no equal, > and will cost you nothing. You can provide support to your users via > that same community at little or no cost to you, and support is the number > one ongoing cost that software developers get saddled with. You can use > the resources of such organizations as the free software foundation to > defend your copyright (don't let the "free" in FSF throw you; you can still > market your product using the GPL licence). > > And finally, you get to give something back. This is a philosophical point > for me, but giving something back to the community that you benefit from, > whether it be your local community, or the computer community, is very > important for us as people. It is a common and refreshing view that you > will find in the open source world, and one reason that I left the > windows world for good. But thats a soapbox for another time. > > Cheers, > > Mathew > I think you are making the mistake many "born again" open-source advocates make, and one that many anti-open-source people also make. There is plenty of place in the world for both open and closed source software. In some situations, one is far better than the other, in some cases either will do the job. Saying that everything should be open source is as bad as saying everything should be closed source. It's a common misunderstanding about Linux ("Software companies should not write for Linux because then they would have to give away all their source code..."). Consider, for example, the program I am writing at the moment. It is in Python - a language whose licence is very clear in stating that all Python-licenced code can be used in open and closed source software (keeping copyright messages intact). The program provides a gui for an embedded motor controller card, and our customer is paying good money for me to write the program. He intends to sell the cards on to his customers, with this controller program to go with it. In the future, he will want a bigger version of the program (supporting several cards simultaneously). He may well want to charge his customers for that software upgrade. He certainly won't want his customers to have full access to the code - they may modify it for use with other supplier's motor cards. This is not a program for which either myself or my customer will gain any benifits from releasing it as open source - no one is going to be making improvements to it that will benifit us. However, there are certainly *parts* of the program that could be released seperately. For example, I may seperate out the graphing parts of the gui into a nice, modular graph widget. That could easily be released as open source (Python licence), for the benifit of others and for our own benifit - if people like it, they will contribute improvements which I can then use. If I make any changes or improvements to the pyserial module that I am using, then I certainly will pass those changes back to the community. But by the time I get as far as making distribution copies of the program, I'll be making two sorts of packages - py2exe packages for easy installation on Windows machines, and .pyc byte-code files for use on Linux (and for Windows users who already have Python). I fully agree that there are often direct benifits from making your own software open source. There is also the personal satisfaction factor - I have not written much that could be of direct benifit to others (my job is embedded systems development - you need our company's hardware to run our software), but I have enjoyed the feeling I get from the few direct contributions I have made. But there are many reasons to write closed source code as well. You do not speak for the Linux-using community when you say that writing closed source is against your principles. From a user's viewpoint, open source is definitely an advantage - just like lower cost, better documentation or more functionality is an advantage. But from the writer or sellers viewpoint, it is a mixed blessing which must be considered sensibly - just like the selling price, the level of documentation and the functionality of the software. The aim of all businesses is to make money - preferably by providing good products and services to their customers. If that end can be best achieved by openning their software, great. If it is best achieved by closing their software, then that's the way it is. From pyth at devel.trillke.net Sat Nov 23 12:26:00 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sat, 23 Nov 2002 18:26:00 +0100 Subject: Proposal: min(None, x) and max(None, x) return x In-Reply-To: ; from bokr@oz.net on Sat, Nov 23, 2002 at 03:42:01PM +0000 References: Message-ID: <20021123182600.N11257@prim.han.de> Bengt Richter wrote: > On Fri, 22 Nov 2002 14:53:42 GMT, Andrew Koenig wrote: > > >Eric> So I told myself: wouldn't it be great if max(None, x) or > >Eric> min(None, x) always simply returned x? > > > >My first thought was that this was an excellent idea. > > > >Then I thought again. > > > >Here's the problem: The notion that max(None, x) and min(None, x) > >should both return x is one of three desirable properties that cannot > >all be true at once. Here are the other two: > > > > 1) Whenever x < y, min(x, y) is x and max(x, y) is y. > > > > 2) < is an order relation over all types. > > > >The desirability of (1) should be obvious. (2) is more subtle, but > >it is necessary for it to be possible to sort a vector of heterogenously > >typed objects. > > > >Now, if max(None, x) and min(None, x) both yield x, and (1) is true, > >then x > None and x < None must both be true. But then (2) cannot > >be true. > > > >So the cost of your proposal would be either to break the consistency > >between max/min and >/<, or to render unsortable vectors of values > >that include None. > > > >I don't think it's worth it. > > > How about adding optional keyword args to min and max, so the semantics > would be something like (not very tested ;-): > > >>> class private_sentinel: pass > ... > >>> def mymax(*seq, **kw): > ... exclude = kw.get('exclude', private_sentinel) > ... empty = kw.get('empty', private_sentinel) > ... try: > ... return max(filter(lambda x: not isinstance(x, exclude), seq)) > ... except ValueError: > ... if empty == private_sentinel: raise > ... return empty > ... > >>> mymax(None, 2, 3) > 3 > >>> mymax(None, 2, 3, exclude=(int,type(None)),empty='nothing left') > 'nothing left' > >>> mymax(None, 2, 3,'a string', exclude=(int,type(None)),empty='nothing left') > 'a string' > > (oops, that 'if empty == ...' would have been better as 'if empty is ...') I like this idea! Maybe the common case should be writable as mymax(x, y , exclude=None) and it doesn't introduce significant backward compatibility issues. regards, holger From e_viola at libero.it Fri Nov 15 14:30:02 2002 From: e_viola at libero.it (bart) Date: Fri, 15 Nov 2002 19:30:02 GMT Subject: BUG URLLIB2 References: <3DD43DA7.5070004@libero.it> Message-ID: <3DD54B15.3080001@libero.it> > That's not a bug in urllib2; google.it is *really* returning 403 > FORBIDDEN. > It appears that this google behaviour is triggered by the header > > User-agent: Python-urllib/2.0a1 > > that urllib2 sends, which, in turn, suggests that Google explicitly bans > urllib2. > Complain to them. > > Regards, > Martin > Thanks to all them that helped me swiftly!!! How can I change User-Agent field presents inside "urllib2"? I find two variables that (I think) define user agent in "urllib2" library: "__name__" and "__version__". I tested to set them following way: __name__="Mozzilla" __version__="5.0" but it failed yet!!! Whatever suggest is accept!!! - Ennio Viola - From bwfc10 at aol.com Sat Nov 16 05:12:20 2002 From: bwfc10 at aol.com (Bwfc10) Date: 16 Nov 2002 10:12:20 GMT Subject: quick question Message-ID: <20021116051220.01520.00000047@mb-bk.aol.com> If you were writing a program aking about peoples favourite flavour of ice cream and you input the number of votes for 5 flavours, how do you get your program to display the most popular (the one with the most votes). This may be easy to most of you but i am new to python. Thanks From aleax at aleax.it Tue Nov 19 16:59:35 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 19 Nov 2002 21:59:35 GMT Subject: zero-copy array slicing References: Message-ID: Trevor wrote: > Alex Martelli wrote in message news:> > Is a zero-copy array slicing operation possible? [..] >> >> [..] if this the behavior you need, the simplest way to get it is exactly >> with the Numeric extensions > > Interesting, thanks! However I don't think Numeric or Numarray > support the buffer interface (or come standard with python), which was > my reason for trying to use the array module. Numeric doesn't come standard with Python, but does give you effective ways to 'get a grip' as you request. It also supports the buffer interface: >>> import Numeric >>> x=Numeric.arange(5) >>> buffer(x) >>> but I doubt that's really what you want to use for the purpose you explain. > What I'm trying to do is interface a C cryptography library to python, > so I can encrypt/hash data in as convenient and efficient a way as > possible. I was thinking the buffer interface would be the best way > to get a grip on the contents of strings (for read-only operations > like hashing) and arrays. If arrays had a subsequence() function then > I could efficiently hash or encrypt-in-place parts of arrays: > > bytes = readArrayFromBigFile() > hash(bytes.subsequence(128)) #hash all but some header > encrypt(bytes) #encrypt whole array > encrypt(bytes.subsequence(start, finish)) #encrypt some section You can do that with slices of Numeric.array instances of course -- Numeric IS designed to for power, flexibility, and speed, while the builtin array is designed for light-weight, simple, no-overhead operation. And, the buffer interface is not necessarily best for your purposes. > I'd be willing to try to add this. But maybe I should explore the > solution space more. What would you recommend as the most Pythonic > approach, given these constraints? > - in-place operation on subsequences of bytes, from the C api > - convenient application to different types (e.g. strings, arrays) > - ideally, no dependency on nonstandard libraries (like Numeric) Wouldn't it be simpler if your functions also accepted optional parameters for offset and size in bytes? So the user could call hash(bytes, 128) encrypt(bytes) encrypt(bytes, start, finish-start) ...? Alex From newt_e at blueyonder.co.uk Wed Nov 13 18:18:03 2002 From: newt_e at blueyonder.co.uk (Newt) Date: Wed, 13 Nov 2002 23:18:03 GMT Subject: property problems Message-ID: Hi, I've got a problem trying to use a property in a class module. The class module is listed below (it's called globals.py): class GlobalVars: def __init__(self): self.l_stats = [] return def set_stats(self,val): self.l_stats = val[:] return def get_stats(self): return self.l_stats stats = property(get_stats, set_stats) gv = GlobalVars() I've got a further module which does the following: from globals import gv gv.stats([['Height',self.height],['Build',self.build],['Strength',str]]) However, I get the following error: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python22\lib\lib-tk\Tkinter.py", line 1292, in __call__ return apply(self.func, args) File "D:\py_stuff\curry.py", line 14, in __call__ return self.fun(*(self.pending + args), **kw) File "D:\py_stuff\chaz.py", line 223, in shownext SelectStats(self) File "D:\py_stuff\stats.py", line 46, in __init__ self.do_widgets() File "D:\py_stuff\stats.py", line 208, in do_widgets gv.stats([['Height',self.height],['Build',self.build],['Strength',str]]) TypeError: 'list' object is not callable Could somebody explain to mw what this means, and how to fix it please! Thanks, Newt -------------- next part -------------- An HTML attachment was scrubbed... URL: From sundae1888 at hotmail.com Sat Nov 2 03:33:11 2002 From: sundae1888 at hotmail.com (sundae) Date: 2 Nov 2002 00:33:11 -0800 Subject: Sending null byte to serial port in Windows using PySerial? References: <49f4e27a.0211010930.56788863@posting.google.com> Message-ID: <49f4e27a.0211020033.6d7b66ac@posting.google.com> > > com = serial.Serial("COM1", 9600, timeout=1) > > sidenote: i sugest to use numbers i.e. 0 <-> "COM1" that makes it easier if > you want to run the prog on other platforms or with jython. Portability isn't a big concern for this application (yet), with the ActiveX I'm using, but I'll take your advice. > > com.write(chr(0)) > > well i'm reading and writing null characters en masse. so no problem. the > port is configured for binary data transmition on all platforms. So that *is* the way to send a null byte? I was wondering if I screwed up there (and/or that WriteFile() doesn't support null byte). > > The device should reply a single byte upon receiving this byte, but I > > never got anything in reply. > > well i suspect that something is wrong with your setup. you're sure your > device is connected to the right port and listening with the same baudrate? > you're reading from the port as you expect, you use a timeout. does the > read function return before your device answers? Hm.. then either a) the protocol (including baudrate, etc) is not the same as the manufacturer's specification states; or b) the port timeout before I read... the device is "supposed to be working" in the "other-apps-can-access-it" sense. Since it's easier to test case (b), my question is, would inWaiting() detect a byte even if the timeout is too fast? Thank you again! From grante at visi.com Mon Nov 25 13:56:10 2002 From: grante at visi.com (Grant Edwards) Date: 25 Nov 2002 18:56:10 GMT Subject: Python Tutorial Was: Guido's regrets: filter and map References: Message-ID: In article , David Brown wrote: >> I never liked filter, map and reduce. So don't use them. ;) > I find lambda and map very useful - used carefully, they can be of great > value to the readability of a program (letting you write exactly what you > mean in a short space, without cluttering up the code with unnecessary > "def"s and function names that are not needed). Filter is less useful - > list comprehensions are often easier to read and write. > Reduce is a lot > less useful, because it is a lot less obvious what it is doing. I find both map and filter easily replaced with list comprehensions. How do you replace a reduce call with a list comprehension? -- Grant Edwards grante Yow! World War Three can at be averted by adherence visi.com to a strictly enforced dress code! From jkraska at san.rr.com Wed Nov 27 22:38:29 2002 From: jkraska at san.rr.com (Courageous) Date: Thu, 28 Nov 2002 03:38:29 GMT Subject: if : References: <3DE4102D.7D4291F4@alcyone.com> <3DE58723.5040306@something.invalid> Message-ID: <3o3buus1f8kv1psdps2nsq3ed8ltq5ece8@4ax.com> >This is a special case of the general principle that it's >usually clearer if expressions don't have side effects. Oh, quite true! As a general rule of thumb, I consider expressions with side effects to be bad coding practice. I don't mind at all that Python doesn't allow them. C// From stojek at part-gmbh.de Fri Nov 29 04:08:10 2002 From: stojek at part-gmbh.de (Marcus Stojek) Date: Fri, 29 Nov 2002 09:08:10 GMT Subject: LAN communication under windows References: <3de60530.10377734@news.easynews.net> Message-ID: <3de72dee.86343953@news.easynews.net> Hi, thanks to all of you. I played around with the socket modul and had a look at all the stuff you mentioned. With my overwhelming knowledge I think PYRO is what I need. Thanks again, marcus From fperez528 at yahoo.com Mon Nov 18 04:18:50 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 18 Nov 2002 02:18:50 -0700 Subject: popkey() method for dictionaries? References: Message-ID: Raymond Hettinger wrote: > Do you have use cases demonstrating the value of a default rather than an > exception? Sure. First, on principle: the exception option is still there, if no default is provided. What giving a default buys you is not having to trap the exception yourself. If you want a missing key to generate an exception, simply don't give a default and that's it. Since it doesn't change the existing semantics (the current form doesn't take any arguments, so there can't be any confusion), I think it's a good addition. But you asked for code. Here's an example from a wrapper which needs to filter out a keyword dictionary given to a function before passing it downstream. It needs to remove keywords which won't be understood by the downstream function, but it knows how to make a default decision if the keyword wasn't given: # Filter out other options the original plot doesn't know hardcopy = popkey(keyw,'hardcopy',psargs['filename'] is not None) titles = popkey(keyw,'titles',0) This uses my popkey() function, with the new method it would be simply # Filter out other options the original plot doesn't know hardcopy = keyw.pop('hardcopy',psargs['filename'] is not None) titles = keyw.pop('titles',0) if my suggestion were accepted. I can always live with my popkey() function instead, if the crippled version is left in the language :) What I _won't_ do is use the crippled pop() and wrap things everywhere with explicit try/except blocks. In the end that only hurts readaility and creates bloat. This is part of the Gnuplot wrappers in IPython, if you want to see the full code (or I can give more context). IPython lives at http://www-hep.colorado.edu/~fperez/ipython > Also, discuss why similarity with dict.get() applies instead of symmetry > with list.pop() or dict.popitem(). - list.pop: I wasn't looking when that was written :) But I could argue similarly that an optional default argument would be a sensible, useful addition. No semantic break for existing code, and it saves people setting up try/except traps. - dict.popitem: this one I'm ok with not having a default value, since it is meant to traverse the dict in essentially random order. Adding a default value would be like having a dict_with_default kind of object, which is definitely different from a regular python dict. popitem() returns a k/v pair and is typically used for exhausting a dict destructively, so it makes a lot of sense to break at the end. But pop(key) is much more specific, so I think it is sensible to be able to control its behavior more closely. Just like dict.get(), which allows straight through the function interface one to control what happens to missing keys. Semantically pop(key) is almost like get(key), with the difference that it deletes the k/v entry from the dict. It seems only natural then that pop() would support the same default arg behavior that get() has. Cheers, f. From ktilton at nyc.rr.com Thu Nov 21 13:47:40 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Thu, 21 Nov 2002 18:47:40 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3DDD0699.5080007@nyc.rr.com> Message-ID: <3DDD2AAA.7040201@nyc.rr.com> Alex Martelli wrote: > Dylan has macros too. yeah, but not quite like CL. But I am out of my depth. The gang on c.l.l. would have better answers. One thing I can tell you is that I /love/ during the rather prosaic task of editing being able to instantly select a sexpr small or large, and as one can imagine this tends to come up a lot because sexprs naturally form integrated wadges of semantics. > So isn't "major source" at least an overbid, if "I'm > not far off" in stating that a language with a totally different syntax > can "capture much" of the same capabilities? I was being nice! No, seriously, Dylan has GC, GFs, MI, macros to a degree, static but optional typing -- but no unhygienic macros which can actually be cool, and... I cannot speak for the author of "major source", I wager it comes down to: the list of things one cannot do without sexprs may be short, but they are vital to the spirit of CL. Again, tho, Major Source should speak for themself. :) -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From martin at v.loewis.de Fri Nov 29 15:43:39 2002 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 29 Nov 2002 21:43:39 +0100 Subject: Windows locale: default charset References: <20021129141801.26007.24999.Mailman@mail.python.org> Message-ID: antonmuhin ?? rambler.ru writes: > I want to find out default Windows charset to perform > encoding/decoding of Unicode strings. > > locale module seems of no help---nl_langinfo function that could > provide me with needed info isn't included in ActiveState Python 2.2. > I found no similar functions in win extensions modules either. > > May anybody point me info or snippets? On Windows, locale.getlocale()[1] works well (although it does not work that well on other systems). In Python 2.3, locale.getpreferredencoding will work uniformly on all systems. Regards, Martin From bhards at bigpond.net.au Wed Nov 27 16:09:01 2002 From: bhards at bigpond.net.au (Brad Hards) Date: Thu, 28 Nov 2002 08:09:01 +1100 Subject: do you guys help newbies?? In-Reply-To: References: Message-ID: <200211280809.01424.bhards@bigpond.net.au> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Thu, 28 Nov 2002 07:38, John Hunter wrote: > >>>>> "malik" == malik m writes: > > malik> i didnt to import that yet but i will try even tho i think > malik> the program did what i want it to:) > > What do you think your mpg is if you drive 3 miles on a tank that > holds 2 gallons? What does your program tell you it is ..... How far is a mile? How much is a gallon? Those are not metric measures, and don't have (as much) meaning outside places dominated by American and English culture. Brad - -- http://linux.conf.au. 22-25Jan2003. Perth, Aust. I'm registered. Are you? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE95TRtW6pHgIdAuOMRAiLPAKDCaRoPT21eYLkq+gphF2C9cNlh5QCdH9GF Tl+9GiV4lE86ZpWYBmsDTMg= =IkSn -----END PGP SIGNATURE----- From jorgencederberg at hotmail.com Tue Nov 12 01:53:19 2002 From: jorgencederberg at hotmail.com (=?iso-8859-1?Q?J=F8rgen_Cederberg?=) Date: Tue, 12 Nov 2002 07:53:19 +0100 Subject: Running python on windows. References: <8b58f27c.0211112121.36e0de25@posting.google.com> Message-ID: "kk" wrote in message news:8b58f27c.0211112121.36e0de25 at posting.google.com... > Hi > I am new to python, tried to run python at >>> prompt its giving > syntax error.Any one help me to run python scripts on windows. Hi kk, you should really read the tutorial http://www.python.org/doc/current/tut/tut.html , that is the way I learned Python. Trying out of the things in the prompt and getting a feeling for the syntax and how to write programs in Python. Otherwise you could also try to look at http://www.python.org/doc/Newbies.html . Regards Jorgen From aleax at aleax.it Mon Nov 25 06:15:12 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 25 Nov 2002 11:15:12 GMT Subject: ~~~ Python Use Question ~~~ References: <2a001b6.0211230739.13aaf7c5@posting.google.com> Message-ID: <4DnE9.70284$Yw.3336342@news2.tin.it> Grant Edwards wrote: > BTW, I believe that there are already games on the market that use Python > as a scripting langauge, aren't there? Yes, see for example Bruce Dawson's paper: http://www.gamasutra.com/features/20020821/dawson_pfv.htm Alex From skip at pobox.com Fri Nov 22 17:18:30 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 22 Nov 2002 16:18:30 -0600 Subject: urllib slow on FreeBSD 4.7? sockets too In-Reply-To: <3dddbfef_1@omega.dimensional.com> References: <3ddd8419_3@omega.dimensional.com> <3dddbfef_1@omega.dimensional.com> Message-ID: <15838.44342.601039.771176@montanaro.dyndns.org> >> What happens if you reach into the file wrapper and grab the raw socket? Mike> How do I do that? u.fp is as close as I seem to be able to get. Oops, I guess makefile() doesn't give you an easy way to get back to its host socket. >> Did you build Python with or without pymalloc? Mike> I installed it from the FreeBSD packages collection. If pymalloc Mike> is not normally built-in, then it's probably not in the package. >> Can you try the opposite? Mike> I'd rather not obliterate my current installation, no. You should be able to build from source and run against the not-installed interpreter. The default (unless the FreeBSD folks muck with the configure settings) should be to build --with-pymalloc. -- Skip Montanaro - skip at pobox.com http://www.mojam.com/ http://www.musi-cal.com/ From gerhard.haering at opus-gmbh.net Mon Nov 4 07:45:10 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 4 Nov 2002 12:45:10 GMT Subject: Need simple algorithm for newbie References: Message-ID: Jason Tudisco [2002-11-04 12:33 GMT]: > I have a list of domains... Some of the domain names in the list look > like this: > > groups.goodle.com > > The information I want is just google.com. I need to know the best way > to do this.. for .com .net .org only.. and to strip the rest of the > garbage.. like in this case.. get rid of groups in groups.google.com > > I need to parse though a huge list so it has to be optimized algorithm I did a little experimentation in the interactive interpreter: C:\>python Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x = "groups.google.com" >>> x.split(".") ['groups', 'google', 'com'] >>> x.split(".")[-2:] ['google', 'com'] >>> ".".join(x.split(".")[-2:]) 'google.com' The [-2:] slicing might not be obvious at first - it slices out the last two elements of the list. -- Gerhard From dave at pythonapocrypha.com Thu Nov 7 12:16:58 2002 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 7 Nov 2002 09:16:58 -0800 (PST) Subject: Making a better textbook (was Re: The Deitel book) In-Reply-To: <200211070101.gA711xx03741@localhost.localdomain> Message-ID: On Wed, 6 Nov 2002, Dave Reed wrote: > I've been using Python for my own projects (from short scripts to > 25,000 line apps) for almost three years now and can't imagine using > anything else right for anything that wasn't extremely computationally > expensive. After attending the panel, I talked my other colleagues > into using it for our CS 1 course this fall. The only thing that > bothers me about Python for teaching is the lack of enforced private > members for classes. As an experienced programmer, I can live with > that because I know better, but I don't know whether the students will > believe me when I tell them it's a bad idea to directly access them > outside of classes :-) Who cares if they believe you though, and why should they anyway? Part of becoming a good programmer is getting bit by taking shortcuts (over doing it the "right" way), learning from it, and moving on - and it's a great thing to learn through experience that the prof might actually know what he's talking about! :) > I also suspect this issue may prevent other universities from seriously > considering Python for introductory courses. Yeah, but in reality it shouldn't. Up-and-coming programmers routinely ignore what we consider to be even the most basic best practices. I mean, what first year (or any year, for that matter!) languages force people to use good variable names, limit their use of global variables, avoid magic numbers, and stay away from creating 1000-line functions? Anyway, it was exciting for me to read your observations so far from using Python at the university level, especially the idea that more problem-solving time is being spent in "algorithm space" than "syntax space" (which shouldn't surprise me since that's the experience Python users tend to have). I'd love to hear more of what you learn as time goes on - please keep posting! -Dave From just at xs4all.nl Wed Nov 20 03:38:14 2002 From: just at xs4all.nl (Just) Date: Wed, 20 Nov 2002 09:38:14 +0100 Subject: changing the Python grammar ? References: <2259b0e2.0211181221.2eab9db7@posting.google.com> <7h3zns5vkrf.fsf@pc150.maths.bris.ac.uk> Message-ID: In article <7h3zns5vkrf.fsf at pc150.maths.bris.ac.uk>, Michael Hudson wrote: > mis6 at pitt.edu (Michele Simionato) writes: > > > Browsing on the on-line refencence manual you can find the formal > > definition of the Python grammar: > > http://python.org/doc/current/ref/grammar.txt > > Bear in mind that that is a descriptive grammar. The real one is > Grammar/Grammar in the source distribution. [ ... ] > > Notice that I do NOT want to introduce ugly perlish-like identifiers in > > Python, I simply want to know how much it is possible to customize the > > Python grammar: is this a simple hack or a nightmare ? > > Somewhere between those. As your customizations get more ambitious, > you'll probably find yourself rapidly heading for the "nightmare" end > of that scale. Perhaps it's an idea for the OP to look at the compiler module? I have no experience with it, but I would expect that experiments like this would be more manageble with it. Just From hgg9140 at seanet.com Fri Nov 15 19:30:29 2002 From: hgg9140 at seanet.com (Harry George) Date: 15 Nov 2002 16:30:29 -0800 Subject: module to generate RTF? References: Message-ID: Adam Przybyla writes: > Harry George wrote: > > We need to traverse a database, and generate a Word document. If we > > do that via COM, we are locked into running on a MS WIn** box, so we'd > > prefer to do RTF. I can generate the raw RTF codes inline with write > > statements, but it would be nice if someone had already done some > > syntactic sugar on that. Anything available? > ... XML+python -> docbook -> rtf ;-) Regards > Adam Przybyla I thought of that first. In fact, I even thought of pdx->docbook->rtf. But I chickened out, worried the templates I'll need to splice into will not be (easily) do-able through docbook. You've inspired me to take another look. -- Harry George hgg9140 at seanet.com From ghillie at suse.de Wed Nov 13 11:22:02 2002 From: ghillie at suse.de (Gernot Hillier) Date: Wed, 13 Nov 2002 17:22:02 +0100 Subject: crash (SEGV) in Py_EndInterpreter() in multithreaded program Message-ID: Hi! I experience a 80% reproducable SIGSEGV in a multithreaded app I wrote using different embedded sub interpreters in its threads. I have a C++ class (PClass) which encapsulates the sub-interpreters somehow - it creates a new one in its constructor and deletes it in the destructor (see below). When 2 objects of this class are destroyed at nearly the same time thus resulting in subsequent calls to Py_EndInterpreter(), I get the following SIGSEGV in most cases: > gdb application core.31889 [...] Program terminated with signal 11, Segmentation fault. [...] Reading symbols from /lib/ld-linux.so.2...done. Loaded symbols for /lib/ld-linux.so.2 Reading symbols from /usr/local/lib/python2.2/lib-dynload/time.so...done. Loaded symbols for /usr/local/lib/python2.2/lib-dynload/time.so #0 0x08078763 in class_dealloc (op=0x81a8624) at Objects/classobject.c:169 169 _PyObject_GC_UNTRACK(op); (gdb) bt #0 0x08078763 in class_dealloc (op=0x81a8624) at Objects/classobject.c:169 #1 0x080daefa in PyThreadState_Clear (tstate=0x816b7f0) at Python/pystate.c:190 #2 0x080dab89 in PyInterpreterState_Clear (interp=0x81427e8) at Python/pystate.c:77 #3 0x080dce1e in Py_EndInterpreter (tstate=0x816b7f0) at Python/pythonrun.c:381 #4 0x0805c287 in ~PClass (this=0x81421d0) at pclass.cpp:123 When the 2nd object is destroyed some seconds later, everything seems to be fine. It only crashes when the 2 objects are deleted within a short period of time. I've tried this with the SuSE RPMs of Python 2.2.1 and a self-built Python-2.2.2 with the same result. :-( I've absolutely no clue what goes wrong here. I would appreciate any suggestion where to have a look. Perhaps some of you have an idea... TIA!! Here's a very short snippet of the python related code in my class: // Constructor, initializes Python sub-interpreter PClass::PClass() { PyEval_AcquireLock(); py_state=Py_NewInterpreter(); PyEval_SaveThread(); } // destructor, kills the Python sub-interpreter PClass::~PClass() { PyEval_RestoreThread(py_state); Py_EndInterpreter(py_state); py_state=NULL; PyEval_ReleaseLock(); // release lock } // thread code, runs Python function void PClass::run() { PyEval_RestoreThread(py_state); PyObject_CallFunction(...) PyEval_SaveThread(); } -- Ciao, Gernot From rmunn at pobox.com Mon Nov 25 17:50:41 2002 From: rmunn at pobox.com (Robin Munn) Date: Mon, 25 Nov 2002 22:50:41 GMT Subject: Python IRC dictatorship References: <29304.91T434T13743504threeseas@earthlink.net> Message-ID: Timothy Rue wrote: [Snip a large IRC log] > ThreeSeas I'm a genius... If I can't answer your question I will try and make ^^^^^^^^^^^^^^^ > out that you don't know what you are talking about..... but are there really > 120 users here that hail to ...... dash A free piece of advice for you. It's been my experience, along with the experience of many others, that anybody who claims publicly to be a genius: a) Almost certainly has an ego problem, and b) Usually isn't worth listening to. I'm afraid that you won't find too many people on this newsgroup sympathetic to you until you approach matters with a little humility and begin first by considering the possibility that you might be wrong. If you start by assuming "I'm must be right, therefore anybody who doesn't agree with me is an idiot," you will find that very few people are willing to listen to you. I, in fact, am not one of those people willing to listen to you. If you reply to this message, I won't see your reply; my newsreader will filter it out automatically. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From pieroul at attglobal.net Mon Nov 18 20:37:07 2002 From: pieroul at attglobal.net (Pierre Rouleau) Date: Mon, 18 Nov 2002 20:37:07 -0500 Subject: shutil module References: Message-ID: <3DD995C3.8070401@attglobal.net> Harvey Thomas wrote: >>i wanted to copy a file to another directory so i used the shutil module's copy() function. The name of this file will >>change everyday.eg, events-18-Nov-2002.txt and tomorrow will be events-19-Nov-2002.txt >> >>i used: >>import shutil >>import glob >>shutil.copy (glob.glob(r'c:\winnt\temp\events*'), r'c:\temp') >> >>i couldn't seem to copy the file to c:\temp..it says >>Traceback (most recent call last): >> File "", line 1, in ? >> shutil.copy(glob.glob(r'c:\winnt\temp\events-*'),r'c:\temp') >> File "C:\Python22\lib\shutil.py", line 61, in copy >> dst = os.path.join(dst, os.path.basename(src)) >> File "C:\Python22\Lib\ntpath.py", line 190, in basename >> return split(p)[1] >> File "C:\Python22\Lib\ntpath.py", line 149, in split >> while i and p[i-1] not in '/\\': >>TypeError: 'in ' requires character as left operand >> >>i checked the output of glob and it says >> >>>>>glob.glob(r'c:\winnt\temp\events-*') >>>> >>['c:\\winnt\\temp\\events-18-Nov-2002.txt'] >> >>could it be the double slash that is making the fault....?? >> >>thanks for anyhelp > > > The arguments to shutil.copy are strings - the pathnames of the source and destination files. glob.glob, however, returns a list of strings, as you can see above where you have a list containing one string - > ['c:\\winnt\\temp\\events-18-Nov-2002.txt']. > > So, try (untested) > > for src in glob.glob(r'c:\winnt\temp\events*'): > shutil.copy (src, r'c:\temp') > How about a little function that make sure that you always use forward slashes (even under Windows) called unixpath() and then using shutil.copy() with normal forward slashes (which work in Windows and are more portable) like this: def unixpath(thePath) : """Return a path name that contains Unix separator. [Example] >>> unixpath("d:\\test") 'd:/test' >>> unixpath("d:/test/file.txt") 'd:/test/file.txt' >>> """ thePath = os.path.normpath(thePath) if os.sep == '/': return thePath else: return thePath.replace(os.sep,'/') allFiles = glob.glob('c:/winnt/temp/events*') for index in xrange(len(allFiles)): shutil.copy(unixpath(allFiles[ii]),'c:/temp') -- Pierre Rouleau From max at malva.com.uaREMOVE.IT Thu Nov 28 06:20:41 2002 From: max at malva.com.uaREMOVE.IT (Max Ischenko) Date: Thu, 28 Nov 2002 13:20:41 +0200 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3de1f902$0$695$edfadb0f@dread12.news.tele.dk> Message-ID: <96u4sa.llp.ln@cvs> Robin Munn wrote: [...] > where each indentation level would be a different color (foreground? > background?). I wonder how hard it would be to modify lisp.vim to allow > this? Well, that's not a project I really have time for at the moment; > maybe later on. This's been done already: === from Vim/after/syntax/lisp.vim " lisp.vim: highlights different levels of () with different shades of " grey. Only good for gvim plus lisp " Author: Charles E. Campbell, Jr. " Date: Mar 04, 2002 if has("gui_running") if version < 508 command! -nargs=+ HiLink hi else command! -nargs=+ HiLink hi def endif syn region lispParen1 transparent matchgroup=lispP1 start="(" matchgroup=lispP1 end=")" contains=@lispListCluster,lispParen2 syn region lispParen2 contained transparent matchgroup=lispP2 start="(" matchgroup=lispP2 end=")" contains=@lispListCluster,lispParen3 syn region lispParen3 contained transparent matchgroup=lispP3 start="(" matchgroup=lispP3 end=")" contains=@lispListCluster,lispParen4 syn region lispParen4 contained transparent matchgroup=lispP4 start="(" matchgroup=lispP4 end=")" contains=@lispListCluster,lispParen5 syn region lispParen5 contained transparent matchgroup=lispP5 start="(" matchgroup=lispP5 end=")" contains=@lispListCluster,lispParen6 syn region lispParen6 contained transparent matchgroup=lispP6 start="(" matchgroup=lispP6 end=")" contains=@lispListCluster,lispParen7 syn region lispParen7 contained transparent matchgroup=lispP7 start="(" matchgroup=lispP7 end=")" contains=@lispListCluster,lispParen1 HiLink lispP1 term=NONE cterm=NONE gui=NONE guifg=white HiLink lispP2 term=NONE cterm=NONE gui=NONE guifg=bisque1 HiLink lispP3 term=NONE cterm=NONE gui=NONE guifg=bisque2 HiLink lispP4 term=NONE cterm=NONE gui=NONE guifg=bisque3 HiLink lispP5 term=NONE cterm=NONE gui=NONE guifg=bisque4 HiLink lispP6 term=NONE cterm=NONE gui=NONE guifg=chocolate3 HiLink lispP7 term=NONE cterm=NONE gui=NONE guifg=chocolate4 endif -- The Web site you seek cannot be located but endless others exist. From mcfletch at rogers.com Tue Nov 19 15:29:47 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 19 Nov 2002 15:29:47 -0500 Subject: very large inserts References: Message-ID: <3DDA9F3B.8070609@rogers.com> Isn't that what the executemany method in DBAPI is intended to allow? *executemany*(operation,seq_of_parameters) Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence |seq_of_parameters|. Modules are free to implement this method using multiple calls to the |execute()| method or by using array operations to have the database process the sequence as a whole in one call. That is, the DB may optimise it, or it may have to go through execute, but this is where the optimisation comes if it's available. If I understand correctly, you'd create a parameterised insert: insert = """INSERT INTO table (col1, col2, col3, col4) values (%1, %2, %3, %4)""" And then call executemany( insert, my_values_list ) Good luck, Mike Kempf, Reed wrote: >Hello, > >My name is Reed and I am new to the list as of today. I have been working >with python for about 6 months and I have an issue where I am stumped. > >My background is in python, pl/sql and oracle database management with a >touch of mysql database management. > >Anyway, I know in mysql you can do a bulk insert or an insert where you can >insert many records with one insert statement like this: > >MYSQL - insert into table (col1, col2, col3, col4) > values (1,2,3,4),(2,3,4,5),(3,4,5,6),(4,5,6,7); > >In oracle, you would have to do 1 insert at a time unless you are using >pl/sql in which you can do a bulk insert (as far as I know). > >ORACLE - insert into table (col1, col2, col3, col4) > values (1,2,3,4); > insert into table (col1, col2, col3, col4) > values (2,3,4,5); and so forth....... > >My question is, can python simulate a mysql bulk insert in python? > >I am running a linux distribution 6.2 with kernel 2.4.17 and oracle 8.1.7.4 >patch set. I am also using python 2.1. Currently in my python script I >loop through a python dictionary and build an insert statement which I then >pass through a connection to update oracle and move onto the next python >dictionary key. > >This works but I would sincerely like to build one very large insert >statement and pass it to the oracle connection all at once. This is an >issue for me since I am going through sqlnet and across a VPN to update the >oracle database. The less cursors I pass through the connection, the >better. > >Thanks in advance, > >ReedK > > > > -- _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From aahz at pythoncraft.com Sun Nov 3 10:48:10 2002 From: aahz at pythoncraft.com (Aahz) Date: 3 Nov 2002 10:48:10 -0500 Subject: __coerce__ called for dict keys? References: <3DC02BC8.5020902@NOSPAM-REMOVETHIS-xs4all.nl> Message-ID: In article , Paul D. Lusk wrote: > >I think you need __eq__ rather than __cmp__ in 2.2 Nope. __eq__ gets called before __cmp__, but __cmp__ gets called if __eq__ isn't defined. See PEP 207. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From 2002 at weholt.org Wed Nov 13 15:02:48 2002 From: 2002 at weholt.org (Thomas Weholt) Date: Wed, 13 Nov 2002 21:02:48 +0100 Subject: Referencing Data structures from a different file? References: <3dd2a563$0$28317$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <1fyA9.102$G42.1625@news2.e.nsc.no> in main.py do : import data_structs and use the structures like so : data_structs.your_list.append(1) # or something, and : data_structs.your_dict['a key'] = 'something' or : from data_structs import * and you can access the structures without prefixing them with the module-name; your_list_in_data_structs.append(1) etc. "e-tones.co.uk" wrote in message news:3dd2a563$0$28317$fa0fcedb at lovejoy.zen.co.uk... > Hi all, I have 2 files... > > main.py > data_structs.py > > In data_structs I have a list and a dicionary, how do I make it so main.py > can access these data structures? > > Cheers > Taz > > From writeson at earthlink.net Mon Nov 4 20:24:30 2002 From: writeson at earthlink.net (Doug Farrell) Date: 4 Nov 2002 17:24:30 -0800 Subject: python2.2 and wxPythonGTK problem Message-ID: <88bc63c6.0211041724.17cff049@posting.google.com> Hi all, We just installed RedHat 8.0 on our servers and we're having a problem with Python. The system comes with Python2.2. I installed wxPythonGTK (what's currently available as a binary on wxpython.org) and ran into some trouble. One of our other engineers is working on a system using Python and wxPython for an application. She has been working on Python2.2 (latest release from the python.org site) and wxPython2.3.2.1, which was previously available on the wxpython.org site. Her application worked fine under that setup on RedHat Linux 7.3. However, now the splitter window won't show it's contents with the setup I described above for Linux 8.0 and wxPythonGTK. Does anyone have any idea how I might fix this or what is going on? Thanks, Doug Farrell Scholastic, Inc dfarrell at grolier.com From LogiplexSoftware at earthlink.net Mon Nov 18 19:44:08 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 18 Nov 2002 16:44:08 -0800 Subject: Hmm... An idea: if a,b==c,d: In-Reply-To: <0LeC9.17359$0U1.1724151@news2.east.cox.net> References: <0LeC9.17359$0U1.1724151@news2.east.cox.net> Message-ID: <1037666648.26205.309.camel@software1.logiplex.internal> On Mon, 2002-11-18 at 15:31, Richard Dillingham wrote: > if a,b>c,d: print a > File "", line 1 > if a,b>c,d: print a > ^ > SyntaxError: invalid syntax > > > Consider that when interpreting tuples as coordinates, (1,2) == (2,1) is > probably true since... > > That's not what I want at all, either. 1,2 == 2,1? Eh? Uh. That's not the > same point. It would depend upon how you look at it. They have the same absolute value (i.e. their distance from (0, 0)). Hence if you were to define comparison operators for coordinates (which might be used in sorting, for instance) this is a perfectly valid assumption (otherwise is (2,1) > (1,2)?). > I'm temporarily storing mouse coordinates and comparing with old ones to > determine why I seem to be getting the mouse moved mesage when the mouse > coordinates haven't actually changed yet, among other things (In PyGame). I > was just thinking that the if statement would be shorter and still > understandable if done using commas, like assignment can be. That's all. In that case, it seems you only need to know if they are the same point, not whether one is "greater than" the other (your example of a,b>c,d is misleading in this respect). I would just use if (a,b) != (c,d): # mouse moved ... -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 -------------- 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 camhorn at mac.com Wed Nov 13 15:37:28 2002 From: camhorn at mac.com (Cameron Horn) Date: Wed, 13 Nov 2002 12:37:28 -0800 (PST) Subject: My (late) beef with Simple Generator syntax (PEP 255) Message-ID: <2458268.1037219848120.JavaMail.camhorn@mac.com> If I want to write an empty class, I do this: class foo: pass If I want to write an empty function, I write this: def foo(): pass -or- def foo(): return If I want to write an empty generator, I write this(?): def foo(): return yield "never" Assuming that having an empty generator is as valid as empty functions and classes, what kind of linguistic cruft is that? I expect better out of python, dang it. What I'd like to write is: gen foo(): return From Marten.Bauer at gmx.net Sat Nov 16 07:25:13 2002 From: Marten.Bauer at gmx.net (Marten Bauer) Date: Sat, 16 Nov 2002 13:25:13 +0100 Subject: Python instead of php Message-ID: Hello to ya all, i use python for programming a database (postgresql) project. The Systeminterfaces are written in python and the Userinterface (web based) is written in html/php. Is it possible to use python like php as script language to writte the Userinterfaces also in html and python? Is modpython for apache or Twisted from Tweak Labroratory a possible way? Thanks for helping Marten From rjones at ekit-inc.com Wed Nov 20 21:14:15 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Thu, 21 Nov 2002 13:14:15 +1100 Subject: [updates] PEP 301 -- Package Index and Metadata for Distutils Message-ID: <200211211314.15032.rjones@ekit-inc.com> [if you reply to this message, please only reply to one of the mailing lists!] Hi everyone, PEP 301 has been updated: - changes to the success/failure indicators used by the register.py command. Originally I had copied the idea of using X-PyPI-* headers from PEP 243. Upon advice from Greg Stein, I have switched to using HTTP response codes. - clarifications to Roles - added PKG-INFO upload interface - included overview of online index database schema - updated deliverables in the Reference Implementation section - included implememtation detail for "classifiers" keyword - have implemented the trove classifiers, so various parts of the PEP to reflect reality Also, the web interface and register distutils command have had some development work too: - added Trove metadata to the database, including registration of it, verification and dumping - added "latest stable" release field (unused at the moment) - handle multiline descriptions in PKG-INFO uploads (yay for the email package) - switched from X-Pypi-* headers to HTTP response codes as per PEP - lots of HTML interface cleaning including better stylesheet usage and a nicer navigation bar, better support for logging in and out and finally a single place to go for submitting information There's still a bit to do, but I'd rather wait until I know whether the PEP is to be accepted or not before I start applying spit-n-polish :) Links: PEP: http://www.python.org/peps/pep-0301.html Web: http://www.amk.ca/cgi-bin/pypi.cgi Richard From camhorn at mac.com Wed Nov 13 21:19:52 2002 From: camhorn at mac.com (Cameron Horn) Date: Wed, 13 Nov 2002 21:19:52 -0500 Subject: My (late) beef with Simple Generator syntax (PEP 255) In-Reply-To: Message-ID: <8ED7AF07-F777-11D6-A0F4-000A27B49144@mac.com> On Wednesday, November 13, 2002, at 08:17 PM, Terry Reedy wrote: > > "Cameron Horn" wrote in message > news:mailman.1037219902.17042.python-list at python.org... >> If I want to write an empty generator, I write this(?): >> def foo(): >> return >> yield "never" >> >> Assuming that having an empty generator is as valid as empty > functions and classes, >> what kind of linguistic cruft is that? I expect better out of > python, dang it. > > I challenge the assumption. A generator, by definition, is a > (nonempty) function (and not a separate generator type) that returns > an iterator with __iter__ and next methods. I agree, sort of. The thing is that the implementation seems designed to let you ignore all those iteration details in most simple cases. I just find it weird that writing the simplest possible generator, the one that iterates over no elements, either requires that you write that bit of nonsense above or know enough about the implementation to return an empty iterator. Do you think that a generator that returns an empty iterator (i.e., one that has no elements, as written above) isn't valid or useful? Or that as written above doesn't make such a generator? From cnetzer at mail.arc.nasa.gov Fri Nov 22 18:42:21 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Fri, 22 Nov 2002 15:42:21 -0800 Subject: Proposal: min(None, x) and max(None, x) return x In-Reply-To: References: Message-ID: <200211222342.PAA10255@mail.arc.nasa.gov> On Friday 22 November 2002 14:57, Alex Martelli wrote: > perhaps a slightly better expression of the same idea might be... > > _xMax = [] > for -whatever-: > -big calculation leading to a value of x- > _xMax = [max([x]+_xMax)] > xMax = _xMax[0] Thanks. I knew if I posted this, someone would follow up with an improved way of doing it (I didn't like the .append() myself, and overlooked list concatenation). Note that I put the 'xMax' assignment in the loop (assuming that's what the original poster required); otherwise you can avoid typing '_xMax': xMax = [] for -whatever-: -big calculation leading to a value of x- xMax = [max([x]+xMax)] xMax = xMax[0] -- Bay Area Python Interest Group - http://www.baypiggies.net/ Chad Netzer cnetzer at mail.arc.nasa.gov From mark.charsley at REMOVE_THIS.radioscape.com Thu Nov 7 13:01:00 2002 From: mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) Date: Thu, 7 Nov 2002 18:01 +0000 (GMT Standard Time) Subject: Asking a user for the root password and executing root only c ommands... References: Message-ID: In article , bokr at oz.net (Bengt Richter) wrote: > >> but by default any doorknob rattler could kick it off with > > ctrl-alt-del > >> without being asked for a password. Not a cool default config IMO ;-/ > > > >Thus providing anyone with accesss to the console's power switch a > more >computer-friendly way of rebooting a locked-up machine than > power-cycling >it. > It's a bit too friendly for my taste ;-) I accidentally did it too many > times, > because I am used to the the keying pattern to get past the locking > screensaver > on my NT box, so when I turn to the linux box I just do the same if I > am at all > distracted. Ah I thought you were arguing that the three fingered salute resetting a linux box was a security hole. IMO it's at least as valid to complain about win32 changing the meaning of C-A-D from "reset the machine" as it is to complain about linux maintaining that meaning. Mark From martin at v.loewis.de Fri Nov 15 12:07:45 2002 From: martin at v.loewis.de (Martin v. Löwis) Date: Fri, 15 Nov 2002 18:07:45 +0100 Subject: BUG URLLIB2 References: <3DD43DA7.5070004@libero.it> Message-ID: "bart" wrote in message news:3DD43DA7.5070004 at libero.it... > I'm an italian student and my problem consists about urllib2; urlopen > function, sometimes, give me old (and inexactly) url because the site > has moved in a new location but urlopen doesn't undestand it and return > 403 error FORBIDDEN. That's not a bug in urllib2; google.it is *really* returning 403 FORBIDDEN. It appears that this google behaviour is triggered by the header User-agent: Python-urllib/2.0a1 that urllib2 sends, which, in turn, suggests that Google explicitly bans urllib2. Complain to them. Regards, Martin From rcanderso at yahoo.com Wed Nov 6 15:14:44 2002 From: rcanderso at yahoo.com (rcandersonmn) Date: 6 Nov 2002 12:14:44 -0800 Subject: Zope CMF problem Message-ID: <4c0586a2.0211061214.2bb684dd@posting.google.com> We have setup a new Zope/CMF site with hopes of testing the capabilities of CMF. We are having trouble logging into user-accounts setup with the role of reviewer. After entering user name, password, and hitting submit - the screen redirects back to the login screen with no error statement about bad user name or password. This seems to be a problem out of the box. Any advice would be welcomed. -Ryan From aleax at aleax.it Mon Nov 4 11:01:19 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 04 Nov 2002 16:01:19 GMT Subject: problem's with strings References: Message-ID: Richard Mertens wrote: > first problem: > > I'd like to convert a text-file von unix to windows and vice versa > > Do you know a solution for this > > > When the python script is reading the text-file i have always the Nextline > - Character on the end. How do you I remove it? When you open a file without specifying whether it's text or binary, Python considers it text by default. "text" means that: when reading, the platform-typical line termination combination (\n on Unix, \r on Mac, \r\n on Windows) gets changed into a single line-termination character \n -- when writing, each line-termination character \n gets changed into the platform-typical like termination combination, as above. Use 'rb' (for reading) or 'wb' (for writing) as the second argument to built-in function open if you want to open a file as binary, i.e., without any translation being effected, on neither reading nor writing, to any line-termination character or combination of characters. Note therefore than: -- opening with options 'rb' or 'wb' is the only way to get identical behavior, for a file seen as a given sequence of bytes, independently of what platform you're running on; -- on Unix, there is no difference in behavior whether you open a file as text or binary (because \n is both the conventional line-termination character, AND the way in which line termination is indicated in Unix text files). You don't mention the Macintosh, therefore I assume you are only interested in Unix and Windows platforms. One way to read a file (no matter whether it's using Unix or Windows conventions) into a list of strings, one per line, is for example as follows: lines = open('thefile','rb').read().replace('\r','').splitlines() the .replace part removes any carriage returns that might be in the file, leaving \n as the separator between lines; the .splitlines then forms a list of strings, one per lines (without the line-separators; if you want the \n separator to be left at the end of each string, call .splitlines(1) instead of just .splitlines() at the end). This is only suitable if your file is small enough to fit quite comfortably in memory, of course. Similarly, given a list of lines, one per string and without line termination character, to write them out as a Unix-format text file, whatever platform you're running on: open('thefile','wb').write('\n'.join(lines)) and to write them as a Windows-format text files instead: open('thefile','wb').write('\r\n'.join(lines)) Many other approaches can be preferable depending on several parameters of which you don't inform us, such as -- what platform[s] is/are your script[s] running on, are the files too huge to fit in memory comfortably all at once, do you know when you're reading/writing a textfile in Windows/Unix format and running on what platform[s] or must you be prepared for any eventuality, and so on. I trust that the information in this post can be of help to you in any case. Alex From bebert at tiscali.dk Fri Nov 22 17:58:40 2002 From: bebert at tiscali.dk (Bjarke Dahl Ebert) Date: Fri, 22 Nov 2002 23:58:40 +0100 Subject: Iteration of strings Message-ID: When writing small scripts in Python, I often make the same error: Some function expects a list of strings, and does something like for elem in thestringlist: ... Often, this function is somehow called with a string, instead of a list of strings. This is unfortunate, because in a sense, a string is also a list of strings! I.e., for x in strlist: print repr(x) will print the eight strings: "A" " " "s" "t" "r" "i" "n" "g" if I happen to pass "A string" in as parameter 'strlist'. I started wondering if is anything to do about it. So I made a small analysis of the ways in which a string looks like a container of strings. - len(X) will return the number of elements (which are also strings) - X[i] will return the i'th element - a string. - iter(X) will iterate over characters (i.e., strings). - and therefore, the 'for' construct will accept a string to iterate over. - In a sense, X[i:j] will even look like the list [X[i]...X[j-1]] of strings. Of these, I consider "iter(mystring)" to be the biggest problem in practice. In many ways, 'ABC' works just like ['A', 'B', 'C'], when I would rather think of 'ABC' as an atom. Possible "fixes": - Make iter("abc") a TypeError. Since iter(X) iterates over anything that implements the X[i] protocol, 'str' would probably have to implement the iterator-protocol by raising a TypeError. The iter(str) feature could be replaced by a more explicit str.iterchars() if one really wants to iterate over the characters. - Or at least make iter(str) issue a warning (optionally) - (more radical:) Make a distinct char type with the following properties: - doesn't work in arithmetic expressions (because characters are not numbers) - doesn't work in string concatenation, without explicit str(mychar) A string should then of course be a char container, instead of effectively a container of strings. I like the first best. The last has the drawback of still allowing for s in strlist: ..."%s"%s when strlist is a string. I think the current situation makes the described script bug ("for x in strlist:" when strlist is a string) pass too silently. Often it results in code that "works", because a string is effectively also a list of strings. What do you think? Kind regards, Bjarke From bloke at ii.net Sun Nov 3 11:39:43 2002 From: bloke at ii.net (Rob Hall) Date: Mon, 4 Nov 2002 00:39:43 +0800 Subject: pyqt rules Message-ID: <3dc550fb$0$9008@echo-01.iinet.net.au> Well I've been tinkering with pyqt for a few days now. I must say it is excellent. Developing a gui takes next to no time! And I love the signal/slot mechanism. Piec of cake!! Rog From aleax at aleax.it Tue Nov 19 10:39:14 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 19 Nov 2002 15:39:14 GMT Subject: matching multiple regexs to a single line... References: Message-ID: Alexander Sendzimir wrote: ... > regexs = [ > ( 'regex_id1', sre.compile( r'regex1' ) ), > ( 'regex_id2', sre.compile( r'regex2' ) ), > ( 'regex_id3', sre.compile( r'regex3' ) ), Not sure why you're using sre here instead of re. Anyway, a MUCH faster way is to build a single RE pattern by: onerepat = '(' + ')|('.join([r.pattern for n, r in regexs]) + ')' onere = re.compile(onerepat) of course, it would be even faster without that wasteful compile to put the compiled-re into regexs followed by having to use the r.pattern attribute to recover the starting pattern, but anyway... Then, bind matchobj = onere.match(line) and check matchobj.lastindex. This doesn't work if the patterns define groups of their own, but a slightly more sophisticated approach can help -- use _named_ groups for the join... Akex From jef.mangelschots at iname.com Fri Nov 15 22:04:17 2002 From: jef.mangelschots at iname.com (Jef Mangelschots) Date: Sat, 16 Nov 2002 03:04:17 GMT Subject: redirecting output from spawned processes References: <3dd53e37.86527109@news.genuity.net> Message-ID: <3dd5b449.116753437@news.genuity.net> I know about os.system() and have done that. I use this to run some long duration processing command-line tools which I run overnight. I used os.system() for this, for wich I redirected the output to a log-file. But I noticed repeatedly in the morning that my script misteriously stopped in the middle of processing. I had the impression that running these tools from os.system() somehow messes up things. I was hoping that spawn() would keep my running process intact, even if the called processes fail somehow. But then it was not obvious to me how to redirect output from my process to a log-file. On Fri, 15 Nov 2002 12:28:09 -0800, Trent Mick wrote: >[Jef Mangelschots wrote] >> How do I redirect the output of 'someapp' to the file log_file ? >> >> >> log_file = 'c:\output.log' >> >> os.spawnv(os.P_WAIT, 'some_app', 'p1', 'p2') > >A couple of ways: > > os.system("someapp > %s" % log_file) > >or: > > # get the output > fout = os.popen(someapp) > output = fout.read() > fout.close() > > # then write it to your file > flog = open(log_file, 'w') > flog.write(output) > flog.close() > >I think you want the former though. To redirect stderr as well you need >to do a little bit more work: > > os.system("someapp > %s 2>&1" % log_file) > >or: > > ... look at os.popen3() > > >Cheers, >Trent > >-- >Trent Mick >TrentM at ActiveState.com > From wilk-spamout at flibuste.net Sat Nov 30 04:53:04 2002 From: wilk-spamout at flibuste.net (William) Date: 30 Nov 2002 10:53:04 +0100 Subject: catch output of threads References: <87of88723i.fsf@flibuste.net> Message-ID: <87u1hz75a7.fsf@flibuste.net> Jeff Epler writes: > You can make sys.stdout an object which uses thread.get_ident() to do > "something special" with data written depending on what thread wrote it. Thanks, really brilliant idea ! > > "ThreadedOutputThing" just prefixes all lines of output with the > thread ID. "ThreadedOuputThing2" creates files that contain the PID > and TID. TOT2 keeps a cache of open file objects, but never has more > than ten open at once. > > You could do other things, depending on your needs. > > Jeff > > import sys, thread, time, os > > class ThreadedOutputThing: > def __init__(self, f = sys.stdout): > self.f = f > > def write(self, s): > i = thread.get_ident() > print >>self.f, "Thread %5d: %r" % (i, s) > > class ThreadedOutputThing2: > def __init__(self, b = "%d-%%d.out" % os.getpid(), of="a"): > self.b = b > self.of = of > self.d = {} > > def write(self, s): > i = thread.get_ident() > d = self.d > if not d.has_key(i): > if len(d) > 10: > d.popitem()[1].close() > d[i] = open(self.b % i, self.of) > d[i].write(s) > > def f(): > print "In function f, thread %d" % thread.get_ident() > > if __name__ == '__main__': > #sys.stdout = ThreadedOutputThing() > sys.stdout = ThreadedOutputThing2() > thread.start_new_thread(f, ()) > thread.start_new_thread(f, ()) > thread.start_new_thread(f, ()) > time.sleep(1) > -- William Dode - http://flibuste.net From see_reply_address at something.invalid Thu Nov 28 17:33:28 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 29 Nov 2002 11:33:28 +1300 Subject: Issue with new-style classes and operators References: <3DE215D1.D9A3FEF9@jandecaluwe.com> <5ApE9.52343$744.1917235@news1.tin.it> <3DE49BB7.80D199FB@jandecaluwe.com> <3DE592FC.6020101@something.invalid> <3DE5DDFB.ED92B656@jandecaluwe.com> Message-ID: <3DE699B8.6040208@something.invalid> Jan Decaluwe wrote: > > PEP 254 is a piece of cake! > http://www.python.org/peps/pep-0254.html Oops, sorry, that should have been PEPS 252 and 253. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From nas at python.ca Mon Nov 18 16:58:59 2002 From: nas at python.ca (Neil Schemenauer) Date: Mon, 18 Nov 2002 13:58:59 -0800 Subject: tempfile.mktemp() and symlink attacks In-Reply-To: References: <3ygu9.105734$La5.330766@rwcrnsc52.ops.asp.att.net> Message-ID: <20021118215859.GA8058@glacier.arctrix.com> Aahz wrote: > [I'm reposting this because nobody followed up to it. I tried doing > some research because I know there have been changed for Python 2.3, but > I wasn't able to find the relevant posts on python-dev.] > > In article <3ygu9.105734$La5.330766 at rwcrnsc52.ops.asp.att.net>, > Kent Hu wrote: > >Is using tempfile.mktemp() vulnerable to symlink attacks? Yes. mktemp() just gives you a name. Someone nasty could create a symlink with that name before you. You should open the file using: os.open(name, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700) tempfile.TemporaryFile already does this. 2.3 has a handy function called mkstemp that returns a name and an open file descriptor. HTH, Neil From boud at valdyas.org Sat Nov 2 05:14:39 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Sat, 02 Nov 2002 11:14:39 +0100 Subject: Foot in mouth disease References: Message-ID: <3dc3a6fd$0$84999$e4fe514c@dreader7.news.xs4all.nl> Aahz wrote: > So I've been having a friendly argument for a long time with a friend of > mine who's a real Java booster. The current iteration was sparked by a > discussion of extreme programming, where along the way I repeated what > some people here have mentioned about Python being easier to refactor > than Java. She asked me what -- if any -- Java-based tools were used by > the experienced Java programmers who made that claim. She thinks that > those tools are superior to plain text editors (which are really all > that's needed for Python). > I've tried the various Emacs packages for refactoring -- forgot the names -- java, and I didn't like it. With Java, refactoring is, for me, mostly a matter of renaming, moving stuff and deleting stuff. Jikes will tell me what to do next. Having the Antipatterns book helps in refactoring Java, too. With Python, I'm using grep as my main refactoring tool -- but I'm trying really hard to get into the habit of using bicyclerepairman (from emacs), which seems superior the Java tools I have used. -- Boudewijn Rempt | http://www.valdyas.org From zimmermann.edv at t-online.de Fri Nov 22 11:43:16 2002 From: zimmermann.edv at t-online.de (Bernd Zimmermann) Date: Fri, 22 Nov 2002 17:43:16 +0100 Subject: ctypes and delphi dll References: Message-ID: Thomas Heller wrote: > Should ctypes support the pascal calling convention 'natively'? > Maybe later... Thank you for your work on ctypes and for picking up this issue, Thomas. Calling this Delphi DLL Procedure, declared as 'PASCAL', from Visual C++ 6.0, I had to re-arrange the arguments too. So 'ctypes' is in good company - and - compatible :-) Bernd From Robert_NJ_Sykes at msn.co.uk Tue Nov 19 12:23:38 2002 From: Robert_NJ_Sykes at msn.co.uk (Rob Sykes) Date: 19 Nov 2002 17:23:38 GMT Subject: COM interfaces and inheritance References: <3DDA31DA.D230CCB8@hotmail.com> Message-ID: Alan Kennedy wrote in news:3DDA31DA.D230CCB8 at hotmail.com: > Rob Sykes wrote: > >> I'm having a problem with a (3rd party) IDispatch interface > >> I'm struggling with the upcasting(?) - in Delphi there is >> newBar := CreateFoo() as bar >> >> What is the Python equivalent ? > > There is no casting in python. All resolution of attribute and > method names takes place at execution time. I knew that, i knew that, i knew that It was being to forced to think in Delphi that threw me. The 'as' operator works differently for COM objects (on the lines you have explained else-thread) than for bog-standard classes. Cheers, -- Rob Sykes Born again Bairn | 'The despair I can live with. rob at john-richard dot co dot uk | It's the hope I can't stand' (header email for spambots) | (Anon.) From CousinStanley at HotMail.com Wed Nov 13 19:03:50 2002 From: CousinStanley at HotMail.com (Cousin Stanley) Date: Wed, 13 Nov 2002 17:03:50 -0700 Subject: calendar modules References: <7396d2b2.0211131136.160ee567@posting.google.com> Message-ID: || I tried. But checking the day of the week I was born || didn't work. This calendar seems limited to >= 1970-01-01 It seems there is also a future limit ... ( 1970 , 01 ) <= ( iYear , iMonth ) <= ( 2038 , 01 ) Cousin Stanley From costanza at web.de Sun Nov 10 09:01:48 2002 From: costanza at web.de (Pascal Costanza) Date: Sun, 10 Nov 2002 15:01:48 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h3k7jlwock.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson wrote: > Did you know that s-exps (i.e. the paren heavy Lisp we know today) was > intended to be a temporary syntax, and that John McCarthy intended to > develop a more familiar syntax for Lisp? Somehow he never did -- > maybe because it turned out to be a bad idea? He did. But the programmers who were already using Lisp didn't accept the new syntax. They preferred s-exps. Pascal -- Given any rule, however ?fundamental? or ?necessary? for science, there are always circumstances when it is advisable not only to ignore the rule, but to adopt its opposite. - Paul Feyerabend From maney at pobox.com Wed Nov 27 15:53:32 2002 From: maney at pobox.com (maney at pobox.com) Date: Wed, 27 Nov 2002 20:53:32 +0000 (UTC) Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3de1f902$0$695$edfadb0f@dread12.news.tele.dk> Message-ID: Courageous wrote: > One of Lisp's _lethal_ failings is that anyone not using Emacs (or > something like Emacs) is a second class citizen. The decision to > require a programmer to use a special editor is a fatal one. But perhaps an unavoidable one. This discussion has been quite enlightening to me. Despite all that I have read over the years, including at least two serious attempts with what were said to be good texts for learning Lisp, I have never before seen the true reason Lisp's annoying parentheses-plagued syntax has persisted, let alone why it might be worth putting up with. So now it seems entirely reasonable that it would take a very language-sensitive editor to make what is basically a representation of compiler-internal parse trees readable by normal humans; likewise, I can see why Lisp is so often generated or modified by other Lisp code - after all, compilers use parse trees as an internal representation exactly because they are convenient for programmatic transformations. I'm not sure that knowing this will actually be of much use, should I attempt to scale Lisp once again, but it might at least help allay the frustration that has led me to abandon previous attempts. OTOH, Emacs is another thing off of which I have repeatedly bounced, so maybe it's a lost cause. :-/ From jdhunter at nitace.bsd.uchicago.edu Sun Nov 17 14:54:02 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Sun, 17 Nov 2002 13:54:02 -0600 Subject: learning python and what i need ?help please In-Reply-To: <20021117143159.08975.00000149@mb-fo.aol.com> (jaykay2199113223@aol.com's message of "17 Nov 2002 19:31:59 GMT") References: <20021117143159.08975.00000149@mb-fo.aol.com> Message-ID: >>>>> "Jaykay2199113223" == Jaykay2199113223 writes: Jaykay2199113223> hi there i need advice on what i need to begin Jaykay2199113223> to learn python,do i need to download a Jaykay2199113223> compiler,if so any preferences you could tell to Jaykay2199113223> use and anyother advise thanx stevie Start here: http://python.org/doc/Newbies.html -- download links for the python interpreter are here and lots of other newbie info and here: http://python.org/doc/current/tut/tut.html --the official python tutorial Good luck, John Hunter From tdelaney at avaya.com Sat Nov 23 20:14:21 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Sun, 24 Nov 2002 12:14:21 +1100 Subject: ~~~ Python Use Question ~~~ Message-ID: > From: Terry Reedy [mailto:tjreedy at udel.edu] > > mod editing. I think GPG, for instance, blew it when they designed > and implemented yet another scripting language for Dungeon Siege > instead of using Python (and putting more work into the game itself). Well, if you mean they blew it because they didn't have enough time to produce and interesting game, then yes. Dungeon Siege was one of the mos boring games I've ever tried to play. It is one of the *very* few games I took back. To the original poster - make games like Fallout 1/2 and Arcanum :) Tim Delaney From aleax at aleax.it Thu Nov 21 12:43:03 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 21 Nov 2002 17:43:03 GMT Subject: Redirect question References: <3DD7F71E.9050807@attglobal.net> Message-ID: Karsten Weinert wrote: > Well, after solving my error in the Redirect class with all your help, > I now encountered a new problem. Here is the program: > > import sys, win32ui > > class Redirect: > def __init__(self): > self.s="" > def write(self, s): > self.s+=s > def flush(self): > win32ui.MessageBox(self.s) > > sys.stdout = Redirect() > sys.stderr = Redirect() > print 'Hidey Ho' > print "Hidey hidey hidey ho" > sys.stdout.flush() # is displayed > # from here, no output is produced, e.g. no messagebox > assert 1==0, "Impossible Assertion" > sys.stderr.flush() > > What am I doing wrong? Enclosing the assert statement with try/finally > or try/except only displays an empty message box. > > Kind regards, > Karsten The sys.stderr.flush call can never execute, since it follows a statement that raises an exception. To follow in more detail what is happening, I suggest you add print calls (to sys.__stdout__ for example, to make sure they're going to get out) tracing the behaviour of self.s in Redirect's methods, and run the whole script via python.exe, not pythonw.exe, from a console (aka "Dos Box"). Alex From martin at v.loewis.de Thu Nov 21 18:36:08 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 22 Nov 2002 00:36:08 +0100 Subject: To GC or not to GC? References: <3DDD4751.9050807@nyc.rr.com> <3DDD5E90.8070500@nyc.rr.com> Message-ID: Kenny Tilton writes: > Sorry, I looked at Python years ago and thought I saw /manual/ ref > counting, but maybe that was just the stuff done by C code (which I > understand is ineluctable). Ah, yes. Refcounting in C code is still required from extension writers; all alternatives to it would also require cooperation from extension writers in some way. There was never a need to do explicit refcounting in Python source code. Regards, Martin From pyth at devel.trillke.net Wed Nov 6 11:44:06 2002 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 6 Nov 2002 17:44:06 +0100 Subject: A vision for Parrot In-Reply-To: <3DC943CF.84A68F32@san.rr.com>; from dnew@san.rr.com on Wed, Nov 06, 2002 at 04:31:10PM +0000 References: <20021105221004.339206f3.occitan@esperanto.org> <3DC8623B.88753C16@earthlink.net> <3DC8CDDD.7050103@mindspring.com> <3pE8dhAtvNy9EwoQ@jessikat.fsnet.co.uk> <3DC943CF.84A68F32@san.rr.com> Message-ID: <20021106174406.W30315@prim.han.de> Darren New wrote: > Robin Becker wrote: > > Funnily enough they kept telling me that as soon as I switched to > > F99/C++ etc etc that everything would be portable. > > Your confusion is in thinking that "portable" is a binary value. Fortran > was certainly more portable than assembler, as was C. Tcl is certainly > more portable than Fortran or C. > > The other problem, of course, is that people keep improving their > capabilities, so what was portable is no longer adequate. Fortran is > quite portable, as long as you don't want to do 3D graphics driven by a > data glove. > > As long as you don't want to do development in multiple languages or > dynamically load code safely over the net into some other OS process, > Tcl and Python are pretty good choices. Otherwise, you might want to > consider C# or Java. you can "dynamically load code safely over the net into some other OS process" with python, too. Where do you see the problem? with the other point (developing in multiple languages) i fully agree. Although C/C++ and Java seem to be pretty well integratable with python. I wonder if it would be possible to modify/extend the python-VM to allow for "efficient" execution of C#. We would be set, then, wouldn't we? regards, holger From hancock at anansispaceworks.com Wed Nov 27 23:23:44 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 27 Nov 2002 20:23:44 -0800 Subject: if : In-Reply-To: <20021128040602.16994.73970.Mailman@mail.python.org> References: <20021128040602.16994.73970.Mailman@mail.python.org> Message-ID: On Wednesday 27 November 2002 08:06 pm, Greg Ewing wrote: > maney at pobox.com wrote: > >?Dave Brueck wrote: > >>proof that the language is broken in that area. We don't say, "Is Tuesday > >>today?" or "Is 5 your age?", either. :) > >?Is it Tuesday today? > But these sound *really* odd: > > ? ?Is Tuesday it today? > > ? ?Tuesday is it. > > Some people insist that the verb "to be" should take > the same case before and after, e.g. "I am he" and > not "I am him". But I offer these as evidence that, > in English at least, this verb is NOT symmetrical! Reminds me of Japanese class -- the distinction between "Is Tuesday today?" and "Is today Tuesday?" is significant by what it contrasts against -- are you asking if "today" is Tuesday or some other day, OR if "Tuesday" is today or some other day (such as "tomorrow"). Suppose the answer is negative and explained -- the answer to the first question might be "No, Tuesday is the day after tomorrow." while the answer to the second is "No, today is Sunday." The first sounds odd taken out of context, because the second is more common. On the other hand, if you know something bad is going to happen on Tuesday, you might ask the question in the first form. It reminds me of Japanese, because that's one of the main differences between "topic" and "subject" -- different particles are used, and it's very confusing for an English-speaker. But the same information is carried in word order here. Hmm. Japanese is also an SOV language like German -- I always wondered if reverse-polish notation made more sense to SOV language speakers, since arguably their native language works that way (certainly infix makes more sense to me, and that's analogous to SVO which is what English is. (Usually ;-))). Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From plusk at radford.edu Sun Nov 3 15:08:36 2002 From: plusk at radford.edu (Paul D. Lusk) Date: 3 Nov 2002 20:08:36 GMT Subject: __coerce__ called for dict keys? References: <3DC02BC8.5020902@NOSPAM-REMOVETHIS-xs4all.nl> Message-ID: aahz at pythoncraft.com (Aahz) wrote in news:aq3gfq$356$1 at panix1.panix.com: > In article , > Paul D. Lusk wrote: >> >> I think you need __eq__ rather than __cmp__ in 2.2 > > Nope. __eq__ gets called before __cmp__, but __cmp__ gets called if > __eq__ isn't defined. See PEP 207. Aahz is, of course, correct. The reason I thought you needed __eq__ was because I was using a str subclass that I had created. I'd adapted it from something that been posted here. It had __cmp__ defined, but not __eq__, and I got _interesting_ results when I tried to use it as dict key. You do need _eq_ if your parent class defines __eq_. Paul From karl at elemtech.com Wed Nov 13 13:56:29 2002 From: karl at elemtech.com (Karl G. Merkley) Date: Wed, 13 Nov 2002 11:56:29 -0700 Subject: python, Qt and HOOPS 3D Message-ID: <3DD2A05D.5050007@elemtech.com> I am looking for the python bindings for the HOOPS-Qt widget. Has anybody done this? Is anyone willing to share? If not does someone have any pointers on how to go about doing this? I've been playing around with swig but haven't had any luck making it work yet. Thanks, Karl From jdhunter at nitace.bsd.uchicago.edu Thu Nov 14 17:36:26 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Thu, 14 Nov 2002 16:36:26 -0600 Subject: os.system and wget In-Reply-To: <3DD3B50D.C6A6BA8B@felis.uni-freiburg.de> (Joerg Woelke's message of "Thu, 14 Nov 2002 15:37:01 +0100") References: <7d728336.0211130756.3e39a748@posting.google.com> <3DD3B50D.C6A6BA8B@felis.uni-freiburg.de> Message-ID: >>>>> "Joerg" == Joerg Woelke writes: >> h = os.popen('wget -q -O foo1.txt http://foo.html') h.close() Joerg> What for, if you don't do anything (read/write) with the Joerg> pipe? That's what os.system is for. Not a good reason -- just a guess on my part. I tried the example code with popen and it worked (for me), and thought that perhaps calling the close method before trying to open the file would insure that the system process had completed before he tried to read the resultant file. It appears that the OP has something funny going on with his system, since both the popen and system approaches work fine on my system.... >> import os >>> os.unlink('test1.dat') >>> os.unlink('test2.dat') >>> os.system('wget -q -O test1.dat html://foo.html') 256 >>> print 'test1: ', os.path.exists('test1.dat') test1: 1 >>> h = os.popen('wget -q -O test2.dat html://foo.html') >>> h.close() 256 >>> print 'test2: ', os.path.exists('test2.dat') test2: 1 John Hunter From ygingras at eclipsys.qc.ca Fri Nov 29 17:28:10 2002 From: ygingras at eclipsys.qc.ca (Yannick Gingras) Date: Fri, 29 Nov 2002 17:28:10 -0500 Subject: tempfile.mktemp() and symlink attacks References: <3ygu9.105734$La5.330766@rwcrnsc52.ops.asp.att.net> Message-ID: <_RRF9.7694$cx4.1304051@news20.bellglobal.com> Robin Munn wrote: >>>Is using tempfile.mktemp() vulnerable to symlink attacks? The reason I >>>ask is that the documentation for os.tempnam() and os.tmpnam() has >>>warnings about symlink attacks, but the documentation for >>>tempfile.mktemp() does >>>not. Also, running os.tempnam() and os.tmpnam() actually brings a >>>RuntimeWarning, while I tried comparing the implementations, but couldn't >>>find the source for os.tempnam() and os.tmpnam() in os.py (I'm using >>>version 2.2.1). I was about to post to report the vulnerability. tempfile.mktemp() is REALLY vulnerable to symlink attacks. The default behaviour of tempfile.mktemp() is to return something close to "%s" % ( os.path.join( os.environ['TEMPDIR'], "@%d.%d" % (os.getpid(), num_mktemp_call) ) ) hummm... not as readable as I expected. Supose a process with pid 2344 with the environement variable TEMPDIR set to /tmp call tempfile.mktemp() 3 time, it will receive : /tmp/@2344.0 /tmp/@2344.1 /tmp/@2344.2 the file names are easy to guess and I don't know a way to make file() fail if the file already exists. tempfile.mktemp() will not return a filename already present on the system but by the time you open it, a symlink may have been set. There is an optional argument to tempfile.mktemp() that can help you make the filename harder to guess but you still can't tell if the file have been created by the time you open it. ex. : rnd = Random(time.time()) filename = tempfile.mktemp("%d%d%d" % ( rnd.randrange(100000), rnd.randrange(100000), rnd.randrange(100000) )) In this form, the filename will be appended a large number of random digits. But still, the attacker may understand the pattern and do an infinit number of retry until he guess the right filename ans you have (as far as I know) no way to detect if file() create the file or if it open an existing file. -- Yannick Gingras Coder for OBB : Oratorical Boyish Bozeman http://OpenBeatBox.org From grante at visi.com Mon Nov 18 15:20:34 2002 From: grante at visi.com (Grant Edwards) Date: 18 Nov 2002 20:20:34 GMT Subject: Serial Port References: <3dd47570$1@news.nz.asiaonline.net> <3dd514e8$0$4448$a1866201@newsreader.visi.com> <3dd90d82$0$22206$a1866201@newsreader.visi.com> Message-ID: <3dd94b92$0$22202$a1866201@newsreader.visi.com> In article , David Brown wrote: >> > You don't normally have so many serial ports open at a time >> > that the threading overhead is significant, >> >> I don't? I usually limit my test cases to 32 ports if >> possible, but on occasion have to use 100+ ports. > > Ok, correction - *I* don't normally have that many ports open > at a time. I thought I was unusual in having 6 serial ports on > my PC... Out of curiosity, what is the application? My employer sells serial ports, so it varies. The current problem I'm dealing with was reported by a customer who's using some homegrown SCADA software (Win32 host, written in C) to monitor some sort of power plant monitoring stuff. They're probably talking to a bunch of PLCs or something like that. Other customers talk to large banks of modems, cash registers, barcode scanners, video production equipment, etc. I normally work on Linux drivers and the code inside the Ethernet attached devices. Python is awfully handy for generating little test apps that do various strange things with serial ports. I've found I can usually slap together something analogous to the customer app that demonstrates the problem in Python way faster than I could get a C program running. Especially since I don't have a C compiler for Win32 :) >> I use threads a lot for serial communications too. Sometimes >> one-thread-per-port isn't what is required. > > I sounds like I've been trying to help with the wrong problem, > and I don't think I can be of much help to the real problem. > Good luck! It turns out this problem didn't really have anything to do with overlapping I/O. Sync I/O with a thread-per-port worked just fine: IOW, it failed in the way I wanted it to fail :). This time the bug was caused by calling PurgeComm while the reply was being received, and it would have eventually failed the same way with w/o overlapped I/O. But, one starts out trying to do things the same way the customer does... When you start messing with stuff like overlapped I/O you can really see the VMS heritage of NT. -- Grant Edwards grante Yow! "THE LITTLE PINK at FLESH SISTERS," I saw them visi.com at th' FLUROESCENT BULB MAKERS CONVENTION... From tebeka at cs.bgu.ac.il Tue Nov 19 06:49:53 2002 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 19 Nov 2002 03:49:53 -0800 Subject: A Minimal Python Distribution References: Message-ID: <33803989.0211190349.37b5fb52@posting.google.com> Hello Rod, > We are thinking of using python as the language for prescribing a tool to > install new firmware in our customers development boards. > > We want existing users of our boards to quickly download the installer (and > firmware to be installed) from our website onto a PC, then connect their > boards and update. (The firmware is a few 100K max). > > We found that the complete python distribution is too big to do this kind of > thing.... our customers are hardware guys who probably will (alas) never use > python themselves, want to rapidly download the firmware and won't want > python appearing in their "start menu". > > Is there a recognized minimal/subset of python that we could start from that > would be a short download for them, but provide the features we need? Why not use py2exe (http://starship.python.net/crew/theller/py2exe/) or installer (http://www.mcmillan-inc.com/install1.html)? HTH. Miki. From andrew.thompson at ashecastle.com Tue Nov 12 14:02:57 2002 From: andrew.thompson at ashecastle.com (Andrew Thompson) Date: Tue, 12 Nov 2002 19:02:57 -0000 Subject: Can python find fibonacci series in a single line of code? In-Reply-To: Message-ID: <002601c28a7e$1df5de00$4802a8c0@blair> How about solving the series analytically... map( lambda n: 5.0**-0.5*(((1+5**0.5)/2)**n-((1-5**0.5)/2)**n),range(1,99) ) Ok - tiny rounding errors -- but can remove those easily. -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org] On Behalf Of sismex01 at hebmex.com Sent: 12 November 2002 15:28 To: wganz at texoma.net; a_human_work at hotmail.com; python-list at python.org Subject: RE: Can python find fibonacci series in a single line of code? > From: Will Ganz [mailto:wganz at texoma.net] > I didn't want to participate in this thread, but the main comment in this note gave me pause. > :> My Perl-addicted friend shows me that he can find > :> fibanicci series in a single line of code. As for your friend, ask him to cross a "one-liner" equivalent of a bridge, some shoddy, barely-holding-together piece of dubious engineering. Software is the same thing, and should be raised to the same standards of quality as any other piece of engineering, but that's just my opinion. > Perl is like some of the doctor's writing that I try to > decipher at the hospital. Great for writing prescriptions > but invoke divine intervention to read more than a couple > of sentences. In fact, doctors will ask nurses to interpret > other doctor's writings to read the progress notes.* Same thing here in Mexico; the most responsible doctors I know either write their prescriptions out with a typewriter or on a computer, or dictate them to their nurse or assistant, whom invariably has much nicer writing. > The same with Perl. One liners and anything less than 100 > lines you can do in Perl, but get Python for anything that > you are going to have to maintain later. After having dealt > with 15000 line Perl 'programs' with all global variables > and documented solely by "self documenting variable names" > (?quick, what is the difference in $filedate, $FileDate, and > $Filedate?) Python is quite the relief to use. The "author" of such a horror should be shot and forgotten, for inflicting that kind of pain and cost on others. > * estimated 45,00~>98,000 Americans die annually from > medication errors v.s. 15,980 Americans murdered > in the year 2001 And I suppose, everywhere else in the world. It seems like people, in this case doctors, really don't understand that something as simple as writing out an unreadable prescription is as life-threatening as any disease. Can this be grounds for a medical-negligence suite? -gustavo -- http://mail.python.org/mailman/listinfo/python-list From aleax at aleax.it Wed Nov 20 04:59:47 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 20 Nov 2002 09:59:47 GMT Subject: matching multiple regexs to a single line... References: Message-ID: Alexander Sendzimir wrote: > > # Alex, the reason I used sre is because I feel it is the right module to > # use with Python 2.2.2. Re is a wrapper. However, my knowledge in this > # area is limited and could stand to be corrected. sre is an implementation detail, not even LISTED among the modules at: http://www.python.org/doc/current/lib/modindex.html Depending on an implementation detail, not documented except for a mention in an "implementation note" in the official Python docs, seems a weird choice to me -- and I'm not sure what other knowledge except what can easily be obtained by a cursory scan of Python's docs is needed to show that. > # I should have stated in my last post, that if speed is an issue, > # then I might not be coding in Python but rather a language that > # compiles to a real processor and not a virtual machine. If you had mentioned that, I would have noticed that this is anything but obvious when regular expression matching is a substantial part of the computational load: when the process is spending most of its time in the re engine, the quality of said engine may well dominate other performance issues. That's quite an obvious thing, of course. > # I will say that what I don't like about the approach you propose is that > # it throws information away. Functionally, it leads to brittle code which > # is hard to maintain and can lead to errors which are very hard to track > # down if one is not familiar with the implementation. I suspect it would be possible to construct utteances with which I could disagree more thoroughly than I disagree with this one, but it would take some doing. I think that, since re patterns support the | operator, making use of that operator "throws away" no information whatsoever and hence introduces no brittleness. > # This now said, yours is definitely a fast approach and under the right > # circumstances would be very useful. In my experience, clear writing > # takes precedence over clever implementation (most of the time). There > # are exceptions. I do agree with this, and I think my coding is quite clear for anybody with a decent grasp of regular expressions -- and people WITHOUT such a grasp should simply stay away from RE's (for production use) until they've acquired said grasp. > # As for the code itself, the lastindex method counts groups. If > # there are groups within any of the regular expressions defined, then Really?! Oh, maybe THAT was why I had this in my post: > This doesn't work if the patterns define groups of their own which you didn't even have the decency to *QUOTE*?! Cheez... are you so taken up with the "cleverness" of reducing your posts' readability by making most of them into comments, that ordinary conventions of Usenet, such as reading what you're responding to, and quoting relevant snippets, are forgotten...?! > # lastindex is non-linear with respect to the intended expressions. > # So, it becomes very difficult to determine which outermost expression > # lastindex refers to. Perhaps you can see the maintenance problems > # arising here? No, I always say "this doesn't work" when referring to something I can't see *ANY* problems with -- doesn't everybody? [Not even worth an emoticon, and I can't find one for "sneer", anyway...] > # I've labelled the groups below for reference. If instead of "labeling" in COMMENTS, you took the tiny trouble of studying the FUNDAMENTALS of Python's regular expressions, and named groups in particular, you might be able to see how to "label" *IN THE EXPRESSION ITSELF*. As I continued in my post which you didn't bother quoting, > a slightly more sophisticated approach can help -- use named > groups for the join... I may as well complete this (even though, on past performance, you may simply ignore this, not quote anything, and post a "huge comment" re-saying what I already said -- there MIGHT be some more normal people following this thread...:-): if the re-patterns you're joining may in turn contain named groups, you need to make the outer grouping naming unique, by any of the usual "naming without a namespace" idioms such as unique prefixing. Usual generality/performance tradeoffs also apply. Most typically, documenting that the identifiers the user passes must not be ALSO used as group names in the patterns the user also passes will be sufficient -- doing things by sensible convention rather than by mandated fiat is Pythonic. In many cases it may not be a problem for client code to avoid using groups in the RE patterns, and then the trivially simple solution I gave last time works -- if you want, you can check whether that's the case, via len(mo.groups()) where mo is the match object you get, and fallback to the more sophisticated approach, or raise a suitable exception, etc, otherwise. In some other cases client code may not only need to have no constraints against using groups in the RE patterns, but also want "the match-object" as an argument to the action code. In this case, an interesting approach is to synthesize a polymorphic equivalent of the match object that would result without the or-joining of the original patterns -- however, the tradeoffs in terms of complication, performance, and generality, are a bit different in this case. > # (abcd(cd){1,4})|(abcd)|(abcd(cd)?)|(ab)|(zh192) > # 1 2 3 4 5 6 7 > > # As you can see some expressions are 'identified' by more than one > # group. This is not desirable and is difficult to maintain. If you Nope, that's not a problem at all -- the re module deals just fine with nested groups. The issue is, rather, that since group _numbering_ is flat, i.e. ignores nesting, the group numbers corresponding to the outer-grouping depend on what othe groups are used in the caller-supplied re patterns. Identifying which is the widest (thus from the outermost set of groups) group that participated in the match is easy (go backwards from lastindex 0 or more steps to the last group that participated in the match) but unless you've associated a name with that group it's then non-trivial to recover the associated outer-identifier. Alex From wlfraed at ix.netcom.com Sun Nov 24 18:12:08 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sun, 24 Nov 2002 15:12:08 -0800 Subject: Guido's regrets: filter and map References: <9PvekLArvL49Ewa2@jessikat.fsnet.co.uk> Message-ID: <8cmrra.qvc.ln@beastie.ix.netcom.com> maney at pobox.com fed this fish to the penguins on Sunday 24 November 2002 07:40 am: > > ### revised test with filtering > from time import time > > n = 1000000 > N = xrange(n) > > t0 = time() > S=[] > a = S.append > for x in N: > if x % 2 == 1: > a(str(x)) > print 'for loop took %.2f to make a list of %d items' % ((time()-t0), > len(S)) > > del S > t0 = time() > S = [str(x) for x in N if x % 2 == 1] > print 'list comprehension took %.2f to make a list of %d items' % > ((time()-t0), len(S)) > > del S > t0 = time() > S = map(str,filter(lambda x: x % 2 == 1, N)) > print 'map took %.2f to make a list of %d items' % ((time()-t0), > len(S)) > ### > > Okay, that's enough for now. Well, to add some more embers... Two runs under Mandrake 8.2, on a 733MHz P-III with RDRAM (Dell XPS B733r), Python 2.2, using the program listed above. [wulfraed at beastie wulfraed]$ python t.py for loop took 7.61 to make a list of 500000 items list comprehension took 7.30 to make a list of 500000 items map took 6.84 to make a list of 500000 items [wulfraed at beastie wulfraed]$ python t.py for loop took 7.61 to make a list of 500000 items list comprehension took 7.31 to make a list of 500000 items map took 6.85 to make a list of 500000 items -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From wlfraed at ix.netcom.com Tue Nov 5 20:56:53 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 05 Nov 2002 17:56:53 -0800 Subject: Str and instance concatanation error References: Message-ID: <5ts9qa.io3.ln@beastie.ix.netcom.com> Newt fed this fish to the penguins on Monday 04 November 2002 03:01 pm: > > This occurs in a class module (called globals.py). This is used to > hold all my global variables, and also has a method (called save_char) > to write these to a file. > Is it just me, or does the use of the name "globals" strike a chord... Especially since the builtin function globals() already exists to return the global environment as a dictionary. -- -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From ark at research.att.com Wed Nov 6 15:27:28 2002 From: ark at research.att.com (Andrew Koenig) Date: Wed, 6 Nov 2002 20:27:28 GMT Subject: Long overflow problem References: Message-ID: Tom> If I call the function as such: myFunc(2382373743L, 2382772391L), I get Tom> the following error: Tom> OverflowError: Long int too long to convert to int. Tom> I can't seem to get myFunc to understand that i and j are long integers. Tom> How would I go about doing this? It looks like myFunc is trying to do something with one of its arguments that requires an int and will not accept a long. Without seeing what myFunc does, it's hard to know what that operation might be. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From zoltan at trados.com Thu Nov 14 04:11:30 2002 From: zoltan at trados.com (Zoltan Sekeres) Date: Thu, 14 Nov 2002 10:11:30 +0100 Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> <87y98f566d.fsf@zamazal.org> Message-ID: <3DD368C2.9040205@trados.com> Martin v. Loewis wrote: > Certainly - but then we need entirely new tools (or must modify > existing tools). Have you ever tried to modify Norman Walsh's DocBook > XSLT stylesheets? That may be an excellent piece of software, but it > has a complexity that is not easy to grasp (to put it mildly). IMHO the good thing about DocBook is that it is very modular and you can start using it without knowing the internals. You can approach it step by step while being productive from day one. I have started using DocBook (XML version, XSLT transformation to HTML) last year and had no clue about XSLT. You can set various parameters and when you use a CSS stylesheet the HTML looks great. Actually I started out extending DocBook, but it turned out, that I could achieve my goal just by specifying parameters. I was disappointed about the lacking support for other targets like PDF and FO, but that was last year and I should check again ... -- Zoltan From gleki at gol.ge Tue Nov 26 09:47:20 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Tue, 26 Nov 2002 15:47:20 +0100 Subject: KDEvelpo 3.0 & Python Message-ID: <3DE38978.2B4F502A@gol.ge> Hi all! Has anybody tested KDevelop3 alpha working with Python? TIA, Giorgi From martti.halminen at kolumbus.fi Sat Nov 23 22:00:47 2002 From: martti.halminen at kolumbus.fi (Martti Halminen) Date: Sun, 24 Nov 2002 05:00:47 +0200 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <3DDBD838.10406@nyc.rr.com> <3DDC5851.5060001@nyc.rr.com> Message-ID: <3DE040DF.EACC7D3A@kolumbus.fi> Alexander Schmolck wrote: > Of coure LOOP and FORMAT affect newcomers! They are extremely commonly used > constructs, so you will encounter them quite frequently in other people's > code. And even simple uses of LOOP can easily yield misunderstanding unless > you have some fairly good understanding of what it does (the emulation of > plain English is additionally deceptive in this regard): > > (loop for x below 5 for y = nil then x collect (list x y)) > => ((0 nil) (1 1) (2 2) (3 3) (4 4)) > > as opposed to: > > (loop for x below 5 and y = nil then x collect (list x y)) > => ((0 nil) (1 0) (2 1) (3 2) (4 3)) If it is any consolation, neither LOOP nor FORMAT were noncontroversial in the Lisp community when they appeared, mostly due to their "non-lispy" look and feel. There are some notable Lispers, like Paul Graham, who don't usually use LOOP. FORMAT is nearly-universally used, though somebody claimed that it is a separate, Turing-complete programming language in its own right:-) - LOOP isn't the only iteration construct: I use usually DOTIMES, DOLIST or the mapping functions for simple cases. The old DO also exists for oldtimers. > Hmm, I thought untyped means that variables don't have any type associated > with them at all (like in assembler). In CL, the variables may contain any type of objects, but any piece of data has a known type (unlike in C, where you can cast stuff however you like, whether it makes any sense or not). > > Well, the battle was decided (temporarily?) in favor of static languages > > during the long decades before systems routinely shipped with ghz processors > > and hundreds mb ram. By the time those systems came along, almost everyone was > > using static languages. Folks don't change easily, so CL still does not get > > used widely. > > This explanation has the considerable problem that it would equally have > predicted the miserable failure of Perl, Python, Javascript and I'd guess > Visual Basic. Except that those are rather new languages in comparision, from a time the machine performance had already risen to acceptable values. For comparision, at the time Lisp Machines were the fastest workstations on the planet, they had clock frequencies like 4 MHz. The competition ran 16 MHz Motorola 68020:s. (Cray 1 had 80 MHz, IIRC.) > Well, it's not just "pragmatic advantages", I do believe that in some points > python's *design* is just superior. Iteration and container classes seem > fairly crufty to me in CL (not knowing CL that well, I might be wrong, in > which case I'd much appreciate to be enlightend). No such thing as "iteration class" in the language: Lisp had already existed for a quarter century before it got a standardized object system (plenty of non-standard, non-compatible versions before that), so the control flow constructs are rather othogonal to the object system. Also, no container class in the meaning of unifying lists and hash tables. On the other hand, the language has what CL calls sequences, i.e. plenty of stuff work the same on lists and one-dimensional arrays (including strings). > Now if you want to define you own collection classes, you're really in for a > hard time: I fail to see what is so hard in that. Obviously you have to design your own wrapper class if you want similar behaviour from different data structures, given that the language doesn't have it built-in, but as you yourself show, any given operation is only a few lines. > python: CL: > > > x = list[index] (elt arrayOrList index) > x = hash[key] (gethash key hash) ;; *why* this arg-order? Why not? It is consistent with most of the language, most similar functions are defined as ( ). The major exceptions are where there may be variable amount of arguments, like array indices: (aref ....). ELT probably for similarity with AREF. > x = myType[indexOrKey] ; no generalized item access (elt sequence index) works for all sequence types. For your own types you can define whatever accessor patterns you like. There are tools to make your accessor to work with the generic assignment command (setf ) > > > > del container[indexOrKey] ; no generalized deletion mechanism (delete item sequence) for all sequence types, (remhash key table) for hash tables. Not that difficult, I'd think. > > container[indexOrKey] = x (setf (elt arrayOrList index) x) > (setf (gethash key hash) x) > > > for item in list: (loop for item in list) > print item (loop for item in list do (print item)) ; to be exact > for key in dict: (loop for key being the hash-keys of h > print key do (princ key)) > > for value in dict.values(): (loop for value being the hash-values of h > print value do (princ value)) Alternative ways for playing with hash tables: MAPHASH and WITH-HASH-TABLE-ITERATOR. > > for item in container: ; no convienient idiom (?) > print item - For printing the usual idiom is usually just (print container), though hash tables do not have a defined machine-readable output form. Nothing to prevent you from defining one. > LOOP does offer monstrous complexity, but no mechanism to extend it to handle > anything beyond integers, lists, arrays and hashs. Already handles also floats, rational numbers, complex numbers (with some care in end test due to the mathematical properties of complex numbers: FROM ... TO isn't well defined), strings and packages (symbol tables). For that matter, it is a macro, and sources are available, so expanding it to handle anything else you wish is possible, with no runtime performance implications. Not that many wish: it is quite sufficiently complex already for most people. > Similarly, functions like > concatenate only know about lists and arrays (which all can't even be > subclassed, right?). - Strings too, as a subclass of arrays. As that was about all system-defined types with sensible semantics for concatenation, I don't know what you are missing. I've never had any reason to wish subclass built-in types, so I don't see it as a problem. > This really looks like quite a big disadvantage in abstraction and > convienience when compared to python. To some extent this is a style difference in language usage: you seem to want something like C++ -style overloading, making your own constructions to hide in built-in behaviours. Most CL programmers are happy to leave the language built-in parts alone (unless explicitly defining a new language for some reason), and defining their own stuff with different names, thereby reducing surprises for readers. In reading somebody's C++ code I can never guess what + does this week, reading CL I can be relatively safe assuming (+ a b) sums numbers, (plus a b) is probably my own matrix multiplication stuff in my code [unless it happened to be old Maclisp stuff...]. Now what tools did Python have to define your own control flow constructs ? :-) -- From peter.rams at sap.com Tue Nov 12 05:18:17 2002 From: peter.rams at sap.com (Peter Rams) Date: Tue, 12 Nov 2002 11:18:17 +0100 Subject: how good is shelve? Message-ID: Hi, at the moment I'm writing a small web application with python. Because I'm lazy I does not store the data for it in a mySQL-Database or something similar. Instead I use shelve to store the data. Now my question is: will I get problems if my web application becomes famous (I don't think it will, but who knows?) and the data to store gets big? Regards, Peter From syver-en+usenet at online.no Wed Nov 20 16:48:13 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: 20 Nov 2002 22:48:13 +0100 Subject: Advice for using emacs python-mode References: Message-ID: Andrew Koenig writes: > I'm writing a program using Emacs and python-mode, and have run into > a few problems. Hi Andrew, I've been where you are, and it's not a great place to be. One thing I did was to put Python Output into a separate frame (another toplevel window). This keeps the main frame of emacs more stable. (setq special-display-buffer-names '("*Python*" "*Python Output*")) The other problem (when running the interpreter and the module needs to be reloaded), I solved by not using that feature much. I've instead bound a key to an lisp function that uses compile mode to run the current python file. I find that this solution solves two problems, it doesn't freeze emacs and it avoids the problems with reloading. (defun py-unittest () "run unittest on file in the current bufffer " (interactive) (compile (format "python \"%s\"" (buffer-file-name)))) The thing about it running unittest on the current buffer really is a lying comment. It just so happens that all my modules have a if __name__ == '__main__': unittest.main() in the bottom of them, so that running them as a main program is the same as running the unittests contained in the file. In addition if you want to be able to step around your source for tracebacks in the compilation buffer: ;; python TraceBack ;; File "h:/mydocuments/Kode/pythonscript/AdoDb.py", line 496 (add-to-list 'compilation-error-regexp-alist '(".*File \"\\(.+\\)\", line \\([0-9]+\\)" 1 2)) Hope this helps. -- Vennlig hilsen Syver Enstad From quadric at primenet.com Tue Nov 5 20:52:12 2002 From: quadric at primenet.com (quadric at primenet.com) Date: Tue, 05 Nov 2002 18:52:12 -0700 Subject: Obtaining global and local dict's for current interpreter using C API Message-ID: <5.1.1.6.2.20021105185139.01a3e638@pop3.norton.antivirus> Hi, I am new to Python but an experienced C++ programmer familiar with scripting etc..... and very excited about Python. I have successfully embedded/extended it and am attempting to execute Python source from a variety of sources. I have looked through all my Python books for an answers to the following questions and can find none ( at least not yet ). Can someone please help? I'm sure this is incredibly simple, I'm just a bit new at it. I'm using the latest build (2.2.2) and programming using MS Visual C++ 6.0 ( no flame from UNIX/Linux guys please ). Question(s): How , and using which C API functions, do you acquire the PyObject * to the dictionaries ( both local and global) of the current interpreter. I AM NOT looking for the dictionary of an imported module, but rather the dictionary of the current interpreter. You know, the one you get when executing 'dir()' in the interpreter window. The C API docs say to do the following: PyObject * pdict = PyObject_Dir(NULL); and , assuming an execution frame is active, should return the dictionary. 1> What is an execution frame? 2> How do I know if an execution frame is active? 3> I've tried this and only get NULL in return, indicating the absence of an active execution frame, I guess? ----------------------------------------------------------------------------------- My code looks similar to this: PyObject * pres = NULL , * pdict = NULL; int result = 0; Py_Initialize(); pdict = PyObject_Dir(NULL); // Returns a useless NULL pointer if ( pdict != NULL ) { PyRun_SimpleString( "result = 4 + 5" ); pres = PyObject_GetAttrString( pdict , "result" ); PyArg_Parse( pres , "i" , &result); } // decrement any references here Py_Finalize(); -------------------------------------------------------------- The problem is that pdict is always NULL and I cannot retrieve values for variables created within the namespace of the current interpreter by use of the PyRun_xxxx() functions. Any knowledgeable help would be greatly appreciated. Thanks, quadric at primenet.com From goldbb2 at earthlink.net Tue Nov 12 16:13:40 2002 From: goldbb2 at earthlink.net (Benjamin Goldberg) Date: Tue, 12 Nov 2002 16:13:40 -0500 Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DCFCC3E.204D9B45@man.ac.uk> <3DCFEF06.9E74A794@earthlink.net> <3DD11E7F.C12E708A@man.ac.uk> Message-ID: <3DD16F04.517E6720@earthlink.net> Donal K. Fellows wrote: > > Benjamin Goldberg wrote: > > Considering that Jcl and Jython exist, it seems like a reasonable > > goal > > (JCL is something else. I'd rather not remember it thankyouverymuch.) Erm... that's the old IBM Job Control Language? You mean this one? http://www.tuxedo.org/~esr/jargon/html/entry/JCL.html Bleh, forget I mentioned it. :) Twas a horrible typo :) > > would be to make an interpreter which turns Java's .class files into > > Parrot .pasm files. Once that tool exists, one could simply > > translate Jcl and Jython into parrot... there would be no need to > > re-implement them. > > > > And one day, in the distant future, there will be a Perl6 > > decompiler, which will turn Parrot bytecode into Perl6. Then we'll > > be able to convert the translated Jython and Jcl into Perl6 :) > > $10 says that only ever happens with a performance hit. The problem > is that not all bytecodes are created equal. (And Jacl is an > implementation of Tcl in Java more in the way that the usual form of > Tcl is an implementation of the language in C. So Jacl still converts Tcl into, well, Tcl bytecodes, even though it's doing so in Java? Blech. Hmm, is there a way of making tcl dump the tcl-bytecodes to a file? If so, one could probably make an attempt to translate those bytecodes into parrot. (And ignore Jacl). > The fact that Java uses bytecodes is pretty much just a distraction > here. We also have another way of integrating Tcl with Java that > keeps Tcl > implemented in C, but which integrates almost identically with the Java > language.) > > > > This sort of thing tends to make me suspicious that this is little > > > more than a pipe-dream, well, at least as far as Tcl's concerned. > > > (I don't know the other languages nearly well enough to comment > > > in a useful way.) > [...] > > Assuming you thouroughly understand Tcl's bytecodes, why not take a > > look at Parrot, and see whether the set of bytecodes that parrot > > supports is sufficient to do everything that Tcl's bytecodes do? > > I know a bit about Tcl bytecodes, and a key factor about them is that > they are very tightly targetted towards implementing Tcl. > > Hmm. A quick scan through the documentation doesn't really raise my > hopes. Or even leave me with a deep enough understanding of what's > going on; is there any deeper description than > http://www.parrotcode.org/docs/parrot_assembly.pod.html > about? (OK, Tcl's bytecodes need documentation too, but I've already > gone to the effort to understand those as part of my maintenance and > development duties. I've just not got enough hours in the day.) > Unfortunately, the bits that I'm most interested in seem to be the > bits with least info (isn't that always the way with complex software > systems?) > > First impressions: what is meant by "string" anyway? Character > sequence? Byte sequence? UTF-8 sequence? ISO 8859-1 sequence? [FX: > Reads docs] Oh, they carry about what their encoding is with them? > That must make working with them fun. How does it handle things like > the blecherous monstrosities[*] used for system encodings in the Far > East? Having read http://www.parrotcode.org/docs/strings.pod.html only just now myself, it's possible I could be wrong on this, but... Each string's encoding can be one of native, utf8, utf16, utf32, or foreign. So those "blecherous monstrosities" will either be converted to one of the utf formats, or else have their own string vtable. For now, they will probably be converted... the strings.pod.html says this at the bottom: Foreign Encodings Fill this in later; if anyone wants to implement new encodings at this stage they must be mad." > On a quite separate point, is there a strncmp() equivalent? That > would make implementing Tcl much easier... You mean, for testing the first n characters of two strings for equality? There isn't that I know of, but one could always be added; furthermore, it supposedly will be possible to make lightweight strings which are substrings of other strings, without any copying involved. You could make your strncmp be a wrapper around making a substring of the first n characters of each of your two strings, and comparing those substrings. > More generally, Tcl would need to use PMCs throughout. Why? (Not an objection, but I don't know much about Tcl's bytecode) > The problem is that Tcl's value semantics (copy-on-write) do not line > up well with that which Parrot seems to use (object-based) Parrot will do copy-on-write. Furthermore, Parrot may implement some strings as ropes, so that the amount that needs to be copied will be even smaller. > and which, IIRC from the discussions at the time when Parrot was being > created, are closely based on those used in Perl even if not precisely > coincident. Perl is likely never going to implement strings as ropes. It does now have copy-on-write, though this is a recent development. Perl5.6+ has two internal encodings for strings -- bytes and utf8. Parrot not only allows native, utf8, utf16, and utf32, but it also allows any kind of user-defined encoding one might want. I doubt that perl5 will ever do this. > Hence we'd be unable to use ground values except as part of the > implementation of higher-level concepts. That'll impact badly on > performance. > > It's at this point that I feel a round of "Stuff it. I'll stick to > implementing in C." coming on. I've been quietly watching Parrot for > a while now, and I still don't think that implementing Tcl in it is > really a winning proposition. > I'd love someone to prove me wrong, but proof is building a Tcl > interpreter in or on top of Parrot and running the Tcl test suite on > it (and getting a decent proportion of the tests passing.) Parrot does everything in two steps -- compile, then run. Most likely, it will have a compiler which converts Tcl bytecode to Parrot bytecode. Whether or not Parrot will ever translate from Tcl source to Parrot bytecode is another question entirely. Thinking a bit more, particularly about how Tcl often needs to interpret strings at runtime, I realize that no non-trivial Tcl program can work without having a string-to-bytecode compiler. Needless to say, this poses a problem. > BTW, how does Parrot handle calls to foreign code? The docs I've seen > are on the hazy side, and integration with existing C, C++ and FORTRAN > monoliths is (alas) all too important in particularly commercial > development. Although I don't know *how* it will handle foreign code, I do know that it *will* handle foreign code, and have a better interface than Perl5's cruddy XS extension language. -- my $n = 2; print +(split //, 'e,4c3H r ktulrnsJ2tPaeh' ."\n1oa! er")[map $n = ($n * 24 + 30) % 31, (42) x 26] From richie at entrian.com Fri Nov 8 04:49:11 2002 From: richie at entrian.com (Richie Hindle) Date: 8 Nov 2002 01:49:11 -0800 Subject: Python Browser Applets References: Message-ID: <8a6ba1da.0211080149.69190c08@posting.google.com> Hi Neil, > Yes, writing a cross platform plugin is lots of work, especially if you > want it to integrate well into the browser, such as cooperating in sizing > and in event routing including command keys. It is simpler if your plugin > area is a fixed size area that is isolated from the browser. Do you know whether anyone has succeeded in doing this for Scintilla? I'm working on a web-based Python debugger, and I'd love to allow remote editing of source code within the browser using Scintilla. A quick Google didn't turn anything up. -- Richie Hindle richie at entrian.com From johs+n at ifi.uio.no Mon Nov 11 05:18:55 2002 From: johs+n at ifi.uio.no (Johannes =?iso-8859-1?q?Gr=F8dem?=) Date: Mon, 11 Nov 2002 11:18:55 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: * Carl Banks : >> > (funcall '+ 1 1 1) >> 3 >> > (funcall '* 2 3) >> 6 > You mean (funcall #'+ 1 1 1) and (funcall #'* 2 3). If you'd checked the spec, you would see that funcall takes a function designator, not just a function, so his example is correct as well. -- Johannes Gr?dem From syver-en+usenet at online.no Fri Nov 1 16:52:37 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Fri, 01 Nov 2002 21:52:37 GMT Subject: Win32 DDE support documentation? References: Message-ID: Mark Hammond writes: > Syver Enstad wrote: > > "Andrew Thompson" writes: > > > >>I am trying to find some documentation for DDE (ala Microsoft Excel) > but > > >>seem to be going around in circles between Python.org and the > vaults. > > >>Does anyone know where I can find information on either hot or warm > >>links ? > >> > >>Many thanks. > >>Andrew. > > Hi Andrew. I've written a patch for the dde module in win32all to > > provide support for hot links. If you have access to the msvc > compiler > > > I can give you the source for it, or I could send you some compiled > binaries. > > > If this patch is in my inbox, I promise I will get to it . If > not, send it on It is in your inbox Mark. Mail or post here if you any questions. -- Vennlig hilsen Syver Enstad From aleax at aleax.it Mon Nov 18 18:21:46 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 18 Nov 2002 23:21:46 GMT Subject: Hmm... An idea: if a,b==c,d: References: Message-ID: Richard Dillingham wrote: > This would mean that lines like the following: > if posx>=coords[0] and posy>=coords[1] and posx<=coords[2] and > posy<=coords[3]: > > Could be rewritten like so: > if posx,posy>=coords[0],coords[1] and posx,posy<=coords[2],coords[3] It's better written as: if coords[0]<=posx<=coords[2] and coords[1]<=posy<=coords[3]: anyway (besides the many other correct things that have already been pointed out on this thread -- hadn't seen this one though [having admittedly just skimmed the thread...]). Alex From jmpurser at attbi.com Sun Nov 17 14:11:34 2002 From: jmpurser at attbi.com (jmp) Date: Sun, 17 Nov 2002 12:11:34 -0700 Subject: Reading Bluebird/Superdos Index files References: Message-ID: Thanks. I checked there first. It is a great site! But unless I know what format these files are I can't search it very well. I'm fairly sure I'm looking at a standard hash/index file with a OS specific header of 512 Kbytes. I'm thinking about cutting the head off and then asking whichdbm to help me out. John "Robin Munn" wrote in message news:slrnatfsnt.7ah.rmunn at rmunnlfs.dyndns.org... > jmp wrote: > > Hello, > > > > My company has a legacy application originally coded in Business Basic for > > the SuperDos operating system by BlueBird. I can read the data files but > > the index files are a problem. I've tried the whichdb module and got an > > empty string. > > > > Has anyone else run up against this format or can you give me some > > suggestions for deciphering the structure of these index files? > > > > Thanks, > > > > John Purser > > I have no personal experience with this type of file, but Wotsit's Format > (http://www.wotsit.org/) often has information about obscure file types. > > -- > Robin Munn > http://www.rmunn.com/ > PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 > -- > http://mail.python.org/mailman/listinfo/python-list > From zimmermann.edv at t-online.de Tue Nov 19 17:18:36 2002 From: zimmermann.edv at t-online.de (Bernd Zimmermann) Date: Tue, 19 Nov 2002 23:18:36 +0100 Subject: ctypes and delphi dll Message-ID: I want to use a Delphi application - available as DLL - with Python 2.2 and tried the 'cdll' as well as 'windll' interface. The DLL exports only a single procedure expecting two pointers to structures. I can load the DLL and get the procedure handle. But when invoking the prodedure, 'cdll' claims missing 8 Bytes and exits, while 'windll' is silent but does not start the application to work. Is there a problem with DLLs written in Delphi? The DLL is a couple of years old and worked fine when used with Delphi-3. Thanks for any help, Bernd From wlfraed at ix.netcom.com Mon Nov 18 21:37:34 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 18 Nov 2002 18:37:34 -0800 Subject: Multiple instances References: Message-ID: Xiang Zhang fed this fish to the penguins on Monday 18 November 2002 12:51 pm: > I would like to run multiple instances of the same Python script > simultaneously. Does Python support such use? > Well, my SPAM complaint program (run from a Eudora filter [pay no mind to the Mandrake Linux behind the curtain]) tends to suck up W98 resources like mad in my first email pass of the morning. I get some 15-20 filtered spam emails (defined as anything with .ar, .kr, or a CJKV character set) all running the program in parallel. The complaint program extracts host names from all header lines, then does MX lookups, formatting a complaint email to postmaster at mx.lookup.hosts, then feeds it back to Eudora. -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From richie at entrian.com Tue Nov 5 08:21:04 2002 From: richie at entrian.com (Richie Hindle) Date: Tue, 05 Nov 2002 13:21:04 +0000 Subject: Foot in mouth disease References: <3dc3a6fd$0$84999$e4fe514c@dreader7.news.xs4all.nl> <3dc52687$0$84997$e4fe514c@dreader7.news.xs4all.nl> Message-ID: <78hfsuobus726o8361355145pve3ikia5s@4ax.com> Hi Boudewijn, > [...] Eric, a really great debugger written in PyQt I've tried to install Eric with PyQt Non-Commercial and Qt Non-Commercial, but as far as I can see, Qt Non-Commercial is only available for Qt version 2.3 while Eric requires 3.0. Do I have to buy a Qt licence to run Eric? -- Richie Hindle richie at entrian.com From goldbb2 at earthlink.net Mon Nov 11 15:21:17 2002 From: goldbb2 at earthlink.net (Benjamin Goldberg) Date: Mon, 11 Nov 2002 15:21:17 -0500 Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DCFCC3E.204D9B45@man.ac.uk> <3DCFEF06.9E74A794@earthlink.net> <3DCFF6FB.40426F8E@san.rr.com> <3DD00595.B2905D8E@earthlink.net> <3DD00B63.EC604897@san.rr.com> Message-ID: <3DD0113D.79EC23F6@earthlink.net> Darren New wrote: > > Benjamin Goldberg wrote: > > Why would any of these require that strings be eval()ed? > > > > You compile the string to bytecode, *once*, and pass this compiled > > code as the callback for your keystrokes, window events, and async > > file operations. You wouldn't pass a string to be eval()ed -- that > > would be silly. > > Bindings substitute their values. File events get additional > arguments. Etc. So? Pass these in as arguments. There's no need to recompile a procedure for each and every different set of arguments that might be passed to it. That would defeat the point of having procedures in the first place. > > Furthermore, even if one did do something that foolish, the compiler > > needs to be loaded only once... > > I missed your parenthetical comment on first reading. Yes, sorry. Peculiar -- if I'd been reading someone else's description of it, and he didn't say, "(if it's not already loaded)", I would have *assumed* that it wouldn't be loaded if it already had been, *unless* he said something to the contrary (like, "yes, I really do mean reload the compiler from disk each and every time we eval() a string") -- my $n = 2; print +(split //, 'e,4c3H r ktulrnsJ2tPaeh' ."\n1oa! er")[map $n = ($n * 24 + 30) % 31, (42) x 26] From bokr at oz.net Thu Nov 21 11:46:53 2002 From: bokr at oz.net (Bengt Richter) Date: 21 Nov 2002 16:46:53 GMT Subject: Howto wait for multiple queues (Queue.py)? References: Message-ID: On 20 Nov 2002 12:50:07 +0100, Andreas Ames wrote: >Hi, > >as I prefer to use queues for interthread communication, I need >something like a 'mainloop' for my threads in the sense that every >thread can have multiple input queues and I want to be able to block >the consumer thread until input within one (or more) queues is >available. This mechanism should be somewhat comparable to 'select()' >or 'MsgWaitForMultipleObjects()' (on w32). > [......] ISTM there are a lot of questions that need to be answered before anyone can get a grasp of what your problem really is, without making a lot of assumptions. Step back from the implementation issues a moment. You have multiple threads. Ok. They are to communicate. Ok. But what is the possible graph of their communications? Pipeline? Acyclic? Static? etc. Do produced messages have types that sometimes or always require direction to a[?] certain consumer[s?]? Are there ordered subsequences of messages that must arrive in original order at single consumers, even though several consumers might be able to process them? Or, e.g., could a thread simply requeue an item it can't process? I could go on, but I imagine you get the point: the specs are not all visible from here ;-) Regards, Bengt Richter From fperez528 at yahoo.com Fri Nov 8 16:38:48 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Fri, 08 Nov 2002 14:38:48 -0700 Subject: [OT] Cameras (was Re: Why is Python popular, while Lisp and Scheme aren't?) References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: Eddie Corns wrote: > A modern point'n'shoot will allow you to do many of the > things real professionals do (I hope so anyway I'm about to buy one!) but > not > the most extreme. Likewise there are things Scheme can do that would be > crazy > to try in Python. Perhaps I'm being optimistic about the capabilities of > modern p'n's cameras but my impression is most of us wouldn't really want to > venture much outside what they can do - so they don't get in the way. P&S cameras are ok, but their _control_ is fairly limited to none. Some (like the Oly Stylus Epic) have excellent optics, others have crappy optics (pretty much all zoom cameras, you just can't make a decent zoom of that size, physics gets in the way). If you just want convenience for 4x6 prints from negative, a P&S is fine. But even a basic SLR like a Canon Rebel is about as easy to use as a P&S, while allowing you to 'go manual' when you feel like it. What you can't do with a P&S is to set manually the aperture or speed to what _you_ want, you have to let the camera decide what it thinks is best. I learned the techical side of photo taking like that (making _interesting_ pictures is a different story :). I bought a Pentax ZX-5N and used it in auto modes at the beginning, paying attention to the decisions made by the camera. Then I started experimenting by changing things a bit. These days I never use it in full auto, except when I'm in a big hurry or need to give it to someone else. Cheers, f. ps. The above doesn't quite apply to 'prosumer' digital P&S like the Canon G2/G3. Because the sensor is so small, those cameras actually have decent zooms. And they also have all the manual controls typical of an SLR. That's because it's the only way the companies can sell to the market who wants manual control but can't afford a 2k-8k true digital SLR. From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Fri Nov 29 02:18:30 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Fri, 29 Nov 2002 08:18:30 +0100 Subject: mod_python References: Message-ID: <3de714c6$1@news.mt.net.mk> > I figured out how to get mod_python to work, at last, but I ran into a > problem that seems to be fairly common (the solution is harder to find, > though). Any code inserted into mptest.py works great. But when I make > another file in the same directory, the last thing that was in mptest goes > into that file, even if mptest doesn't exist any more. Must be browser > cache or something... Well, I have no idea, since it's a different file. > Does Apache have a cache, too? I have heard that some mistake in the > configuration can make Apache keep referring to mptest. But I can't find > how to fix it... Thats the way mod_python works. read the documentation :) You have registered mptest.py to be a handler for all requests ending in ".py". -- ?????? ?? ?????????? ????? ??????????? ??????... ...?? ???????????? ? ????? ?????????. From david at no.westcontrol.spam.com Tue Nov 19 05:21:22 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Tue, 19 Nov 2002 11:21:22 +0100 Subject: Simple Encryption References: Message-ID: "Bronek Carr" wrote in message news:ard013$obo$1 at sp15at20.hursley.ibm.com... > Hi all, > > I am trying to write a simple ROT-13 encryption script in python. A good > starting point would be a function which gets the ascii value of a character > in a string. I would assume this function already exists in one of the > packages, as it does in every other language I use. I cannot find it if it > does, can anyone help me. > > > Thanks in advance > > Bronek > > You are looking for the "ord" function: >>> ord('a') 97 >>> map(ord, "Hello, world!") [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33] >>> The inverse is "chr" : >>> chr(97) 'a' >>> map(chr, [72, 101, 108, 108, 111]) ['H', 'e', 'l', 'l', 'o'] >>> "".join(map(chr, [72, 101, 108, 108, 111])) 'Hello' >>> From grante at visi.com Tue Nov 12 11:28:26 2002 From: grante at visi.com (Grant Edwards) Date: 12 Nov 2002 16:28:26 GMT Subject: HTML email marketing tool References: Message-ID: <3dd12c2a$0$4491$a1866201@newsreader.visi.com> In article , =?big5?q?Terence=20Ng?= wrote: > Could someone provide me an HTML email marketing > (mailing list) script that allow me to capture the > prospects' email list from MySQL and send HTML email > through Windows 2000, IIS (Internet Information > Server)? The scripts I can find are either too heavy > or in Unix environment. You want to do something most of us probably consider evil. And you want us to actually write it for you! Do the letters FOAD mean anything to you? -- Grant Edwards grante Yow! at TAILFINS!!... click... visi.com From vze4rx4y at verizon.net Fri Nov 15 14:47:20 2002 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Fri, 15 Nov 2002 19:47:20 GMT Subject: What is the best way to join tuples? References: <20021115051600.823.83734.Mailman@mail.python.org> Message-ID: "Terry Hancock" wrote in message > Hearsay says that list comprehensions are slower than regular loops, but I've > never actually compared them. I doubt the difference is really noticeable. > Raymond's solution appears to be more general. > > Personally, I'm more interested in which is clearer. I always find that I > can't write a list comprehension (beyond really trivial cases) until I've > written the solution out as a loop. But after the fact, when I look at the > two, the list comprehension seems clearer (even in this case). To help with the clarity comparison, here's are non-generalized versions: # O(n) dictionary approach xymatches = {} for x,y,z in xyzTuple: xymatches.setdefault((x,y), []).append(z) print [(w,x,y,z) for w,x,y in wxyTuple for z in xymatches.get((x,y), [-1])] # O(n**2) double loop approach wxyzTuple = [(w,x,y,z) for (w,x,y) in wxyTuple for (xp,yp,z) in xyzTuple if (x,y)==(xp,yp)] print wxyzTuple + [(w,x,y,-1) for (w,x,y) in wxyTuple if (x,y) not in [(x,y) for (x,y,z) in xyzTuple]] # O(n log n) sort/merge approach I wasn't able to come-up with code that wasn't convoluted. From tundra at tundraware.com Fri Nov 15 17:30:07 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: 15 Nov 2002 22:30:07 GMT Subject: Possible Win32 Tkinter bug? References: Message-ID: David LeBlanc wrote: > It sounds to me as though you don't have the right modality set for the > message box or something is messed up about your tkinter installation. > > Windows has 3 dialog modalities: > > application modal - the dialog gets the focus, the main app is disabled and > control returns to the app when the dialog is dismissed. IIRC, this is what > a tkMessageBox is by default and there's no option to change the modality. > system modal - the dialog gets the focus, all apps are disabled and control This is my understanding as well. However, I also found this at http://mini.net/tcl/MessagBox from Harald Oehlmann: On windows the tk_messageBox command sets the toplevel . to the top of the window stacking order. After the message box the toplevel . gets the focus. To "repair" this behavior on tcl8.4 one can protect the windows over . by wm attributes -topmost 1 and save the focus over the routine. # tk_messageBox for Windows which keeps focus and stacking order proc messageBox args { # > Save focus set Focus [focus] # > Get the toplevels above . and set topmost attribute set lWindows [wm stackorder .] set TopPos [lsearch $lWindows .] if {-1 != $TopPos && $TopPos != [llength $lWindows]} { incr TopPos set lWindows [lrange $lWindows $TopPos end] foreach Wi $lWindows { wm attributes $Wi -topmost 1 } } else { unset lWindows } } ... I'm still trying to figure out the corresponding Python (I've never really done anything in tcl), but this seems to explain the behavior I am seeing, no? -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From knepley at mcs.anl.gov Mon Nov 18 08:08:21 2002 From: knepley at mcs.anl.gov (Matthew Knepley) Date: Mon, 18 Nov 2002 07:08:21 -0600 Subject: Standard module for import hacks? References: <3DD8E0BB.898E3593@science-factory.com> Message-ID: >>>>> ">" == James Rauser writes: >> Hi, is imputil.py in the 2.2.1 distribution *really* a part of the standard library? I would like to do some >> import hacks (see below), but the information I can find about the "right" way to do it is contradictory. I've >> found references to __import__ (low-level), "ihooks" (no code) and imputil.py (in the library, but not documented). >> The Import-SIG seems to be inactive, but I found an old mail in which Guido says that imputil.py is still >> experimental, and other references which say that its performance is bad. >> Here's the task: we want to use Python as the scripting language for our bioinformatics software, which is >> organized as an (open-ended) collection of C++ shared libraries. These libraries are *not* written as python >> extensions, but they contain meta-information on their exported names which I can use to automagically map the >> exported functions into python callable objects. With this I can create and initialize a python module object. >> The code to do this is in an extension module 'pysf', in a function "sfimport". So, now I can write: >> import pysf # get the root module for our python interface >> pysf.sfimport("FOO") # map libFOO.so into a python module "pysf.FOO" >> from pysf import FOO # I get tired of typing pysf.FOO all the time >> FOO.bar("zot") >> What I'd like to do is eliminate the strange call to pysf.sfimport() and the nested module names and just be able >> to write >> import pysf # get root module, set up import hook >> import FOO # map libFOO.so onto python module FOO >> FOO.bar("zot") >> I'd like to do it in a way that will coexist with any other packages that also hack the import mechanism. What's >> the right mechanism? I believe the right way to go about doing this is to use ihooks.py. The functionality in __import__ is too high level. For instance, it will not allow you to override the search path, just the name binding in the importing space. Likewise, imp is too low-level and not modular enough. The ihooks stuff allows you to target exactly what you want to override (with Hooks() or by deriving a class from their basics). I have used ihooks in the computational PDEs project here. I made import a) Search the entire path for parts of a module, even if some of its is already found (nice for open ended modules) b) Consult a database and augment the search path during import In order to do this I made an 'importer' module which must be loaded first that overrides the default import mechanism, as shown in ihooks. Hope this helps. Matt >> TIA, Jim >> -- ------------------------------------------------------------------------ Jim Rauser Science Factory GmbH >> mailto:j.rauser at science-factory.com Unter K?ster 1 Tel: +49 221 277 399 204 50667 Cologne, Germany -- "Failure has a thousand explanations. Success doesn't need one" -- Sir Alec Guiness From Maric.MICHAUD at cirec.com Tue Nov 26 09:21:11 2002 From: Maric.MICHAUD at cirec.com (Maric MICHAUD) Date: Tue, 26 Nov 2002 15:21:11 +0100 Subject: memory leaks in Tkinter Message-ID: <27E327AB8201B54495D54105FBBBB1485D1320@SRVMSG.GERLAND2.local> I noticied some memory leak in text widget of Tkinter : Python 2.1.1 (#1, Aug 30 2001, 17:36:05) [GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.61mdk)] on linux-i386 Type "copyright", "credits" or "license" for more information. >>> s=open("a big file").read() >>> import Tkinter >>> t=Tkinter.Tk() >>> x=Tkinter.Text(t) >>> x.pack() >>> x.insert(end, s) # growing up memory to a little more than size of s >>> x.delete(1.0, end) # does not free memory >>> x.insert(end, s) # memory goes up again >>> x.delete(1.0, end) # memory freed by only one s >>> Is this a bug ? A problem with the version 1.152 of Tkinter ? From aleax at aleax.it Thu Nov 21 06:31:11 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 21 Nov 2002 11:31:11 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DDA7260.4050905@nyc.rr.com> <87u1ib6bte.fsf@key.localdomain> Message-ID: <3u3D9.49382$Yw.2293340@news2.tin.it> Patrick W wrote: > Alexander Schmolck writes: > >> 2. try to write something in 1-100 lines in CL that couldn't easier be >> written in e.g. python. > > Lots of things are easier in CL. > A simple example: > > (defclass thing () ()) > (defclass paper (thing) ()) > (defclass rock (thing) ()) > (defclass scissors (thing) ()) > > (defgeneric beats? (thing thing)) > (defmethod beats? ((x thing) (y thing)) nil) > (defmethod beats? ((x paper) (y rock)) t) > (defmethod beats? ((x rock) (y scissors)) t) > (defmethod beats? ((x scissors) (y paper)) t) Multimethods are indeed very powerful, but it doesn't show "in the small" (quite typical for many very powerful things), in that the above code isn't any easier than: class thing: pass class paper(thing): pass class rock(thing): pass class scissors(thing): pass def beats(x, y): def are(X,Y): return isinstance(x,X) and isinstance(y,Y) return are(paper,rock) or are(rock,scissors) or are(scissors,paper) and of course this could be further simplified by not even defining that useless class 'thing'...;-). Alex From jon+usenet at unequivocal.co.uk Thu Nov 7 14:22:32 2002 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Thu, 07 Nov 2002 19:22:32 -0000 Subject: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up References: Message-ID: In article , Martin v. L?wis wrote: >> What platforms doesn't it mean that on? What does it mean on those >> platforms? Are you talking about platforms with 16-bit integers? >> If so, I don't care. > > 64-bit platforms. -0x7fffffff-1 is 33 1 bits, followed by 31 zero > bits, on such systems. In future Python versions, it is an infinite > number of 1 bits followed by 31 zero bits. Oh, OK. I don't care about that either because struct.pack("!I") will still take the least-significant 32 bits and discard the 32-to-infinity extra set bits. Sheesh. Metaphors involving "blood" and "stones" come to mind. From treworn at cyberspace.org Mon Nov 11 16:45:15 2002 From: treworn at cyberspace.org (trewornan) Date: Mon, 11 Nov 2002 21:45:15 +0000 Subject: loggin out automatically References: <1036253358.19897.0@doris.uk.clara.net> <3DC853DF.6060509@cyberspace.org> <2emv9-p1g.ln1@news.lairds.org> Message-ID: <3DD024EB.9020409@cyberspace.org> Kyler Laird wrote: >>>>I am responsible for maintaining a PC in a hotel which is available for >>>>use of guests, basically just e-mail and web browsing. We are currently >>>>using a program called "timewatcher" which allows me to provide "access >>>>codes" each code providing a particular period of access - 20, 30, 60 >>>>min or whatever >>> >>>You could use this script as the default shell for guests; it >>>automatically kills bash after a fixed amount of time: >> > > [good simple Python script] > > >>Seconded. Something like this will probably serve you >>even better than your current "timewatcher". I think >>you'll end up pleasantly surprised at how simple and >>flexible such operations are under Linux. > > > Speaking of flexibility, I suggest that after the time > has expired, you check a file for a new code. This > would allow the user to acquire (buy? beg?) more time > and then use it without having to restart everything. > A setuid script could be used to update the file. > > I'd probably also do something more complex than this: > os.kill(pid, signal.SIGTERM) > Maybe just HUP it first and then TERM/KILL it later? I > am thinking it would be good to give it a chance to > save data. > > You're going to run an X server for all of this, not > just give users a command shell, right? You could just > use a similar script to end it. > > --kyler Sorry I haven't replied before but i've been away for the weekend and only just got back. Thanks for all your help, I think I've got enough of an idea now to be able to work towards something. Once again many thanks, Mark From anthony_barker at hotmail.com Wed Nov 6 13:40:14 2002 From: anthony_barker at hotmail.com (Anthony_Barker) Date: 6 Nov 2002 10:40:14 -0800 Subject: SSH/SCP References: <2259b0e2.0211050833.7367bf5f@posting.google.com> Message-ID: <899f842.0211061040.6c79fa5f@posting.google.com> Have a look at unison for syncing data http://www.cis.upenn.edu/~bcpierce/unison/ You can call it like pscp but it is more efficient and it it wraps ssh for you. Anthony http://xminc.com/anthony/ mis6 at pitt.edu (Michele Simionato) wrote in message news:<2259b0e2.0211050833.7367bf5f at posting.google.com>... > claird at lairds.com (Cameron Laird) wrote in message news:... > > In article , > > Matthias Huening wrote: > > >Hi, > > > > > >I am looking for a SSH/SCP module that will work on Windows (2000/XP) > > >and allow me to connect to a Linux server. Suggestions? > > . > > . > > . > > pyssh > > and the ssh module (twisted.conch) of Twisted > > . > > I had a bad experience with pySSH. It only works (with a patch) on Linux. I > don't know about twisted but maybe it is overkill. I simply wanted to > transfer files from my laptop running windows to my desktop running linux. > In this case the simplest way to do is to download (for free) putty > ans use soomething like > > os.system('pscp -pw %s %s %s' % (password,filename,hostname)) > > pscp (Putty secure copy) can also copy directories recursively with > the -r option. It is really a nice little program for simple things. > > > Michele From wlfraed at ix.netcom.com Mon Nov 25 14:45:25 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 25 Nov 2002 11:45:25 -0800 Subject: stupid Python/database connection References: <4cce07d5.0211250918.5c97a929@posting.google.com> Message-ID: animeshk fed this fish to the penguins on Monday 25 November 2002 09:18 am: > This is a really stupid question, I know. > > I am trying to write an app that might connect to an Interbase > database or an Oracle database, depending on a configuration file. > > I have seen some Python code for interfacing with a database, and it > seems to depend on the import statement. import some-lib-or-another > to access one kind of database, import some-other-lib-or-another to > access another kind of database. After the import, it's a matter of > calling that database type's "connect" statement. > > So . . . how can the decision of what-database-to-use be defferred to > runtime? When writing, say, a BDE app in Delphi, it would be a simple > matter of what alias to use. How is this done in Python? > Well, if possible, you could require an ODBC data source to be created for either database, and just use the generic Python ODBC module. Or (untested -- and you have to restrict your usage to the common elements): #read config if dbtype == "Oracle": import OracleSpecificDBModule myDB = OracleSpecificDBModule elif dbtype == "Interbase": import InterbaseSpecificDBModule myDB = InterbaseSpecificDBModule myCon = myDB.connect(...) > Thanks! -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From aleax at aleax.it Mon Nov 11 08:18:19 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 11 Nov 2002 13:18:19 GMT Subject: referencing disjoint array indexes References: Message-ID: Padraig Brady wrote: > Hi, > > Is there any way you can do something like > > size, mtime = os.stat()[8,6] Sure, e.g.: def getat(alist, *idx): return [alist[x] for x in idx] size, mtime = getat(os.stat(), 8, 6) I saw you mentioning in a followup that this "doesn't support slicing". Actually, not supporting slicing polymorphically with indexing is a problem with Python 2.2's builtin sequences (which were still using the C-level equivalent of the obsolete, deprecated __getslice__ &c methods), already overcome in Python 2.3 -- in 2.3a0: >>> def getat(alist, *idx): return [alist[x] for x in idx] ... >>> getat('four score and seven', 2, 3, slice(6,10), 1) ['u', 'r', 'core', 'o'] You do have to use the explicit notation with built-in 'slice' rather than just the colon-notation for slice -- the latter is NOT accepted by Python (even Python 2.3) in general syntactic positions such as argument passing: >>> getat('four score and seven', 2, 3, 6:10, 1) File "", line 1 getat('four score and seven', 2, 3, 6:10, 1) ^ SyntaxError: invalid syntax >>> But that's another issue -- if you want to argue for 6:10 as general syntax sugar for slice(6:10), I guess you should do that on the python-dev mailing list where you might convince the BDFL (I suspect he'll veto it once again as he did on all previous occasions, but, who knows). If you're serious about getting your suggested modification accepted, you are well advised to write a PEP for it first. Making blah[8,6] equivalent to [blah(x) for x in [8,6]] on the other hand is clearly unacceptable because "blah[8,6]" already HAS a meaning, and it is the same as blah[(8,6)]. Maybe that shouldn't be an error when blah is a list -- i.e. maybe a sequence's __getitem__ should be able to accept a sequence (in this case, a tuple) as well as an integer or a slice -- but I have no indication that the BDFL is currently prone to accepting further complications in the semantics of sequence indexing. Still, I don't claim to channel the BDFL (that's the timbot's job, not mine), so, again, python-dev is where you might possibly convince him (again, start by writing a PEP -- the bigger the change you want, the more a PEP is needed -- ideally, a sample patch wrt the current 2.3a0 CVS tree should also go with it, but that's nowhere like mandatory except in cases where a mod's very feasibility is in doubt). Alex From aleax at aleax.it Fri Nov 15 10:12:17 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 15 Nov 2002 15:12:17 GMT Subject: eMail including attachment on Linux References: Message-ID: Andreas Penzel wrote: > I am writing a Python program on Linux which should be able to send eMails > including an attachment with sendmail. > How to do that? For example: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52243 Alex From aleax at aleax.it Wed Nov 13 07:37:24 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 13 Nov 2002 12:37:24 GMT Subject: Convert type() to string? References: Message-ID: <8IrA9.4648$Yw.197307@news2.tin.it> Robert Oschler wrote: > I want to be able to print out the type() of a string for a "structure > walker" I'm writing. I need to be able to prepend a string of pad > characters to the type() so the following: > > print padstr + type(x) > > won't work because type() does not return a string. What's a good way to > do > this? I'm using Python 2.1 + Python 2.2 (2.1 for Jython). Either print "%s%s" % (padstr, type(x)) or print padstr + str(type(x)) (or many other variations) will work for your purposes. Alex From SBrunning at trisystems.co.uk Fri Nov 8 12:26:39 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Fri, 8 Nov 2002 17:26:39 -0000 Subject: Why is Python popular, while Lisp and Scheme aren't? Message-ID: <31575A892FF6D1118F5800600846864DCBDAD0@intrepid> > From: eddie at holyrood.ed.ac.uk [SMTP:eddie at holyrood.ed.ac.uk] > Intercal! don't be such a wuss - have a look at > http://www.eleves.ens.fr:8080/home/madore/programs/unlambda/ Too easy - try Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From ktilton at nyc.rr.com Sat Nov 30 19:29:09 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Sun, 01 Dec 2002 00:29:09 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3de1f902$0$695$edfadb0f@dread12.news.tele.dk> <96u4sa.llp.ln@cvs> Message-ID: <3DE95849.6040105@nyc.rr.com> Robin Munn wrote: > Max Ischenko wrote: > > If you're a > veteran Lisper, you'll have used proper indentation, of course; but if > you're a newbie, or if you're reading code written by a newbie, you > can't necessarily trust that indentation matches actual code structure. The two IDEs I've used (MCL and ACL) had editors which indented "properly" automatically when you hit the tab character (it is effectively a "auto-indent" command, /not/ a character insertion. If I suspect someone has been editing without reindenting, I select as much code as I like and (under ACL) hit ctrl-shift-p, which reindents. Me, after a lot of editing on a function, i like to start at the top and tab-downarrow-tab-downarrow zipping down the function watching each line reindent so anything out of the way jumps out at me. But it raely does. Those parens demarcate logical chunks of code, so i can edit the way I refactor, shuffling interesting semantic chunks effortlessly. This is not possible without parentheses. Folks afraid of Lisp's parens need to realize /no/ Lisper even thinks about them after a few weeks of coding, until the day we have to edit other languages, at which point we miss them badly. When i coded other languages I was pretty fussy about layout and had pretty firm indentation policies. The code looked fine, but I did wonder how much time I was spending on reformatting after refactoring. In Lisp its one key-chord. -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From pyth at devel.trillke.net Fri Nov 15 09:29:47 2002 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 15 Nov 2002 15:29:47 +0100 Subject: Python urllib.urlretrieve vs. Perl getstore In-Reply-To: <3DD3F7E8.519BC0BF@yahoo.se>; from musikintresserad@yahoo.se on Thu, Nov 14, 2002 at 07:22:16PM +0000 References: <3DD3F7E8.519BC0BF@yahoo.se> Message-ID: <20021115152947.D30315@prim.han.de> Adam S wrote: > > I have a Perl and a Python version of a program designed to fetch > large files (40MB) from a remote HTTP server. > > Initial tests indicate that the Perl version, using getstore() > is 3-4 times faster than the Python version. Is there a reason > for this and is there another Python library HTTP file fetch > function I can use? I don't want to use FTP as there > is no anonymous logon for this server. Please be more specific and post relevant code-snippets and which python-library you use. IMO perl's as well as python's retrieving functions should be 99% IO-bound meaning that there shouldn't be a speed difference unless you are having a Gigabit-Internet-Connection :-) regards, holger From bloke at ii.net Thu Nov 7 06:26:18 2002 From: bloke at ii.net (Rob Hall) Date: Thu, 7 Nov 2002 03:26:18 -0800 Subject: idiom for initialising variables References: <3dc964fa$0$12989@echo-01.iinet.net.au> Message-ID: <3dc96c81$0$12990@echo-01.iinet.net.au> Sorry, mistyped the first eg - should have been: class myClass: a = 1 def __init__(self): ...more stuff here I had ' self ' so firmly entrenched in my mind it just went there automatically. When I read code using this method I actually ' read ' self.a event though there was no self there! Thanks to all those who pointed out my mistake... it makes sense now that i READ it properly! Rob Hall wrote in message news:3dc964fa$0$12989 at echo-01.iinet.net.au... > I'm just wondering on the correct python idiom for initialising variables. > I see some code like this: > > class myClass: > self.a = 1 > def __init__(self): > ...more stuff here > > > > I also see: > > class myClass > def __init__(self): > self.a = 1 > ...more stuff here > > > Which is the correct idiom? or is there a subtle difference I am missing? > > > Rob > > From skip at pobox.com Fri Nov 15 06:25:22 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 15 Nov 2002 05:25:22 -0600 Subject: Reverse dictionnary In-Reply-To: References: Message-ID: <15828.55714.226904.829040@montanaro.dyndns.org> Julien> Does "reverse dictionnary" exists in python ? Nope. Julien> If this does not exists, I will simply do two dictionnaries, That's the usual technique, though this only works properly for one-to-one mappings. If your keys and values are truly of different types you can just use one dictionary: d1 = { 1:"str1", 2:"str2", "str1":1, "str2":2 } -- Skip Montanaro - skip at pobox.com http://www.mojam.com/ http://www.musi-cal.com/ From newsread at seabass.yi.org Mon Nov 18 20:17:47 2002 From: newsread at seabass.yi.org (michael eng) Date: 19 Nov 2002 01:17:47 +0000 Subject: infinite recursion Message-ID: Hello My program has a deeply recursive function which hits some upper bound in Python 2.2.1. I fear such madness comes from being forced to program in Prolog. Anyway, is there a way in which I can remove the upper bound, such that the recursion depth is only limited by the constraints of the machine? All the documentation I have found tells me how to set it to an arbitrary finite value. Thanks Michael -- From fperez528 at yahoo.com Mon Nov 18 14:25:15 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 18 Nov 2002 12:25:15 -0700 Subject: popkey() method for dictionaries? References: Message-ID: John Hunter wrote: >>>>>> "Fernando" == Fernando P?rez writes: > > Fernando> Sure. First, on principle: the exception option is still > Fernando> there, if no default is provided. What giving a default > Fernando> buys you is not having to trap the exception > Fernando> yourself. If you want a missing key to generate an > Fernando> exception, simply don't give a default and that's > Fernando> it. > > But then you break the symmetry with get, which provides None as a > default if no default is provided. Aren't you now back in danger of > violating the principle of least surprise? Mmmh. I hadn't used get without default in a long time, and I'd forgotten its not-found return was a None instead of an exception. I would argue _that_ violates the 'explicit is better than implicit' rule of python, but it's a bit late to change that one :) In general, since these are all wrappers around dict[key] access operations, and at the most basic level such an access to a non-existent key _will_ trigger an exception, I'd argue that the default behavior of all these functions (get, pop, popitem) should be to raise an exception. In this way they would most naturally mimic the underlying semantics, without magic behaviors. On the other hand, I think it is _useful_ syntactic convenience to have a way of explicitly overriding the exception triggering, for the reasons Alex Martelli and I argued elsewhere in this tread. Unfortunately these functions (get/pop/popitem) have already been written with (it seeems to me) inconsistent interfaces, and we'll just get used to keeping track of who does what with post-it notes. Cheers, f. From mwh at python.net Tue Nov 12 09:18:40 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 12 Nov 2002 14:18:40 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCE003C.9080505@mindspring.com> <7h3lm402zq5.fsf@pc150.maths.bris.ac.uk> <3DD09242.9010103@something.invalid> Message-ID: <7h33cq63mdp.fsf@pc150.maths.bris.ac.uk> Greg Ewing writes: > Michael Hudson wrote: > > > I think the d in cdr stands (stood) for decrement, not data. But the > > web seems confused on the issue. It just means "second half of cons > > cell" to me... > > > I gather there were also two 3-bit fields interspringled > with those, and Lisp originally had functions for accessing > those, too... I was surprised to find that my departments AMNAG (Applied Mathematics and Numerical Analysis Group) library contains a copy of the Lisp 1.5 manual -- I could probably go and look these things up... Cheers, M. -- > Why are we talking about bricks and concrete in a lisp newsgroup? After long experiment it was found preferable to talking about why Lisp is slower than C++... -- Duane Rettig & Tim Bradshaw, comp.lang.lisp From zoltan at trados.com Thu Nov 14 12:36:34 2002 From: zoltan at trados.com (Zoltan Sekeres) Date: Thu, 14 Nov 2002 18:36:34 +0100 Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> <3DD36C57.8050604@trados.com> Message-ID: <3DD3DF22.8050105@trados.com> Martin v. Loewis wrote: > The problem that I still consider unsolved is how may translators can > work on a single document, and how retranslation of the entire > document in case of changes can be avoided. This can be solved > theoretically, by assigning IDs to relevant elements (and then finding > out which IDs need to change), but I'm not sure whether this would > work in practice. (It drifts into off-topic space, but ...) That's what translation memories in general and XTranslate from Trados are good for. Translation memories save segments for re-use, either in the same document or in later versions. But the segments are usually stored without context, so the translator still has to check. Additionally there is XTranslate which takes an old version of a document including translation and a new version without. XTranslate will then use the context to identify segments which were added or were changed. The translator has to check less. Using IDs for this purpose didn't catch on AFAIK. Especially as segmenting, finding the correct units for those IDs, is a though job. -- Zoltan From moxie_is at yahoo.com Wed Nov 27 21:01:10 2002 From: moxie_is at yahoo.com (moxie) Date: 27 Nov 2002 18:01:10 -0800 Subject: wxSocketServer in wxPython Message-ID: I'm trying to use the wxSocketServer and wxSocketClient classes in wxPython, but wxPython does not recognize these classes. wxSocketServer and wxSocketClient both are in the wxWindows documentation, so I guess these classes are only available for C++ at the moment. Any ideas? ~= moxie =~ From a.schmolck at gmx.net Wed Nov 6 09:50:51 2002 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 06 Nov 2002 14:50:51 +0000 Subject: regex puzzle References: <3dc91095$1_1@omega.dimensional.com> Message-ID: "Mike Brown" writes: > I need an example of a regular expression that: > > - matches an empty string > - matches a non-empty string > - does NOT match a string consisting of only a linefeed Try ``re.match('(?!\n)', s)`` (unless of course you can do if s != '\n'). alex From ehagemann at comcast.net Tue Nov 12 20:03:55 2002 From: ehagemann at comcast.net (eric hagemann) Date: Tue, 12 Nov 2002 20:03:55 -0500 Subject: Installing dislin (scientific data plotting software) References: <3DD12A29.8B34ED2C@cs.nott.ac.uk> Message-ID: <3OednWogkaIkOUygXTWcog@comcast.com> Turhan, Did you direct dislin to that particular directory location ? It is my experience that dislin installs itself in c:\dislin vice c:\program files\dislin. I would remove and reinstall, letting it go to the default. Your symptoms indicate that you are having problems with spaces in the directory names. I currently have dislin 8 running with the exact set of packages -- and it works fine Cheers Eric "Turhan Ozen" wrote in message news:3DD12A29.8B34ED2C at cs.nott.ac.uk... I downloaded dl-80-py.zip and after unzipping, I installed dislin, then I added the following lines to the autoexec.bat: SET DISLIN = c:\program files\dislin SET PYTHONPATH = C:\program files\dislin\python But It seems that I have not installed it properly. When I choose the dislin or readme files from from the windows2000's start>programs>dispy, I get an error message dialogue box with the title "readme" and message "Open error in c:\program". When I try to use dislin in python it either crashes (doesn't respond and I have to end the program or gives the same dialogue box output or just quits python. I can import the dislin module but I can't use the plot function. And if I go to the dislin/python folder and double-click on the sample python files there the graphs are plotted. One more item that I want to mention is I use windows extensions to python (win32all-148). Numerical Python (Numeric-22.0.win32-py2.2) is the only other module installed at the moment. I would be most grateful if you could explain to me what is wrong and what I could do in order to be able to use dislin or direct me to a source that contains the answer to my problem. Best regards, Turhan -------------- next part -------------- An HTML attachment was scrubbed... URL: From e_viola at libero.it Thu Nov 14 19:20:47 2002 From: e_viola at libero.it (bart) Date: Fri, 15 Nov 2002 00:20:47 GMT Subject: BUG URLLIB2 Message-ID: <3DD43DA7.5070004@libero.it> I'm an italian student and my problem consists about urllib2; urlopen function, sometimes, give me old (and inexactly) url because the site has moved in a new location but urlopen doesn't undestand it and return 403 error FORBIDDEN. EXAMPLE: Python 2.2.1 (#1, Aug 30 2002, 12:15:30) [GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import urllib2 >>> con=urllib2.urlopen('http://www.google.it/search') Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/urllib2.py", line 138, in urlopen return _opener.open(url, data) File "/usr/lib/python2.2/urllib2.py", line 322, in open '_open', req) File "/usr/lib/python2.2/urllib2.py", line 301, in _call_chain result = func(*args) File "/usr/lib/python2.2/urllib2.py", line 785, in http_open return self.do_open(httplib.HTTP, req) File "/usr/lib/python2.2/urllib2.py", line 779, in do_open return self.parent.error('http', req, fp, code, msg, hdrs) File "/usr/lib/python2.2/urllib2.py", line 348, in error return self._call_chain(*args) File "/usr/lib/python2.2/urllib2.py", line 301, in _call_chain result = func(*args) File "/usr/lib/python2.2/urllib2.py", line 400, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 403: Forbidden >>> What can I do to repair the situation? Help me please!!! Thanks... -Ennio- From peter at engcorp.com Wed Nov 6 23:43:05 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 06 Nov 2002 23:43:05 -0500 Subject: PyGTA next meeting will be Thursday Nov. 14 Message-ID: <3DC9EF58.4F50FBCD@engcorp.com> Peter Hansen wrote: > > Ian figures we'll be able to have the next meeting in mid-November, > barring unexpected setbacks. > > He or I will post here shortly with an announcement, as soon as > something is firm. I'm happy to announce the next meeting of the recently formed Toronto Area Python/Zope User Group: PyGTA. The details of the venue are as follows: Site: 519 Church St. Community Centre Room no: TBD (signs will be posted) Address: 519 Church St., near Wellesley Date: Thurs. Nov. 14 Time: 8-10 PM There is metered parking available on Church St. and side streets. Metered parking spots are free after 9pm. The site is one block east of the Wellesley subway stop. There is a Green Spot parking lot on Wellesley, between Yonge and Church, on the south side. There are several good pubs including the Keg on Jarvis, within a block or two of the community center. Please visit our web site at http://web.engcorp.com/pygta for further details (unfortunately not updated as I write this, but I didn't want to delay the announcement any longer). I'll be posting this note shortly to the PyGTA mailing list for those who asked to be subscribed. -Ian Garmaise, Peter Hansen, PyGTA organizers From pyth at devel.trillke.net Sat Nov 30 08:41:02 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sat, 30 Nov 2002 14:41:02 +0100 Subject: Newbie Question: Giving names to Elements of List/Tuple/Dict In-Reply-To: <20021130144547.A1438@hishome.net>; from oren-py-l@hishome.net on Sat, Nov 30, 2002 at 02:45:47PM +0200 References: <1038571003.6023.20.camel@localhost.localdomain> <20021129141954.GA1876@hishome.net> <20021129160115.C11257@prim.han.de> <20021130144547.A1438@hishome.net> Message-ID: <20021130144102.E11257@prim.han.de> Oren Tirosh wrote: > On Fri, Nov 29, 2002 at 04:01:15PM +0100, holger krekel wrote: > > Additionally using > > > > class Struct: > > def __init__(self, **kw): > > self.__dict__.update(kw) > > > > is also a nice idiom. You can then say > > > > >>> one = Struct(name='guido', phone='5555') > > >>> one.name > > 'guido' > > >>> one.phone > > '5555' > > If you want something even fancier, try this: > > class record(dict): > def __init__(self, initfrom=(), **kw): > dict.__init__(self, initfrom) But this pollutes the instance's namespace. Is inheriting from the dict class really neccessary? > self.update(kw) > self.__dict__ = self So overall i think it's a neat trick but isn't worth the namespace pollution. holger From aahz at pythoncraft.com Tue Nov 5 19:46:50 2002 From: aahz at pythoncraft.com (Aahz) Date: 5 Nov 2002 19:46:50 -0500 Subject: The Deitel book (was Re: Textbooks on Perl/Python) References: <87b0ada6.0211011453.1df4d216@posting.google.com> Message-ID: In article , Chris Gonnerman wrote: > >I was one of the technical reviewers for this book, and frankly >I wasn't impressed. They only asked me for review of factual >information, not presentation or style; and I feel it is the latter two >that torpedo this book. That's all they asked me for, too, but I gave 'em my opinions, anyway. (Big surprise, right? ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From claird at lairds.com Mon Nov 4 12:37:45 2002 From: claird at lairds.com (Cameron Laird) Date: Mon, 04 Nov 2002 17:37:45 -0000 Subject: loggin out automatically References: <1036253358.19897.0@doris.uk.clara.net> <3dc3fcf4$0$7369@echo-01.iinet.net.au> <3DC451D3.4060907@cyberspace.org> Message-ID: In article , Ken Starks wrote: >In article <3DC451D3.4060907 at cyberspace.org>, trewornan > writes >>> >>> Some combination of the above, I'd say. Some people might suggest that you >>> were silly to not just /try/ your command in a python interpreter, e.g.-- >>> >> >>Good point but I don't have one running on linux and the installation of >> linux on another computer is being considered but is dependent on the >>feasibility of some system to limit access on a timed basis. >> >>Anyway thanks for letting me know why it won't work - I'll look more >>thoroughly at the linux documentation for possible answers. >> >>M >> >> >You can get python to run a telnet session to the linux machine, >without human intervention. change to super user, change to >any other user, kill processes, whatever. >Better not to send your root password though. > > >-- >Ken Starks So: did that make it clear? No, you cannot use system("logout") or a close variation to achieve what you want, but, yes, there are several Python-based ways to write it. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From LogiplexSoftware at earthlink.net Fri Nov 29 20:40:07 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 29 Nov 2002 17:40:07 -0800 Subject: importing question ? In-Reply-To: <3DE80A5B.2040309@nyc.rr.com> References: <3DE7F96B.1030606@nyc.rr.com> <3DE80A5B.2040309@nyc.rr.com> Message-ID: <1038620405.21793.257.camel@software1.logiplex.internal> On Fri, 2002-11-29 at 16:42, Kenny Tilton wrote: > Kenny Tilton wrote: > > > >> 'from classes import *' brings all the toplevel objects in classes > >> into your local namespace, so you can access them just through the > >> name. Generally, though, I think this is considered bad practice, as > >> it could create overlaps. > > > > > > I just ran into this and I do not like it, because I have what I > > consider one little subsystem (Cells) but I have it spread over ten > > source files. > > I just saw the option to: > > from import * > > along with listing all modules in an __all__ definition in the __init__ > file in the package directory. hope eternal. but it seems I then have to > qualify any reference with the module name (which I think I grok--it is > importing everything into the current namespace in go (nice) but then > leaves them compartmented by module when it does so (not what I wanted, > viz, a flat namespace for the package). Would the following sort of arrangement work for you? # --- file f1.py --- def fun1(): print "f1" # --- file f2.py --- def fun2(): print "f2" # --- file f3.py --- def fun3(): print "f3" # --- file f.py --- from f1 import fun1 from f2 import fun2 from f3 import fun3 # --- file main.py --- import f f.fun1() f.fun2() f.fun3() Just use an intermediary module to import the other files into (this could be the __init__.py file in a package directory). > -- > > kenny tilton > clinisys, inc > --------------------------------------------------------------- > ""Well, I've wrestled with reality for thirty-five years, Doctor, > and I'm happy to state I finally won out over it."" > Elwood P. Dowd -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 -------------- 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 loewis at informatik.hu-berlin.de Sun Nov 3 09:23:56 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 03 Nov 2002 15:23:56 +0100 Subject: Python2.1->2.2 broke my thread/signal code? References: Message-ID: Hugo van der Merwe writes: > n.skip() # This does the job when using 2.1, but not when using 2.2 Can you please elaborate what you expect to happen, and what happened instead? Regards, Martin From aahz at pythoncraft.com Sat Nov 16 17:30:48 2002 From: aahz at pythoncraft.com (Aahz) Date: 16 Nov 2002 17:30:48 -0500 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: In article , wrote: > >But it might avoid that if it were def'd as a nested function, if I've >got that straight? I'm not sure I grok that in fullness - does the >nested def get recompiled on every call to the containing function, or >is it compiled once and then skipped? Come to think of it, at least >some bits must be processed per call-of-containing or else some of the >recipies that bind to default args of the nested function wouldn't >work. I think. Pending further study of this small, simple language. > Nested functions are definitely parsed only once, creating a code object with bytecodes. However, the function object is recreated each time the enclosing function is executed. I'm not sure exactly what other steps are taken. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From e_viola at libero.it Fri Nov 15 14:31:37 2002 From: e_viola at libero.it (bart) Date: Fri, 15 Nov 2002 19:31:37 GMT Subject: BUG URLLIB2 References: <3DD43DA7.5070004@libero.it> Message-ID: <3DD54B71.1080806@libero.it> > That's not a bug in urllib2; google.it is *really* returning 403 > FORBIDDEN. > It appears that this google behaviour is triggered by the header > > User-agent: Python-urllib/2.0a1 > > that urllib2 sends, which, in turn, suggests that Google explicitly bans > urllib2. > Complain to them. > > Regards, > Martin > Thanks to all them that helped me swiftly!!! How can I change User-Agent field presents inside "urllib2"? I find two variables that (I think) define user agent in "urllib2" library: "__name__" and "__version__". I tested to set them following way: __name__="Mozzilla" __version__="5.0" but it failed yet!!! Whatever suggest is accept!!! - Ennio Viola - From joel.quinet at be.unisys.com Thu Nov 21 16:56:32 2002 From: joel.quinet at be.unisys.com (Quinet, Joel) Date: Thu, 21 Nov 2002 15:56:32 -0600 Subject: Inheritance and delegation problem. Message-ID: <8D7B1A876CBBD2119E6A00105AC57EF003AC679C@BE-BRU-EXCH-1> Hi all, I have an object using delegation to another one by replacing __getattr__ and __setattr__. It works fine. now, I have to do it a thread, I have added the threading inheritance. My problem is the threading.__init__ methode is NOT call apparently due to __getattr__ and __setattr__ redefinition. How can I do that ? Thanks for help Joel class ConfigPyroServer(threading.Thread): __instanceMarketsConfigParser = MarketsConfigParser() def __init__(self, group=None, target=None, name=None, args=(), kwargs=''): threading.Thread.__init__(self, group=None, target=None, name=None, args=(), kwargs='') self.sortie = 0 self.cond = EIA.Common.pyroserver.ConditionCounter() def run(self): self.serverP = EIA.Common.pyroserver.PyroServer( self.getPyroServerNameServerHostName(), ':' + self.getPyroServerObjectGroupName() ) self.serverP.createGroup( ':' + self.getPyroServerObjectGroupName() ) self.serverP.registerObjectPersistent( PyroInterfaceMarketsConfigParser, 'Config') while (self.sortie == 0): self.serverP.requestLoop( cond = self.cond.cond ) print 'Looping' print 'Stop looping' self.serverP.disconnect() self.serverP.shutdown() def __getattr__(self, attr): return getattr(self.__instanceMarketsConfigParser, attr) def __setattr__(self, attr, value): return setattr(self.__instanceMarketsConfigParser, attr, value) def stop(self): self.sortie = 1 From b.hall at irl.cri.nz Tue Nov 12 15:40:06 2002 From: b.hall at irl.cri.nz (Blair Hall) Date: Wed, 13 Nov 2002 09:40:06 +1300 Subject: simple metaclass question References: Message-ID: <3DD16726.56DD0137@irl.cri.nz> sismex01 at hebmex.com wrote: > > > This is the problem: you're deriving your metaclass > from 'object', instead of 'type'. > Well if you try my code with M(type) instead of M(object) nothing changes regarding my problem. From claird at lairds.com Mon Nov 4 10:55:19 2002 From: claird at lairds.com (Cameron Laird) Date: Mon, 04 Nov 2002 15:55:19 -0000 Subject: Book recommendation please References: <1036349092.40578.0@iapetus.uk.clara.net> <1036355743.4079.0@doris.uk.clara.net> Message-ID: In article <1036355743.4079.0 at doris.uk.clara.net>, Geoff wrote: . . . >out why some application I download won't compile. I would now like to >reconnect with programming and do something more creative. The silly >thing is that I had this preconception (left over from C64 days I guess), >that any worthwile language must be compiled and I did not pay any real >attention to python until I read a little more about it a few weeks ago - >since then it has been fun all the way :-) . . . Great! To congratulate you on your insight that worthwhile languages need not be compiled (in the usual sense), let me reinforce it: Python (and other high-level languages) have a record of achievement that compares favorably to those of C++, Java, ... in every way, apart from marketing. Python isn't universal; it comes as close to that dream as any language, though. My guess is that, however broad the horizons you now see for Python, the true ones are actually even more expansive. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From hancock at anansispaceworks.com Sun Nov 3 03:59:29 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 03 Nov 2002 08:59:29 GMT Subject: Python Browser Plugins (summary/proposal) Message-ID: After looking at all the replies I got to my "Python Browser Plugins" question and following up the links, I've put together what I see as a reasonable strategy for solving my clientside support problem. It amounts to a fairly large project, but it should be feasible for us to implement it over the course of 2003. Naturally any contributions or comments will be greatly appreciated. I wanted to link to the summary here and ask for any additional comments: Narya Clientside Implementation Concept http://www.anansispaceworks.net/NaryaInfo/client_html Cheers, Terry -- Anansi Spaceworks http://www.anansispaceworks.com From oren-py-l at hishome.net Sat Nov 30 07:45:47 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sat, 30 Nov 2002 14:45:47 +0200 Subject: Newbie Question: Giving names to Elements of List/Tuple/Dict In-Reply-To: <20021129160115.C11257@prim.han.de>; from pyth@devel.trillke.net on Fri, Nov 29, 2002 at 04:01:15PM +0100 References: <1038571003.6023.20.camel@localhost.localdomain> <20021129141954.GA1876@hishome.net> <20021129160115.C11257@prim.han.de> Message-ID: <20021130144547.A1438@hishome.net> On Fri, Nov 29, 2002 at 04:01:15PM +0100, holger krekel wrote: > Additionally using > > class Struct: > def __init__(self, **kw): > self.__dict__.update(kw) > > is also a nice idiom. You can then say > > >>> one = Struct(name='guido', phone='5555') > >>> one.name > 'guido' > >>> one.phone > '5555' If you want something even fancier, try this: class record(dict): def __init__(self, initfrom=(), **kw): dict.__init__(self, initfrom) self.update(kw) self.__dict__ = self def __repr__(self): return "%s(%s)" % (self.__class__.__name__, ', '.join(['%s=%s' % (k, repr(v)) for k,v in self.items()])) You can access fields as either attributes or dictionary items. Even tab completion works. The repr of this object is the constructor call to re-create it. Oren From fperez528 at yahoo.com Mon Nov 18 15:16:31 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 18 Nov 2002 13:16:31 -0700 Subject: Fast construction of Python list from large C array of int's - Extension Module References: Message-ID: quadric at primenet.com wrote: > I'm a bit of a Python newbie and I've written a C extension module. One > of the functions must return a Python list whose source is a large (5000 - > 6000) C array of integers. You may want to look at Numeric (http://www.pfdubois.com/numpy/) cheers, f. From hungjunglu at yahoo.com Wed Nov 27 16:24:51 2002 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 27 Nov 2002 13:24:51 -0800 Subject: Implementation of the global statement References: <8ef9bea6.0211270526.5a1278c5@posting.google.com> <7h3adjvqgs4.fsf@pc150.maths.bris.ac.uk> Message-ID: <8ef9bea6.0211271324.2c1a13aa@posting.google.com> Michael Hudson wrote in message news:<7h3adjvqgs4.fsf at pc150.maths.bris.ac.uk>... > hungjunglu at yahoo.com (Hung Jung Lu) writes: > > The global statement as in > > ... > > is a directive to the parser. > > Well, compiler, really. >From Guido's Python Language Reference Manual, Section 6.13 The global statement: "... Programmer's note: the global is a directive to the parser. It applies only to code parsed at the same time as the global statement. ..." Hung Jung From wurmy at earthlink.net Mon Nov 11 21:50:43 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Tue, 12 Nov 2002 02:50:43 GMT Subject: PEP #99484663 References: Message-ID: <3DD06E11.6080409@earthlink.net> Ian Bicking wrote: > As an exception, anyone who uses or implements Python-embedded-in-HTML > style systems wants (and usually adds) an explicit block delimiter. > It's essential in that domain. It is? In Kaa, you can use embedded code like this: <% foo.bar() %> for an expression, or <# for x in somelist: do_something(x) #> for statements. I don't see why explicit block delimiters are essential here. :-) Cheers, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ Kaa:: http://www.awaretek.com/nowak/kaa.html From animeshk at yahoo.com Tue Nov 12 12:57:43 2002 From: animeshk at yahoo.com (animeshk) Date: 12 Nov 2002 09:57:43 -0800 Subject: newbie question: how to get directory of script? Message-ID: <4cce07d5.0211120957.6d4934@posting.google.com> I'm sure this has been asked and answered a few zillion times: sorry! I want to be able to get the path of the script I am running (the idea is that I might have a data file or an ini file sitting in the same directory as the py file). Okay . . . so how do I get it? BTW, I am running Python 2.2.2 under Windows XP, with the wincom extensions. The docs said that sys.argv[0] should have the name of the script and, depending on the platform, the full path. Nope: sys.argv[0] has the full path of python.exe (this is occurring within the Wing IDE environment, within PythonWin, and even from the command line). The docs also said that sys.path[0] should have the directory of the script. Again, nope: it has the directory of python.exe. However, I saw the directory of the script in sys.path[1]. Problem: this works fine from the command line and from within the Wing IDE, but not in PythonWin (PythonWin sets sys.path[1] to ''). So . . . is there some "official"/"safe"/"standard" way of getting this information? Thanks! From grante at visi.com Fri Nov 8 15:27:10 2002 From: grante at visi.com (Grant Edwards) Date: 08 Nov 2002 20:27:10 GMT Subject: Complex numbers, abs results in mag, what results in phase? References: <071120021741272463%soufle@yahoo.com> <081120020724547965%soufle@yahoo.com> Message-ID: <3dcc1e1e$0$4458$a1866201@newsreader.visi.com> In article <081120020724547965%soufle at yahoo.com>, noyb wrote: > In article , Alex Martelli >> >> > I realize the angle is atan(b,a) but I need to use my_complex_variable >> > as input and not a,b. >> >> import math >> def phase(mcv): >> return math.atan2(mcv.imag, mcv.real) > > This seems obvious now! It always does after Alex explains it. -- Grant Edwards grante Yow! They don't hire at PERSONAL PINHEADS, visi.com Mr. Toad! From heafnerj at spam.vnet.net Mon Nov 4 22:09:26 2002 From: heafnerj at spam.vnet.net (Joe Heafner) Date: Mon, 04 Nov 2002 21:09:26 -0600 Subject: can't assign value to array element References: Message-ID: Dennis Lee Bieber wrote: > Uhmmm... Assuming zeros(m, Float) produces an array indexed from > 0..(m-1), then won't the last iteration of the for loop generate y[10] > =... IE, out of range... > Yes, and I fixed that one. :-) From jsaul at gmx.de Wed Nov 20 10:05:01 2002 From: jsaul at gmx.de (jsaul) Date: Wed, 20 Nov 2002 16:05:01 +0100 Subject: SWIG interface to access C array members Message-ID: <20021120150501.GA7731@jsaul.de> Hi there, I've got stuck with the following problem. In a C++ extension module, which I create from existing C++ code using SWIG, I need to access elements of array members of a class. Here is a trimmed-down version: %module xyz %{ #include "xyz.h" %} class xyz { public: xyz(); int a[10]; }; In Python, this doesn't quite behave as I would want it to: >>> import xyz >>> xx=xyz.xyz() >>> xx.a '_e0011708_p_int' >>> xx.a[0] '_' That is I get Python-'a' as textual representation of address and type of C-'a'. Through extending my class: %extend xyz { int __getitem__(int i) { return self->a[i]; }; } I get a little bit closer to what I want: >>> xx[0] 1 which is what I initialized 'a' with. But still, I would like to be able to write >>> xx.a[0] Any ideas about what I have to do? I don't want to touch the original codes. Cheers, jsaul -- Que le gusta rrrodarrr la errre. From blah at blah.org Fri Nov 29 02:23:03 2002 From: blah at blah.org (nospam sumofan) Date: Fri, 29 Nov 2002 02:23:03 -0500 Subject: python 2.2.2 install has unworking IDLE in windows 2000 Message-ID: Hey, I've just installed python 2.2.2 and although the command line interpreter works okay, the IDLE gui doesn't even run. I've loaded this both ways under Advanced settings, even checked Task Manager for hung processes. Nothing. Any ideas? I can't find anything out there about it ;) TIA --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.423 / Virus Database: 238 - Release Date: 11/25/2002 From costanza at web.de Tue Nov 12 17:25:16 2002 From: costanza at web.de (Pascal Costanza) Date: Tue, 12 Nov 2002 23:25:16 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3dce5e2f$0$35917$edfadb0f@dread13.news.tele.dk> Message-ID: Jeremy Hylton wrote: > Alex Martelli wrote in message news:... > >>Hmmm, on a slightly different tack, this DOES help me articulate one >>source of my slight reluctance to get really deep into Ruby: Ruby >>gives the programmer just a little bit MORE dynamicity/flexibility/ >>power than Python, by messing with the fundamentals of built-ins and >>passing "unevaluated code blocks" to methods (that's how you do >>iterators in Ruby, while Python's iterators are utterly different) -- >>although that's still not a full-fledged macro system, I may be >>subconsciously worrying that the little extra power IS just enough >>to get into "newbie cravings" territory. > > > I asked Matz about this at LL2 on Saturday. I asked if he could think > of examples where he wanted to change the language syntax. He said > the blocks were powerful enough that they could accomodate new > features without syntax change. > There are cases where blocks don't help you, but you're right in that blocks can take you very far. I must admit that I don't know enough about Python's philosophy, but if you are concerned about Python's cleanliness you could alternatively build in macros as a kind of "experimental" feature, or as a kind of preprocessor. This would allow you at least to play around with new constructs, and if they turn out to be useful they can be incorporated into the main Python language. And again, I definitely think that a combination of Python and Common Lisp would be beneficial for both communities. You could do 90% of coding in Python with more mainstream and thus more widely readable syntax, and the rest of the really hard stuff could be done on the Common Lisp level. I don't know if this could really work out, but I would like to use something like that... (Something like Python as the modern m-expressions of Lisp... ;) Pascal P.S.: We could name this "Biggus Dickus". ;-) -- Given any rule, however ?fundamental? or ?necessary? for science, there are always circumstances when it is advisable not only to ignore the rule, but to adopt its opposite. - Paul Feyerabend From mfranklin1 at gatwick.westerngeco.slb.com Fri Nov 8 10:31:35 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Fri, 08 Nov 2002 15:31:35 +0000 Subject: java to python In-Reply-To: <1036768161.439599@news.liwest.at> References: <1036768161.439599@news.liwest.at> Message-ID: <1036769496.1106.4.camel@m-franklin> On Fri, 2002-11-08 at 15:17, Christian Stockhammer wrote: > Hello List! > > I've got homework I have to solve in python but i just know a little bit > java and i got my homework to run in java. Is there anybody who can help me > to translate that code to python? > > Here it is: > > public class Tilgung{ > public static void main(String [] args){ > tilgungsplan(100000.0,5.0,20000.0); > } > > static void tilgungsplan(double schuld,double zinsfaktor,double tilgung){ > double zinsen; > double echteTilgung; > > System.out.println("Periode Restschuld Zinsen Tilgung"); > > for(int i=0;i<5;i++){ > zinsen=(schuld*zinsfaktor)/100; > echteTilgung=tilgung-zinsen; > System.out.println(" "+i+" "+schuld+" "+zinsen+" "+echteTilgung); > schuld=schuld-echteTilgung; > } > System.out.println(" Restzahlung: "+schuld); > } > } > > This is what it produces: (it is a calculator for paying back a credit)!!! > Periode Restschuld Zinsen Tilgung > 0 100000.00 5000.00 15000.00 > 1 85000.00 4250.00 15750.00 > 2 69250.00 3462.50 16537.50 > 3 52712.50 2635.63 17364.38 > 4 35348.13 1767.41 18232.59 > Restzahlung: 17115.53 > > Is there anybody who is willing to help me. I really appreciate any > suggestions > > Cheers Christian > > Some translations for you to get started: JAVA: System.out.println(""); Python: print "" JAVA: for(int i=0;i<5;i++) Python: for i in range(5): JAVA: static void tilgungsplan(double schuld,double zinsfaktor,double tilgung) Python: def tilgungsplan(schuld, zinsfaktor, tilgung): Otherwise make sure you indent coerrectly and get rid of those semicolons! (;) Now go grab a copy of the Python tutorial:- http://www.python.org/doc/current/tut/tut.html HTH Martin From martin at v.loewis.de Wed Nov 13 16:30:23 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 13 Nov 2002 22:30:23 +0100 Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> Message-ID: Gerhard H?ring writes: > But XML says *nothing* about semantics. So the *real* problems stay just as > hard as they were before. We digress, but to me, the main advantage of XML is that it eliminates the need for parsers, and the compiler construction business. You can use off-the-shelf parsers, instead of hand-crafting them using a parser-generation toolkit. You are right that all back-end processing (the synthesis phase in compilers) is still up to the application. There are traditional two camps of XML users: the "documents" people, and the "structured data" people. The former want to use XML for markup; the latter to represent some data structures externally. I can associate with the latter group - I think the former group is better served with SGML, since that allows to save typing. Regards, Martin From wlfraed at ix.netcom.com Sun Nov 10 17:46:39 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sun, 10 Nov 2002 14:46:39 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCE003C.9080505@mindspring.com> Message-ID: Pascal Costanza fed this fish to the penguins on Sunday 10 November 2002 05:45 am: > > I guess you are referring to "car", "cdr" and the like. They're > actually not funny but very useful. ("car" returns the first element As I recall, they also derive from the hardware that LISP was first implemented on -- C)ontents A)ddress R)egister, and C)ontents D)ata R)egister (or some variation thereof). Something to the effect that the original machine storage unit (words) effectively held two pointers, accessed as address and data... -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From aleax at aleax.it Sat Nov 9 02:24:54 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 09 Nov 2002 07:24:54 GMT Subject: Determining Presence Of GUI Support References: <42aiqa.jp82.ln@boundary.tundraware.com> Message-ID: Tim Daneliuk wrote: > Is there a portable method of determining whether the current runtime > environment supports a GUI or text-based interface? I would like to > write a single program which autosenses the presentation environment > and works accordingly. Well, you could do something like: try: import tkinter # or whatever other GUI toolkit you want except: # set things for no-GUI else: # set things for yes-GUI but that depends on what you mean by "support" -- it's conceivable that tkinter might load but then not be able to display anything because for example X11 isn't started (a rather platform-specific issue), or because it's started with parameters inappropriate to the display so the display is actually showing just a jumble of color streaks (more and more platform-specific), and so on. Alex From admin at e-tones.co.uk Wed Nov 13 14:17:11 2002 From: admin at e-tones.co.uk (e-tones.co.uk) Date: Wed, 13 Nov 2002 19:17:11 -0000 Subject: Referencing Data structures from a different file? Message-ID: <3dd2a563$0$28317$fa0fcedb@lovejoy.zen.co.uk> Hi all, I have 2 files... main.py data_structs.py In data_structs I have a list and a dicionary, how do I make it so main.py can access these data structures? Cheers Taz From max at alcyone.com Wed Nov 6 19:29:56 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 06 Nov 2002 16:29:56 -0800 Subject: Long overflow problem References: Message-ID: <3DC9B404.1AA625EC@alcyone.com> Tom wrote: > def myFunc (i, j): > for a in range(i, j): > print a > > I get the same error. Are there any implicit conversions going on > here? Yes, range only accepts two ints. This really shouldn't be too surprising; range actually builds a list, so if you really need to talk about numbers that different enough that you need longs, you pro-obably don't want to build a list containing all those values. If the size of the range (j - i) is small, then you could simply call range with the difference (an int) and each time through the loop add it to i (a long). Otherwise, just start with i, and keep adding 1 until you get to j. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Awards are merely the badges of mediocrity. \__/ Charles Ives EmPy / http://www.alcyone.com/pyos/empy/ A system for embedding arbitrary Python in template text as markup. From jkraska at san.rr.com Thu Nov 28 12:03:47 2002 From: jkraska at san.rr.com (Courageous) Date: Thu, 28 Nov 2002 17:03:47 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <20021128000512.T11257@prim.han.de> <7h3n0nuovvh.fsf@pc150.maths.bris.ac.uk> Message-ID: <3vicuu46ft9te78npuqm88d98v6entgs1o@4ax.com> >You'd have to know at compile time whether g() referred to a generator >of not, wouldn't you? No, you wouldn't. C// From donn at drizzle.com Mon Nov 18 00:08:31 2002 From: donn at drizzle.com (Donn Cave) Date: Mon, 18 Nov 2002 05:08:31 -0000 Subject: Get Stdout from external script startet through python References: Message-ID: <1037596109.791821@yasure> Quoth Pearu Peterson : ... | But may I extend the question to extension modules, that is, how to get | the (stdout or stderr) output that originates, say, from a | fprintf(stdout, ...) statement in an Python/C extension module? | | This questions has been raised also in f2py-users mailing list where | there was a wish to catch the stdout of a Fortran subroutine, wrapped to | Python. So far I have only an idea that this could be achieved | 1) by determining the pty (with os.ttyname(sys.stdout.fileno())) where | these messages go; | 2) and then using socket and termios modules to get the Fortran or C | messages. Ouch. You may be pleased to learn that it is not nearly such a hard problem (or perhaps disappointed to find that it's worse than that.) The basic question is, ``how can I read my own output?'' The obvious answer is, redirect it to storage - a disk file, or a pipe if you're absolutely certain the output gathered in one write session will be small enough to fit in the pipe (in other words, don't use a pipe.) Your UNIX operating system provides the means to do this redirection. 1. fd = posix.open(tmpfile, posix.O_WRONLY|posix.O_CREAT) 2. save_fd = posix.dup(1) 3. sys.stdout.flush() 4. posix.dup2(fd, 1) ... call functions, saving output 5. sys.stdout.flush() 6. posix.dup2(save_fd, 1) ... now output is back to normal ... repeat from (3) as required. So this redirection applies indiscrimately to your entire process, whether it's Python code or whatever. Donn Cave, donn at drizzle.com From mwh at python.net Mon Nov 18 10:53:12 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 18 Nov 2002 15:53:12 GMT Subject: wrapping all class methods References: Message-ID: Carl Banks writes: > (Maybe you can assign to it's __class__ attribute, but I recall > that assigning to __class__ is being phased out.) I don't think so -- in fact I'm currently trying to create a patch for 2.3 that will allow assignment to __bases__, so I think things are getting more permissive here... Cheers, M. -- I'm a keen cyclist and I stop at red lights. Those who don't need hitting with a great big slapping machine. -- Colin Davidson, cam.misc From glongman at ilangua.com Wed Nov 27 11:43:00 2002 From: glongman at ilangua.com (Graeme Longman) Date: Wed, 27 Nov 2002 16:43:00 +0000 Subject: Xml.Sax.Saxutils.escape() reverse ? Message-ID: <3DE4F614.1F65BB6F@ilangua.com> Hi, Does anyone know how to achieve the opposite of the escape method in Xml.Sax.Saxutils ? I've managed to escape my data so that I don't get a 'not well-formed' error but I don't know to get my data back into it's original form after the xml has done it's stuff. Thanks a lot. Graeme From aahz at pythoncraft.com Sat Nov 23 18:25:14 2002 From: aahz at pythoncraft.com (Aahz) Date: 23 Nov 2002 18:25:14 -0500 Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DDE711E.3010005@web.de> <2259b0e2.0211230554.1cde87bb@posting.google.com> Message-ID: In article , wrote: > >Or, as Joel's characters put it, balance is the way... ObJennie: Joel Rosenberg, _D'Shai_ ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From edream at tds.net Wed Nov 6 10:32:09 2002 From: edream at tds.net (Edward K. Ream) Date: Wed, 06 Nov 2002 15:32:09 GMT Subject: Guilty secret: globals baffle me References: <3U9y9.19300$ko1.2872530@kent.svc.tds.net> <82ay9.98000$TD1.4405986@news2.tin.it> Message-ID: > The global statement only makes sense inside a function. !! This is what I have been missing. Thanks very much. - Edward From mwh at python.net Tue Nov 12 09:15:12 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 12 Nov 2002 14:15:12 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: <7h37kfi3mjh.fsf@pc150.maths.bris.ac.uk> Marco Baringer writes: > but the problem is that the coressponding python code doesn't do the > same thing: > > in openmcl 0.13b: > > ? (* 1e10 (parse-float "0.4e-10")) > 0.4 > > in python 2.2 (whatever apple ships with jaguar): > > >>> float("0.4e-10") * 1e10 > 0.39999999999999997 This is a matter of printed representations. OpenMCL is lying (slightly) to you. Cheers, M. -- ZAPHOD: Listen three eyes, don't try to outwierd me, I get stranger things than you free with my breakfast cereal. -- The Hitch-Hikers Guide to the Galaxy, Episode 7 From aleax at aleax.it Wed Nov 20 09:08:50 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 20 Nov 2002 14:08:50 GMT Subject: Pickles References: Message-ID: William Kennedy wrote: > How big can a pickled object be. No direct limit AFAIK, except ones connected to the amount of memory you have available. > I am looking at an index 800 records long, should I be using a database "index" and "record" are not primitive concepts in Python, so it's hard to understand exactly what you mean. A relational database may give several advantages, with different cost/benefits tradeoffs as you move from lightweight ones such as Gadfly or SQLite up to enterprise-level heavies such as SAP/DB or Oracle, but amount of data you're handling is hardly ever going to be the only consideration in your choice of storage strategy. Alex From bhards at bigpond.net.au Tue Nov 5 16:10:28 2002 From: bhards at bigpond.net.au (Brad Hards) Date: Wed, 6 Nov 2002 08:10:28 +1100 Subject: power TypeErrors In-Reply-To: <200211052054.PAA05238@nealtech.net> References: <200211052054.PAA05238@nealtech.net> Message-ID: <200211060810.28875.bhards@bigpond.net.au> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Wed, 6 Nov 2002 08:02, anton wilson wrote: > I'm trying to understand the possible type errors for ** > > The language reference states that > > > The power operator has the same semantics as the built-in pow() function, > when called with two arguments: it yields its left argument raised to the > power of its right argument. The numeric arguments are first converted to a > common type. The result type is that of the arguments after coercion; if > the result is not expressible in that type (as in raising an integer to a > negative power, or a negative floating point number to a broken power), a > TypeError exception is raised. Looks like the docs are outdated. I'm not sure about the "broken power" bit. [bradh at localhost USB-guide-head]$ python Python 1.5.2 (#1, Jul 5 2001, 03:02:19) [GCC 2.96 20000731 (Red Hat Linux 7.1 2 on linux-i386 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> 1**-2 Traceback (innermost last): File "", line 1, in ? ValueError: integer to the negative power >>> -1.2**0.5 - -1.09544511501 bradh at squirt python $ python Python 2.2.1 (#1, Oct 4 2002, 09:50:49) [GCC 2.95.3 20010315 (release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 1**-2 1.0 >>> -1.2 ** 0.5 - -1.0954451150103321 Brad - -- http://linux.conf.au. 22-25Jan2003. Perth, Aust. I'm registered. Are you? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE9yDPEW6pHgIdAuOMRAjdTAKCDtA6nJWu5JsuWHRws+URhIxZbggCfVqjG noMdw5mMvn0VMAQ0SILvCOc= =eq55 -----END PGP SIGNATURE----- From peter.maas at mplusr.de Thu Nov 14 05:10:58 2002 From: peter.maas at mplusr.de (Peter Maas) Date: Thu, 14 Nov 2002 11:10:58 +0100 Subject: Newbie question References: Message-ID: <3DD376B2.2010301@mplusr.de> Firdaus Janoos schrieb: > I know this is kind of dumb, but i cant figure out how to execute a .py > file (not a module - a pgm ) from IDLE. I am unable to "load" the file. Guess you open the debugger from the debug menu abd press "go" in the debug window. Or you import the module in the shell and run some method. 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 jjl at pobox.com Tue Nov 19 13:32:00 2002 From: jjl at pobox.com (John J Lee) Date: 19 Nov 2002 10:32:00 -0800 Subject: timeoutsocket & sendall / Python 2.1 References: Message-ID: Surely somebody out there knows if this is correct? Does nobody use timeoutsocket any more? If not, what do you use? Thanks for any help "John J Lee" wrote in message news:... > It seems that Python 2.1 added a sendall method to socket objects. I > think something like this needs adding to timeoutsocket.py: [...] > + def sendall(self, data, flags=0): > + while data: > + n = self.send(data, flags) > + data = data[n:] > + # end sendall [...] > I've never used sockets directly, so apologies if this is broken / > hopelessly naive. > > I'm surprised that nobody has bumped into this before, which is > why I'm posting it here -- I have a feeling I must be missing > something. John From shadowlord13_1 at yahoo.com Mon Nov 18 17:58:36 2002 From: shadowlord13_1 at yahoo.com (Richard Dillingham) Date: Mon, 18 Nov 2002 22:58:36 GMT Subject: Hmm... An idea: if a,b==c,d: References: Message-ID: > Instead, (a, b) >= (c, d) is defined as (a>c or (a==c and b>=d)). I just keep reading that again and again and thinking "WTF? Why? Wha...." *shudders* Now I'm sorry I asked... From fperez528 at yahoo.com Thu Nov 7 14:20:47 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 07 Nov 2002 12:20:47 -0700 Subject: power TypeErrors References: <7h3ptthzlf0.fsf@pc150.maths.bris.ac.uk> <3DCAB43A.6EFA9A25@alcyone.com> Message-ID: Erik Max Francis wrote: > Note that in the interests of nitpickery, C99 does have a builtin > complex type. I know, and I'm happy to see it. Unfortunately, we all know how long it will be before C99 is fully supported by most compilers. I'll be glad when I can write C with complex numbers with no worries about portability or bizarre bugs. [snip] > That's probably the best rationalization I've seen for including complex > number support in the language itself. Implementing a complex number > class oneself is pretty straightforward, and the vast majority of > non-scientific users will never have a need for it, but when you want to > do scientific work and the builtins don't play nice with complex > numbers, it's a huge inconvenience. Thanks. I actually am a bit irked that in python, things like the power operator and other math functions aren't 100% complex-safe. But I understand that is tricky to do right, and manpower is limited. Maybe as the language gains popularity in scientific circles, someone will come out with the time to go in and fix those ugly corners. Cheers, f From b.e.n.c.a.t.7.3. at .t.p.g...c.o.m...a.u Sat Nov 9 00:29:52 2002 From: b.e.n.c.a.t.7.3. at .t.p.g...c.o.m...a.u (Ben C) Date: Sat, 9 Nov 2002 16:29:52 +1100 Subject: Question about drawing simple graph in Python? References: Message-ID: <3dcc9ce6@dnews.tpgi.com.au> Hi there try these http://py.vaults.ca/apyllo.py?find=graph I am sure that you will find something there that will do the job cheers Ben C "Mindy" wrote in message news:mailman.1036730290.879.python-list at python.org... > I have two lists, say: > list1 = ['s1','s2','s1','s3'...] > list2 = ['t1','t2','t3','t3'...] > > I want to draw a simple graph, with 's1' points to > 't1', which means drawing one line between 's1' and > 's2' and an arrow pointed to 't1'. (for i in > range(len(list1), there's an edge between list1[i] and > list2[i]). So how to draw this graph in Python? I > searched on google but didn't find some easy way to > implement this. Thanks for any hints! > > > > ===== > Cheers > -Mindy > > __________________________________________________ > Do you Yahoo!? > U2 on LAUNCH - Exclusive greatest hits videos > http://launch.yahoo.com/u2 > From anonymous at nodomain.none Fri Nov 29 19:26:46 2002 From: anonymous at nodomain.none (Tetsuo) Date: Sat, 30 Nov 2002 00:26:46 GMT Subject: mod_python References: <3de714c6$1@news.mt.net.mk> <3de7c1bb$1@news.mt.net.mk> Message-ID: >> That sounds so complex, clumsy and dumb that it's probably not the >> way. How do I make every script handle itself? I tried the publisher >> handler, and it proved useless. > > The publisher handler will do what you want How? Instructions give no clues. I tried to put in: AddHandler python-program .py PythonHandler mod_python.publisher With this, opening any script gives a not-found. Like the description says it should. That's not what I want. > >> I thought about importing everything to one script from others, but >> that isn't what I need at all. That's just pointless. > > And that's the way the publisher works You lost me. > >> And how do I make it so typing in a directory gives me a page >> (index.htm) instead of a list of the files in the directory? (Goes to >> take another look at the publisher) > > I dont believe that's connected to mod_python. I see. > I just want to know... How do other people do it? Because I'm lost and don't know what I want any more. I want to make a ratings site, kinda like Epinions, so what do I need for that? For now, I want to know how to run multiple scripts from one directory. If modpython can't do that, can Zope? From gminick at hacker.pl Sun Nov 17 11:21:52 2002 From: gminick at hacker.pl (Wojtek Walczak) Date: Sun, 17 Nov 2002 16:21:52 +0000 (UTC) Subject: What is the best way to merge two lists? References: <3DD71094.2030606@attglobal.net> <3DD7B7E8.2020402@attglobal.net> Message-ID: Dnia Sun, 17 Nov 2002 10:38:16 -0500, Pierre Rouleau napisa?(a): [...] > Is there a more efficient way to merge heterogenous lists than the brute > force approach used by uniq() above? Functions: --- flatten() --- import types flatret = [] def flatten(x, a=1): for i in x: if type(i) == types.ListType or type(i) == types.TupleType: flatten(i, 0) else: flatret.append(i) if a==1: return flatret --------------- --- mergelist() --- def mergelist(*lists): c = {} [[c.__setitem__(a,0) for a in flatten(i)] for i in lists] return c.keys() ------------------- A code to check if it works: --- def nic(): pass a = [1,2,3,[3]] b = [4,'b',1] c = [5,nic,['a', nic, 'b', [1, nic, 'b']]] d = [2,'a',8] e = [7,6,3] f = [1,nic,3] print mergelist(a,b,c,d,e) --- ...and it returns that: ['a', 1, 2, 3, 4, 5, 6, 7, 8, , 'b'] HTH in any way... ;> -- [ ] gminick (at) underground.org.pl http://gminick.linuxsecurity.pl/ [ ] [ "Po prostu lubie poranna samotnosc, bo wtedy kawa smakuje najlepiej." ] From bulbul at ucla.edu Tue Nov 26 22:02:34 2002 From: bulbul at ucla.edu (Leston Buell) Date: Tue, 26 Nov 2002 19:02:34 -0800 Subject: dbhash/bsddb problem, old bsddb version? Message-ID: <3DE435CA.5090800@ucla.edu> Hi. I have this nifty web-based address book program that i wrote a couple of years ago in Python. It is hosted on a web host, so i have no control over the way Python or other programs are installed. My web host, which is running a very old version of Red Hat Linux, probably 5.1, recently upgraded from Python 1.5 to 2.2. Now my program doesn't work. The program uses the anydbm module to store its data, in a file named "address.db". When i do whichdb.whichdb("address.db"), i'm told that this file is in dbhash format. However, when i try to open it using dbhash (on my home machine), i get the following: >>> dbhash.open( 'address.db', 'r' ) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/dbhash.py", line 16, in open return bsddb.hashopen(file, flag, mode) bsddb.error: (-30990, 'Unknown error 4294936306') I recall that when i first wrote this program a few years ago there was some sort of change in database format that required me to do something to make this file readable again (a discrepency between bsddb on my web host and a newer version on my home machine), but i don't remember what. My web host's new installation of Python doesn't even have the bsddb module installed (which is why anydbm.open fails). So, i've written a little program to convert my data file to gdbm (on my home machine). However, on my own machine i can't open the file using dbhash, as i just described. Can someone please tell me what i need to do to get at my data again? Oh, and another piece of advice i would appreciate. As i mentioned, i've already written a little program to convert my dbhash file to gdbm format. Is there any reason i should be using dbm instead of gdbm? Thanks. Leston bulbul at ucla.edu From skip at pobox.com Tue Nov 26 13:55:39 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 26 Nov 2002 12:55:39 -0600 Subject: Python Tutorial Was: Guido's regrets: filter and map In-Reply-To: <3de39ce9$0$22220$a1866201@newsreader.visi.com> References: <3de39ce9$0$22220$a1866201@newsreader.visi.com> Message-ID: <15843.50091.965638.345147@montanaro.dyndns.org> Grant> I see how you use list comprehensions to replace map and filter, Grant> but I don't understand why list comprehensions are touted as a Grant> replacement for reduce and lambda. In general, I don't think they are (though people make mistakes or aren't as precise as they ought to be at times). Map, filter, reduce and lambda get lumped together in the "functional programming" pot. List comprehensions only replace map and filter. -- Skip Montanaro - skip at pobox.com http://www.mojam.com/ http://www.musi-cal.com/ From maney at pobox.com Sun Nov 24 10:40:09 2002 From: maney at pobox.com (maney at pobox.com) Date: Sun, 24 Nov 2002 15:40:09 +0000 (UTC) Subject: Guido's regrets: filter and map References: <9PvekLArvL49Ewa2@jessikat.fsnet.co.uk> Message-ID: Robin Becker wrote: > I repeatedly get > > for loop took 5.81 > list comprehension took 8.16 > map took 4.23 > > with 2.2.2 win32 on a 1GHz pentium. Two runs each on the otherwise idle P3/850, Debian stable. Default Python is 2.1.3, other is 2.2.1: maney at wheel2:~$ python regrets.py for loop took 7.40 list comprehension took 7.98 map took 4.32 for loop took 7.34 list comprehension took 7.94 map took 4.32 maney at wheel2:~$ python2.2 regrets.py for loop took 6.91 list comprehension took 7.35 map took 4.35 for loop took 6.91 list comprehension took 7.34 map took 4.35 BTW, your tests include the 'del S' in the timed portion. Oddly, moving that to come after the end of the timed period doesn't have any effect on the for loop time, but reduces the other two tests by about 10%. I also tried adding a pre-charging construction before the for loop (I used the map, since it was fastest, of course), but that had no significant effect on any of the results. Odd. Although after seeing a 25% hit from changing the for loop to use the more natural S.append(...), I am left wondering how much of the speedup from using map I would ever see in actual practice. Hmmm... If we add a fairly trivial filter to the test things the differences become a great deal less significant: maney at wheel2:~$ python sorry.py for loop took 5.22 to make a list of 500000 items list comprehension took 5.22 to make a list of 500000 items map took 4.33 to make a list of 500000 items maney at wheel2:~$ python2.2 sorry.py for loop took 5.06 to make a list of 500000 items list comprehension took 4.90 to make a list of 500000 items map took 4.52 to make a list of 500000 items The test is a bit contrived, but seems a reasonable proxy for the low end of complexity of the sort of things I seem most often to be doing (usually with list comprehension syntax since I've been able to migrate away from 1.5 on all my active targets): ### revised test with filtering from time import time n = 1000000 N = xrange(n) t0 = time() S=[] a = S.append for x in N: if x % 2 == 1: a(str(x)) print 'for loop took %.2f to make a list of %d items' % ((time()-t0), len(S)) del S t0 = time() S = [str(x) for x in N if x % 2 == 1] print 'list comprehension took %.2f to make a list of %d items' % ((time()-t0), len(S)) del S t0 = time() S = map(str,filter(lambda x: x % 2 == 1, N)) print 'map took %.2f to make a list of %d items' % ((time()-t0), len(S)) ### Interesting chages when the filter is changed to select every seventh item (s/x % 2/x % 7/ in three places): maney at wheel2:~$ python sorry.py for loop took 2.57 to make a list of 142857 items list comprehension took 2.57 to make a list of 142857 items map took 2.94 to make a list of 142857 items maney at wheel2:~$ python2.2 sorry.py for loop took 2.58 to make a list of 142857 items list comprehension took 2.46 to make a list of 142857 items map took 3.24 to make a list of 142857 items Okay, that's enough for now. From sindrehi at c2i.net Tue Nov 19 09:22:11 2002 From: sindrehi at c2i.net (Pål Sindre Hiåsen) Date: Tue, 19 Nov 2002 15:22:11 +0100 Subject: read from user Message-ID: Hello! Is there somthing i have to think about when i write code who ask for input from user? I tried this: antall = input('some instruction ') #read a int for i in range(10): L[i]= raw_input('write names ') #read string What is wrong?? Sindre Hi?sen From martin at v.loewis.de Fri Nov 15 08:07:48 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 15 Nov 2002 14:07:48 +0100 Subject: Python documentation in DocBook References: Message-ID: anton at vredegoor.doge.nl (Anton Vredegoor) writes: > Of course the PSF has to be careful to not accept potential poisonous > contributions but it is the responsibility of the PSF to thoroughly > check legal problems and the contributor should not be burdened with > these matters. If the contributor contributes code using a BSD license > for the code, the code should be compatible to the Python license or > else the Python license itself would not be compatible to BSD. I think if the contributor contributes under any other but the Python license, we would ask him to reconsider, and license it (to us) under the Python license. > Yes you should be careful, but be careful by checking the code and > it's license. If you start assuming people to be taking advantage > unless they can proove that they are not you miss a lot of chances. This is unclear. People who want to contribute are, in my experience, very open to suggestions for changing their licenses - unless they are bound already by other obligations. In that case, we will have to consider whether Python should be bound by the same obligations. > >So anonymous contributions are clearly out of question. > > I hope I gave an example of someone not being able to contribute as > you asked about in a previous post, although it's a situation > occurring only for the very few people that care about these matters > :-) Yes, I do acknowledge that problem: and it did cause contributors to withdraw their contribution (in most cases, because they could not get the necessary clearance from their company). That is a serious issue, but independent from the issue of the documentation processing tool chain. > 128 bits of type checking is not pythonic and will severely limit the > set of possible interactions with your clients. I am not discussing > data: I am discussing protocols. The please elaborate: You have no problems with giving some of your private data to SourceForge, but you are concerned about the specific protocol mechanism? Can you please elaborate? In what specific scenarious would the protocol be inadequate? Regards, Martin From fclift at verio.net Fri Nov 8 13:39:33 2002 From: fclift at verio.net (Fred Clift) Date: Fri, 8 Nov 2002 11:39:33 -0700 (MST) Subject: complicated class question Message-ID: <20021108113625.E58344-100000@vespa.dmz.orem.verio.net> If any of you could spare a moment of your time and perhaps help me figure out a problem I'm having, I'd be most grateful. If you dont have time or dont want to bother with me, then feel free to ignore this email message :). My problem has to do with looking for a way to override methods in a system library that I dont want to modify, that is used in a 3rd party library that I dont want to modify. I can summarize the problem with a toy example: class a: def foo(self): print "hi" class b: def bar(self): ainst = a() ainst.foo() say that a is defined in a system library and that b is in a 3rd party library. I'd like to get b to use a modified version a, without having to change the code of either my code would do something like: binst = b() binst.bar() and I'd like the version of a.foo that is called be def myfoo(self): print "bye" Does that make sense? I could just derive a new class from B and override bar, but in this case, bar is like 80 lines of code and the the use of the a-classed object is relatively minimal -- I'd have to basically copy the whole thing - maintainace problems with new versions of the library etc. I'm stumped :). If you've read this far, thanks for your kind interest. Fred -- Fred Clift - fred at clift.org -- Remember: If brute force doesn't work, you're just not using enough. From gcash at luncheonmeat.cfl.rr.com Sat Nov 9 00:57:48 2002 From: gcash at luncheonmeat.cfl.rr.com (gcash) Date: Sat, 09 Nov 2002 05:57:48 GMT Subject: ftplib two server "proxy" support References: <4rashloo.fsf@cfl.rr.com> Message-ID: Andrew Markebo writes: > / gcash wrote: > | Is there anyone who's done support for the 2 server model of the FTP > | RFC-959, the thing that most UNIX FTP clients call "PROXY" ?? > | > | I'm talking about Figure 2 in Section 2.3 of RFC-959 and *NOT* a firewall > | or other type of intermediate proxy. > > When reading the ftplib source of Python 2.2 I find a function ftpcp > that seems to do this.. WOW! I totally missed that... thank you VERY much. I though I'd gone through that code with a fine-tooth comb, but evidently not. -gc -- Christmas is weird. What other time of the year do you sit in front of a dead tree and eat candy out of your socks? -- Metamorph at mmcable.com (alt.gothic) From fperez528 at yahoo.com Sat Nov 9 17:52:06 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Sat, 09 Nov 2002 15:52:06 -0700 Subject: Numarray append References: <1ggz9.11678$Zn2.332778@twister1.libero.it> Message-ID: Fabrizio wrote: > Hi, > > Is there a quick way to append elements to a Numarray array ? > > I could not find any. You are thinking of numarrays as python lists. They are much more like C arrays: homogeneous, fixed-size structures. That's why things can be done fast with them, but the price you pay is flexibility. If you need to grow a numarray, the easiest way is to allocate a new one of the desired final size, then copy into it the data of the original and fill in the new data as needed. With judicious use of take & friends all this can be done efficiently. Cheers, f. From joconnor at cybermesa.com Sun Nov 3 08:53:48 2002 From: joconnor at cybermesa.com (Jay O'Connor) Date: Sun, 03 Nov 2002 13:53:48 GMT Subject: Foot in mouth disease References: Message-ID: <3dc52a19.3339913@news.cybermesa.com> On 1 Nov 2002 23:06:06 -0500, aahz at pythoncraft.com (Aahz) wrote: >So I've been having a friendly argument for a long time with a friend of >mine who's a real Java booster. The current iteration was sparked by a >discussion of extreme programming, where along the way I repeated what >some people here have mentioned about Python being easier to refactor >than Java. She asked me what -- if any -- Java-based tools were used by >the experienced Java programmers who made that claim. She thinks that >those tools are superior to plain text editors (which are really all >that's needed for Python). > >Anyone wanna help me out here? Nope, sorry. I really like Python, but I still miss the development tools I have when using Smalltalk Take care, Jay Jay O'Connor joconnor at cybermesa.com http://www.cybermesa.com/~joconnor "God himself plays on the bass strings first, when he tunes the soul" From hat at se-46.wpa.wtb.tue.nl Thu Nov 28 10:42:30 2002 From: hat at se-46.wpa.wtb.tue.nl (Albert Hofkamp) Date: Thu, 28 Nov 2002 15:42:30 +0000 (UTC) Subject: LAN communication under windows References: Message-ID: On Thu, 28 Nov 2002 08:42:52 -0600, sismex01 at hebmex.com wrote: >> From: stojek at part-gmbh.de [mailto:stojek at part-gmbh.de] >> Sent: Thursday, November 28, 2002 6:11 AM >> >> Hi, >> >> for a little (net) game i am planning, i have to write two components, >> a client and a server module. If one of the gamers starts the >> Except that I have no idea how to start or where to look? Do I have to >> use services or sockets or something else? I am sure there is a simple >> example somewhere, but i can't find it. Python documentation, library reference manual, socket module. Albert -- Unlike popular belief, the .doc format is not an open publically available format. From grante at visi.com Sun Nov 24 19:19:07 2002 From: grante at visi.com (Grant Edwards) Date: 25 Nov 2002 00:19:07 GMT Subject: Bug in Win32file WaitCommEvent ??? References: <3ddaa58d$0$4459$a1866201@newsreader.visi.com> <3DDD711D.2000802@skippinet.com.au> <3dde5012$0$4491$a1866201@newsreader.visi.com> <3dde5e18$0$22192$a1866201@newsreader.visi.com> Message-ID: In article , Mark Hammond wrote: >>> Also much easier for me to code ;) > >> When in doubt, do whatver is simpler. > > Yes, good philosophy. > > How about I make a deal with you - I will add this support, and you > translate your C++ code that demonstrates the mask change into Python > once this is available? The next win32all is about due anyway. Sure. Is the mask object returned by an overalapped read going to know how to turn itself into an int (analogous to the way it knows how to turn itself into a string), or do I need to access individual bytes and do that in user-code? -- Grant Edwards grante Yow! Actually, what at I'd like is a little toy visi.com spaceship!! From gmuller at worldonline.nl Mon Nov 4 14:07:06 2002 From: gmuller at worldonline.nl (GerritM) Date: Mon, 4 Nov 2002 20:07:06 +0100 Subject: pyqt rules References: <3dc550fb$0$9008@echo-01.iinet.net.au> <2Dkx9.42039$Lg2.11444432@news2.news.adelphia.net> Message-ID: "Phil Thompson" schreef in bericht news:mailman.1036400645.4450.python-list at python.org... <...snip...> > > >The binary of PyQt for Qt NC is at >> >http://www.riverbankcomputing.co.uk/pyqt/download.php >> >> So I get the binary (exe's) for both...run 'em and now I can do PyQt? > > Correct - so long as you conform to the license conditions. > > Phil The license conditions sound awefully complex again. They assume a clear separation between private and professional life, which I don't experience as such. Although Eric looks nice, the license issues sound too complicating, I prefer the openness of Python. This means I will have to work with the clearly less powerfull but simple Idle regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From diltonm at pacbell.net Fri Nov 22 13:15:32 2002 From: diltonm at pacbell.net (Dilton McGowan II) Date: Fri, 22 Nov 2002 18:15:32 GMT Subject: Bug in Win32file WaitCommEvent ??? References: <3ddaa58d$0$4459$a1866201@newsreader.visi.com> Message-ID: <8vuD9.2706$nF2.182560030@newssvr21.news.prodigy.com> "Grant Edwards" wrote in message news:3ddaa58d$0$4459$a1866201 at newsreader.visi.com... > I'm trying to figure out how WaitCommEvent() works in Python, > and it looks like there's a problem when it's used in > overlapped mode. > > My understanding is that (in C) you: > > 1) Call WaitCommEvent() and give it three parameters: > * File handle > * a pointer to where the output mask value is to be stored > * a pointer to an overlapped struct > > 2) WaitCommEvent() returns immediately. > > 3) Call one of the WaitXXX() functions to wait on the event in > the overloapped struct. > > 4) When the event is triggered WaitXXX() returns. Check the > value stored via the output mask pointer passed in 1) > above. > > [I've gleaned most of this from > http://msdn.microsoft.com/library/en-us/devio/base/waitcommevent.asp] > > > What I can't figure out: How is this supposed to work in Python? > > 1 /* File : win32file.i */ > [...] > 2089 static PyObject *MyWaitCommEvent(PyObject *self, PyObject *args) > 2090 { > 2091 PyObject *obHandle, *obOverlapped = Py_None; > 2092 if (!PyArg_ParseTuple(args, "O|O", > 2093 &obHandle, // @pyparm |handle||The handle to the communications device. > 2094 &obOverlapped))// @pyparm |overlapped||This structure is required if hFile was opened with FILE_FLAG_OVERLAPPED. > 2095 // If hFile was opened with FILE_FLAG_OVERLAPPED, the lpOverlapped parameter must not be NULL. It must point to a valid OVERLAPPED structure. If hFile was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the function can incorrectly report that the operation is complete. > 2096 // If hFile was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, WaitCommEvent is performed as an overlapped operation. In this case, the OVERLAPPED structure must contain a handle to a manual-reset event object (created by using the CreateEvent function). > 2097 // If hFile was not opened with FILE_FLAG_OVERLAPPED, WaitCommEvent does not return until one of the specified events or an error occurs. > 2098 return NULL; > 2099 HANDLE handle; > 2100 if (!PyWinObject_AsHANDLE(obHandle, &handle, FALSE)) > 2101 return NULL; > 2102 OVERLAPPED *poverlapped; > 2103 if (!PyWinObject_AsOVERLAPPED(obOverlapped, &poverlapped, TRUE)) > 2104 return NULL; > 2105 DWORD mask; > 2106 BOOL ok; > 2107 Py_BEGIN_ALLOW_THREADS > 2108 ok = WaitCommEvent(handle, &mask, poverlapped); > 2109 Py_END_ALLOW_THREADS > 2110 DWORD rc = ok ? 0 : GetLastError(); > 2111 if (rc!=0 && rc != ERROR_IO_PENDING) > 2112 return PyWin_SetAPIError("WaitCommError", rc); > 2113 return Py_BuildValue("ll", rc, mask); > 2114 } > > I've been looking at the sources above, and the output mask > pointer passed in 1) points to a _local_ DWORD variable [lines > 2105, 2108]. Right? > > When used in overlapped mode, WaitCommEvent returns before the > event has happened (and therefore before the output mask value > has been written). What happens when the event actually occurs > [between 3) and 4) above] and Win32 writes the output mask > value? The mask pointer which Win32 has stashed away from the > call at 1) is no longer valid. I think. Maybe. > > How _do_ you get the output mask value in overlapped mode in > Python? > > In C, you do it by passing a mask pointer that points to a > variable whose lifetime extends past the point in time when the > event actually happens and the WaitXXX() call returns [and then > you check the output mask value]. > > Disclaimer: I'm a Unix guy and find the Win32 stuff to be > overly complex and baroque. Perhaps I haven't > understood the MSDN docs and the example C code > I've seen. If so, I'd be eternally grateful if you > could point me to decent docs for the Win32 serial > port API. > > -- > Grant Edwards grante Yow! Now KEN and BARBIE > at are PERMANENTLY ADDICTED to > visi.com MIND-ALTERING DRUGS... This is from a C++ port read method I wrote some time back. It works for reading characters. --------begin--------------- BYTE Byte; DWORD dwCommModemStatus, dwBytesTransferred; // Specify a set of events to be monitored for the port. //SetCommMask (m_hPort, EV_RXCHAR | EV_CTS | EV_DSR | EV_RLSD | EV_RING); SetCommMask(m_hPort, EV_RXCHAR); #ifdef _DEBUG cout << "\nAbout to wait for comm event" << endl; #endif // Wait for an event to occur for the port. WaitCommEvent(m_hPort, &dwCommModemStatus, NULL); // WaitCommEvent(m_hPort, &dwCommModemStatus, &m_overlapped); #ifdef _DEBUG cout << "\nAfter wait for comm event " << endl; #endif // Re-specify the set of events to be monitored for the port. //SetCommMask (m_hPort, EV_RXCHAR | EV_CTS | EV_DSR | EV_RING); SetCommMask(m_hPort, EV_RXCHAR); if (dwCommModemStatus & EV_RXCHAR) { #ifdef _DEBUG cout << "\nIts a receive char" << endl; #endif // Loop waiting for the data. int loop = 0, ret = 0; do { // Read the data from the serial port. ret = ReadFile(m_hPort, &Byte, 1, &dwBytesTransferred, 0); //ret = read((int) m_hPort, (void*) &Byte, 1); // Capture the data read. if (dwBytesTransferred == 1) byteArr[loop] = Byte; loop += 1; if(loop > MAX_RECV_BUF) { #ifdef _DEBUG cerr << "Serial::PortRead() Exceeded buffer size." << endl; char msg[512]; memset(msg, '\0', sizeof(msg)); sprintf(msg, "Serial::PortRead() Exceeded buffer size."); AddToMessageLog(msg); #endif return PORT_READ_ERROR; } } while (ret != 0 && dwBytesTransferred == 1); // Read the data from the serial port once more // to be sure no characters are left. ret = ReadFile(m_hPort, &Byte, 1, &dwBytesTransferred, 0); } return 0; -----end------------------- From aleax at aleax.it Mon Nov 18 04:51:58 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 18 Nov 2002 09:51:58 GMT Subject: How to write Inline Functions in Python? References: Message-ID: <2L2C9.22705$744.831937@news1.tin.it> Michael Stenner wrote: ... > I'm not convinced that it would be "worth it" to have "inline > functions" or "auto-inlined code" or whatever you want to call it. > That's what I'm trying to discuss. I'm interested in your (and > others') thoughts on the matter. So far though, I find your claims > that they would be useless unconvincing. Let's try another tack -- how would it work? def f(x): return g(x+1) right now, the Python compiler is not ALLOWED to assume, when compiling this code, that name 'g' refers to whatever it's referring "RIGHT NOW", i.e., at compile-time -- indeed at the time the compilation is taking place it's quite usual and typical for name g to be undefined-yet. Python's semantics guarantee that g will be looked up AT RUN-TIME and call whatever callable is bound to name 'g' at the time of each call to f, quite possibly a different one each time. g need not be a function -- it might be an instance of any callable class, and then quite likely might be a different instance upon different calls to f. OK so far? This is where we're starting from. Now, what black magic would you be willing to put up with, to enable the user to state that g should not be called (despite the presence of the call-operator "open and close parens":-) but rather "expanded"? That's the issue as I see it. If g is a qualified name, as it often will be when using functions defined in another module: def ff(x): return gmod.gfun(x+1) it becomes even murkier. Do you think the huge irregularity involved in "inline is only allowed for functions whose def statement precede the inline-use in this very module" would be an acceptable price to pay, for whatever modest benefits you think having the compiler inline things rather than having to do that yourself might bring? The discussion needs to be split in two alternative threads depending on this crucial decision. If "inline" must only apply to functions whose "def" statement is in this very module, then its miniscule applicability will substantially reduce the benefits. The costs in terms of making the language more complicated are still there (nowhere as large as in the more general case): defining precisely what happens to scoping, who if anybody is allowed to rebind global name 'g' in this module and what happens if they try, what happens when the function object bound to name g is used in any other way except calling it immediately, etc, etc. If "inline" is to be of any measurable usefulness and therefore also apply to functions imported from other modules, then we need to introduce an entirely new concept of "compiletime import" (as well as dealing with all the issues mentioned in the above paragraph, further complicated by having to deal with the various level of names in a qualified name). Summarizing, my working hypothesis is NOT "inline would be TOTALLY useless"; rather, it is, for either possible choice regarding what functions inlining could apply to, the costs and complications would be SO huge compared with the possible benefits that it almost defies belief that somebody would propose such changes in earnest. Analogy: suppose the UN came up with a plan to distribute a small piece of mint candy to every single person in the world. Would that be COMPLETELY useless? No: SOME people in the world like mint candy, or have never been able to taste it (being appallingly poor) and would like it if they could; so, ignoring the costs for an instant, overall human happiness MIGHT be ehanced by implementing such a plan (despite the risks of some people misusing their candy, e.g. by eating it when they have diabetes and shouldn't) -- it's at least possible. However, the costs and complications are so obviously huge -- just the logistics involved are staggering -- compared with the miniscule benefits, that it defies belief that anybody would seriously entertain such a notion in earnest, particularly when thinking of the many other obvious ways those enormous resources might be used, could they be summoned, to enhance overall human happiness (e.g. by fighting hygiene problems, illnesses, and malnutrition, rather than focusing all of those resources on distributing mint candy). So, I would not feel moved to criticize somebody who described such a plan as "useless", even though the term is not strictly and literally applicable. Alex From gerhard.haering at opus-gmbh.net Wed Nov 27 07:49:48 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 27 Nov 2002 12:49:48 GMT Subject: what does is ? References: <3de4a6dd$0$86531$ba620e4c@news.skynet.be> <3DE4B96D.1060808@Linux.ie> Message-ID: Padraig Brady wrote: > Gerhard H?ring wrote: >> Jonas Geiregat wrote: >> >>>I saw something >>>import string >>>string._StringType is str >>>what does this specially that IS >> >> The "is" operator compares object *identity*, rather than equality, which >> the "==" operator does. > > Well why does the following happen on 2.2? > Is Python being clever about merging variables? > > s1="123" > s2=s1[:] > s1 is s2 #true? Yes. Certain strings (not all) are being "interned". And certain ints (not all) are interned, too: >>> a = 5 >>> b = 10/2 >>> a is b 1 >>> x = 1000000000000 >>> y = 2000000000000 / 2 >>> x is y 0 But it seems to me that the [:] slicing has an additional optimization, apart from interning. -- Gerhard H?ring OPUS GmbH M?nchen Tel.: +49 89 - 889 49 7 - 32 http://www.opus-gmbh.net/ From theller at python.net Thu Nov 21 06:25:27 2002 From: theller at python.net (Thomas Heller) Date: 21 Nov 2002 12:25:27 +0100 Subject: Understanding PyEval_InitThreads References: <7kf83526.fsf@python.net> <95959723.0211201844.7ce3458@posting.google.com> <1037851388.29783@yasure> Message-ID: "Donn Cave" writes: > Quoth hansgeunsmeyer at earthlink.net (hg): > ... > | As far as I understand it, it doesn't really matter _what_ the thread > | state is that you swap into the current state before you do the > | callback, as long as it is _some_ valid thread state (not NULL). So, > | before you do the callback, at any moment when you're in the main > | Python thread, you could store a pointer to the then current > | threadstate. > > Why are there multiple thread states, then? If we might as well just > use the existing state of any thread, it seems like we are put to a > lot of trouble to hunt one up. The thread state is, well, the state of a thread. So at least they cannot be shared across threads. I had multiple other schemes saving thread states when calling out to C from Python, and getting thread states when calling back into Python from C, including stacks of thread states in thread local storage. Some of them worked, some were fragile. The current scheme (saving it in a local var when calling 'out' and creating a new one when calling 'in') works well, also for multithreaded programs. It's also the one used (I believe) in Mark's win32all. There are some drawbacks with this approach as far as I can see: First a performance hit, because thread states are frequently created and destroyed again. Second, profiling and setting breakpoints won't work across callouts and callins because the profiling and tracing is done with objects stored in the thread state itself, and creating a new one doesn't inherit them from the saved state. This also affects exceptions, which are not propagated back into the 'callout' from the 'callin'. Hm, can anyone understand the last sentence? What I mean is: When an exception occurs in the callback (which runs with a newly created thread state), simply PyErr_Print() is called before the thread state is deleted, because there's no way to pass the exception somewhere else. Thomas From adam at gliwice.pl Fri Nov 15 19:34:42 2002 From: adam at gliwice.pl (Adam Przybyla) Date: Sat, 16 Nov 2002 00:34:42 +0000 (UTC) Subject: module to generate RTF? References: Message-ID: Harry George wrote: > We need to traverse a database, and generate a Word document. If we > do that via COM, we are locked into running on a MS WIn** box, so we'd > prefer to do RTF. I can generate the raw RTF codes inline with write > statements, but it would be nice if someone had already done some > syntactic sugar on that. Anything available? ... XML+python -> docbook -> rtf ;-) Regards Adam Przybyla From wlfraed at ix.netcom.com Sat Nov 23 21:06:18 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sat, 23 Nov 2002 18:06:18 -0800 Subject: Simple Checkbutton Question? Please.... References: Message-ID: Josiah fed this fish to the penguins on Friday 22 November 2002 09:00 pm: > What am I doing wrong in this sample? When I press the "status" > button, the printout shows that "self.var.get()" returns a "0" weather > the box is checked or not! Help please. > Thanks! Bloody web-posting users... I can't identify what architecture you are running under so I have to be blunt and demanding. WHAT OS? WHAT Python version? I just copied your source to a file under Mandrake 8.2, and ran it... [wulfraed at beastie wulfraed]$ python t.py 1 0 1 Nothing wrong here, except that I don't know which graphic is "checked" vs "unchecked" -- the empty (white) hole, or the protruding (grey) mound -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From 2002 at weholt.org Mon Nov 4 07:53:41 2002 From: 2002 at weholt.org (Thomas Weholt) Date: Mon, 04 Nov 2002 12:53:41 GMT Subject: Need simple algorithm for newbie References: Message-ID: Don't know how optimized this is, but it's start : import string addresses = ['groups.google.com', 'ftp.google.com', 'ftp.google.net', 'whatever.google.org'] parsed_result = {} for address in addresses: parsed_result[address[string.index(address, '.')+1:]] = None print parsed_result.keys() Thomas "Jason Tudisco" wrote in message news:d1a9617c.0211040433.1eddb118 at posting.google.com... > I have a list of domains... Some of the domain names in the list look > like this: > > groups.goodle.com > > The information I want is just google.com. I need to know the best way > to do this.. for .com .net .org only.. and to strip the rest of the > garbage.. like in this case.. get rid of groups in groups.google.com > > I need to parse though a huge list so it has to be optimized algorithm > > No need to write complete code.. Just get me in the right direccion.. > Still learning python and I am not sure what would be the fastest way > to go about it.. From d_blade8 at hotmail.com Wed Nov 13 14:36:11 2002 From: d_blade8 at hotmail.com (Lemniscate) Date: 13 Nov 2002 11:36:11 -0800 Subject: calendar modules References: Message-ID: <7396d2b2.0211131136.160ee567@posting.google.com> Absolutely correct. However, you can save a teensy bit of typing by using prmonth instead. For example: >>> calendar.prmonth(1976, 10) October 1976 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 >>> btw, I set the deafult first weekday to Sunday. >>> calendar.setfirstweekday(6) Have fun, Lem Gerhard H?ring wrote in message news:... > In article , Geiger Ho wrote: > > Hi all, > > > > Wondering around the modules, I find that "calendar" does not function > > well in MS Windows. When I type "calendar.month(2002,11)", it outputs a > > string > > > > ' November 2002\nMo Tu We Th Fr Sa Su\n 1 2 3\n 4 5 6 > > 7 8 9 10\n11 12 13 14 15 16 17\n18 19 20 21 22 23 24\n25 26 27 28 29 > > 30\n' > > > > but rather in proper formating. > > Try "print calendar.month(2002, 11)" instead of the implicit repr that's called > in your case. > > > This seems calendar module is not platform > > It is. From eppstein at ics.uci.edu Wed Nov 13 16:55:06 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 13 Nov 2002 13:55:06 -0800 Subject: My (late) beef with Simple Generator syntax (PEP 255) References: <3DD2C505.96B41A1C@hotmail.com> Message-ID: In article <3DD2C505.96B41A1C at hotmail.com>, Alan Kennedy wrote: > Cameron Horn wrote: > > > If I want to write an empty generator, I write this(?): > > def foo(): > > return > > yield "never" > > What is the semantic of "an empty generator", i.e. what does it mean? A > generator that never generates any values? What I wonder is, why does it need to be a generator? What's wrong with def foo(): return ( ) ? -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From uwe.schmitt at procoders.net Fri Nov 1 09:50:57 2002 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 1 Nov 2002 14:50:57 GMT Subject: could python serve web scripts ? References: Message-ID: black wrote: > Howdy~ > I'm learning ASP these days and bothered VBScript much, I want to kick it off and I wonder if Python could be substitution. and what about other scripts if not, thanx~ Have a look at the WebWare: http://webware.f.net Havn't tried it myself, but it looks very promising. Greetings, Uwe -- Dr. rer. nat. Uwe Schmitt Computer science is no more about Computers, uwe.schmitt at num.uni-sb.de than astronomy is about telescopes. (Dijkstra) http://www.procoders.net From jdhunter at nitace.bsd.uchicago.edu Wed Nov 13 11:39:55 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Wed, 13 Nov 2002 10:39:55 -0600 Subject: os.system and wget References: <7d728336.0211130756.3e39a748@posting.google.com> Message-ID: >>>>> "zunbeltz" == zunbeltz writes: zunbeltz> os.system('wget -q -O foo.txt http://foo.html') You may want to look at the popen commands: http://python.org/doc/current/lib/os-newstreams.html#os-newstreams. For your example: import os h = os.popen('wget -q -O foo1.txt http://foo.html') h.close() s = open('foo1.txt').read() Also, for the specific case of wget, python's builtin urllib can provide a bunch of these services import urllib h = urllib.urlretrieve('http://foo.html', 'foo2.txt') Or if you want to work with the returned data directly in python, you can use urlopen, which returns a filehandle h = urllib.urlopen('http://foo.html') for line in h.readlines(): print line You can get fancier (cookies, recursive retrieval). See websucker as an example python script built around urllib that has much of the wget functionality: http://www.pythonware.com/people/fredrik/websucker.htm. If you have the python src, you'll find it in the src tree at Tools/webchecker/websucker.py John Hunter From abcdebl2 at bellatlantic.net Sun Nov 10 17:16:49 2002 From: abcdebl2 at bellatlantic.net (David Lees) Date: Sun, 10 Nov 2002 22:16:49 GMT Subject: Commercial scale space tourism References: Message-ID: <3DCEDAD3.5C04CC0@bellatlantic.net> Victor, You are definitely on the right track, but your herpatological background appears weak. The Indian rope trick, is associated with a Cobra, not Python, so your post here in c.l.p is clearly accidental. I am sure if you learn more about Cobras, snake charming, the Indian rope trick and Fakir magic in general, you will be successful. Further, Fakirs are well known for performance of levitation, so it is not quite clear why you need 10 million, when tickets are usually in the range of 10 to 20 dollars. Plus, there is no need to wait 2 years when performances are available in most metropolitan areas. On the other hand be careful not to giver fakers a bad name. You may want to be carefull that your brilliant ideas are not stolen by others. For example, a new movie is opening on Friday (Harry Potter and the Chamber of Secrets), which appears to be a Hollywood ripoff stealing much of your work without giving you any credit. Finally, I want to strongly suggest you use the web to promote yourself by registering at a site which is an excellent match to your needs: http://www.crank.net/antigravity.html david lees VR wrote: > > Hello everyone, > > My name is Victor Rozsnyay, CEO of Gravity Control Technologies. For the > last 5 years my company has been developing aerospace technology capable of > controlling gravity for flight. Such technology would be instrumental in > introducing commercial scale space tourism flights within the next decade. > Everyone would have the opportunity of visiting space. From dsavitsk at e-coli.net Fri Nov 1 12:05:54 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Fri, 01 Nov 2002 17:05:54 GMT Subject: could python serve web scripts ? References: <0Zow9.3620$mN6.1025961@newssrv26.news.prodigy.com> Message-ID: "dsavitsk" wrote in message news:0Zow9.3620$mN6.1025961 at newssrv26.news.prodigy.com... > "black" wrote in message > news:mailman.1036123142.8986.python-list at python.org... > Howdy~ > I'm learning ASP these days and bothered VBScript much, I want to kick it > off and I wonder if Python could be substitution. > > you can use Python for active server pages. here's an example how ... > > #------------------------------- > <%@ Language=Python %> > #-------------------------------- > > thanx much !!! but I know not much on how to > control ASP with Python, any tutorials or links > please ??? and my database is SQL server, could > it connect with Python too ??? for an example of using ADO w/ Python see www.e-coli.net/pyado.html, for other ways, search this newsgroup for a message from Oct 29 with the subject "Using Python with Microsoft SQL Server" > sorry that I tried the code but ASP refused it. it > says "script language Python couldnt be found in your > server", how to fix it please ? Have you installed Python? you must do it in one of two ways. either install Python + win32all (available from www.python.org) or install ActivePython from www.activestate.com. In general, please post to the newsgroup or to the newsgroup + email rather than email alone. also, most beginner questions can be answered easily via a google groups search. however, if you can't find an answer, then by all means post here. good luck, -d From cliechti at gmx.net Wed Nov 13 18:54:02 2002 From: cliechti at gmx.net (Chris Liechti) Date: 14 Nov 2002 01:54:02 +0200 Subject: wxPython program failing after upgrade References: Message-ID: "Blake Garretson" wrote in news:ut5re93g8s0556 at corp.supernews.com: > I upgraded to wxPython 2.3.3.1 using the precompiled win32 binary, and > now my wx program won't work. (I previously used 2.3.2.1) I'm using > a DC client to draw some graphics, and it fails when it goes to > refresh the screen. Here's the error that shows up in a popup dialog: > > """ > c:\projects\wx\src\msw\dcclient.cpp(216): assert "wxFalse" failed: > wxPaintDC may be created only in EVT_PAINT handler! > Do you want to stop the program? > """ i think you need to use a exClientDC outside of the paint method. or in other words when an other thread is drawing to the screen. > (By the way, that path doesn't exist on my machine!) thats normal. the "assert" messages are compiled in so they have the path of the source during compilation. > Then another error gets printed to stderr: > > """ > File "C:\Python222\Lib\site-packages\wxPython\gdi.py", line 607, in > DrawText > val = apply(gdic.wxDC_DrawText,(self,) + _args, _kwargs) > OverflowError: long int too large to convert to int > """ there should be more, like the location of the exception in your program. print the values you use at that line. maybe you're realy drawing somwhere outside screen and just have not discovered that yet? > Any ideas what's going on here? as you said, you have upgraded ;-) the old version of wxPython might be a bit more tolerant to bad values at some places. whatever, i have upgraded to that version of wx and had to correct some small issues so that it runs on the old and new version, but now it runs fine. chris -- Chris From ods at strana.ru Tue Nov 12 07:22:10 2002 From: ods at strana.ru (Denis S. Otkidach) Date: Tue, 12 Nov 2002 15:22:10 +0300 (MSK) Subject: Cyrillic letters in 'Entry' widget In-Reply-To: Message-ID: On 11 Nov 2002, Martin v. [iso-8859-1] L?wis wrote: MvL> "Bobirkhon Ismailov" writes: MvL> MvL> > I am trying to enter cyrillic letters in text entry MvL> widgets, but it MvL> > looks like trash. I was wondering if is there any way to MvL> display entered MvL> > characters correctly on screen. MvL> MvL> Did you read my reply to your previous message? MvL> MvL> >>> import Tkinter MvL> >>> t=Tkinter.Entry() MvL> >>> t.pack() MvL> >>> t.insert(0,u'\N{CYRILLIC SMALL LETTER ZHE}\u0437') MvL> >>> MvL> MvL> works fine for me. What does that give for you? This helps for output only. To recieve input you need patching Tkinter: http://prefnews.ru/forum/viewtopic.php?t=19 -- Denis S. Otkidach http://www.python.ru/ [ru] From johnroth at ameritech.net Wed Nov 27 14:27:43 2002 From: johnroth at ameritech.net (John Roth) Date: Wed, 27 Nov 2002 14:27:43 -0500 Subject: *args and **kwargs References: <87d6orq0oz.fsf@uiuc.edu> <_S7F9.14648$kz4.657484@news2.west.cox.net> Message-ID: "Wojtek Walczak" wrote in message news:slrnauah8l.199.gminick at hannibal.localdomain... > Dnia Wed, 27 Nov 2002 18:08:58 GMT, Dan napisa?(a): > > thanks for the answer specifically for "args". Still I don't quite > > understand the Python syntax. > > > > *something = encapsulate into a set ?? > > **something = encapsulate into a Dictionary?? > Yes, but only when defining a function. > You can call a function in two ways (depends on a way it was defined): > > def first(**a): > print "\n".join([ "%s==%s" % (k,v) for k,v in a.items()]) > > first(a="b",b="c",c="d") > > > def second(a): > print "\n".join([ "%s==%s" % (k,v) for k,v in a.items()]) > > second({"a":"b", "b":"c", "c":"d"}) > > In first case you know, that you need to pass a dictionary from > function's declaration (seeing **a just tells you that). In second case, > you don't, you need to take a look at code or documentation. > Maybe not at all, but, for sure, in some way that strange construction > is about readability. I don't believe that's the case. What the * and ** constructions do is give a name to a tuple and dictionary, respectively, that contain extra positional and keyword parameters. Notice the word 'extra' here, it's important. On the calling side, they allow you to create a sequence and a dictionary that contain the positional and keyword parameters. As one of the posters says, it's a shortcut for the apply() built-in function, and one that Guido prefers. He's said he wants to get rid of (or at least depreciate) apply(). The fact that the function definition contains either * or ** has nothing to do with how you call it. John Roth > > -- > [ ] gminick (at) underground.org.pl http://gminick.linuxsecurity.pl/ [ ] > [ "Po prostu lubie poranna samotnosc, bo wtedy kawa smakuje najlepiej." ] From ktilton at nyc.rr.com Fri Nov 29 18:22:08 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Fri, 29 Nov 2002 23:22:08 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3de1f902$0$695$edfadb0f@dread12.news.tele.dk> Message-ID: <3DE7F792.6040004@nyc.rr.com> maney at pobox.com wrote: > Courageous wrote: > >>One of Lisp's _lethal_ failings is that anyone not using Emacs (or >>something like Emacs) is a second class citizen. The decision to >>require a programmer to use a special editor is a fatal one. > > > But perhaps an unavoidable one. I have been doing CL nonstop for seven years and have yet to learn Emacs, tho I /did/ use MCLs emacs-like editor and I do have ACLs editor in "Emacs mode". But this just has to do with the key combos being the same, not the whole nine yards. and with acl i do not even have to do emacs mode. No matter what Lisp IDE you use (LW, ACL, Corman, MCL) you'll get a Lisp-aware editor, the way IDLE is Python-aware. > I have never before seen the true reason > Lisp's annoying parentheses-plagued syntax has persisted, let alone why > it might be worth putting up with. If you ever get out of the starting blocks, the parentheses will disappear (but make editing much easier). Python code looks nice and clean thx to the indentation thang, but Lisp code is self-indenting thx to the parens. ie, I can select as big a function I like and just say re-indent, and I'm done. And because Lisp is self indenting, when i hit tab (telling it to reindent that line, not insert a tab) I can see at one if I have typed too few or not enough parens. This happens rarely because any matching parens is highlighted after I type a parens, so I just look around if I lose track or get way deep into an expression and need several parens to get out. The bottom line is that no regular Lisper is bothered by parens and in fact we all prefer them thanks to their facilitation of editing chunks of code (by double-clicking a form of any size). -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From stuart at bmsi.com Fri Nov 8 22:55:23 2002 From: stuart at bmsi.com (Stuart D. Gathman) Date: Sat, 09 Nov 2002 03:55:23 GMT Subject: Getting SSL certificate References: Message-ID: On Fri, 08 Nov 2002 07:01:01 -0500, Martin v. L?wis wrote: > Erno Kuusela writes: > >> || The httplib modules supports SSL, but does not check certificates. > > Can you please explain what it means to check a certificate? I know of two level of checking: 1) an automatic level that verifies all digital signatures on the cert this tells you that someone registered the cert with the CA, and it has not been forged (presumably the SSL protocol signs some random data unique to the session along with the cert to prevent replay). 2) a manual level where a person or high level program checks that the name on the certificate is one they expect, or feel like trusting. In my case, there is only one cert that the application will trust - but I need to make sure it hasn't been forged. >> and cert_file was for a certificate authority that the server cert >> should be checked against. but it is a faint impression :) That would make sense, but the docs say that checking the server certificate is not implemented. >> in case it is so, this still does not let you at the server >> certificate... > Is there a missing here? Definitely, because even if the checking for level (1) above were automatic (as the arguments seem intended for), the application still needs to get at the server certificate in some form to check that they are talking to the right entity. Anybody and their dog can get a signed certificate. (And I remember a Slashdot story about someone getting a certificate for their dog to illustrate how weak the checking at Verisign is.) -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From sismex01 at hebmex.com Fri Nov 15 12:05:03 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 15 Nov 2002 11:05:03 -0600 Subject: A really bad idea. Message-ID: > From: Daniel Dittmar [mailto:daniel.dittmar at sap.com] > Sent: Friday, November 15, 2002 10:43 AM > > holger krekel wrote: > > But in fact i'd like to see some examples of what is readable and > > what is not readable in your oppinion. > > zip, enumerate: readable, because you can search the docs for > the words. It is also easy to implement variations: returning > other datatypes, returning an iterator to preserve memory. Thus > the whole program becomes easier to understand because similar > task are called in a similar way. > > list comprehension: not readable, because you don't know what to > search for. You can't create dictionary comprehension or generator > comprehension (both have been proposed on c.l.p), thus making the > resulting program less regular. > > Daniel > But these are your *opinions*. And while valid, others on the same list (or lists) have expressed nothing but rave reviews on the same things you don't like. So, what to do? Macros, a-la Lisp, so anyone can have whatever syntax they want? A mishmash of features, like Perl? -gustavo From roy at panix.com Fri Nov 8 21:17:10 2002 From: roy at panix.com (Roy Smith) Date: Fri, 08 Nov 2002 21:17:10 -0500 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <9b8hqa.eo3.ln@beastie.ix.netcom.com> Message-ID: David Eppstein wrote: > The most important similarity I see is that in both languages, > values have types but variables are untyped, but that was also true in > radically different languages such as Snobol and APL; is that really > enough to conclude that Python and Lisp are more like each other than > anything else? The biggest lisp-like thing I see in Python is that from the point of view of what a container can hold, data and code (and classes, and modules, and types) are the same kind of thing. A "def" statement is really just a definition of a lambda body and an assignment of that to a name (variable) all rolled into one. That being said, I agree with David; only a computer scientist interested in language theory would consider Python and Lisp to be similar. From kseehof at neuralintegrator.com Wed Nov 20 00:46:24 2002 From: kseehof at neuralintegrator.com (Ken Seehof) Date: Tue, 19 Nov 2002 21:46:24 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? In-Reply-To: References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: <4.3.1.0.20021119210841.02456d70@pop.hurrah.com> At 08:15 PM 11/19/2002 Tuesday, Anna wrote: >On Mon, 11 Nov 2002 07:50:57 +0000, Robin Munn wrote: > > > Brad Hards wrote: > >> I'm certainly amazed at the tolerance people have for questions that > >> are readily answered in a number of on-line tutorials, and in both the > >> Python books that I have (Learning Python and the Python Cookbook). In > >> the end, the friendly attitude may be the killer feature. > > > > Out of curiosity, do you think a response like: "That's covered in the > > Python tutorial -- look at [URL]" will strike a newbie as friendly or > > not? I ask because that's the kind of answer I will tend to write when > > I'm in a hurry. Sometimes I will take the time to phrase the answer in > > my own words, but often I won't want to duplicate the work that someone > > else has already done in writing that tutorial. So if you were a newbie > > getting a curt response like that, would you feel it was a brushoff, or > > would you feel like your question had been answered? > >Okay - you asked. And since I am a newbie, I?ll answer. > >Before asking a question here, I?d have already read the tutorial (and >probably 3 more tutorials and done a google search too). I wouldn?t feel >comfortable asking here unless I had. > >So if I?m still here asking, it?s because I need an answer that *isn?t* >just a reference to the tutorial, something from a live human being... So, >yeah, I guess I would consider it a brushoff, unless you took the time to >expand on the tutorial in some way... Personally, I?d far rather get no >answer than ?RTFM, silly newbie?... cuz chances are, I already did... > >Just my $.03 worth. > >Anna I think it's okay to refer the newbie to a specific page in the manual, in the form of a url, if that is providing useful information, and isn't a brushoff like "RTFM". When I ask a question on a newsgroup, my favorite responses are often urls. The main problem newbies have with documentation is that there is so much of it, and it is usually not obvious which "FM" to read. The important thing is for us to avoid the impulse to make a potential python fanatic feel unwelcome. It's not so much whether the newbie is being referred to a manual, but the underlying message: Are we saying, "You fool, stop wasting our precious time...", or "Here, I hope this helps, enjoy...". Ken From jeremy at alum.mit.edu Tue Nov 12 13:37:34 2002 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: 12 Nov 2002 10:37:34 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3dce5e2f$0$35917$edfadb0f@dread13.news.tele.dk> Message-ID: Alex Martelli wrote in message news:... > Hmmm, on a slightly different tack, this DOES help me articulate one > source of my slight reluctance to get really deep into Ruby: Ruby > gives the programmer just a little bit MORE dynamicity/flexibility/ > power than Python, by messing with the fundamentals of built-ins and > passing "unevaluated code blocks" to methods (that's how you do > iterators in Ruby, while Python's iterators are utterly different) -- > although that's still not a full-fledged macro system, I may be > subconsciously worrying that the little extra power IS just enough > to get into "newbie cravings" territory. I asked Matz about this at LL2 on Saturday. I asked if he could think of examples where he wanted to change the language syntax. He said the blocks were powerful enough that they could accomodate new features without syntax change. The question came up in the context of a recurring debate over the utility of macros. I noted that as a Python developer, I'd love to have access to macros to experiment with new syntax without having to munge the grammar and compiler. Jeremy From ianb at colorstudy.com Wed Nov 13 22:25:43 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 13 Nov 2002 21:25:43 -0600 Subject: Visual programming, looking for graphics layer Message-ID: <1037244343.1825.113.camel@dsl-65-184-205-5.telocity.com> All the language discussions got me to thinking, and I was thinking of Logo and got a bit of an itch. After implementing a little Logo interpreter, I wanted to do something more novel and interesting, like Boxer. In the extremely likely case you don't know anything about Boxer, the website is at: http://www.soe.berkeley.edu/boxer/ It's a neat teaching language, where it has some graphical ways to present programming structure. Sadly its only available for Macs, and I don't know if development is active. But I've put up a little graphic taken from one of the papers (and fixed up a bit) to give a feel: http://colorstudy.com/tmp/boxer-capture.gif Basically to indicate structure there are boxes (hence the name) that contain code. So the code: def sum(number_list): number = 0 for n in number_list: number += n return number Might look like: +------------------+ | sum(number_list) | +------------------+--------------------+ | | | number = 0 | | for n in number_list +-------------+ | | | number += n | | | +-------------+ | | return number | | | | +--------+ | | | number | | | /----------\ | | | 0 | | | \----------/ | | | +---------------------------------------+ Of course, in this case I use Python-like syntax, and some of the semantics are kind of fuzzy. Like "number" is initialized, but it's value is also tracked (nice for debugging) -- it's as though every local variable is a C-style static variable. There's lots of details to be worked out with the semantics, but that's not what I'm asking about here. The hard part is that this sort of layout is fairly hard to do. Not only do you have text inside different sorts of boxes, but an important part of the language is that you also have non-text literals (like colors and shapes, and even lists may be represented in a graphical fashion). All these need to be manipulatable. I'm hoping to get some advice or pointers on something already available that can make this easier. I could use pygame, maybe even with pyui, but that's still a long way from what I'd have to do for even the most minimal functionality. I've also had a hard time understanding pyui's architecture -- there's something magic in there and I can't tell where things actually get *done*... but I'm sure that's surmountable. Maybe that's where I should be looking. Any of the GUI kits (Tkinter, wxWindows, etc) aren't nearly flexible enough, except maybe things like Tk's canvas, or other equivalent widgets. Do any of these offer functionality that would help in making this editing environment? Looking forward to suggestions... Ian From knepley at mcs.anl.gov Fri Nov 22 09:23:08 2002 From: knepley at mcs.anl.gov (Matthew Knepley) Date: Fri, 22 Nov 2002 08:23:08 -0600 Subject: int() shortcoming? Message-ID: Is there a reason I should have to specify the base for a string conversion using int() when it is already clear from the form? For instance: >>> oct(15) '017' >>> int('017') 17 >>> int('017', 8) 15 and hexidecimal actually generates an error. Thanks, Matt -- "Failure has a thousand explanations. Success doesn't need one" -- Sir Alec Guiness From mark.charsley at REMOVE_THIS.radioscape.com Mon Nov 25 08:32:00 2002 From: mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) Date: Mon, 25 Nov 2002 13:32 +0000 (GMT Standard Time) Subject: How to write Inline Functions in Python? References: Message-ID: In article , tdelaney at avaya.com (Delaney, Timothy) wrote: > I assume you're coming from C++. In that case, I suggest you take a good > hard look at why you want to write inline functions/methods anyway. If > you're doing it for performance reasons, your compiler is almost > certainly > going to be better at deciding what to inline, and has the option to do > so > unless you explicitly tell it not to. If you're doing for any other > reason > (such as putting code in header files) I strongly advise against it. > > Inline was developed when computers were slower and compilers were more > stupid. These days I see no need to inline whatsoever. While blatantly off-topic, inlining in C++ has two advantages: - saves the expense of a function call - gives the compiler visibility into the function giving it vastly greater optimisation opportunities. The first is usually insignificant even in C++, so if performance is that important, one shouldn't use Python (ooh look: briefly on-topic). The last is of major importance and is more important with today's smart compilers than it was years ago with dumb optimisers. Mark From mwh at python.net Thu Nov 7 06:03:07 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 7 Nov 2002 11:03:07 GMT Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DC8623B.88753C16@earthlink.net> <3DC8CDDD.7050103@mindspring.com> <3pE8dhAtvNy9EwoQ@jessikat.fsnet.co.uk> <3DC943CF.84A68F32@san.rr.com> <20021106184401.X30315@prim.han.de> Message-ID: <7h3y985zlu2.fsf@pc150.maths.bris.ac.uk> Robin Becker writes: > As you point out psyco can do the compilation, but only into the generic > multiply (unless psyco can be hinted in some way). You hint pysco by calling the function with ints :) I hadn't appreciated how clever psyco was until I went to Armin's EuroPython talk. You can get the slides at psyco.sf.net, but I can't remember how much of the interesting stuff was in the slides and how much was in what he said. Cheers, M. -- This song is for anyone ... fuck it. Shut up and listen. -- Eminem, "The Way I Am" From bokr at oz.net Tue Nov 26 09:59:19 2002 From: bokr at oz.net (Bengt Richter) Date: 26 Nov 2002 14:59:19 GMT Subject: Python Tutorial Was: Guido's regrets: filter and map References: Message-ID: On Tue, 26 Nov 2002 06:23:24 GMT, Courageous wrote: > >>I find lambda quite useful for creating simple anonymous functions to pass >>to GUIs as button commands and the like. > >Simple indeed. It's a consequence of the Python syntactic structure that lambdas >shall _always_ be nothing more than a tiny little sub language in which certain >normal Python expressions can never occur. > Well, you could write new.function(compile('print "anonymous hi"','','exec'),{}) if no one wants to pursue anonymous-def-as-expression ;-) Regards, Bengt Richter From brian at sweetapp.com Mon Nov 4 17:30:11 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 04 Nov 2002 14:30:11 -0800 Subject: old SimpleXMLRPCLib classes In-Reply-To: Message-ID: <003a01c28451$bcc3a130$21795418@dell1700> > No, it doesn't, because I didn't know of this page or, apparently, > grok the real purpose of system.methodSignature; I thought it > documented the signature of the underlying (Python) callable, not the > xmlrpc method itself. > I can't find definitive specs for the system > methods -- most web resources cite the currently nonexistent > http://xmlrpc.usefulinc.com/doc/reserved.html -- but I now see > that Eric Kidd's listMethods implementation is probably meant to > behave as you suggest. Yeah, it's weird that that URL is no longer valid. Fortunately I was privileged enough to read it before it died :-) > My module may be correct were it to implement system.methodHelp so > that it return both the Python method signature (as opposed to the > xmlrpc method signature) and the docstring, while ceasing to > automatically implement system.methodSignature; but should I bother? > Does anyone actually call this method programmatically as part of a > discovery routine, or is it only useful as human-readable > documentation, in which case conformance to the "spec", such as it is, > is arguably not of great importance? In my implementation, I don't include the signature with system.methodHelp. My feeling was that most python doc strings include the method signature, if it is relevant. I'm not sure that anyone uses system.methodSignature, but I wouldn't use that name if the used is non-standard. Cheers, Brian From maney at pobox.com Sat Nov 30 16:49:53 2002 From: maney at pobox.com (maney at pobox.com) Date: Sat, 30 Nov 2002 21:49:53 +0000 (UTC) Subject: if : References: Message-ID: Sean McSomething wrote: ... > Of course, this could all be complete & utter bullshit, but it's a > reasonable extrapolation from what facts I have & my understanding of > things. Trying to intuit the often arbitrary, or at any rate highly contingent, reasons for what actually happened is one of those beyond-NP-hard problems. :-/ There are certainly some correct bits in your reconstruction: some features are present in the C language and/or came to be commonly used at least in part because of code size and speed considerations. The op-assign (+=, et. al.) were largely present to take advantage of PDP instructions that could do that to most any two operands in one op; even with that, though, both the desire to get that efficency with a small, relatively brainless compiler as well as the notational efficency were probably important factors. In the case of operator=, I'm afraid your proposed motivation is more of a chimera. The real roots of this are almost certainly to be found in C's pre-history as a simplified version of the BCPL language, in which *everything*, including statements, had a value. This is very likely the original cause of both operator= and the conditional operator?:. The latter provides, in more limited form, something that BCPL could do with an if/else statement inside one of it's valof blocks. C's backstory in BCPL (by way of an even less wisely known language named 'B') also explains the otherwise cryptic comment (by Ritchie?) about the uncertainty over whether C's hypothetical successor (this was before C++, but that wasn't exactly a successor to C anyway) should be named 'D' or 'P'. Programmer humor. :-/ Actually, though, didn't the notion of operator= come out of Algol? Ooops, no, that was just "assignment spelled differently than equality test". Never mind! From mwh at python.net Fri Nov 15 08:08:29 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 15 Nov 2002 13:08:29 GMT Subject: A really bad idea. References: <7h3d6p7xelx.fsf@pc150.maths.bris.ac.uk> Message-ID: <7h3u1ijvv9q.fsf@pc150.maths.bris.ac.uk> Thomas Heller writes: > Michael Hudson writes: > > > C without it's library would get a rating of "useless"... guess this > > is true for most languages, but C more than most. > > > Not at all, imo. You just have to write the library yourself, > and you *can* do it in C. I guess... but not portably, surely? Anyway, it meant to be a serious comment, just the observation that C puts very little into the language and (relatively speaking) more in the stdlib. Cheers, M. -- ... when all the programmes on all the channels actually were made by actors with cleft pallettes speaking lines by dyslexic writers filmed by blind cameramen instead of merely seeming like that, it somehow made the whole thing more worthwhile. -- HHGTG, Episode 11 From schlenk at uni-oldenburg.de Tue Nov 12 18:38:36 2002 From: schlenk at uni-oldenburg.de (Michael Schlenker) Date: Wed, 13 Nov 2002 00:38:36 +0100 Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DCFCC3E.204D9B45@man.ac.uk> <3DCFEF06.9E74A794@earthlink.net> <3DD11E7F.C12E708A@man.ac.uk> <3dd17f27$0$195$edfadb0f@dread16.news.tele.dk> Message-ID: MikkelFJ wrote: > Sorry for the repost at perl, I didn't release the post was crossposted (I > entered via Ruby). > > > "Neil Madden" wrote in message > news:LRaA9.1325$J55.292310 at newsfep2-win.server.ntli.net... > > >>Hmm.. the more I think about this, the more problems it seems to present. > > I'd > >>love to be able to write an extension, and have it instantly work with x >>different langauges. Also, I'd love to be able to use Python and Perl >>extensions from Tcl, without loading seperate interpreters and all that. > > Am I > >>dreaming of an impossible Utopia? > > > I wrote some DLL helper logic that makes it easy to query a vtable by name > in another DLL. > The vtables can be created in whatever way, but the vtable is not assocated > with allocated memory, as is the case with COM. This makes it quite flexible > without really being limited because one could decide that the first > function should return a 'this' pointer and the second function should be > the destructor, or whatever. Basically the same as the Tcl STUBS mechanism for loading extensions in different versions of the tcl interpreter without recompiling or relinking the extension. Michael From bokr at oz.net Wed Nov 27 12:27:02 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Nov 2002 17:27:02 GMT Subject: Python Tutorial Was: Guido's regrets: filter and map References: <3de39ce9$0$22220$a1866201@newsreader.visi.com> <3DE44D27.3030904@something.invalid> <6GH59kKkXIpD092yn@gnosis.cx> <6q4ra3nwlq.fsf@salmakis.intevation.de> Message-ID: On 27 Nov 2002 11:19:29 +0100, Bernhard Herzog wrote: >Lulu of the Lotus-Eaters writes: > >> Actually... here's an... ummm... "improved" version: >> >> reduce = lambda func, seq, init=None:\ >> [(l.append(func(l[i],seq[i])),l[-1]) >> for l in [[init or seq[0]]] >> for i in range(len(seq))][-1][1] > >It doesn't work correctly: > >>>> import operator >>>> reduce(operator.add, [1,2]) >4 > >That should have been 3. > > Bernhard > Nobody(?) seems to have noticed the version I posted the other day: On 26 Nov 2002 16:21:57 GMT, bokr at oz.net (Bengt Richter) wrote: >On Mon, 25 Nov 2002 23:19:46 -0800, Terry Hancock wrote: >[...] >> >>map(), filter(), and reduce() do not represent all of the uses for filter, >>and thus, they can't all be replaced by list comps (BTW, I never used >>reduce, never understood what it was good for, and don't immediately >>see how it can be done using list-comps -- would be genuinely interested >>in seeing a couple of example if anyone's willing). >> >I guess I'll bite: > > >>> def lcreduce(fn, seq, init=None): > ... return [first > ... for first, rest in [ init is None and > ... (list(seq[:1]), list(seq[1:])+[id]) or > ... ([init], list(seq)+[id])] > ... for y in rest if y is id or first.append(fn(first.pop(), y))][0][0] > ... > >>> seq = range(10) > >>> lcreduce(int.__add__,seq) > 45 > >>> lcreduce(int.__add__,seq,5) > 50 > >>> seq = (1,2) > >>> lcreduce(int.__add__,seq) > 3 > >>> lcreduce(int.__add__,seq,5) > 8 > >>> seq = [3] > >>> lcreduce(int.__add__,seq) > 3 > >>> lcreduce(int.__add__,seq,5) > 8 > >>> seq = () > >>> lcreduce(int.__add__,seq,5) > 5 > >>> lcreduce(int.__add__,seq) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 3, in lcreduce > IndexError: list index out of range > >But that last is ok: > >>> reduce(int.__add__,seq) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: reduce() of empty sequence with no initial value > >I suspect reduce is a little faster than lcreduce ;-) > >Regards, >Bengt Richter It uses id as a sentinel, which should be generated inside the list comprehension to be really clean, but it seems to work. Regards, Bengt Richter From irmen at NOSPAM-REMOVETHIS-xs4all.nl Thu Nov 7 19:42:23 2002 From: irmen at NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 08 Nov 2002 01:42:23 +0100 Subject: Search a SOAP module In-Reply-To: <3dc7fe24$0$5127$626a54ce@news.free.fr> References: <3dc7fe24$0$5127$626a54ce@news.free.fr> Message-ID: <3dcb086f$0$46609$e4fe514c@news.xs4all.nl> Try the SOAP module that is part of PyGOOGLE, http://diveintomark.org/projects/pygoogle/ Irmen From cnetzer at mail.arc.nasa.gov Fri Nov 15 18:14:02 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Fri, 15 Nov 2002 15:14:02 -0800 Subject: How to write Inline Functions in Python? In-Reply-To: References: Message-ID: <200211152314.PAA12423@mail.arc.nasa.gov> On Friday 15 November 2002 00:15, David Brown wrote: > "Chad Netzer" wrote in message > > On Thursday 14 November 2002 04:47, David Brown wrote: > > > The question then is when will gcc support such > > > link-time code generation, [snip] > > > > I'm guessing there may be patent issues in this particular area, which > > could restrict gcc's ability to implement some of these features. > > Really? It's an obvious idea - I thought of it years ago, and I have never > written a compiler. I couldn't imagine that anyone who has really thought > about it would see it differently. The implementation, on the other hand, > could be tough (and presumably is tough - or it would have been done long > ago), especially for gcc where the linker is very much a seperate entity > from the compiler. Right, it is the details of implementation that might be a bit of a patent minefield (not the idea). In the back of my head I seem to recall listening to a discussion with more knowledgable people about such patents. Various people in the gcc community are obviously more informed in this area, than I. -- Bay Area Python Interest Group - http://www.baypiggies.net/ Chad Netzer cnetzer at mail.arc.nasa.gov From claird at lairds.com Fri Nov 15 09:15:59 2002 From: claird at lairds.com (Cameron Laird) Date: Fri, 15 Nov 2002 14:15:59 -0000 Subject: tkMessageBox: Changing Fonts, Colors, etc. References: <83d1ra.p19.ln@boundary.tundraware.com> Message-ID: In article , Eric Brunel wrote: >Tim Daneliuk wrote: > >> I cannot seem to find a reference on how to change the font type, size, >> etc. and colors for one of the tkMessageBox critters like showinfo() or >> showwarning() >> >> Could some kind soul, direct me to same, please? > >AFAIK, you just can't. These message boxes are managed internally by Tk, >sometimes by directly using API calls for the current platform (e.g. on >Windows, where the message boxes are regular Windows ones, as can be seen >in non-english versions of Windows: on a french version, a call to askyesno >will show a dialog with buttons labelled "Oui" and "Non" ...). > >If you're on Un*x, there are tcl scripts that actually implement the >dialogs. You'll find them near the libtk.so library, in the >tk directory. You may hack them to do want you want, but you still >won't be able to customize them from your application... . . . Yes, to a first approximation. There's actually more to it. Tcl/Tk specialists have been intending to write up the details, but none of us have got- ten around to it, yet. In the meantime, see or . -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From loewis at informatik.hu-berlin.de Thu Nov 21 07:39:05 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 21 Nov 2002 13:39:05 +0100 Subject: Interfaces References: Message-ID: Lee Harr writes: > Are interfaces still a happening proposition? If you give it enough time (like 10 years or so), it might happen. > Did we decide that we are not interested? Or are we waiting to see > how this goes in Zope before making any commitment? Who is that "we" that you are referring to. I'm personally not very interested in interfaces as a language feature; I'm just fine with interfaces as a concept and documentation vehicle. What "we" are interested in is irrelevant. To make it happen, you need a single individual determined enough to make it happen. That individual should be prepared to get holes shot into the first 50 proposals that she comes up with. IOW, it hasn't happened yet because it is really difficult. Regards, Martin From TuxTrax at fortress.tuxnet.net Fri Nov 1 06:20:06 2002 From: TuxTrax at fortress.tuxnet.net (TuxTrax) Date: Fri, 01 Nov 2002 11:20:06 -0000 Subject: Protect Python Source References: Message-ID: On Fri, 1 Nov 2002 16:35:28 +0800, hope Wrote in Steve Ballmers hair grease: > Hi, > > If i am to develop a full fledge commercial application using Python : > > a. Can i compile my python source into binary ? I have read about py2exe for > windows. Is there one for Linux ? > > b. Can I distribute the bytecode only (.pyo, .pyd) and not the source (.py) > ? Can the bytecode be 'de-compiled' to source ? > > Please advice. > > Cheers, > Peter Hello Peter. You ask good questions here, and give me an opportunity to present to you some ideas you may not have yet considered. First to answer your questions: As you probably know, python is an interpreted language that does not lend itself well to compiling. When you use the traditional compiler, you convert to binary and link to executable, your source code. Think of it this way: The interpreter is a compiled program that runs your code. In order for your code to run, the interpreter has to be present. Py2exe therefore has to compile your program, all it's modules, *and* the interpreter into one package. I don't know from experience, but have read, that this process can present difficulties and may not work with all programs. Others who have real experience can no doubt tell you more on this count. As for whether or not this type of pseudo-compiler is avaialable for Linux, I am going to address that question in a bit. Can you distribute the bytecode and not the source? My friend, you can distribute it any old way you want. More on this to come. Can bytecode be decompiled? Anything can be decompiled. You should know that compiling is not the security that many believe it to be. Just because a program is compiled does not mean it is safe from prying eyes. It is trivial to obtain decompiling software for traditionally compiled languages. I want you to read and consider what I am about to write, and I don't want you to feel that I am in any way attacking you. I'm not. But I feel a few well placed observations are in order. Your comments reveal a thoughtful and curious approach that is quite healthy. It also reveals a world view that has in large part been shaped by the philosophies of proprietary software companies. Is a python compiler available for linux? I don't know. I do know that no Linux users I know would even consider using one. It would never cross our minds to make our source closed to others. This is where the whole open source software movement takes a completely different world view. In open source software, you retain the right to make a profit from your work, while still granting others the right to copy, distribute, modify and view the source code. Just a year ago, this whole concept was horrifying to me. I could not concieve of allowing others to have free access to my source code. As a Long time windows user, I had some un-learning to do. But unlearn I did. I started thinking in terms of the advantages of open source. First, it keeps you honest; you write your best code because you know that your peers are going to be seeing it all over the world. Second, with open source, once you release it, other programmers may modify it helping it to become more than you ever could have made it on your own (unless you choose to forbid the modification of your code, but that's another subject). Third, the distribution of your product using the open source community, has no equal, and will cost you nothing. You can provide support to your users via that same community at little or no cost to you, and support is the number one ongoing cost that software developers get saddled with. You can use the resources of such organizations as the free software foundation to defend your copyright (don't let the "free" in FSF throw you; you can still market your product using the GPL licence). And finally, you get to give something back. This is a philosophical point for me, but giving something back to the community that you benefit from, whether it be your local community, or the computer community, is very important for us as people. It is a common and refreshing view that you will find in the open source world, and one reason that I left the windows world for good. But thats a soapbox for another time. Cheers, Mathew -- My Family is Microsoft Free. Running Mandrake Linux 8.0 kernel 2.4.3-20 I use quality open source software alternatives on my PC. Yes, I am a Penguin cult high priest. Flipper readings upon request. ROT13 this email address to mail me: bar jbeq abg guerr - uvtu qrfreg zna, ng lnubb qbg pbz From amk at amk.ca Sat Nov 16 10:58:16 2002 From: amk at amk.ca (A.M. Kuchling) Date: Sat, 16 Nov 2002 09:58:16 -0600 Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> <87y98f566d.fsf@zamazal.org> Message-ID: On Fri, 15 Nov 2002 19:55:10 -0500, David Mertz, Ph.D. wrote: > The more one learns about XML, the less of a glow surrounds the > technology... I suppose following the trend, those who *truly* > understand XML would never *use* it. Not at all. It's just that XML is useful for *interchange* between different applications written by different people. Maintaining your software's internal data structures in XML form -- as a DOM tree, say -- is certainly silly, on the other hand, because it's so much easier to have native Python/C++/whatever objects. --amk From aleax at aleax.it Thu Nov 21 06:20:37 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 21 Nov 2002 11:20:37 GMT Subject: matching multiple regexs to a single line... References: <7SUC9.34440$744.1277405@news1.tin.it> Message-ID: <9k3D9.35511$744.1314342@news1.tin.it> maney at pobox.com wrote: ... >>> This is one point on which I agree with Alexander: it seems to me to be >>> the usual case that the regexp both identifies and parses the target. >> >> It's one case, but it's very far from being the only one. > > Right, and I didn't say it was. I notice you aren't disagreeing that > it's a very common style of use, No, I don't disagree it's common -- that why I mentioned it myself! > and this both-identifying-and-parsing > use has been at least implied all along. It was explicitly described, > though not explicitly shown in the pseudo-code snippets, back in the > first post in this thread. Guess I must have missed that, because I saw no "at least implied". For such a crucial issue, making such an important difference, I find myself hard put to believe that people would "just imply" it without even showing it. So maybe there was a lot more talking at cross-purposes throughout the thread -- you yourself remarked that you were commenting on a post you "quite possibly didn't read all the way", and that kind of thing seems to insure there will be lots of misunderstanding. >>> If it isn't being used in that dual mode, then the whole issue >>> addressed here (and in at least two other threads during the past week) >>> doesn't exist. >> >> Why doesn't it? Alexander's post to which I was replying had no >> groups at all in the regex patterns > > Not in the sample code, no. There were groups in a lot of non-code > exposition, and as I say, they've been implicitly and explicitly a > major part of the motivation for this, at least IMO. After all, if you > don't have any groups, what do you need the match object for outside of > the conditional test? The match object gives you more than just groups you put in the pattern! It's quite typical, for example, that all you need to know is the exact substring that was matched: >>> import re >>> are=re.compile('ab+c') >>> mo = are.match('abbbcccdd') >>> mo.group(0) 'abbbc' >>> See? No explicit groups in the re's pattern, yet pretty obvious potential usefulness of the resulting match-object anyway. So, if your question was meant to be rhetorical, it seems particularly inappropriate to me. If instead it was asked in earnest, to learn crucial facts you didn't know about how re's and mo's work or about how they're often used, then I think you might usefully have refrained from criticizing what you suspected you didn't fully understand. But I do gather that trying to understand a subject before criticising is quite an obsolete approach these days. > And then the motivating problem, or at least > what I have seen as the motivating problem, is the dual use of the > result of the regexp's application. You can have some level of dual use without _necessarily_ having any group in the res' patterns. Of course you may often be interested in having groups, but your repeated attempts to imply that it would be _necessarily_ so seem quite misplaced to me. > The elephant seems very like a pillar on this side... :-) That can be a particularly dangerous partial-perception, should the pachyderm suddenly decide to shuffle its feet. I have already outlined quite briefly what I think could be one interesting approach should one need to pass on a match object that 'hides' the join-all-with-| approach to matching multiple re patterns in one gulp -- synthesize a suitable object polymorphic to a real matchobject. A completely different tack, simpler though needing some time measurement to check its worth, is to do TWO matches (still better than doing N one after the other...) -- one vs the patterns joined into one by |, just to identify which of them is the first (if any) to match; then a second versus the specific "first matching pattern" only, just to build the match object one needs. At this point I'm not highly motivate to spend more time and energy trying to help out with this, so I think I'll leave it at this "suggestive and somewhat helpful handwaving" level unless some other reader, perceptive enough to SEE how vastly superior the join-all-patterns approach is, but needing to get the specific match-object too, should express interest. As far as I'm concerned, people who still can't see it probably don't want to, and so they're welcome to wear out their CPUs looping uselessly to their hearts' contents. Alex From hgg9140 at seanet.com Sat Nov 9 20:11:12 2002 From: hgg9140 at seanet.com (Harry George) Date: 09 Nov 2002 17:11:12 -0800 Subject: ZODB "cannot create 'function' instances" Message-ID: I'm just starting with ZODB: ------------ Problem ------------ class Base(Persistent): def __init__(self): self.id=mkid() # e.g., '_001' .... class MyClass(Base): def __init__(self): Base.__init__(self) .... (has some dicts and lists) x=MyClass() userdb[x.id]=x get_transaction().commit() Fails in copy_reg._reduce: "state = base(self)" with TypeError: cannot create 'function' instances ------------- Questions ------------- What function does it think I'm creating? Do I need to make all dicts and lists Persistent? Isn't it adequate to commit when they are loaded (and thus not care about dirty flags)? Is there a working example of something like this pattern? -- Harry George hgg9140 at seanet.com From trentm at ActiveState.com Tue Nov 12 17:25:51 2002 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 12 Nov 2002 14:25:51 -0800 Subject: running batch scripts In-Reply-To: <%ZeA9.7$sN2.52@news.oracle.com>; from trilok.agarwal@oracle.com on Tue, Nov 12, 2002 at 02:10:53PM -0800 References: <%ZeA9.7$sN2.52@news.oracle.com> Message-ID: <20021112142551.B7181@ActiveState.com> [tagarwal wrote] > Hi > anyone can help me to write a python script to invoke a windows batch script > (.bat file) > and then keeping the cmd (cmd.exe or the dos window)window alive so as to > use the same window to run some other commands. > I tried using popen2, but how do i tell the cmd.exe to execute the command > once i place the command on stdin. You need to launch your batch file with "cmd.exe /k". From cmd.exe's help: C:\> cmd /? ... /K Carries out the command specified by string but remains ... so try this Python code: os.system("cmd.exe /k your_batch_file.bat") Cheers, Trent -- Trent Mick TrentM at ActiveState.com From wesc at deirdre.org Tue Nov 12 14:14:37 2002 From: wesc at deirdre.org (Wesley Chun) Date: Tue, 12 Nov 2002 11:14:37 -0800 (PST) Subject: ANN: BayPIGgies mtg Wed 11/13 7:30pm Message-ID: BayPIGgies: Silicon Valley-San Francisco Bay Area Python Users Group When: November 13, 2002 @ 7:30pm Where: Stanford University, Palo Alto, CA Agenda: Editing Digital Video using Linux and Python Speaker: Drew Perttula I want to edit digital video in a unix way. That means I want an open-source suite of non-monolithic, flexible tools and transparent data formats that I can use with all my other unix tools. I won't stand for any segfaults or other data-losing behavior. And most of all, I need it by yesterday. Development started mid-September, and by late October I was transcribing and logging captured DV footage into my xml format. Soon after that, the timeline-style editor was running, and we were dragging thumbnails from footage index pages (in html displayed in Mozilla) right into the timeline. There's even the beginning of an effects plugin system, which I currently use to handle the mixing of audio tracks. At November's meeting, I'll be demoing the editor itself and discussing the tools I used, the components I had to build, and where I plan to go with it next. I have a sloppy wiki site at http://bigasterisk.com/editor where I've put some screenshots, samples of the xml formats, use cases, and other notes I made during development. The wiki also gives instructions for getting all the code via anonymous CVS. The code is still very poorly packaged, so it's probably near-impossible to get the code to run anywhere else as of yet. # Upcoming Meeting: December will be another popular "Newbies Night" (see April 2002 meeting on the website) # Call For Talks: We are actively seeking speakers for BayPIGgies! If you would like to give a talk at one of our 2003 meetings (any Python related topic), contact us to coordinate! more info including directions: http://www.baypiggies.net hope to see some of you on Wednesday! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, ? 2001 http://starship.python.net/crew/wesc/cpp/ Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies) http://deirdre.org/baypiggies wesley.j.chun :: wesc at deirdre.org cyberweb.consulting : henderson, nv : cyberweb at rocketmail.com http://www.roadkill.com/~wesc/cyberweb/ From jacek.generowicz at cern.ch Mon Nov 11 03:38:09 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 11 Nov 2002 09:38:09 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: Carl Banks writes: > You can say, "I won't use the advanced stuff that requires me to > think like a machine," Indeed you can. > but then Lisp is pointless, because then it's nothing but a hard to > read, complicated, and faster Python. I beg to differ. You *can* use Lisp as a Python-with-s-expressions. Once you get over the parentheses (let's not argue whether one can get over them or not), it really is very simple, if you stick to the simple things. For the more adventurous, all of Lisp's power is also available. From mhammond at skippinet.com.au Sun Nov 24 18:15:38 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 24 Nov 2002 23:15:38 GMT Subject: Bug in Win32file WaitCommEvent ??? In-Reply-To: References: <3ddaa58d$0$4459$a1866201@newsreader.visi.com> <3DDD711D.2000802@skippinet.com.au> <3dde5012$0$4491$a1866201@newsreader.visi.com> <3dde5e18$0$22192$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: > In article , Mark > Hammond wrote: >> Also much easier for me to code ;) > When in doubt, do whatver is simpler. Yes, good philosophy. How about I make a deal with you - I will add this support, and you translate your C++ code that demonstrates the mask change into Python once this is available? The next win32all is about due anyway. Mark. From martti.halminen at kolumbus.fi Mon Nov 11 22:00:58 2002 From: martti.halminen at kolumbus.fi (Martti Halminen) Date: Tue, 12 Nov 2002 05:00:58 +0200 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: <3DD06EEA.7FA2590C@kolumbus.fi> Neil Schemenauer wrote: > (defun parse-float (s) > (let ((*read-eval* nil)) > (read-from-string s))) > > (defun doit () > (dotimes (i 100000) > (parse-float "3.1415927"))) > > (time (doit)) > > takes 1.507 seconds on my machine using SBCL. The corresponding Python > code takes 0.19. read-from-string isn't quite as good as a purpose-built parse-float; there isn't one in the ANSI standard, though. On my machine, using the parse-float from CMU AI repository, I get 50 % shorter runtime than with this read-from-string trick. - Should perhaps take a look at the corresponding Python part, whether it does the same thing. Often some CL parts are slower than corresponding operations in other languages due to more thorough error checking or handling more odd cases. -- From pinard at iro.umontreal.ca Wed Nov 13 10:08:39 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 13 Nov 2002 10:08:39 -0500 Subject: perl2python In-Reply-To: References: <87y97xmy6o.fsf@flibuste.net> Message-ID: [Wojtek Walczak] > Dnia 13 Nov 2002 13:49:51 +0100, William napisa?(a): > > I want to convert a little perl script to python, is there a tools for > > that ? > Haven't heard of something like that... I have something in the works, within my pile of dreams. But it seems like a major and difficult project. It currently holds 16500 lines of Python. > > or a little doc to learn the minimum of perl for python users ? > [...] my little proposition is to learn perl 'from scratch' :) Yet I would suggest, as far as possible of course, not loosing to much time in the Perl direction, that could be better invested deepening your knowledge of Python. Unless you are seeking for distractions? :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From opengeometry at yahoo.ca Tue Nov 5 19:31:47 2002 From: opengeometry at yahoo.ca (William Park) Date: 6 Nov 2002 00:31:47 GMT Subject: Speeding up a script -- looking for ideas References: Message-ID: Richard Bow wrote: > I'm hoping to get some hints for significantly speeding up the below > script. I've found 43 integers between 1 and 1,000,000 that satisfy the > condition, and would like to push on toward 10,000,000 in hopes of finding > an integer for which there are 3 pairs. Of course, another reason for > asking is to learn more Python from you guys. > > Thanks in advance, > > Richard Bow > > ====================================================================== > # This finds integers n for which there are 2 pairs of positive integers, > #(a,b) and (c,d) such that (a**3) + (b**3) = n, and (c**3) + (d**3) = n. > # see http://www.mathpages.com/home/kmath028.htm > > start = 1000000 > end = 2000000 > > import time > t1= time.time() > > for n in range(start, end + 1): > crn = int(n**(1/3.0)) + 2 # because of float probs, add 2 to be sure > list = [] # crn is large enough > > for a in range(1,crn): > a3 = a ** 3 > for b in range(a,crn): > b3 = b ** 3 > if a3 + b3 == n: > list = list + [(n,a,b)] > if len(list) >= 2: > # e.g. [(1729, 1, 12), (1729, 9, 10)] and > # [(994688, 29, 99), (994688, 60, 92)] > > print list > print > > t2 = time.time() > print "Time's up!", t2 - t1, "seconds have elapsed" > > print "EEEEEEEEEnnnnnnnnnnddddddddd" > > ##total for n = 1 thru n = 1,000,000 is 43 integers > ========================================================== Well, brute-force method is not that bad. Since you are calculating the pairs a^3 + b^3 = n, for n=[1,2000000] where a=1, b=1,2,3,...,126 a=2, b=2,3,4,...,126 a=3, b=3,4,5,...,126 ... anyways, write a Python script to print them out. Then, 'sort' and 'uniq'. For example, consider script 'abn.py', maxn=2e6 maxi=math.ceil(maxn**(1/3.0)) for a in range(1, maxi+1): for b in range(a, maxi+1): n = a**3 + b**3 if n > maxn: break print a, b, n then, python abn.py | sort -n -k 3 | uniq -dc -f 2 > abn spits out 64 integers in 0.23 second on my dual-P3/800. And, going to maxn=10e6 gives 150 integers in 0.65 second, and maxn=1e9 gives 1554 integers in 14.7 seconds. You can search for 3 pairs just as easily. There 8 integers with 3 pairs for n < 1e9. -- William Park, Open Geometry Consulting, Linux solution for data management and processing. 1986 VW Jetta, 350000km :-)) From bhards at bigpond.net.au Mon Nov 18 05:25:47 2002 From: bhards at bigpond.net.au (Brad Hards) Date: Mon, 18 Nov 2002 21:25:47 +1100 Subject: 'for' loop in python, error: unsubscriptable object In-Reply-To: <7913deb3.0211180155.4a243cdf@posting.google.com> References: <7913deb3.0211180155.4a243cdf@posting.google.com> Message-ID: <200211182125.47231.bhards@bigpond.net.au> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Mon, 18 Nov 2002 20:55, george wrote: > Hello: > I am new to python. /AOL. > for max in range[CLA, RBW, BAG, MRB, NOG]: What are you trying to do here? Do you just want to iterate through the values? Let's look at the on-line help for range(): range(...) range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. I can't see what possible values you could put into the five arguments to the heat() function that would make sense as arguments to range(). Perhaps you just want to do for max in [CLA, RBW, BAG, MRB, NOG]: instead? > BUT WHEN I EXECUTE IT , > THE PROGRAM SAYS "for max in range[CLA, RBW, BAG, MRB, NOG]: > type error: unsubcriptable object" Please don't shout (which is the what user uppercase means on the net). Also, can you show how you are calling heat()? Brad - -- http://linux.conf.au. 22-25Jan2003. Perth, Aust. I'm registered. Are you? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE92MArW6pHgIdAuOMRAoxOAJsFSr8AMAfEYWy7sF3HG47iIIfDCgCgjAno 1WcCFa4XL2YU2Rlx+aS3UhQ= =3YTl -----END PGP SIGNATURE----- From sismex01 at hebmex.com Fri Nov 15 09:27:21 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 15 Nov 2002 08:27:21 -0600 Subject: Calling A Deconstructor Message-ID: > From: John Abel [mailto:john.abel at pa.press.net] > Sent: Friday, November 15, 2002 7:47 AM > > Hi, > > I have a class, with an __init__, and a main function, basically a > wrapper around smtplib. I wish to add a __del__ to the class. Two > questions: Do I need to do it this way? If so, how do I can > close the instance, so the __del__ is called? The script will be > permanently resident, so I wanted to make sure that I didn't have > various connections open to the smtp server. > > Thanks > > John > Hmm... interesting conundrum. An object is "deleted" automatically when the last reference to it disappears (goes out of scope, is deleted expl?citly, etc). BUT, you can't force the __del__ method to be called, it's an implementation detail that depends on the memory management scaffolding in place. For example. In CPython, memory management is done via reference counting; when the refcount of an object drops to zero, it's immediately destructed and deallocated; BUT, in Jython, memory management is done via Java's machinery, and there is no assurement of *when*, or *if*, the destructor is going to be called on the object. So, for sanity's sake, use a .close() method, or a .done(), or something like that, to explicitly close your connection to your SMTP server, so you won't have to depend on __del__ doing it for you. Python doesn't have the fixed semantics for destructor invocation that C++ has, so you have to take that into account when designing your software. HTH -gustavo pd: TGIF! From rmunn at pobox.com Fri Nov 1 08:59:03 2002 From: rmunn at pobox.com (Robin Munn) Date: Fri, 01 Nov 2002 13:59:03 GMT Subject: What the heck has happened to PythonWin??? References: Message-ID: On Thu, 31 Oct 2002 at 23:11 GMT, David LeBlanc wrote: >> > From: Mark Hammond [mailto:mhammond at skippinet.com.au] >> > >> [snip] > >> > There is no binary distribution yet for good reason - significant, >> > incompatible changes are still being made. But if you are >> > brave enough, >> > all the source code is there (it is all pure-Python once you >> > have win32all) >> > >> > It-works-for-four-people-that-I-know-of >> >> I'd be happy to be a guiniea pig :-) >> >> -- bjorn > > Ditto!! > > Dave LeBlanc > Seattle, WA USA The way to be a guinea pig is simple: 1. Go to http://spambayes.sourceforge.net/ 2. Follow the CVS instructions to get the most recent code 3. Sign up on the spambayes mailing list 4. Run around on your hamster^H^H^H^H^H^H^Hguinea-pig wheel! -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From karpierz at _NOSPAM_alpha.pl Sat Nov 2 04:44:44 2002 From: karpierz at _NOSPAM_alpha.pl (Adam Karpierz) Date: Sat, 2 Nov 2002 10:44:44 +0100 Subject: Python 2.1, COM (Excel), and Threads... References: <24420294.0210311031.18f8b3e0@posting.google.com> Message-ID: Uzytkownik "Mark Hammond" napisal: > This is wrong though. It should look more like: Of course :) Sorry for my mistake. Adam Karpierz karpierz at zope.pl From eppstein at ics.uci.edu Tue Nov 19 12:38:47 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 19 Nov 2002 09:38:47 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <44d4f61c.0211181708.465f5838@posting.google.com> <3DDA7385.2020609@nyc.rr.com> Message-ID: In article <3DDA7385.2020609 at nyc.rr.com>, Kenny Tilton wrote: > > There are two things which make me cringe. 1) When a Pythonista > > complains about allergies to strange delimiters, and 2) when a Lisper > > calls other languages too slow. > > The numbers I hear are that CL runs on average 20% slower than C. This is after how many decades of Lisp compiler development? -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From jdhunter at ace.bsd.uchicago.edu Wed Nov 27 09:58:39 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 27 Nov 2002 08:58:39 -0600 Subject: Serial.py woes In-Reply-To: <65c27c6b.0211262305.36235eed@posting.google.com> (Norbert.Klamann@klamann-software.de's message of "26 Nov 2002 23:05:17 -0800") References: <65c27c6b.0211262305.36235eed@posting.google.com> Message-ID: >>>>> "Norbert" == Norbert Klamann writes: Norbert> So be it: Norbert> Maybe this post can help you : It turns out the problem was more mundane -- there was a character that I was not outputting which I discovered by reading the manual for the 18th time. It was documented in the language reference for the device, but I did find it in another section of the manual. All is well now -- thanks for the input. John Hunter From bokr at oz.net Mon Nov 4 19:55:07 2002 From: bokr at oz.net (Bengt Richter) Date: 5 Nov 2002 00:55:07 GMT Subject: Str and instance concatanation error References: Message-ID: On Mon, 04 Nov 2002 23:01:05 GMT, "Newt" wrote: >I keep getting the following error when trying to write to a file. > >Traceback (most recent call last): > File "C:\Python22\lib\lib-tk\Tkinter.py", line 1292, in __call__ > return apply(self.func, args) > File "D:\py_stuff\curry.py", line 14, in __call__ > return self.fun(*(self.pending + args), **kw) > File "D:\py_stuff\chaz.py", line 144, in savefile > gv.save_char() > File "D:\py_stuff\globals.py", line 96, in save_char > file.write('' + self.creator + '') >TypeError: cannot concatenate 'str' and 'instance' objects > >This occurs in a class module (called globals.py). This is used to hold all >my global variables, and also has a method (called save_char) to write these >to a file. > >self.creator is initialised in the __init__ as "". Should I create it as a >stringVar instead, or am I doing something incredibly stupid. > Well, the error message is a strong clue, but if it doesn't make sense, what do you do when you don't know why something like self.creator is causing a problem (besides post a question ;-) ? I'm not being sarcastic, I'm wondering why you wouldn't just plunk in a print statement to see what everything involved is. You say you think it is initialized to as "", which shouldn't cause a problem. So what could it have become so that it does cause a problem? What can you do to find out what it is at the point where it causes the problem? Well, make the program tell you more. E.g., just before the file.write above, put print 'self.creator =', `self.creator` or print 'self.creator =', repr(self.creator) (I recommend the back ticks or repr just to make sure you get something you can see, like '' for a null string etc.) If you mustn't touch the code, make a safe copy, and verify that you've restored it afterwards, or make a wholesale hacking copy and just mess with it any way that forces it to tell you what you want to know. Often, it will be less typing and faster than posting a question. HTH Regards, Bengt Richter From aahz at pythoncraft.com Tue Nov 5 11:07:13 2002 From: aahz at pythoncraft.com (Aahz) Date: 5 Nov 2002 11:07:13 -0500 Subject: The Deitel book (was Re: Textbooks on Perl/Python) References: <87b0ada6.0211011453.1df4d216@posting.google.com> Message-ID: In article , Michael Hudson wrote: >Alex Martelli writes: >> >> if and when a student manages to work all through it, I think the >> student WILL feel pretty confident in their mastery of the subject. > >("it" is Deitel & Deitel's Python : How To Program) > >My concern was that the student might feel confident in the subject >after reading the book, but that this might not be justified. It does >cover a huge amount of material, but not with enormous depth (at >least, not in the chapters *I* tech reviewed). My concerns were primarily teaching of poor coding techniques (e.g. use of magic numbers instead of well-named constants) and an approach that I can best describe as Python written by a Java programmer (rather than teaching a Pythonic approach). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From matt at mondoinfo.com Thu Nov 7 22:24:24 2002 From: matt at mondoinfo.com (Matthew Dixon Cowles) Date: 08 Nov 2002 03:24:24 GMT Subject: Email Parse and Python Cookbook References: Message-ID: On Thu, 7 Nov 2002 14:54:29 -0800, David McInnis wrote: > My problem is this. I am using a sample out of the Python Cookbook > but this example fails on some messages. Works on most. > mydomain.com/support/Maildir/cur/1036006414.8616.wf.mydomain.com,S=14076 > 8:2, > raise Errors.HeaderParseError( > email.Errors.HeaderParseError: Not a header, not a continuation Dear David, I've never seen a situation in which the email module raised that error and it wasn't correct. You might want to look at the files in question and see if it is. I recall that there has been some discussion recently on the mimelib-devel list (mimelib is the old name for the email module) about what to do when that error would be raised or there are other sorts of incorrect formatting. You can argue it both ways: On the one hand, if common email software can read the message, people will expect the email module to parse it. On the other hand, chasing bug-for-bug compatibility with every possible RFC violation is a fool's errand. Of course, none of that sort of philosophizing will help your current problem. First, I'd make sure that you're using version 2.4.3 of the module. I think that it requires a relatively recent version of Python and I don't think that there have been any recent changes that would affect the problem you're seeing but it might be worth a try. If the messages are formatted incorrectly and the most recent version of the module can't parse them, you could subclass the module's Parser and override its _parserheaders method with a less strict version. By convention, you're not intended to override methods that begin with underscores but you might not have much choice. You could also catch the exception and do something about it. You might try using the rfc822 module in that case (it may be less strict) as long as you didn't mind not having the message's body parsed. You could also rewrite the file to fix the formatting and run the Parser on it again. BTW, many people consider it best not to post HTML to newsgroups. Regards, Matt From support at internetdiscovery.com Sun Nov 17 14:38:28 2002 From: support at internetdiscovery.com (Mike Clarkson) Date: Sun, 17 Nov 2002 19:38:28 GMT Subject: Tkinter wart: bug or feature? References: <3dd563db.9499247@nntp.ix.netcom.com> Message-ID: <3dd7f032.1870592@nntp.ix.netcom.com> On Sat, 16 Nov 2002 14:57:28 GMT, "Fredrik Lundh" wrote: >David Eppstein wrote: > >> ...or do all the ugly bookkeeping necessary to make sure that image1 >> gets deleted when and only when it is no longer needed > >where all the "ugly bookkeeping necessary" is one extra line: > > lbl = Tkinter.Label(win.window, image=image1) > lbl.photo = image1 This is still a bug workaround, just like using global. You're still expecting the end user to do ugly bookkeeping, but only for images: I don't have to hold a reference to text1 global for it to work. No other commonly used entity in the Tkinter API has this counter-intuitive behavior. It's also very counter-intuitive to what Tkinter is wrapping, namelyTk itself. I've seen a number of different bug workarounds for this, but my question remains: is this a bug or feature? It has been Benevolently declared to be Not a Bug, but clearly others have had trouble with this too. If it's reopened as a bug we can do something about it as there are obvious fixes as I pointed out, but if it's a feature there's nothing we can do. > "When someone says 'I want a programming language in which I > need only say what I wish done,' give him a lollipop." -- Alan Perlis "All that is necessary for evil warts to triumph, it is that a few good men do nothing." -- Edmund Burke, perhaps. Mike From lisior at manta.univ.gda.pl Thu Nov 21 02:20:53 2002 From: lisior at manta.univ.gda.pl (Daniel Lisewski) Date: Thu, 21 Nov 2002 08:20:53 +0100 Subject: A simple question: How to exit from a python script? Just like the exit() in C++ In-Reply-To: References: Message-ID: On Thu, 21 Nov 2002, Wang Hanbo wrote: > Hi, > > I have a simple question as is written in the header, how can I > exit from a python program using a call such as "exit()" in C++? > > I am a novice on this list, and also a rookie on python > language, all of you answers will be my best impetus! > Thanks > There is a procedure called exit in module sys. So to use ut you have to write sys.exit(), and of course you need to import sys module. Hope that will help. Daniel ( lisior at manta.univ.gda.pl ) From csshi99 at yahoo.com Tue Nov 5 13:09:00 2002 From: csshi99 at yahoo.com (xinghua shi) Date: Tue, 5 Nov 2002 10:09:00 -0800 (PST) Subject: More about simple question In-Reply-To: <001d01c28494$f31103c0$ba01010a@local> Message-ID: <20021105180901.76557.qmail@web21208.mail.yahoo.com> Hey,thanks you all. Actually, I messed up the indentation and I first thought it's not a big problem as I used to write in C. I still have another question. If I have a file named: foo.py. then how can I get an excetable, say foo? In C, I could use % gcc foo.c -o foo So how can I do similar in Python? %python foo.py -o foo doesn't work of course. Thanks! __________________________________________________ Do you Yahoo!? HotJobs - Search new jobs daily now http://hotjobs.yahoo.com/ From missive at frontiernet.net Tue Nov 19 17:35:34 2002 From: missive at frontiernet.net (Lee Harr) Date: Tue, 19 Nov 2002 22:35:34 -0000 Subject: PersistentList (ZODB) References: Message-ID: In article , Thomas Guettler wrote: > Hi! > > I use PersistentList v1.3 from Zope2.6. > > If I do the following > > mylist=PersistentList() > type(mylist) > mylist.append(5) > mylist=[1, 2, 3] # (*) [1, 2, 3] is a list, not a PersistentList > type(mylist) > > mylist is not a PersistentList anymore. Is there > a way to change PersistentList that way that the line > marked with (*) does not delete the PersistentList, > but creates a new empty one? > I have not looked at it, but what methods does PersistentList have? Is there something to replace its contents? or to empty it out completely? You might have to dig around in the source code. I have found with Zope that is sometimes the only way to find anything out. From jwbaxter at spamcop.net Wed Nov 6 15:51:11 2002 From: jwbaxter at spamcop.net (John Baxter) Date: Wed, 06 Nov 2002 12:51:11 -0800 Subject: Guilty secret: globals baffle me References: <3U9y9.19300$ko1.2872530@kent.svc.tds.net> <82ay9.98000$TD1.4405986@news2.tin.it> Message-ID: To the old favorite programmer complaints: Constants aren't. Variables don't. Python adds: Globals aren't. --John From justin at gnubian.org Fri Nov 15 11:24:55 2002 From: justin at gnubian.org (Justin Ryan) Date: 15 Nov 2002 10:24:55 -0600 Subject: changing unix password with python In-Reply-To: References: Message-ID: <1037377496.20555.16.camel@qutang> > Google is your friend. Asking for "Python PAM" reveals > > http://www.tummy.com/Software/PyPam/index.html Thanks.. I actually came across this, but had a bit of trouble getting my head around it and thought I'd be better off asking a general question on the list than focusing on a module that may not be the only or the best.. should have mentioned this before -- my mistake.. > If you find you need to make changes, don't forget to contribute them > back to Rob Riggs. but of course.. Thanks again! -Justin -------------- 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 opengeometry at yahoo.ca Fri Nov 15 16:41:38 2002 From: opengeometry at yahoo.ca (William Park) Date: 15 Nov 2002 21:41:38 GMT Subject: Permutations algoritm? References: Message-ID: sismex01 at hebmex.com wrote: > Does anybody have a clear, simple, permutations algorithm > in Python? Would you care to explain this? Permutation can mean different things. Concrete example might be good... -- William Park, Open Geometry Consulting, Linux solution for data management and processing. From andymac at bullseye.apana.org.au Sat Nov 23 23:15:12 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 24 Nov 2002 14:15:12 +1000 (est) Subject: urllib slow on FreeBSD 4.7? sockets too In-Reply-To: <3ddf4fb7$1_2@omega.dimensional.com> Message-ID: On Sat, 23 Nov 2002, Mike Brown wrote: > "Jarkko Torppa" wrote: > > Seems that stdio is somehow confused, try this > > > > import urllib, time, os > > > > starttime = time.time() > > u = urllib.urlopen('http://localhost/4m') > > fn = u.fp.fileno() > > bytea = [ ] > > while 1: > > bytes = os.read(fn, 16 * 1024) > > if bytes == '': > > break > > bytea.append(bytes) > > bytes = ''.join(bytea) > > u.close() > > [...] > > Well, look at that... > > bytes: 4241.5K; time: 0.322s (13171 KB/s) > > That's much better. At least, it now seems to be hitting the socket speed > cap. I'm glad that I said (in my previous post) that realloc() _may_ be the cause of what you're seeing, because its not. I haven't gotten right to the bottom of the matter, however the following patch against the 2.2.2 sources makes an enormous difference on my system: ---8<---8<---8<---8<--- *** Lib/httplib.py.orig Mon Oct 7 11:18:17 2002 --- Lib/httplib.py Sun Nov 24 14:44:16 2002 *************** *** 210,216 **** # See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details. def __init__(self, sock, debuglevel=0, strict=0): ! self.fp = sock.makefile('rb', 0) self.debuglevel = debuglevel self.strict = strict --- 210,216 ---- # See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details. def __init__(self, sock, debuglevel=0, strict=0): ! self.fp = sock.makefile('rb', -1) self.debuglevel = debuglevel self.strict = strict ---8<---8<---8<---8<--- With the 2.2.2 release source, I get about 113kB/s retrieving a 4MB file from a localhost URL. With the patch applied, I get 4-5.5MB/s. This on a FreeBSD 4.4 SMP system (dual Celeron 300A, 128MB RAM) with ATA66 drives. The change turns the socket's file object from unbuffered, to buffered with a default buffer size (which I believe is 1024 bytes). I don't know what the implications of this change in other circumstances are, so can't recommend this as a permanent patch. There appears to be no easy way to set this buffering option from the urllib or even httplib APIs. At the moment I don't have the FreeBSD library source readily accessible to investigate the stdio (specifically fread()) implementation in the unbuffered case. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From aleax at aleax.it Sat Nov 9 03:02:43 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 09 Nov 2002 08:02:43 GMT Subject: NEWBIE: Extending Python with C References: <3dcc7e2c.3568851@news.earthlink.net> Message-ID: engsol at teleport.com wrote: ... > What I want to do is call (or invoke) a C exe from Python, and return the > results to Python. Or pass values of some sort to the C exe, and again ... > I'm using Python 222 on NT. If I understood how to do "Hello world" (in > C, called from Python), I might be able to go from there. Then you have a mind-boggling array of possibilities to perform the task you require. Simplest: hello.c: #include int main() { puts("Hello world"); return 0; } compile and link hello.c to produce hello.exe, say specifically placed in c:\kraip\hello.exe. Now in python hello1.py: import os os.system('c:/kraip/hello.exe') This does the "call or invoke" part but doesn't really "return the results to Python" -- hello.exe doesn't really have "results" but rather performs output to standard-output, and invoking it with os.system just lets it perform its output normally. To capture hello.exe's resulting output as a string for Python use, hello2.py: import os hellopipe = os.popen('c:/kraip/hello.exe', 'r') results = hellopipe.read() hellopipe.close() print "Python here: %r" % results This limits the "pass values of some sort" spec to passing starting arguments to the other program you're invoking. E.g. hello3.c: #include int main(int args, char** argv) { printf("Hello %s\n", argv[1]); return 0; } and hello4.py: import os argument = 'pythonista' hellopipe = os.popen('c:/kraip/hello3.exe %s' % argument, 'r') results = hellopipe.read() hellopipe.close() print "Python here: %r" % results This is more or less the end of the line in terms of what os.popen can offer -- due to buffering and suchlike there's no practical way for python to drive BOTH standard input and standard-output of another external program. What you'll read about as EXTENDING python doesn't use an external PROGRAM but rather an external MODULE, which in Windows will take the form of a .DLL file. But Windows in particular offers many other approaches too. DDE (old and cranky), Windows Messages (old but OK for simple things), COM (not newest any more, but still VERY powerful and well-designed), not to mention many other possibilities such as shared memory ("file mappings") and other kernel objects for inter-process communication, "named pipes", etc. And in platform-independent terms, there's XPCOM (a sort of open-source clone of COM), Corba, XML-RPC, SOAP -- just for starters. Back when I did Windows programming full-time for a few years, I would have reached for COM almost by reflex. Now that most of my programming is cross-platform or even Linux specific, the reflex has dimmed a bit (I *do* miss COM, darn it -- only technical aspect of Windows I do miss!), so I would consider forgetting the "call (or invoke) a C exe" part of the specs, deeming it an unfortunate slip of the tongue, and go for Python extension and embedding (even though it means that either the C-coded thingy will be a DLL, NOT an exe, or else if it's an exe IT will have to start the ball rolling by calling (or invoking) Python, not vice-versa). Even within this compass, you have so many choices it hurts: C-level coding for the "Python-C API"; C++ use with SCXX, CXX, Boost Python, SIP (yes you've specified C, not C++, but people sometimes say one thing while they mean another...); and SWIG, too. The best way to choose is to delineate as precisely as you can all constraints and possible future developments of your needs. If such constraints and futures do not include using any other platform except Windows, then COM is most likely still best: by exposing a COM/Automation model from your EXE, not only will you let Python drive it, BUT you'll have a potentially important "bullet point" on your app's feature list for marketing purposes -- sophisticated customers or 3rd party integrators will also be able to drive your app from (e.g.) Visual Basic, Delphi, etc; and even get an automatic dotNET wrapper to drive said app from C# and the like, too. This DOES help sell... Alex From martin at v.loewis.de Wed Nov 13 16:42:01 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 13 Nov 2002 22:42:01 +0100 Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> <87y98f566d.fsf@zamazal.org> Message-ID: DaveP writes: > >> Yes, but the documentation author has to fill in the URL. In Python > >> documentation, the RFC URL provided at formatting time; currently, it > >> points to www.faqs.org. > > OK, So too could the xml processing chain, probably in the same way. > By holding the url in the stylesheet and indexing off some key. Certainly - but then we need entirely new tools (or must modify existing tools). Have you ever tried to modify Norman Walsh's DocBook XSLT stylesheets? That may be an excellent piece of software, but it has a complexity that is not easy to grasp (to put it mildly). > > - There's no clear benefit from switching to Docbook right now. All > > the difficult work has already been done for LaTex and switching to > > Docbook provides no clear advantage. Plus, the difficult work would > > have to be done *again*. > > Yep.... But are you going to march onwards to Omega to pick up Unicode? > The only given in the future is change. We are not talking about the big picture here; I happily leave views and architectures to others. What we are talking about is the Python documentation, which has small but precise needs. Being able to represent arbitrary characters is not a requirement at the moment. > > I'd suggest to anybody who wants to make the Docbook transition happen > > to provide XSLT/CSS stylesheets that make the HTML output of Docbook > > look *exactly* like the current one. > > Justification? To proof that it can be done, and to smoothen the transition. Many URLs in the world point to specific pages of the documentation at python.org. It is desirable that as few as possible of these URLs break just because the formatting engine changes. > > Those who are working on the Python documentation will certainly not > > do this work for you, as they've better work to do. Namely, writing > > documentation and not fighting the toolchain. Adjusting the tools has > > been done once already, and that should suffice for a few years ;-) > > Few being? Three or four, I think. Conversion to DocBook has been studied for three years, atleast, and everytime this comes up, the conclusion is that it is not worth the effort. > My wild guess would be that there are today more people familiar with XML > than there are with \tex. How long will the supply of tex afficianado's > last? You don't need to be a Tex aficionado to contribute to the Python documentation. I don't like Tex myself, and I don't use it for anything but the Python documentation. However, when writing Python documentation, I don't think of it as writing Tex. It is a special language that is much easier to learn than Tex, since the processor is much more forgiving (it is processed by Fred Drake, after all). > Change is inevitable. That may be the case. Change to Docbook can be avoided if necessary. Regards, Martin From fredrik at pythonware.com Wed Nov 6 16:17:12 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 06 Nov 2002 21:17:12 GMT Subject: newbie re question References: <1osisu81483e4k3j905dun6diio6rt29ao@4ax.com> Message-ID: Gon?alo Rodrigues wrote: > I've been trying to grok re's and settled myself a little exercise: > concoct a re for a Python identifier. > > Now what I got is > > >>> pattern = re.compile(r'(\s|^)([\w_][\w\._]*)(\s|$)') > >>> pattern.findall('aadf cdase b ad:aa aasa a.aa a@ aa _aa _aafr@ aa_aa aa__a?jk') > [('', 'aadf', ' '), (' ', 'b', ' '), (' ', 'aasa', ' '), (' ', 'aa', '> '), (' ', 'aa_aa', ' ')] > > But as you can see from the results, not all valid identifiers get > caught. For example, why isn't 'cdase' caught? findall returns non-overlapping matches. there's only a single space between "aadf" and "cdase", and that was used by the first match. here's a better pattern: pattern = re.compile(r'\b([a-zA-Z_]\w*)\b') From mwh at python.net Mon Nov 11 05:00:10 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 11 Nov 2002 10:00:10 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: <7h3pttc2zvh.fsf@pc150.maths.bris.ac.uk> Jacek Generowicz writes: > I can imagine that you could put """ """ around your Python > definitions, do something similar by processing the resulting string, > and then eval it ... but it sounds far too painful to try. Been there. It can be done, but you're right in saying that it's not fun. Cheers, M. -- ARTHUR: But which is probably incapable of drinking the coffee. -- The Hitch-Hikers Guide to the Galaxy, Episode 6 From Patrick.Carabin at MyRealBox.COM Tue Nov 12 07:41:21 2002 From: Patrick.Carabin at MyRealBox.COM (Patrick.Carabin at MyRealBox.COM) Date: 12 Nov 2002 04:41:21 -0800 Subject: How do I reply to an item in the list ? References: Message-ID: <44ee1dc2.0211120441.465eeb62@posting.google.com> testing with Netscape to see if ?reply? works IN the thread From martin at v.loewis.de Tue Nov 12 11:29:39 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 12 Nov 2002 17:29:39 +0100 Subject: Calling methods in embedded python References: Message-ID: "Krzysztof Wasilewski" writes: > 2) I import the module I want to use > 3) I get the dictionary of that module > 4) From the dictionary I get the function I need using > PyDict_GetItemString() > 5) I construct the parameter tuple > 6) I execute the function using PyObject_CallObject() Notice that these could be combined into a single function call PyObject_CallMethod(moduleobj, "functionname", "format string", args); since CallMethod is really the same as moduleobj.functionname(args); > 5) Then I try to instantiate an object of this class using PyInstance_New(), > passing the class I created. Unfortunately, this always fails - NULL is > returned. Can anyone explain why? No. Did you try printing the exception? As you know, a return value of NULL *always* indicates that an exception was raised, which carries more information about the nature of the problem. > What should be passed for kw? I tried an empty tuple, an empty list, PyNone > and other things, but in vain. It's the dictionary of keyword arguments (**kw), so it should be a dictionary; NULL would also be acceptable. > 6) Once I get an answer to this one, I plan to call a method of the > instantiated object calling PyObject_CallMethod(). I hope that this is OK. That should work fine. Regards, Martin From anders at gamebox.net Sat Nov 9 06:01:21 2002 From: anders at gamebox.net (A Nilsson) Date: Sat, 09 Nov 2002 12:01:21 +0100 Subject: zip/unzip pictures doesn't work References: <3DCCE633.5040301@gamebox.net> <3DCCE828.E8F646DD@alcyone.com> Message-ID: <3DCCEB01.4040004@gamebox.net> You're right! Thanks! My first (failed) attempts were made on a Win NT. Now I'm back on my own trustworthy linux machine and, hey, it works! Erik Max Francis wrote: > A Nilsson wrote: > > >>I've been messing around with the zipfile module and discovered >>something strange. >>When I zip/unzip ordinary text files there's no problem but when i use >>pictures (JPG and GIF) they get corrupted. I believe it is during the >>unzip operation they get messed up. > > > Sniff, sniff. I smell a text/binary distinction (and I see you're on > Windows). Make sure you open the relevant files in binary mode by > appending a 'b' character to the mode string. > From b.e.n.c.a.t.7.3. at .t.p.g...c.o.m...a.u Sat Nov 9 04:50:19 2002 From: b.e.n.c.a.t.7.3. at .t.p.g...c.o.m...a.u (Ben C) Date: Sat, 9 Nov 2002 20:50:19 +1100 Subject: Point an MS Access / VB developer in the right direction... References: <3dcb9830$1@duster.adelaide.on.net> Message-ID: <3dccd9eb@dnews.tpgi.com.au> Hi there, the choices you will have to make are between GUI toolkits are 1. wxWindows ( works fine ) 2.Qt ( also works fine ... a little more polished than wxWindows though ) I have built client front ends quite succsesfully to PostgreSQL (nice DB but don't run it under Cygwin ... it's a bitch ;) ... and MS SQL server ( I had to do it for work ... so no flames please) using wxWindows on win32 Systems and Linux ... If you run Postgres ... there is a GUI tool which will do a similar job as a M$ Acess front end ... pgAccess ... their is also a win32 admin utility pgAdminII which you can use if you don't want to telnet into the server and use the psql admin shell I am currently working on an app using the embedded SQLite DB rather than use Access and wxWindows ... (though this will be the last wxWindows app I plan to write) ... this might be a good starting point? SQLite will run on windows and linux and can be easily accessed using the pySQLite module ... SQLite is typless and doesn't have ODBC connectivity as far as I know?? (though someone might have written an ODBC driver for it) ... however if you keep your statements similar to ANSI SQL statements (with type declarations) you can suck in whole tables etc into Postgres later on without too much mucking around ... I am now looking to shunt across to Qt though as IMHO I feel that Qt is a little more evolved and www.thekompany.com have finally got a release of Blackadder for Python 2.2 today ... woohay! I hope that helps? cheers Ben C "Dan" wrote in message news:3dcb9830$1 at duster.adelaide.on.net... > Hi all. > > I've been an Access / VB developer for 5 years. I've run Linux at home > for 3.5 years, and I think it's about time I learned how to program for > Linux. > To start with, I would like to re-write some simple Access database > front-ends from work (which connect to a MySQL & SQL Server backend) in > Python. > Now I assume that I'm not going to find on open source IDE which allows > me to set up a query and connect it to a grid to display on a form in > 'datasheet' mode (please correct me if I'm wrong). So where do I start? > Also I to choose a gui widget thingy set. I have looked at the > boa-constructor IDE, which uses wxwindows. This would be nice in my case > as it works on Win2k and Linux. Any thoughts on this? I am also > considering buying Rekall from The Kompany. It seems to provide what I > want, but it's commercial. It's not that I have a problem with using a > commercial product, but if I have a reasonable open-source choice I'll > take it. > Maybe someone has a link to a HOW-TO on making a simple data-aware form? > Any advice greatly appreciated. > > Dan > From usenet at soegaard.net Tue Nov 12 19:29:55 2002 From: usenet at soegaard.net (Jens Axel Søgaard) Date: Wed, 13 Nov 2002 01:29:55 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCFDE7A.8010404@web.de> Message-ID: <3dd1ffd9$0$63936$edfadb0f@dread15.news.tele.dk> Andreas Leitgeb wrote: Pascal: >> If you are used to this kind of syntax, it's very simple. I don't >> know enough Python (yet) in order to translate this, but in Java it >> would look as follows. >> 1 boolean buttonPressed (int slotId, Vector cardList) { >> 2 return !(cardList.size() == 0) && >> 3 cardList.get(0).isVisible() && >> 4 ((slotId == 1) || (slotId > 5)); >> 5 } > > I'd have rewritten it differently (to show the point I was > trying to make by calling the scheme-snippet ugly): > 2 if (cardList.size() == 0) return false; > 3 else if (!cardList.get(0).isVisible()) return false; > 4 else return ((slotId == 1) || (slotId > 5)); > Now this doesn't make a big difference here, but it makes > a lot of a difference, once, things get longer and deeper nested. I find Pascal Constanzas version the easiest to read. The if-then-else construction makes it hard to see that it is boolean expression. -- Jens Axel S?gaard From cbbrowne at acm.org Tue Nov 5 00:16:11 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 5 Nov 2002 05:16:11 GMT Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> Message-ID: In an attempt to throw the authorities off his trail, Daniel Pfeiffer transmitted: > this morning it struck me that it would be nice to have Parrot not > only run Perl 6 and similar byte code, but that any of the common > interpreted languages be compiled to this same byte code. I'd think it quite plausible that if someone took the project on, there could readily be a pretty functional Python compiler for Parrot /before/ a Perl 6 one would be likely to emerge... -- (reverse (concatenate 'string "ac.notelrac.teneerf@" "454aa")) http://www3.sympatico.ca/cbbrowne/sap.html Signs of a Klingon Programmer - 7. "Klingon function calls do not have 'parameters' - they have 'arguments' -- and they ALWAYS WIN THEM." From max at alcyone.com Wed Nov 13 19:19:47 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 13 Nov 2002 16:19:47 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h3k7jlwock.fsf@pc150.maths.bris.ac.uk> <76c4da8e.0211101357.6a804d20@posting.google.com> Message-ID: <3DD2EC23.4A96D358@alcyone.com> Anton Vredegoor wrote: > Without confirming that I want that, I would like to mention that > functional languages can't have side effects. That's usually what I've heard people call "pure functional languages," which are really relegated to academia. Most program domains need to do _some_ side effecting, like taking input and output. (There are ways to cleverly hide this in a functional way, but the input and output is still technically a side effect.) In my experience, most people use "functional language" to indicate a language where things primarily get done via return values of functions only but side effects are a necessary evil (for I/O or environment changes). Common Lisp and Scheme are functional languages, but they're not pure functional. One might talk about languages that _support_ functional paradigms but don't primarily rely upon them; Python would qualify in this respect. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ I do not like work even when someone else does it. \__/ Mark Twain Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From josiah7 at hotmail.com Sun Nov 24 07:53:31 2002 From: josiah7 at hotmail.com (Josiah) Date: 24 Nov 2002 04:53:31 -0800 Subject: Repost: Tkinter Checkbox Question References: Message-ID: Jeff: Thank you so Much, This has been driving me nuts! When I used "self.var = IntVar(master)", in the above code as you suggested, it works fine! This is under windows XP (Sorry I didn't mention). Thanks! From jkraska at san.rr.com Sat Nov 30 13:16:48 2002 From: jkraska at san.rr.com (Courageous) Date: Sat, 30 Nov 2002 18:16:48 GMT Subject: Is there a bright future for open software projects? References: Message-ID: >What companies like ActiveState.com or similar live on if they offer free software? There are many companies, even ones with a predominately software business, that actually don't sell packaged software, but instead sell software development _services_. These companies are usually supportive of internal open source efforts, because a successful open source project provides marketing material for selling the company's services. The downside is that, in companies like this, one has to be billable to a client a great deal of the time. Clients usually have specific problems that they want solved, and your open software effort is of no concern to them. C// From maney at pobox.com Sat Nov 16 12:00:43 2002 From: maney at pobox.com (maney at pobox.com) Date: Sat, 16 Nov 2002 17:00:43 +0000 (UTC) Subject: Python instead of php References: Message-ID: Marten Bauer wrote: > Is it possible to use python like php as script language to writte > the Userinterfaces also in html and python? Yes, Python is an excellent language for web site/app scripting! > Is modpython for apache or Twisted from Tweak Labroratory a possible > way? Yes. You might want to take a look at the Quixote publishing framework. It seems to me to be a good match to code-intensive web apps. I'm using it for one such that is heavily database-driven with very good results. http://www.mems-exchange.org/software/quixote/ Quixote scripts can easily be moved between plain CGI (slow, but great for development as your changes take effect instantly), fastCGI, or modpython; I use the first two of these myself. Luck! From johnroth at ameritech.net Sat Nov 23 08:29:59 2002 From: johnroth at ameritech.net (John Roth) Date: Sat, 23 Nov 2002 08:29:59 -0500 Subject: int() shortcoming? References: Message-ID: "Matthew Knepley" wrote in message news:y8h3cptpttf.fsf at spinetta.mcs.anl.gov... > Is there a reason I should have to specify the base for a string > conversion using int() when it is already clear from the form? For instance: > > >>> oct(15) > '017' > >>> int('017') > 17 > >>> int('017', 8) > 15 > > and hexidecimal actually generates an error. To whom is this clear? For me, it is one of the many idiocies foisted off on a gullable programming community by the inventors of the 'c' programming language (although it may have deeper roots.) In other words, what's "clear" depends on your background. The numeric literal syntax is not at all clear to a novice; it's simply an idiom that they have to learn. John Roth > > Thanks, > > Matt > -- > "Failure has a thousand explanations. Success doesn't need one" -- Sir Alec Guiness From aleax at aleax.it Thu Nov 21 05:49:26 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 21 Nov 2002 10:49:26 GMT Subject: "properties" idiom References: Message-ID: Terry Hancock wrote: > I could swear I saw a conversation about this on list, but I'm having > trouble finding anything relevant. > > Let's say I have a class that exposes an attribute x as part of it's > public API: > > class spam: > def __init__(self, x): > self.x = x > > Due to later development, however, it's clear (hypothetically) > that setting or getting the value of x, requires a method call > (to update a database, for example). Perfectly right, and a frequent occurrence: you are designing a class, thus implicitly an interface that the class 'publishes' to other code using it ('client code'); right now the implementation naturally suggests making attribute 'x' a client-code-accessible data attribute, but you want to reserve the option to change things in the future so that client code accessing to setting x causes some method to execute. That's exactly motivation number one for the "property" concept: it lets you expose your attributes WITHOUT worrying that this will restrict your options in the future, so you never have to design boilerplace accessor and mutator methods just to keep flexibility. > Is there a standard idiom for calling that method when an outside > caller does something like: > > spaminstance.x = 42 > > or > > y = spaminstance.x Yes: there are in fact two of them. One works in every version of Python since at least 1.5.2 (earlier I believe) and with every kind of Python class, but is a bit clunky. The other standard works only with Python 2.2 and later and with "new-style" classes, but is slicker. The classic approach hinges on methods __setattr__ and __getattr__. If your class C defines a C.__setattr__, then ANY setting of an attribute of an instance I of C actually calls __setattr__ instead: I.x = 42 actually becomes I.__setattr__('x', 42) You must code your __setattr__ method to deal with ALL attribute settings appropriately, e.g. via self.__dict__[name] = value when you want to treat such a setting of attribute name to value in the "normal/usual" way -- that's what makes the approach a bit clunky. There is no distinction between code "inside" vs "outside" the class. __getattr__ is different -- it's only called when the NORMAL ways to look for an attribute (in the object's dictionary, in the object's class, in the bases of said class) have failed -- so it's really quite a bit handier. But exactly because it's only called for otherwise-failing lookups, this gives constraints: -- __getattr__ must raise AttributeError for attributes you don't want to appear to be there -- you must keep the actual value of the attribute somewhere the normal search process won't find it, so __getattr__ gets a chance -- popular approaches are [a] using attribute '_x' to hold the value of what's accessed from outside as 'x', or [b] having _another_ per-instance dict besides self.__dict__ and using the OTHER dict to keep attributes such that attempts to access them must go through __getattr__ So, all in all, it's quite feasible, and enough to remove worries in interface-design work, but when called upon to operate, it's a bit clunky. Which is why, in 2.2 and only for new-style classes, the alternative 'property' built-in was introduced -- I see others have already covered that, so I won't repeat it. My suggestion: use 'property' when you possibly can, but don't worry, since if for any reason it's an old-style class you need, or in order to keep compatibility with old Python versions, you can get the same effect in whatever kind of class and whatever version of Python, albeit with more work and less speed. > (i.e. when we see this, my class actually calls an internal method, > spaminstance.__set_x(42)). If so, I'd have the same flexibility as if I > had used get_x()/set_x() accessor methods, but my code would > be simpler for the most common case. Can you do this with Python > today? I was thinking there might be a way using __getattr__ and > __setattr__, but it initially looks very complex -- is there a preferred > way to do it? Right on target on both scores. > I'm defining an interface now, and I'm wondering whether I should > go with attributes or accessor-methods. I've been using accessor > methods, but it bloats the interface quite a bit, and I'm wondering if I > can make the interface simpler this way. And here, too. Cluttering your class with accessors is quite unPythonic. Use properties and you'll be much happier! Alex From joconnor at cybermesa.com Thu Nov 7 23:51:03 2002 From: joconnor at cybermesa.com (Jay O'Connor) Date: Fri, 08 Nov 2002 11:51:03 +0700 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: <20021108.115059.1034949299.9010@cybermesa.com> In article , "David Garamond" wrote: > Oleg wrote: >> I don't know much about Python, but I looked at this comparison between >> Python and Common Lisp ( >> http://www.norvig.com/python-lisp.html ), and I couldn't help but >> wonder why Python is popular, while Common Lisp and Scheme aren't? > > one sentence: "syntax matters." for people in denial, make it two: "yes > it really does." > > or, rephrased: indentation and "1+1" scare people less than parentheses > and "(add 1 1)" or something like that. Yes, I was a Python advocate in a TCL shop for awhile and had a hard time convincing people that there was a qualitative difference between. set x [lindex [lindex $var 5] 5] and x = var[5][5] -- Jay O'Connor joconnor at cybermesa.com http://www.r4h.org/r4hsoftware From aaron at reportlab.com Tue Nov 12 10:54:01 2002 From: aaron at reportlab.com (Aaron Watters) Date: 12 Nov 2002 07:54:01 -0800 Subject: lisp scheme lush python etc. References: Message-ID: <9a6d7d9d.0211120754.5245cc65@posting.google.com> > > It seems to me that Lush (http://lush.sourceforge.net) has the potential to be really useful. > And, the developers mention "bindings to the JavaVM API and to the Python C API" > (as I can see, this is yet not here, but things are rapidly changing in CVS everyday). > The symbiosis of Lisp and Python can be very interesting... > > > Mike Well I got curious and looked at Lush. It seems that if you are interested in using an experimental language only on Linux Lush could be interesting, but I'm going back to (stackless) python after I write this. I abandoned Lisps and scheme for Python about a decade ago (with misgivings) primarily because 0) portability and stability 1) libraries and portable extension framework 2) it's friendly to other software (from above and below and anywhere else) 3) the syntax doesn't stink (but if it was done over I'd add brackets) 4) it's easy enough for noneggheads 5) Everything I liked to do that was easy in Lisps was also easy (and clearer too) in Python. (ymmv) It seems to me that most similar languages still fail on at least one of the above. (1,3,5) are very much judgement calls, of course. The major thing that is missing, of course is some sort of (optional, inferred) type checking. I'm also getting nervous about bloat... my 2c. -- Aaron Watters --- Never eat anything bigger than your head. -Kliban From hgg9140 at cola2.ca.boeing.com Thu Nov 7 09:33:34 2002 From: hgg9140 at cola2.ca.boeing.com (Harry George) Date: Thu, 7 Nov 2002 14:33:34 GMT Subject: slow on HPUX, SunOS, fast on MS Win2K and Linux? Message-ID: Is there some reason python code which builds objects should be notably slow on HPUX or SunOS? Some known code optimization problem? We are seeing: > ----------- > import cPickle > f = > open("/acct/mad5486/SpecEngineV0/bac5117-compiled.xml-pickled",'r') > xml_dom_object = cPickle.load(f) > ----------------------------END------------------------------- > ---------- > > Times: > > 5 seconds on Intel / Linux > 5 seconds on Intel / Win2k > 33 seconds on HP-UX 11.0 (uname -a: HP-UX dblv018 B.11.00 E 9000/800) > 22 seconds on Sun OS (uname -a: SunOS wizard 5.8 > Generic_112953-02 sun4u sparc SUNW,Ultra-Enterpris) > 17 seconds on HP-UX 10.2 (uname -a: HP-UX drtn029 B.10.20 E 9000/819) > The Win2K and Linux boxes are (nearly) identical hardware. The others are serious machines with substantial RAM. The guy running the tests tried to isolate for these issues: 1. No one else on the machine; light load of background tasks. 2. Code and datafile cached in RAM (no delays due to LAN-based file servers). 3. Results similar for Py 1.5.2 and 2.2.1 on each machine. 4. According to "top" process was getting 99% of CPU, and it was CPU bound. 5. While this example is from the pickle, the same effects were seen for the original PyXML parse of the DOM. -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 294-8757 From brian at sweetapp.com Wed Nov 13 05:05:28 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 13 Nov 2002 02:05:28 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? In-Reply-To: Message-ID: <002701c28afc$320427c0$21795418@dell1700> Martin wrote: > You'll be wanting to throw out all manner of things on that basis, since > there's nothing of much use that hasn't been the source of problems for > some. I know, you have to draw the line somewhere, but to me this seems > like a good deal of value to lose for what IME is little gain in > idiot-proofing. I can agree that the value seems to be lower in Python in > that the need for this arises less often than in, say, C. I haven't yet > decided if I think that's due more to the language itself or to the way > the lack of operator= has led to the construction of facilities to > make it unnecessary for common uses. :-/ The fact that VC++ and CW both generate warnings for inline assignment (I don't know about gcc) leads me to suspect that it is a particularly frequent source of problems. > Think about the straightforward implementation of this in legal Python > with less undersized indentation than I used before: So you do not intend every block in other programming languages? I do... > Yes, that approach occurred to me. It seemed, and still seems, like a > great deal of overhead and effort for little if any gain in clarity, > although it certainly does solve the marching right off the > screen problem. How are you measuring overhead? Lines of code? Performance? My technique actually uses less lines of code as the number of record types increases. And if it required a lot of effort, I wouldn't have written the code for this discussion :-) In total it probably took me 30 seconds to think of the solution and 2 minutes to type it (mostly because my mail client doesn't autoindent). > > Notice that: > > - it is very easy to add new record types > > You have two things that have to be added for each new case: a regexp and > a code block. But I don't have to go looking through the file processing code to add my regexp and code block. I just add it to a list. > neither does the savings in explicit logic > boilerplate appear to outweigh the function-form bolierplate it requires. They code size is identical in either case. I don't really understand your complaint. My solution has a few advantages over the inline assignment version and only costs you about three lines of code. So it is really worth arguing for inline assignment? I would say no, at least from looking at this example. Cheers, Brian From brian at sweetapp.com Tue Nov 12 16:47:42 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 12 Nov 2002 13:47:42 -0800 Subject: pitfall for your amusement In-Reply-To: <20021112190718.A31484@ibook.distro.conectiva> Message-ID: <000d01c28a95$213cfb40$21795418@dell1700> I don't like the augmented operations because, depending on the object, the operation may or may not be done in-place. I think that it is better to be explicit and use assignment or method call. That way you know what you are getting. Cheers, Brian From csshi99 at yahoo.com Fri Nov 8 23:30:59 2002 From: csshi99 at yahoo.com (Mindy) Date: Fri, 8 Nov 2002 20:30:59 -0800 (PST) Subject: Questions about tuple? In-Reply-To: <000f01c287b7$af068440$310aa8c0@duallie> Message-ID: <20021109043059.52296.qmail@web21208.mail.yahoo.com> > It's called a dictionary. > > dict = {"a":1, "b":3, "l":2, "p":8, "m":(1,2,3,4,5), > "z":"blah"} > > dict.keys() > >>> ("a", "b", "l", "p","m","z") > > dict.values() > >>> (1,3,2,8,(1,2,3,4,5),"blah") > > dict["a"] > >>>1 > dict["m"] > >>>(1,2,3,4,5) Thanks for your reply. In this example, actually what I want is to get 1,2,3,4,5 seperately from (1,2,3,4,5) and put them into five different lists, say, list1 = [1],list2=[2],list3=[3],list4=[4],list5=[5]. Is there any simply way to "split" a tuple? Thanks! ===== Cheers -Mindy __________________________________________________ Do you Yahoo!? U2 on LAUNCH - Exclusive greatest hits videos http://launch.yahoo.com/u2 From tdelaney at avaya.com Tue Nov 26 17:49:41 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 27 Nov 2002 09:49:41 +1100 Subject: if : Message-ID: > From: maney at pobox.com [mailto:maney at pobox.com] > > That part, however, does not match my own experience. After the typos > that the compiler catches have been fixed, the "real" errors don't > include a very large percentage of =/== confusion. I didn't mean to imply that these were the only studies, and that other studies didn't produce any other conclusions, only that there *have* been extensive studies which have returned these conclusions. Most studies after all do have a specific agenda in mind ;) Tim Delaney From mis6 at pitt.edu Sat Nov 23 08:54:47 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 23 Nov 2002 05:54:47 -0800 Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <2259b0e2.0211210838.7647301a@posting.google.com> <2259b0e2.0211220946.5f61f641@posting.google.com> <3DDE711E.3010005@web.de> Message-ID: <2259b0e2.0211230554.1cde87bb@posting.google.com> > I would like to know more specifically what features make Python > special to you. As Kenny put it, in what regards is Pythonthink > different from Otherlangthink? Different languages have different "natural" ways of doing things, so you have to think accordingly to the language you have at your disposal. I want to be specific here, and I take an example you cited in this tread, i.e. the problem discussed in http://csis.pace.edu/~bergin/patterns/ppoop.html Here the authors discuss different ways of solving a simple problem in the same language, according to different phylosophies. Here it is the solution I came out in Python in two seconds of thinking, the "natural" solution at this stage of my knowledge of Python: def print_OS_evaluation(): "Gives a thought evaluation of operating systems" import sys def GoodBox(): print "This is a good box" def BadBox(): print "This is a bad box" def UnknownBox(): print "This is not a box" printEvaluation={ 'linux2':GoodBox, 'sunos5': GoodBox, 'win32':BadBox}.get(sys.platform,UnknownBox) return printEvaluation The code is pretty obvious, but let me discuss how would I have "naturally" solved the problem in other languages. Was I coding in Basic or Fortran, I would have written something like if platform='linux' then call GoodBox() elseif platform='win32' then call BadBox() elseif ... Very ugly, but these languages (I refer to the old Basic of the early 80's I learned as my first programming language, or Fortran 77 which is unfortunately still too much used in the scientific environment) don't allow you to do much more than that. You cannot simply *think* of another solution. On the other hand, was I working in Pascal or C, where "case" and "switch" constructs exist, I would have certainly used them. The code would have been less ugly, and more adapted to these languages, not simply a translation from Basic. When I learned Python I discovered dictionaries and I immediately get in love with them; I started using dictionaries from my first programs. They allow me to *think* better, I believe, and now I use the if..elif.. construct much less than before. The idea of having a dictionary of functions appeals to me much more than a switch statement; still I couldn't have thought of this possibility before the discovery of Python. Dictionaries have strongly changed my way of solving problems: and you will agree that this is a feature that not all languages have or stress as much as Python. I am sure Lisp has even more sophisticated ways of doing the same thing; actually I always wanted to know more about Lisp, but the parenthesis always stopped me ;-<. I want to comment on OOP, too. As a I said in a previous posting, I am still in the process of learning OOP. At this state of my knowlegde, I tend to think that OOP is a great idea, but sometimes overkill and too verbose. That's the reason why even if the original code in http://csis.pace.edu/~bergin/patterns/ppoop.html used a class, I prefer to use a function instead. It seems to me that, for simple tasks, functions are still better and easier to grasp. Of course objects have their advantages, but if I don't plan to inherit from a class doing the job of print_OS_evaluation, why should I use a class at all ? Functions are shorter and easier to maintain, in my view. Still, the biggest issue I have with OOP is a syntactical one: too verbose for my taste. The fact that the code before has come to me naturally, let me suppose that I *think* dictionaries and I *think* functions; but not yet objects. I will say that I will think *Python* when ALL the constructs of Python, including dictionaries,lists, strings, functions, objects, etc. will be natural to me. The reason is that Python is multiparadigm himself: therefore if you want to understand Python you must become multiparadigm yourself. To be open to different views is in the phylosophy of the language. Other languages have different phylosophies: for instance Ruby claims one of its strenghts to be "pure" OOP. If you want to *think* that language, than you must think "pure" OOP and starting subclassing from numbers... ;-) I hope I have answered your question this time: Q: what features make Python special to you ? A: dictionaries (and a lot of other stuff ;-) Ciao, Michele From nicholas.y at NOSPAM.immersivetechnologies.com Thu Nov 7 21:48:51 2002 From: nicholas.y at NOSPAM.immersivetechnologies.com (Nicholas Yue) Date: Fri, 8 Nov 2002 10:48:51 +0800 Subject: Approach to Python extension with C++ Message-ID: <3dcb261e$0$15742@echo-01.iinet.net.au> I have a need to write Python interfaces to some commercial libraries that are available on Windows and Linux. I have read about the steps to do that in Mark Hammond's Python Programming book and have also read the extending Python in the Python Essential Reference (first version). I am attempting to write the interface in a cross platform manner, is the use of Setup.in and compile.py the way to go. I am using ActiveState Python 2.2.2 on Windows and probably 2.0/2.1/2.2 on Linux. I am writing the interface code in C++. What is your advice? From david at no.westcontrol.spam.com Tue Nov 12 03:27:42 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Tue, 12 Nov 2002 09:27:42 +0100 Subject: Can python find fibonacci series in a single line of code? References: Message-ID: "Carl Banks" wrote in message news:aqp3b3$jm3$1 at solaris.cc.vt.edu... > > > Because it's fun!!! > Fair enough - I too have tried writing illegable python code (see below). I remember once having a game for the BBC Micro writen in a single line of Basic... > > while 1: globals().setdefault("a",0); globals().setdefault("b",1); \ > __import__("sys").stdout.write("%d "% a); a,b=b+a,a > I've learned something here - I didn't know you could access globals() in this way. (I also didn't know you could do such on-the-fly imports, but that has less use outside the scope of one-liners). Here's a challenge for perl programmers - define a function to take a string and produce a CRC checksum of the string, all in one line: foobar = lambda ts : reduce(lambda x, y : reduce(lambda (x, s), b : (x, (((s \ << 1) & 0xff) + ((x & (1 << b)) > 0)) ^ ((s & 0x80) >> 7) * 0x8d), range(8), \ (0, x^y))[1], map(ord, [t for t in ts]), 0) Usage: foobar("Hello") From op73418 at mail.telepac.pt Thu Nov 14 10:54:51 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Thu, 14 Nov 2002 15:54:51 +0000 Subject: Seeking advice on locking iterators Message-ID: Hi, My problem is the following: I have a top object Application, roughly corresponding to the main thread, that spawns some child threads - objects on their own sake, deriving from the Thread class in the threading module. They communicate when they need to via queues in the usual way. So far so nice. The problem is that those same child objects expose some public attributes (or properties, or methods, does not matter) that the Application object may need to change/call and doing the change via the queue mechanism is conceptually wrong (and a real PITA). The solution is obvious: wrap the attributes with locks around it. What is not so obvious is when these attributes are complex objects themselves, in particular they are iterables. In order to call iter() on these objects safely I coded the following helper class: #WARNING: Brittle - use this at your own risk. class TIter(object): """The TIter helper class, wrapping an iterator for thread safe acess.""" def __init__(self, lock, iterator): super(TIter, self).__init__(lock, iterator) self.__lock = lock self.__iterator = iter(iterator) #Acquire lock => You cannot change the underlying structure #while iter not exhausted. self.__lock.acquire() self.__acquired = 1 #Iterator protocol. def __iter__(self): return self def next(self): try: ret = self.__iterator.next() except StopIteration: self.__lock.release() self.__acquired = 0 raise StopIteration else: return ret def __del__(self): if self.__acquired: self.__lock.release() The idea is that for the wrapping of a given attribute one has an associated lock (a reentrant lock, usually) that is passed to the ITer constructor. I have to ensure two things, though: * The lock is acquired while the iterator is alive. * The lock is released when the iterator is disposed of. So, finally, my question is: Is the above enough to ensure this? Can I be sure that __del__ is called if the iterator is garbage collected before being exhausted? Or is there a better (e.g. safer) mechanism for this? Any enlightenment is appreciated, with my best regards, G. Rodrigues From ngps at netmemetic.com Thu Nov 14 20:11:03 2002 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 15 Nov 2002 01:11:03 GMT Subject: simple rsh and python question References: Message-ID: According to Chris Liechti : > rwadkins at flash.net (Randy Wadkins) wrote in > news:d453156a.0211141053.7de1422 at posting.google.com: > > Is there any way to rsh from a shell script to nodes in a cluster and > > execute a python script that will run in the background on each node? > > It appears that the execution is stopped once the rsh command is > > completed. > > look up "nohup". otherwise any programm attached to the terminal are > terminated when the terminal is closed. (HangUP signal) Supposing OP wrote those scripts he's executing remotely, he can also fix them to DTRT wrt dissociating from the terminal and all that daemonic stuff. I'm sure there must be some recipes floating about for that. -- Ng Pheng Siong * http://www.netmemetic.com From akakakhel at attbi.com Tue Nov 26 19:11:35 2002 From: akakakhel at attbi.com (Ali K) Date: Wed, 27 Nov 2002 00:11:35 GMT Subject: CVS Message-ID: What is CVS? From jkraska at san.rr.com Fri Nov 29 12:17:34 2002 From: jkraska at san.rr.com (Courageous) Date: Fri, 29 Nov 2002 17:17:34 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3de1f902$0$695$edfadb0f@dread12.news.tele.dk> <3DE666F0.32F64BA6@alcyone.com> <3DE67AD1.59C3560D@alcyone.com> <3DE72071.D9D35392@alcyone.com> Message-ID: <338fuu0rv7nf4v7kre5kkbb1emgfrmo2sr@4ax.com> >My point was not that Lisp programming is not facilitated by a >Lisp-aware editor. I'm an emacs user myself, and am fully aware of >standard Lisp notations, and am fully ware of lisp-mode in emacs. It would seem that you are, after all, fully aware of my point. C// From jepler at unpythonic.net Wed Nov 20 21:10:44 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Wed, 20 Nov 2002 20:10:44 -0600 Subject: Need Function To Run As Long As Button Widget Pressed In-Reply-To: References: Message-ID: <20021120201034.A15580@unpythonic.net> I spot several errors in your program. > self.buttonGo = Button(frame, text= "Print", command=self.Go) The command of a button only fires after a mouse button is pressed and then released inside the widget. So self.Go will be called too late, after the button is released. Instead, make "go" be called when the button is first pressed, on the event. > def IsPressed(event): The first argument of each method must be the 'self' argument. All events (as opposed to a button's command) have an event parameters in the callback. You need def IsPressed(self, event): ... > self.after(10, self.Go()) You want to perform the function "Go" after 10ms, not the function returned by "Go". Instead, write self.after(10, self.Go) Also, I don't see how your 'self' gets an 'after' attribute (method) since it doesn't derive from BaseWidget. You might consider using "after_idle(self.Go)". Instead of waiting 10ms, it will wait until all events have been serviced, then call Go. Or, depending on your situation, you could write 'Go()' as a function which calls "self.frame.update()" from time to time. "update()" handles peding events and then returns. This way, you can write your processing loop in the straightforward way: def go(): for i in range(1000): process_a_little(i) self.frame.update() instead of the cumbersome (and possibly wrong) way: def go(): i = self.i if i < 1000: process_a_little(i) self.afterid = self.frame.after_idle(go) self.i = i + 1 My solution also uses a label instead of a button since it doesn't use any of the button's builtin bindings anyway (mostly, these implement the mechanics of -command). It still uses plain after(). Otherwise, it uses the suggestions I've made here. Jeff from Tkinter import * class App: interval = 100 def __init__(self, master): self.button = Label(master, text="Go", relief="raised") self.button.bind("", self.press) self.button.bind("", self.release) self.button.bind("", self.release) self.button.pack() self.status = 0 self.afterid = None self.after = master.after self.after_cancel = master.after_cancel def press(self, ev): self.button.configure(relief="sunken") self.status = 1 if self.afterid is None: self.afterid = self.after(self.interval, self.go) def release(self, ev): self.button.configure(relief="raised") if self.afterid is not None: self.after_cancel(self.afterid) self.afterid = None def go(self): print "Working" self.afterid = self.after(self.interval, self.go) root = Tk() app = App(root) root.mainloop() From anton at vredegoor.doge.nl Thu Nov 7 08:25:27 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 07 Nov 2002 14:25:27 +0100 Subject: using the PSF license for one's code References: <918bc22f.0211051301.2010d077@posting.google.com> <3dc867de$0$24754$7b0f0fd3@reader.news.newnet.co.uk> <918bc22f.0211060732.47b2198d@posting.google.com> <918bc22f.0211061829.2d94e681@posting.google.com> Message-ID: On Thu, 7 Nov 2002 10:33:51 +0100, "David Brown" wrote: >Have you considered whether Python is really a suitable language for this >job? It is probably ideal for your first project, but not necessarily for >the second one. Python makes it easy to write great software, but it also >makes it easy to make mistakes which can only be found at run-time. You >might want to consider writing the key working parts of the software in a >language designed with safety and reliability in mind, such as Ada (not C!), >while using Python for the secondary work (user interface, logging results, >or whatever). This thread is filled with reverse psychology! First the idea is proposed to use the GPL because it's in the best interest of the babys, which is doubtfull. Then it amounts to using lawyers to protect the interests the authors of the sourcode, which would certainly damage the interests of the babys. Now it reaches a state where using a "safe and reliable" language is proposed instead of using python, which is comparabale to throwing away the babys and keeping only the bathing water. Please stop trying not to start a flame war. AV. From nelson at crynwr.com Sun Nov 10 22:48:26 2002 From: nelson at crynwr.com (Russell Nelson) Date: 10 Nov 2002 22:48:26 -0500 Subject: PEP #99484663 References: <3DCE065A.D770FADF@alcyone.com> Message-ID: Erik Max Francis writes: > Program in the language you're using. The proper answer to "How do I > make language X (which I'm learning) more like language Y (which I'm > used to)?" is "Learn language X separately from language Y." How is this going to stop them from whinging about significant indentation? I think we're trying to solve different problems. -- -russ nelson http://russnelson.com | Crynwr sells support for free software | PGPok | it's better to be free 521 Pleasant Valley Rd. | +1 315 268 1925 voice | than to be correct. Potsdam, NY 13676-3213 | +1 315 268 9201 FAX | From grante at visi.com Wed Nov 13 11:33:26 2002 From: grante at visi.com (Grant Edwards) Date: 13 Nov 2002 16:33:26 GMT Subject: python gui rant References: <3dd217e2$0$231$4d4ebb8e@news.nl.uu.net> Message-ID: <3dd27ed6$0$4440$a1866201@newsreader.visi.com> In article , Bengt Richter wrote: > Your mention of Delphi made me recall that you can right click on a gui form > and select 'view as text' from the popup menu, and you get to see all the > parameters that define your layout. E.g. a default form with one button dropped > on it near the top left: > > object Form1: TForm1 > Left = 200 > Top = 108 > Width = 544 > Height = 375 > Caption = 'Form1' [...] > object Button1: TButton > Left = 40 > Top = 24 > Width = 75 > Height = 25 > Caption = 'Button1' One warning: there is a very special place reserved in hell for people who design GUI dialogs with hard-wired widget locations so that the dialogs can't be resized. One of the reasons I really hate working with MS-Windows because of all the dialog boxes that use 80% of the space in a dialog for useless crap, and then show only four lines in a list-box containing 100+ elements. A decent GUI would let you resize the dialog so you could see more of the stuff in the list-box. But not MS-Windows.... -- Grant Edwards grante Yow! When you get your at PH.D. will you get able to visi.com work at BURGER KING? From andre.hates.spam at ifi.uio.no Mon Nov 25 11:18:38 2002 From: andre.hates.spam at ifi.uio.no (=?ISO-8859-1?Q?Andr=E9_N=E6ss?=) Date: Mon, 25 Nov 2002 16:18:38 +0000 Subject: if : References: Message-ID: sismex01 at hebmex.com wrote: >> From: Andr? N?ss [mailto:andre.hates.spam at ifi.uio.no] >> Sent: Sunday, November 24, 2002 8:00 AM >> >> When I started learning Python one of the things that >> surprised me was that you couldn't do assignments inside >> the if clause, e.g.: >> >> if myvar = someFunction(): >> > > Why does it surprise you? > > Most all languages, except those of C descent, don't > have if . Well then you're probably not surprised that my background is in C, Java, and PHP, hence my surprise. :) Andr? N?ss From johnfabel at btinternet.com Mon Nov 25 10:14:22 2002 From: johnfabel at btinternet.com (John Abel) Date: Mon, 25 Nov 2002 15:14:22 +0000 Subject: Multi Recipients With smtplib? In-Reply-To: References: Message-ID: <3DE23E4E.9050804@btinternet.com> Sorry for the confusing question, but you got the gist of it (Phew!). I'm pulling the list of addresses out of .ini file, e.g. mailfrom=me at mydomain.org mailto=you at yourdomain.org,me at myotherdomain.org Basically, what I was doing, was passing the mailto value to .sendmail(). The header seem correct (viewed via Mozilla, with headers set to all), which is what was confusing me. Thanks for the pointers! Regards John Steve Holden wrote: >"John Abel" wrote in message >news:mailman.1038231874.18339.python-list at python.org... > > >>Hi, >> >>I am trying to send a mail, to multiple recipients, without much >>success. A single mail address works fine, but when I add another, >>using a comma to separate the addresses, the second address fails to >>receive the mail. Any ideas? Here's the code I am using: >> >> mailMessage = "From: %s \r\nTo: %s\r\n" % (self.mailFrom, >>self.mailTo) >> mailMessage += "Subject: %s\r\n%s" % (mailSubject, mailBody) >> try: >> self.MailConn.sendmail( self.mailFrom, self.mailTo, >> >> >mailMessage) > > >> except (smtplib.SMTPRecipientsRefused, >>smtplib.SMTPSenderRefused), ErrorMsg: >> print "There Was A Problem Sending The Mail. Reason: %s" % >>ErrorMsg >> >>Any help would be appreciated, as this is driving me mad! >> >> >> > >Given that yout code is arranged to print an error message it's a pity you >didn't give us the benefit of its output so we knew a little more about the >erre that's occurring. > >The arguments to the .sendmail() method should be: > > a string containing the sender's address > a list of strings containing an address for each recipient, and > an RFC822-formatted mail message > >I am guessing that when you say "but when I add another, using a comma to >separate the addresses, the second address fails to receive the mail" you >are setting the self.mailTo attribute to be a comma-separated list ot >recipients? Frankly I'm not sure how you are managing to get this mail >formatted. > >What you really want for multiple recipients is something like the >following: > > > self.mailFrom = me at mydomain.com > self.mailTo = ["him at hisdomain.com", "her at herdomain.com", >"it at itsdomain.net"] > ... > mailMessage = "From: %s \r\nTo: %s\r\n" \ > % (self.mailFrom, ", ".join(self.mailTo)) > mailMessage += "Subject: %s\r\n%s" % (mailSubject, mailBody) > try: > self.MailConn.sendmail( self.mailFrom, self.mailTo, mailMessage) > except (smtplib.SMTPRecipientsRefused, > smtplib.SMTPSenderRefused), ErrorMsg: > print "There Was A Problem Sending The Mail. Reason: %s" \ > % ErrorMsg > >In other words, use a comma-separated list of recipients in the message >body, but a list of email addresses as the second argument to .sendmail(). > >regards >----------------------------------------------------------------------- >Steve Holden http://www.holdenweb.com/ >Python Web Programming http://pydish.holdenweb.com/pwp/ >Previous .sig file retired to www.homeforoldsigs.com >----------------------------------------------------------------------- > > > > > From max at alcyone.com Sat Nov 23 01:33:05 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 22 Nov 2002 22:33:05 -0800 Subject: Time Problem [more] References: <7396d2b2.0211221046.4a5216dd@posting.google.com> Message-ID: <3DDF2121.653A66E6@alcyone.com> Lemniscate wrote: > I posted an issue with the time module, it turns out that I think I > was just being stupid. GMT right? If so, Sorry. Yep. When you're seeing weirdness when dealing with times programmatically (whether in Python or not) and it's only varying in the hour, it's a solid bet that time zone differences are involved. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ The little I know, I owe to my ignorance. \__/ Sacha Guitry Bosskey.net: Counter-Strike / http://www.bosskey.net/cs/ A personal guide to Counter-Strike. From graik at web.de Wed Nov 6 14:17:01 2002 From: graik at web.de (Raik Gruenberg) Date: Wed, 06 Nov 2002 20:17:01 +0100 Subject: segmentation fault when unpickling an object in another Python instance Message-ID: <3DC96AAD.9090503@web.de> Hi all, I have got some home-made class. From within the same Python interpreter I can create, dump and load it back without any problem. But, if I try to load it after re-starting the interpreter, I end up with a segmentation fault. Example (Traj is the trouble maker, Load and Dump are just wrappers for cPickle.load and dump): from Traj import Traj from tools import Load, Dump t = Traj(['../test/lig.pdb'], '../test/lig.pdb') Dump( t, 't.t' ) ----- ... NOW RESTART PYTHON ... ----- >>> from tools import * >>> Load( 't.t' ) Process Python segmentation fault It's all the same regardless whether I use Python 2.2 or 2.1. Switching to pickle.load and dump doesn't change anything either. However, only this particular class is affected. Given the segmentation fault, at least, some sort of Python bug must be involved, right? Obviously, it is also somewhat the fault of this particular class. I narrowed down the problem somewhat. But, before bothering you with all the details, perhaps anyone knows this problem or has some promising idea??? Thanks for any hints/suggestions! Raik From johnroth at ameritech.net Wed Nov 20 15:38:50 2002 From: johnroth at ameritech.net (John Roth) Date: Wed, 20 Nov 2002 15:38:50 -0500 Subject: Python as first language (Re: static variables?) References: Message-ID: "Brian Quinlan" wrote in message news:mailman.1037821774.32088.python-list at python.org... > Hung Jung Lu wrote: > > Sorry for digressing, but this reminds me of an old debate on whether > > Python is suitable as the first language to teach. > > > > Well, the thing is that Python works with "name binding". And the > > concepts of name spaces, name binding, objects, mutability, etc. are > > just a bit non-obvious. Once a person understands these things, or if > > a person knows about pointers, hashmaps and memory structure, > > everything becomes clear. But for someone not familiar with either of > > these sets of concepts, Python can be hard to explain. > > I think that the conceptual problem that people have with assignment > being a binding operation is that they are used to names labeling some > sort of memory mailbox. If you take the word "memory" out of there, that does describe Python. I think this is a false distinction. I can find only two issues with names: One is languages where the name itself has properties (static typed languages are a great example of this, although Python is moving toward this with the notion of properties in 2.2) The other is where there are separate name spaces for certain things. For example, methods in Java aren't first class objects, so Java can have multiple methods with the same name, and keep them separate. Python's name model can't - there can only be one object bound to a name at a time (although again, properties seem to violate that rule). > > If you had not preconceived notion of what "names" mean then you might > have fewer problems. > > Cheers, > Brian > > From mertz at gnosis.cx Tue Nov 12 00:44:40 2002 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Tue, 12 Nov 2002 00:44:40 -0500 Subject: Can python find fibonacci series in a single line of code? References: Message-ID: |"Pittaya" wrote in message |> My Perl-addicted friend shows me that he can find fibanicci series in |> a single line of code. |> perl -le '$b=1; print $a+=$b while print $b+=$a' |> can python do something like this? Sure: python -c "import urllib; print urllib.urlopen('http://gnosis.cx/fib.txt').read()" *wink* Yours, Lulu... -- _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/ _/_/ ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~ _/_/ _/_/ The opinions expressed here must be those of my employer... _/_/ _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/ From johnroth at ameritech.net Wed Nov 27 20:21:41 2002 From: johnroth at ameritech.net (John Roth) Date: Wed, 27 Nov 2002 20:21:41 -0500 Subject: *args and **kwargs References: <87d6orq0oz.fsf@uiuc.edu> <_S7F9.14648$kz4.657484@news2.west.cox.net> Message-ID: "Wojtek Walczak" wrote in message news:slrnaual6k.20i.gminick at hannibal.localdomain... > Dnia Wed, 27 Nov 2002 14:27:43 -0500, John Roth napisa?(a): > > The fact that the function definition contains either * or ** has > > nothing to do with how you call it. > By saying this I thought about that, when you're using ** notation > you need to call your function like this: > > function(a="b",b="c",c="d") True. the ** parameter picks up unspecified keywords. > In second of my examples, you can call a function by passing > a dictionary to it as is: > > second({"a":"b", "b":"c", "c":"d"}) This example is a single positional parameter which happens to be a dictionary. John Roth > > See that visual difference? I was talking just about that. > > -- > [ ] gminick (at) underground.org.pl http://gminick.linuxsecurity.pl/ [ ] > [ "Po prostu lubie poranna samotnosc, bo wtedy kawa smakuje najlepiej." ] From goldbb2 at earthlink.net Mon Nov 11 14:31:33 2002 From: goldbb2 at earthlink.net (Benjamin Goldberg) Date: Mon, 11 Nov 2002 14:31:33 -0500 Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DCFCC3E.204D9B45@man.ac.uk> <3DCFEF06.9E74A794@earthlink.net> <3DCFF6FB.40426F8E@san.rr.com> Message-ID: <3DD00595.B2905D8E@earthlink.net> Darren New wrote: > > Benjamin Goldberg wrote: > > In all cases that I can think of, your dynamic code is essentially a > > string which gets eval()ed (with a language-dependent eval). The > > solution is to make the eval() function/operator compile into a > > sequence of operations along the lines of: Load the compiler for > > this language, (if it's not already loaded), pass that string to the > > compiler, run the generated bytecode. > > Seems like an awful lot of overhead for every keystroke, window event, > and async file operation. Why would any of these require that strings be eval()ed? You compile the string to bytecode, *once*, and pass this compiled code as the callback for your keystrokes, window events, and async file operations. You wouldn't pass a string to be eval()ed -- that would be silly. Furthermore, even if one did do something that foolish, the compiler needs to be loaded only once... So, (ignoring the first one, where the compiler gets loaded) each keystroke, window event, or async file operation would merely compile the string to bytecode, then run the bytecode. This is no different from what Tcl does all the time, except that it's a different kind of bytecode. -- my $n = 2; print +(split //, 'e,4c3H r ktulrnsJ2tPaeh' ."\n1oa! er")[map $n = ($n * 24 + 30) % 31, (42) x 26] From dnew at san.rr.com Mon Nov 11 14:56:19 2002 From: dnew at san.rr.com (Darren New) Date: Mon, 11 Nov 2002 19:56:19 GMT Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DCFCC3E.204D9B45@man.ac.uk> <3DCFEF06.9E74A794@earthlink.net> <3DCFF6FB.40426F8E@san.rr.com> <3DD00595.B2905D8E@earthlink.net> Message-ID: <3DD00B63.EC604897@san.rr.com> Benjamin Goldberg wrote: > Why would any of these require that strings be eval()ed? > > You compile the string to bytecode, *once*, and pass this compiled code > as the callback for your keystrokes, window events, and async file > operations. You wouldn't pass a string to be eval()ed -- that would be > silly. Bindings substitute their values. File events get additional arguments. Etc. > Furthermore, even if one did do something that foolish, the compiler > needs to be loaded only once... I missed your parenthetical comment on first reading. Yes, sorry. From bokr at oz.net Tue Nov 19 15:02:47 2002 From: bokr at oz.net (Bengt Richter) Date: 19 Nov 2002 20:02:47 GMT Subject: static variables? References: Message-ID: On Tue, 19 Nov 2002 04:18:16 GMT, "Josh" wrote: >Hi guys, > >I am a python newbie, and I am sure there is an easy answer but, Is there >any equivalent to C's static variables in Python? If not, how can you have >variables inside a function, that 'remember' their values between function >calls? > There's more than one way to get the effect. You can do it with a function or you can do it with a class instance that acts like a function. you would like the effect, say, of def foo(): # print x x = x + 1 We need to attach the value to something persistent. The function itself is handy. You can just attach named values as attributes, and they'll be "remembered": >>> def foo(): ... global foo ... print foo.x ... foo.x += 1 ... >>> foo.x = 3 >>> foo() 3 >>> foo() 4 >>> foo() 5 But this depends on foo finding its own name in the global directory You can avoid that by defining it inside another function that returns it. It finds itself in the enclosing name space of the outer function, and that environment is preserved in a closure attached to the returned function, so it's not lost when the outer function returns: >>> def mkfoo(): ... def foo(): ... print foo.x ... foo.x += 1 ... foo.x = 0 ... return foo ... >>> foo = mkfoo() >>> foo() 0 >>> foo.x 1 You could pass something to mkfoo to initialize foo.x with if you wanted to. Also, you could use other ways to store the value. An attribute is just easy to write. To make a class instance that acts similarly, but uses self.x instead of foo.x, you can do this: >>> class Foo: ... def __init__(self, x=0): self.x = x ... def __call__(self): ... print self.x ... self.x += 1 ... >>> foo = Foo(3) >>> foo() 3 >>> foo() 4 >>> foo() 5 mkfoo() and Foo() create independent foo's that have separate states, but you could make them all operate on a single shared state also. Regards, Bengt Richter From dave at pythonapocrypha.com Fri Nov 22 16:51:00 2002 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 22 Nov 2002 13:51:00 -0800 (PST) Subject: Proposal: min(None, x) and max(None, x) return x In-Reply-To: <20021122181124.K11257@prim.han.de> Message-ID: On Fri, 22 Nov 2002, holger krekel wrote: > Dave Brueck wrote: > > > Opinions anyone? > > > > Sure! Write two functions, and put them in your sitecustomize.py file. No > > PEPs to write, no patches to submit, no battles to win, and you get all > > the functionality you want _today_. > > This reasoning is a bit broad and could be applied to many new ideas. > Which doesn't mean it's wrong :-) Yeah... since the OP was fishing for opinions I decided to give mine, which is simply that there should be a really compelling reason to change the language, doubly so when, as you pointed out, backwards compatibility is affected. And since he's already calling a function (min/max) anyway, it doesn't look like there's a ton to be gained by the change. Just my 2 cents, -Dave From ktilton at nyc.rr.com Fri Nov 29 19:42:17 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Sat, 30 Nov 2002 00:42:17 GMT Subject: importing question ? References: <3DE7F96B.1030606@nyc.rr.com> Message-ID: <3DE80A5B.2040309@nyc.rr.com> Kenny Tilton wrote: > >> 'from classes import *' brings all the toplevel objects in classes >> into your local namespace, so you can access them just through the >> name. Generally, though, I think this is considered bad practice, as >> it could create overlaps. > > > I just ran into this and I do not like it, because I have what I > consider one little subsystem (Cells) but I have it spread over ten > source files. I just saw the option to: from import * along with listing all modules in an __all__ definition in the __init__ file in the package directory. hope eternal. but it seems I then have to qualify any reference with the module name (which I think I grok--it is importing everything into the current namespace in go (nice) but then leaves them compartmented by module when it does so (not what I wanted, viz, a flat namespace for the package). -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From lists at battleface.com Tue Nov 12 16:35:18 2002 From: lists at battleface.com (Alexander Sendzimir) Date: Tue, 12 Nov 2002 21:35:18 GMT Subject: matching multiple regexs to a single line... References: Message-ID: John, Thanks for your response. This is what I was afraid of. This seems really sloppy. You don't think there is any better way of doing such a thing? In the mean time, what you propose is exactly what I've been doing. Hmmmm. Alex On Tue, 12 Nov 2002 15:18:01 +0000, John Hunter wrote: > > That's what I usually end up doing > > for line in myfile: > m = r1.match(line) > if m: > do_something() > break > > m = r2.match(line) > if m: > do_something_else() > break > > > John Hunter From see_reply_address at something.invalid Wed Nov 13 19:09:04 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 14 Nov 2002 13:09:04 +1300 Subject: pythonic way to optimize access to imported value? References: <3DD1AB92.3030409@something.invalid> Message-ID: <3DD2E9A0.8050500@something.invalid> Bengt Richter wrote: > Plus that version retains a reference to math, where I'd like to think that > I would wind up with just a reference to a double with the 3.14.. value. I.e., > def foo(pi = math.pi): > return pi Yes, that's probably what I should have written. > Also I think I would like a keyword that governs > a block scope instead of just the scope of an assignment. E.g., > > def foo(): > predef: > import math > pi = math.pi > del math > seven = 7 > return pi, seven Too complicated. You could get the same effect by putting the code outside the def: from math import math_pi def foo(): const pi = math_pi const seven = 7 ... del math_pi -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From Paul_Rudin at scientia.com Mon Nov 11 10:18:52 2002 From: Paul_Rudin at scientia.com (Paul Rudin) Date: 11 Nov 2002 15:18:52 +0000 Subject: something like "if" that returns a value? References: Message-ID: >>>>> "hk" == holger krekel writes: hk> Paul Rudin wrote: >> - potentially both y and z are evaluated; and hk> no. more precisely, only hk> if x is true and y is false is z also considered. I said "potentially" - so we're agreeing - there are circumstances in which both y and z have to be evaluated. Sometimes this might not matter, others it could be very significant. >> - there's a degree of obfuscation here, the code is less >> comprehensible than something like: if x then y else z. hk> IMO it's not overly hard to get used to it. It certainly isn't as hk> evident (as has the aforementioned pitfall) as in some other hk> languages. Funny enough, i don't need this ternary operation hk> often. hk> And if one the expressions is more complex i use a proper hk> if-clause. I guess these things depend on what you're used to - I now program mostly in lisp; I used to program mostly in c++; I'm very used to using such a construct. Using an if-then-else type construct without a return value makes some code rather inelegant, it seems to me. But no doubt one can get used to it. -- Were these parsnips CORRECTLY MARINATED in TACO SAUCE? From pinard at iro.umontreal.ca Tue Nov 26 08:28:08 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 26 Nov 2002 08:28:08 -0500 Subject: Python Tutorial Was: Guido's regrets: filter and map In-Reply-To: References: Message-ID: [Grant Edwards] > In article , David Brown wrote: > >> I never liked filter, map and reduce. > So don't use them. ;) Some languages (think PL/I, some LISP implementations, and surely many others) are full of constructs people do not use. Each user has his/her own preferred subset, and it often happens that a program written by someone may not easily be read by someone else, without keeping the language reference manual nearby. I essentially learned Python with version 1.5.2, and it was still true at the time that there was (about) only one way to do it, for most "it". This was a good guarantee towards legibility. I'm now an happy user of Python 2.2.1, in which there is now many ways to do many things. I quite appreciate the novelties, they are often incredibly handsome. Yet, legibility (of others' programs) is getting impaired by the multiplicity. To really maintain legibility in the long run, Python designers have to consider they have to clean a bit behind. Of course, "You do not like it, so do not use it." conveys health and sanity. But we have to stay aware that this attitude might not be fully proper in the long run. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From ktilton at nyc.rr.com Tue Nov 19 13:20:49 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Tue, 19 Nov 2002 18:20:49 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <44d4f61c.0211181708.465f5838@posting.google.com> <3DDA7385.2020609@nyc.rr.com> Message-ID: <3DDA81DE.7@nyc.rr.com> David Eppstein wrote: > In article <3DDA7385.2020609 at nyc.rr.com>, > Kenny Tilton wrote: > > >>>There are two things which make me cringe. 1) When a Pythonista >>>complains about allergies to strange delimiters, and 2) when a Lisper >>>calls other languages too slow. >> >>The numbers I hear are that CL runs on average 20% slower than C. > > > This is after how many decades of Lisp compiler development? > Omigod! First of all, re situations C knows about, CL does just as well. Remember, the 20% slower is /on average/. I am sure you know that CL like Python is dynamic. Getting that stuff to run almost as fast as C suggests CL compiler technology is superb. -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From treworn at cyberspace.org Sat Nov 2 17:29:39 2002 From: treworn at cyberspace.org (trewornan) Date: Sat, 02 Nov 2002 22:29:39 +0000 Subject: loggin out automatically References: <1036253358.19897.0@doris.uk.clara.net> <3dc3fcf4$0$7369@echo-01.iinet.net.au> Message-ID: <3DC451D3.4060907@cyberspace.org> > > Some combination of the above, I'd say. Some people might suggest that you > were silly to not just /try/ your command in a python interpreter, e.g.-- > Good point but I don't have one running on linux and the installation of linux on another computer is being considered but is dependent on the feasibility of some system to limit access on a timed basis. Anyway thanks for letting me know why it won't work - I'll look more thoroughly at the linux documentation for possible answers. M From cmkleffner at gmx.de Fri Nov 29 12:00:09 2002 From: cmkleffner at gmx.de (cmkl) Date: 29 Nov 2002 09:00:09 -0800 Subject: Is it possible to write web-based GUI using Python? References: <3DE4448E.5080201@attglobal.net> Message-ID: <3b091a1c.0211290900.61d974e3@posting.google.com> stephan.diehl at gmx.net (Stephan Diehl) wrote in message news:... > "David Mitchell" wrote in message news:... > > On Tue, 26 Nov 2002 23:05:34 +0000, Pierre Rouleau wrote: > > > > (snip) > > > > > > What I'd like to be able to do is implement a complete GUI-based control > > > application (with buttons, slider, whatever widgets the app needs) > > > accessible over the web. > > > > > > Is this possble with Python? If so, where the best place to start looking? > > > > I'm looking for exactly the same thing. I know Perl has the > > CGI::Widget::* modules which do pretty much exactly this, but I don't want > > to use Perl for this particular project. > > > > Regards > > > > Dave Mitchell > > While researching the web about the same question, I found > http://www.nextapp.com/products/echo/ > With that (ahem) Java Framework, it is possible (at least they claim) > to write a web application just like a normal GUI application. > On the Python side, at least Alex Martelli has thought about providing > a HTML backend to anygui > (http://anygui.sourceforge.net/platforms.php). > If this ever worked it'd had the advantage to have one codebase for > the webapp and a native GUI for the same app. > If one is only looking into a way to separate HTML and programming > logic, Cheetah (cheetahtemplate.org) can be used to write a kind of > widget set. > > Cheers > > Stephan It seems to be rather difficult to get a standard answer to the question: "how to develop highly responsive interactive web applications" A lot of effort is going to webify applications with Java Struts and similar techniques. You can create highly dynamic but still page based web apps. The more interactive the application is - a lot of ui updates necessary within user interaction - the more network traffic and page rendering by the browser has to be done. You can use Java applets but many people dont like it because of its akward AWT based user interface. Of course there are similar python techniques to the latter. Some other web based client server projects I am aware of: XWT is an interesting project (www.xwt.org). It is browser and OS independant. It only needs a Java or ActiveX enabled browser on the client side and supports a self installing thin client component (ActiveX component or Java jar file). The ultimate solution for the software deployment problem? Not python enabled so far, but they discussed the usage of Jython rather than Rhino as scripting framework inside the Java based client component. Picogui (www.picogui.org) is another one with a rather fat client software to display (potentially python based) applications over the web. And there is curl and ..... I am interested in a discussion of usuable and reliable frameworks for this problem (beside Struts and Java applets) Carl From fredrik at pythonware.com Sun Nov 3 12:49:10 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 03 Nov 2002 17:49:10 GMT Subject: get data from a Toplevel when closing it References: <3DC51D8A.90808@wanadoo.fr> Message-ID: "polux" wrote > I made a class derivated from the Tkinter's Toplevel class like this : > > Myclass(Toplevel): > > def __init__(self,master,**arg) > > Toplevel.__init__(master,arg) > self.master = master > > > Now, I want to get data from this Toplevel (eg data from entries > widgets) when I'm closing it. The easiest way is to install a WM_DELETE_WINDOW handler; see the "Protocols" section on the following page for more info and examples: http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm From txo at cs.nott.ac.uk Mon Nov 18 10:38:57 2002 From: txo at cs.nott.ac.uk (Turhan Ozen) Date: Mon, 18 Nov 2002 15:38:57 +0000 Subject: Installing dislin (scientific data plotting software) References: <3DD12A29.8B34ED2C@cs.nott.ac.uk> <3OednWogkaIkOUygXTWcog@comcast.com> Message-ID: <3DD90991.28DD1488@cs.nott.ac.uk> from S. Gonzi: To your DISLIN problem. I had used DISLIN on Windows XP for a few month, but switched eventually to Linux because Windows is more or less a pain. Whenever I had encountered problems I have contacted the author of DISLIN. He was very responsive. I suggest you to contact Michels directly and post the solution again back to comp.lang.python just in case others are faced by a similar problem. ------------------------------------------------------------------------ from Helmut Michels (Dislin's author): I have tested IDLE of Python 2.2 with multiple DISLIN windows. It seems to be ok. The multiple windows were created with the DISLIN routine opnwin. I will check the ActivePython IDE in the near future, but I think it is not compatible with DISLIN. I will let you know my results. DISLIN will be free for Python users in the future too. Changes in DISLIN will be compatible with the current DISLIN versions. From martin at v.loewis.de Sat Nov 9 02:00:26 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 09 Nov 2002 08:00:26 +0100 Subject: pickle-ing two instances of the same class on MSW References: Message-ID: nw_moriarty at yahoo.com (Nigel Moriarty) writes: > I have a list of two instances of the same class in a list which I can > pickle on LINUX but it fails on MSW with this error. > > cPickle.PicklingError: Can't pickle two.Task: its not the same object as two.Task > > which is stating the obvious. No. It does not talk about the instances, it complains that the instance claims to be a an instance of two.Task, however two.Task is not the class of the instance. That may have happened when two was reloaded, or when Task is a class nested within some class in two. HTH, Martin From stephan.diehl at gmx.net Fri Nov 8 10:18:53 2002 From: stephan.diehl at gmx.net (Stephan Diehl) Date: 8 Nov 2002 07:18:53 -0800 Subject: Virtual Filesystem (Was: Adding ftputil to the Python distribution?) References: Message-ID: Bengt Richter wrote: >>>... >>> >>>http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/skunkweb/skunkweb/pylibs/vfs/ >>> >>>Features: >>> >>>1. implementations for local fs, ftp, zip/tar/tgz archives, and a >>>>... >> >>Thanks, that's excactly what I was thinking of/looking for. And it >>shows to me that there is nearly nothing that has not been written in >>one form or another. I'd really like to see a vfs in the standard >>python distribution. > > I too. But I believe any given implementation will implicitly reflect > conventions with respect to operations in abstract name space, and I think > that ought to be laid out in a PEP before adopting any particular implementation. Sure, I agree. I was mainly thinking in terms of a protocol like the DB API for SQL Server. > > Otherwise there is likely to be special limitations, e.g., not being able > to delegate parsing of path tails to other vfs's mounted within the first, etc. > Also a virtual name space brings with it opportunity for orderly conventions > of use as opposed to ad hoc quilts of usage. A PEP can at least draw attention > to LSB/FHS type issues. > > >>Maybe, one day, we'll have a central register for python libraries. It >>seems to me that to many people (including me) are reinventing the >>wheel all the time because they just can't find the right library for >>the task at hand and just don't know project xyz that already solved >>the problem (and doesn't show up when googling) >> > > As a habitual wheel re-inventor, I'll second the thought ;-) > > OTOH, I think re-inventing has positive aspects sometimes. A certain > amount of reinventing is necessary for natural selection to have something > to select from in the evolutionary improvement of things. OTOH2, for > well-explored problems, it's an indulgence to reinvent something if you can find > and use something already implemented. (Of course, it _is_ satifying to find > that you have re-invented, even approximately, an algorithm that some real guru > has previously invented, and feel that you walked in the same ancient hallowed land, > even as you realize that you could have spent your time better for practical purposes). Rereading my original statement I realize that my point was indeed too narrow. It is satisfying to reinvent something if it is coupled with a deeper understanding about the subject. Actually, sometimes it is not possible to understand something if one has not spend hours thinking about it (and implementing it). But then, there are the problems where it is perfectly clear what must be done and programming is just a tendious task. > > The vfs above is very close to what I was talking about recently. But not > exactly, and not quite from the same POV. And any discussion of general > or genericized (v)file access will garner reminders that lisp has a lot > of prior art ;-) > > My main thought before was that a virtual name space can be platform > independent (or at least contain such a subspace), and that could serve > the purpose of platform independence for Python. So, finally, Python will be the OS :-) Why not, actually? The discussions about "What's the best OS in the world" are just tiring and Python has shown that it is possible to abstract a lot from the underlying OS. > > Regards, > Bengt Richter Stephan From anton at vredegoor.doge.nl Tue Nov 12 08:51:11 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 12 Nov 2002 14:51:11 +0100 Subject: Newbie response, was Re: Why is Python popular, while Lisp and Scheme aren't? References: <20021111084619.3410.38803.Mailman@mail.python.org> Message-ID: On Mon, 11 Nov 2002 19:55:27 -0800, Terry Hancock wrote: >Professional programmers who are in it for the money, will benefit by making >their language of choice seem difficult. This causes a barrier to entry, >creates scarcity, and drives the salaries for those who are *in* up. You see >this behavior frequently in the languages of choice for proprietary software >development (and it's been around in many trades, long before software was >invented). There's a lot of truth in this, as in the other part's of your - greatly appreciated - post, but I would like to add that it's often not possible for language designers to design a language that is not *considered* difficult and that is also not difficult in a more objective sense. We are living in a world where drinking brown colored and fizzling water with added sugar and artifical taste producing chemicals out of an aluminium (!) can is considered to be more natural than just drinking water. Regards, Anton. From usenet at jasoegaard.dk Sun Nov 10 08:23:15 2002 From: usenet at jasoegaard.dk (=?windows-1252?Q?Jens_Axel_S=F8gaard?=) Date: Sun, 10 Nov 2002 14:23:15 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: <3dce5e2f$0$35917$edfadb0f@dread13.news.tele.dk> Pascal Costanza wrote: > Rocco Moretti wrote: >> "Johannes Gr?dem wrote in message >> news:... >> >>> Because Lisp has a powerful macro system, it is actually possible to >>> have an infix-macro, which lets you use infix-syntax. And you can >>> write macros to support all sorts of weird syntax, if you want. >> >> >> I've heard this argument a number of times, and have never really >> bought it. To me it seems equivalent to saying "Because (Brainf*ck/ >> Intercal/ Unlambda/ Malbourge /etc) are Turing Complete, you can write >> any program in them." Sure, you *can*, but why bother? > > > ...because macros in Common Lisp allow you to do extremely powerful > things and write very compact code. [A very nice example] A frequently asked question for new comers to Python is "Why did you leave out my favorite loop construction?". I mean, there are always someone that likes do-while better than repeat-until and vice versa. In a language with macros such as CommonLisp or Scheme one can use macros to make new control structures. One example is the "missing" loop. The point is that the programmer can add to the power of the language without asking Guido first. Another example is pattern matching. Scheme is born without, but using a library written using macros one can use pattern matching the SML-way. To some extent this objection the objection "There are no macros" has the same cause as the the reaction to the displine-and-bondage language Pascal. Is it the language designer or the programmer that has the final word? Is new control structures useful? To a newcomer to the world of macros the answer seems to be no. But once you have gotten uses to the idea, one an amazing amount of uses. Pascal Constanzas example showed one use. From anonymous at nodomain.none Fri Nov 29 13:38:11 2002 From: anonymous at nodomain.none (Tetsuo) Date: Fri, 29 Nov 2002 18:38:11 GMT Subject: mod_python References: <3de714c6$1@news.mt.net.mk> Message-ID: ?????? ?. wrote in news:3de714c6$1 at news.mt.net.mk: > >> I figured out how to get mod_python to work, at last, but I ran into >> a problem that seems to be fairly common (the solution is harder to >> find, though). Any code inserted into mptest.py works great. But when >> I make another file in the same directory, the last thing that was in >> mptest goes into that file, even if mptest doesn't exist any more. >> Must be browser cache or something... Well, I have no idea, since >> it's a different file. Does Apache have a cache, too? I have heard >> that some mistake in the configuration can make Apache keep referring >> to mptest. But I can't find how to fix it... > > Thats the way mod_python works. read the documentation :) > > You have registered mptest.py to be a handler for all requests > ending in ".py". > > > Here's what I can gather: if I want to have another script, I have to put it in a new directory and create a directive in the conf for that new file. That sounds so complex, clumsy and dumb that it's probably not the way. How do I make every script handle itself? I tried the publisher handler, and it proved useless. I thought about importing everything to one script from others, but that isn't what I need at all. That's just pointless. And how do I make it so typing in a directory gives me a page (index.htm) instead of a list of the files in the directory? (Goes to take another look at the publisher) From greg2567 at yahoo.com.au Sun Nov 3 22:15:18 2002 From: greg2567 at yahoo.com.au (=?iso-8859-1?q?Greg=20Aumann?=) Date: Mon, 4 Nov 2002 14:15:18 +1100 (EST) Subject: file iterators and codecs, a bug? Message-ID: <20021104031518.15902.qmail@web14612.mail.yahoo.com> Recently I figured out how to use iterators and generators. Quite easy to use and a great improvement. But when I refactored some of my code I came across a discrepancy that seems like it must be a bug. If you use the old file reading idiom with a codec the lines are converted to unicode but if you use the new iterators idiom then they retain the original encoding and are returned in non unicode strings. Surely using the new "for line in file:" idiom should give the same result as the old, "while 1: ...." I came across this when using the pythonzh Chinese codecs but the below code uses the cp1252 encoding to illustrate the problem because everyone should have those codecs. The symptoms are the same with both codecs. I am using python 2.2.2 on win2k. Is this definitely a bug, or is it an undocumented 'feature' of the codecs module? Greg Aumann The following code illustrates the problem: ------------------------------------------------------------------------ """Check readline iterator using a codec.""" import codecs fname = 'tmp.txt' f = file(fname, 'w') for i in range(0x82, 0x8c): f.write( '%x, %s\n' % (i, chr(i))) f.close() def test_iter(): print '\ntesting codec iterator.' f = codecs.open(fname, 'r', 'cp1252') for line in f: l = line.rstrip() print repr(l) print repr(l.decode('cp1252')) f.close() def test_readline(): print '\ntesting codec readline.' f = codecs.open(fname, 'r', 'cp1252') while 1: line = f.readline() if not line: break l = line.rstrip() print repr(l) try: print repr(l.decode('cp1252')) except AttributeError, msg: print 'AttributeError', msg f.close() test_iter() test_readline() ------------------------------------------------------------------------ This code gives the following output: ------------------------------------------------------------------------ testing codec iterator. '82, \x82' u'82, \u201a' '83, \x83' u'83, \u0192' '84, \x84' u'84, \u201e' '85, \x85' u'85, \u2026' '86, \x86' u'86, \u2020' '87, \x87' u'87, \u2021' '88, \x88' u'88, \u02c6' '89, \x89' u'89, \u2030' '8a, \x8a' u'8a, \u0160' '8b, \x8b' u'8b, \u2039' testing codec readline. u'82, \u201a' AttributeError 'unicode' object has no attribute 'decode' u'83, \u0192' AttributeError 'unicode' object has no attribute 'decode' u'84, \u201e' AttributeError 'unicode' object has no attribute 'decode' u'85, \u2026' AttributeError 'unicode' object has no attribute 'decode' u'86, \u2020' AttributeError 'unicode' object has no attribute 'decode' u'87, \u2021' AttributeError 'unicode' object has no attribute 'decode' u'88, \u02c6' AttributeError 'unicode' object has no attribute 'decode' u'89, \u2030' AttributeError 'unicode' object has no attribute 'decode' u'8a, \u0160' AttributeError 'unicode' object has no attribute 'decode' u'8b, \u2039' AttributeError 'unicode' object has no attribute 'decode' ------------------------------------------------------------------------ http://careers.yahoo.com.au - Yahoo! Careers - 1,000's of jobs waiting online for you! From nelsonis at earthlink.net Thu Nov 28 10:48:15 2002 From: nelsonis at earthlink.net (Ian S. Nelson) Date: Thu, 28 Nov 2002 08:48:15 -0700 Subject: Python JAR files? Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Has anyone built something like JAR files for python yet? Any plans to? As a packaging medium and for installing stuff on to machines it would be nice to have a python app that resides within one file. tar.gz or .zip or something also compress quite nicely. thanks, Ian Nelson -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.0 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQE95jq6V28blwDT2YMRAgKhAJ44YrDyXj139zEDfK+sPq/cdq2npQCdHYvs 0aNK+kwVJ9zhLgdxpsQF8KY= =imEq -----END PGP SIGNATURE----- From teaandbikkie at aol.com Thu Nov 14 19:22:33 2002 From: teaandbikkie at aol.com (TeaAndBikkie) Date: 15 Nov 2002 00:22:33 GMT Subject: windows api message References: Message-ID: <20021114192233.02463.00000060@mb-fv.aol.com> >From: Chris Johnson chris.johnson at netiq.com > >I am interested in building a tool for automating gui testing. I have already started one of these for Python. Its early days yet, but can drive notepad's windows, menus & buttons and grab text off it. If you are interested, I'll start a sourceforge project and you can help me with it. I have heaps of ideas for it, including (eventually) a parser for interpreting or translating WinRunner scripts, hooks for the popular keyword-driven test frameworks, and some functional-mapping framework stuff of my own. Perhaps you can help with emulating some useful Segue functions. >So I have heard some people say its gonna be based on win32 api messaging. Yes this is a large component. The win32all module is useful for some functions, and calldll / npstruct / ctypes (someone convince me to use ctypes?) for the missing functions and c-structures. >Chris Johnson Kind regards, Misha From lbates at swamisoft.com Wed Nov 6 16:24:21 2002 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 6 Nov 2002 15:24:21 -0600 Subject: I "think" global is broken Message-ID: <06qdnevbopUGFFSgXTWc3Q@comcast.com> The following code works as expected. class test: global _trace def __init__(self): if _trace: print "entering test.__init__" return global _trace _trace=1 x=test() Now if I move the class into a separate module called test.py and change the main program it no longer works from test import * global _trace, _debug _trace=1 x=test() I get undefined global error I just don't believe that this is the way it should work. I understand that in this simple example I could do an import test and (according to other posts I've read it should work). But in a real world example the external module has 8 classes in it (and growing). It just doesn't seem right that I would need to split it into 8 different modules. Am I missing something? Thanks in advance for any assistance. Regards, Larry Bates lbates at swamisoft.com From b.e.n.c.a.t.7.3. at .t.p.g...c.o.m...a.u Sat Nov 23 19:19:53 2002 From: b.e.n.c.a.t.7.3. at .t.p.g...c.o.m...a.u (Ben C) Date: Sun, 24 Nov 2002 11:19:53 +1100 Subject: Inheritance And Instantiation Of Instance Variables Message-ID: <3de00ca8@dnews.tpgi.com.au> Hi there, I just wanted to clarify something ... if I create a class such as class Blah: def __init__(self, parameterA, parameterB) self.parameterA = parameterA self.parameterB = parameterB and then I inherit from that class is it really necessary to initialise the argumnets to the inherited class twice ? ie. class NewBlah(Blah): def __init__(self, parameterA, parameterB) Blah.__init__(self, parameterA, parameterB) From gmuller at worldonline.nl Wed Nov 6 15:38:25 2002 From: gmuller at worldonline.nl (GerritM) Date: Wed, 6 Nov 2002 21:38:25 +0100 Subject: Foot in mouth disease References: <3dc3dc4e$0$12762$afc38c87@news.optusnet.com.au> Message-ID: "Derek Thomson" schreef in bericht news:vR1y9.45$8%5.8453 at news.optus.net.au... > GerritM wrote: > > "Derek Thomson" schreef in bericht > > news:3dc3dc4e$0$12762$afc38c87 at news.optusnet.com.au... <...snip...> > > Do you by any means have the data at hand (kloc's for Java, kloc's for > > comparable Python; ORB and/or IDL compiler)? I am highly interested in any > > substantiated evidence with respect to language efficiency/expressiveness. > > Nope, I was just replying based on my feelings for an average task, > which was the tone of the OP. Think about how difficult it is to do the > equivalent of a list slice assigment in Java, for example. > > For some harder numbers, I compared JacORB (a Java ORB) to Fnorb (a > Python ORB), and Fnorb is about one half the lines of code of JacORB, > just for the core ORB itself. > > Now, that's for an ORB, which is low level enough (marshalling and > unmarshalling data on-the-wire, and connection management), that it > doesn't play too well to Python's expressiveness. But still, that's > quite a difference. > > As the application becomes higher level, I'd expect the gains to be much > greater. > > -- > D. > I share the same expectation. It would be nice to have some more factual comparison of larger application(s). The shootout site http://www.bagley.org/~doug/shootout/ does a great job in comparing "small" well defined problems. In general Python scores well in expressiveness (=small amount of loc), but not as much as factors 2 or higher. It would be interesting to know if our expectations are realistic for large applications, or only hopes. I have seen many oversold technologies, which don't pass a more factual comparison. regards Gerrit From kevin at cazabon.com Fri Nov 8 22:36:49 2002 From: kevin at cazabon.com (Kevin@Cazabon.com) Date: Sat, 09 Nov 2002 03:36:49 GMT Subject: TclError: bad option "": must be cget or configure Message-ID: I'm having some weird Tcl errors, and can't seem to track them down, any help? 1) these are happening in multiple locations, when I use the "configure" method for widgets 2) the calls work 99.9% of the time, but when the system is under heavy load they fail with "TclError: bad option "yellow": must be cget or configure" errors 3) I'm using a valid "configure" command (such as self.label.configure(text="yellow")), and it seems to think I called "self.frame.yellow()" or self.frame.configure(yellow = xxx). My application is multi-threaded (3 threads total, all using locks/mutexes on shared objects, only one thread is doing Tcl stuff), and I'm using ActivePython 2.2.1 build 222. Thanks! Kevin. From cnetzer at mail.arc.nasa.gov Fri Nov 15 20:32:39 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Fri, 15 Nov 2002 17:32:39 -0800 Subject: help plz ive been to atleast 10 different faqs and guides In-Reply-To: <004801c28d0b$cdc93ef0$aed7bd18@mouseoh7s2nyon> References: <004801c28d0b$cdc93ef0$aed7bd18@mouseoh7s2nyon> Message-ID: <200211160132.RAA18768@mail.arc.nasa.gov> On Friday 15 November 2002 17:02, cmvb wrote: > um yes id like to make a program so when you ask a question it responds > with a preset set of random responses is this possible? You mean like a Magic 8-Ball (tm)? import random # World's stupidest magic 8-ball simulator def answer_question( question ): # Responses are probably copyright of Mattel responses = [ "Ask Again Later", "Better Not Tell You Now", "Concentrate and Ask Again", "Don't Count on It", "It Is Certain", "Most Likely", "My Reply is No", "My Sources Say No", "No", "Outlook Good", "Outlook Not So Good", "Reply Hazy, Try Again", "Signs Point to Yes", "Yes", "Yes, Definitely", "You May Rely On It" ] i = int( random.randrange( len( responses ) ) ) return responses[ i ] def get_question(): return raw_input( "What is your question?: " ) if __name__ == '__main__': print "Please ask 'Yes/No' questions..." while 1: print answer_question( get_question() ) print -- Bay Area Python Interest Group - http://www.baypiggies.net/ Chad Netzer cnetzer at mail.arc.nasa.gov From fperez528 at yahoo.com Mon Nov 11 17:48:51 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 11 Nov 2002 15:48:51 -0700 Subject: Can python find fibonacci series in a single line of code? References: Message-ID: logistix wrote: > a_human_work at hotmail.com (Pittaya) wrote in message > news:... >> My Perl-addicted friend shows me that he can find fibanicci series in >> a single line of code. >> >> perl -le '$b=1; print $a+=$b while print $b+=$a' >> >> can python do something like this? > > Guys, c'mon. How are you supposed to lock up your computer when you > only print the first 10 numbers? > > python -c "a,b=1,1;exec('while 1:\n\tglobal a,b\n\tprint > a\n\ta,b=b,a+b\n\n')" The globals aren't needed, exec() defaults to your current namespace: python -c "a,b=1,1;exec('while 1:\n\tprint a\n\ta,b=b,a+b\n')" Just how annoying this is to even read should make the point of the sillyness of one-liner battles :) Cheers, f From dsavitsk at e-coli.net Thu Nov 14 14:57:12 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Thu, 14 Nov 2002 13:57:12 -0600 Subject: Variable names on the fly? References: <3dd3f5fd$0$28311$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <7eTA9.55$P4.8534@news.uchicago.edu> "Gon?alo Rodrigues" wrote in message news:r9u7tu8csfau7sjrpkbg85ttsjrphsec7t at 4ax.com... > On Thu, 14 Nov 2002 19:13:22 -0000, "e-tones.co.uk" > wrote: > > >Hi all, does python allow the creation of variable names on the fly, more > >importantly lists. > > > >I have a stock list containing 5 elements, [0,0,0,0,0] > > > >Lets call it: list > > Don't - in your code that is. It will shadow the name of the list > builtin and a sure way to make a mess out of your program. > > > > >Now, via a loop, can I create list1, list2, list3 on the fly by replicting > >the original list, eg > > > >i = 1 > >for i in range(2) > > list+i = list > > > >Whats the proper format to concatenate (sp?) variable names. I used list+i, > >obviously this doesnt work, but what does :) > > As far as I know you cannot do this - but why would you? Why would you > need such a weird thing? Just use a mapping dictionary > > -> value > > For example: calling our dictionary dct (not dict!) and your list lst > > for i in range(2): > dct['list' + str(i)] = lst you could also do something like this (not that you should) for i in range(2): exec('list' + str(i) + ' = lst') From rkempf at rightnow.com Tue Nov 19 13:04:28 2002 From: rkempf at rightnow.com (Kempf, Reed) Date: Tue, 19 Nov 2002 11:04:28 -0700 Subject: very large inserts Message-ID: Hello, My name is Reed and I am new to the list as of today. I have been working with python for about 6 months and I have an issue where I am stumped. My background is in python, pl/sql and oracle database management with a touch of mysql database management. Anyway, I know in mysql you can do a bulk insert or an insert where you can insert many records with one insert statement like this: MYSQL - insert into table (col1, col2, col3, col4) values (1,2,3,4),(2,3,4,5),(3,4,5,6),(4,5,6,7); In oracle, you would have to do 1 insert at a time unless you are using pl/sql in which you can do a bulk insert (as far as I know). ORACLE - insert into table (col1, col2, col3, col4) values (1,2,3,4); insert into table (col1, col2, col3, col4) values (2,3,4,5); and so forth....... My question is, can python simulate a mysql bulk insert in python? I am running a linux distribution 6.2 with kernel 2.4.17 and oracle 8.1.7.4 patch set. I am also using python 2.1. Currently in my python script I loop through a python dictionary and build an insert statement which I then pass through a connection to update oracle and move onto the next python dictionary key. This works but I would sincerely like to build one very large insert statement and pass it to the oracle connection all at once. This is an issue for me since I am going through sqlnet and across a VPN to update the oracle database. The less cursors I pass through the connection, the better. Thanks in advance, ReedK From DaveP at NEARLYdpawson.freeserve.co.uk Fri Nov 15 03:28:03 2002 From: DaveP at NEARLYdpawson.freeserve.co.uk (DaveP) Date: Fri, 15 Nov 2002 08:28:03 -0000 Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> <87y98f566d.fsf@zamazal.org> Message-ID: mertz at gnosis.cx (David Mertz, Ph.D.) wrote in news:mailman.1037232380.29621.python-list at python.org: > DaveP has written a bunch of things insulting other posters. If that was the received message I apologise. Not intended. I've praised what I previously perceived to be Fred's material in the past and consider it an excellent suite of documentation. I still stand by that, otherwise I wouldn't have posted at all. And a > bunch more observing (correctly enough) that with a whole lot of work, > the documentation toolchain could eventually get back to the state its > in now. > > But for the life of me, I cannot figure out what good, however slight, > would come of such a conversion. > > Of course, I write a few columns on XML, so I guess I'm prejudiced. :-) If that had been 'in XML' instead of 'on XML' I'd have asked why you can't figure it out. Martin mentioned fashion, it is fashionable. Its also flexible and has a full toolsuite. It simply appeared as a natural for a job such as the python docsuite. If my comments are being taken as insulting I really will shut up. regards DaveP From mwh at python.net Thu Nov 28 05:42:29 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 28 Nov 2002 10:42:29 GMT Subject: With what module can Python handel *.tar.gz file? References: Message-ID: <7h3adjuou7n.fsf@pc150.maths.bris.ac.uk> Gerhard H?ring writes: > This way, I can continue refusing to learn eLISP and Emacs and > switching to GNUS;-) Gnus by default does no more with HTML than slrn. You can make it fire up w3-mode or w3m-mode, I think but, given that you can make Gnus do anything at all, this is probably not news. Cheers, M. -- Those who have deviant punctuation desires should take care of their own perverted needs. -- Erik Naggum, comp.lang.lisp From cliechti at gmx.net Fri Nov 1 18:26:29 2002 From: cliechti at gmx.net (Chris Liechti) Date: 2 Nov 2002 01:26:29 +0200 Subject: how to stop a running python command in pywin ide References: <7xEw9.9$%f4.153@news.oracle.com> Message-ID: "tagarwal" wrote in news:7xEw9.9$%f4.153 at news.oracle.com: > > > you should actualy repeat you question in the message body or at leat write one word... you can stop a running programm by clicking on the icon in the taskbar (near the clock) and select the appropriate point in the popup menu. chris -- Chris From pinard at iro.umontreal.ca Fri Nov 15 20:32:21 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 15 Nov 2002 20:32:21 -0500 Subject: help plz ive been to atleast 10 different faqs and guides In-Reply-To: <004801c28d0b$cdc93ef0$aed7bd18@mouseoh7s2nyon> References: <004801c28d0b$cdc93ef0$aed7bd18@mouseoh7s2nyon> Message-ID: [cmvb] > um yes id like to make a program so when you ask a question it responds > with a preset set of random responses is this possible? `cmvb' not Cc:ed, of course. Some probably read and think, a bit like they write. :-) Sigh! :-( -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From andreas at andreas-jung.com Fri Nov 29 02:21:12 2002 From: andreas at andreas-jung.com (Andreas Jung) Date: Fri, 29 Nov 2002 08:21:12 +0100 Subject: Newbie Question, list = list + x VS append (x) In-Reply-To: References: Message-ID: <1283675.1038558072@[0.0.0.3]> Because "+" acts like appending every item of the right hand list to the left hand list. -aj --On Freitag, 29. November 2002 07:14 +0000 Chuck wrote: > Just a quick question from a Python newbie (I've only been reading the > tutorial for about 10 minutes ) > > Could someone explain why these two bits of code act differently? > > > def add2(n): > return [n+2] > > x = y = [1,2] > > print x # [1,2] - Ok > > x = x + add2(5) > > print x # [1,2,7] - why not [1,2,[7]]? add2 returns answer inside "[ ]" > > ># ...vs... > > > print y # [1,2] - Ok > > y.append( add2(5) ) > > print y # [1,2,[7]] - Ok; What I expected it to do > > > I'm not clear what's going on when I do "list = list + function that > returns list", i.e. why it's taking the 7 out of a list, where .append > keeps it in... > > Thanks! > -- > http://mail.python.org/mailman/listinfo/python-list --------------------------------------------------------------------- - Andreas Jung http://www.andreas-jung.com - - EMail: andreas at andreas-jung.com - - "Life is too short to (re)write parsers" - --------------------------------------------------------------------- From nas at python.ca Wed Nov 13 08:52:13 2002 From: nas at python.ca (Neil Schemenauer) Date: Wed, 13 Nov 2002 05:52:13 -0800 Subject: pitfall for your amusement In-Reply-To: <20021112164933.A29726@ibook.distro.conectiva> References: <20021112164933.A29726@ibook.distro.conectiva> Message-ID: <20021113135213.GA27219@glacier.arctrix.com> Gustavo Niemeyer wrote: > > This note is mostly for entertainment purposes. > > > > >>> x = (1, 2, 3) > [...] > > >>> x += (4, 5, 6) > > Hey, shouldn't this raise an exception? Should: x = 1 x += 1 raise an exception? Neil From rjones at ekit-inc.com Thu Nov 21 16:06:29 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Fri, 22 Nov 2002 08:06:29 +1100 Subject: SHA-2 state of the art? In-Reply-To: <3DDCE92C.70803@tismer.com> References: <3DDCE92C.70803@tismer.com> Message-ID: <200211220806.29617.rjones@ekit-inc.com> On Fri, 22 Nov 2002 1:09 am, Christian Tismer wrote: > Hi friends, > > I am looking for implementations of SHA-256 > and SHA-512, and I found CryptKit so far. > http://eevolved.com/cryptkit/ > Does anybody know of alternative activities? shax-py from http://philosophysw.com/software/ via http://www.amk.ca/cgi-bin/pypi.cgi?:action=display&name=shax-py&version=0.9 :) Richard From wilk-spamout at flibuste.net Fri Nov 29 04:19:45 2002 From: wilk-spamout at flibuste.net (William) Date: 29 Nov 2002 10:19:45 +0100 Subject: Services in Python References: Message-ID: <87ptso91hq.fsf@flibuste.net> "Ricardo M. Reyes" writes: > Hi: > > I'm considering using Python to write a little smtp server, to do some > automated processing of emails in my office, and I need to know if > it's possible to make a server in Python that runs permanently under NT > server, even when there's no user logged in, like if it was a service. > I don't mind if it's not exactly an NT service, I just need that > particular characteristic. > > Do you think it's possible? If it is, then I'll get greedy and ask for > something else: when there IS a user logged in, I'd like the program > to be invisible, with no icon in the task bar. Again, you think this > is possible? there is an example of service in py2exe. (i've never tried) http://starship.python.net/crew/theller/py2exe/ -- William Dode - http://flibuste.net From whisper at oz.net Tue Nov 12 03:19:06 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 12 Nov 2002 00:19:06 -0800 Subject: HTML email marketing tool In-Reply-To: Message-ID: > I never use the "remove" link/option -- if it's spam, it > goes to a > filter, said filter sends a complaint message to > postmaster@ > Which probably marks you just as "live" as opting out. dev/null is the place to send trash ;) Dave LeBlanc Seattle, WA USA From see_reply_address at something.invalid Tue Nov 26 22:00:23 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 27 Nov 2002 16:00:23 +1300 Subject: int() shortcoming? References: <3DDE4274.3070902@Linux.ie> Message-ID: <3DE43547.6030009@something.invalid> Padraig Brady wrote: > However this is not backwards compatible. > I.E. int('017') would give a different answer. Which is an excellent reason for *not* doing this! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From pu at myRealBox.com Mon Nov 4 15:12:55 2002 From: pu at myRealBox.com (pu) Date: Mon, 4 Nov 2002 21:12:55 +0100 Subject: Python 2.2.2 on AIX 4.3.3 / AIX 5.1 References: <3dc40e9c_2@news.vo.lu> Message-ID: <3dc6d402_1@news.vo.lu> anything special to do, or just the usual "dance" ? I've never done it before, but hope to do so ASAP with a local UNIX system engineer. "Gernot Krause" wrote in message news:aq5jfi$t9a$1 at innferno.news.tiscali.de... > oops -> right is python 2.2.2 and not 2.2.1b ! > > > > From aleax at aleax.it Fri Nov 22 05:51:20 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 22 Nov 2002 10:51:20 GMT Subject: Inheritance and delegation problem. References: Message-ID: Quinet, Joel wrote: > Hi all, > > I have an object using delegation to another one by replacing __getattr__ > and __setattr__. It works fine. now, I have to do it a thread, I have > added the threading inheritance. > My problem is the threading.__init__ methode is NOT call apparently due to > __getattr__ and __setattr__ redefinition. I think threading.Thread.__init__ IS likely being executed, judging from your code below; however, instead of setting attributes on the self object, it's going to set them on the classwide __instanceMarketsConfigParser thingy, because that's where __setattr__ is shunting the destination of every assignment of the form self.whatever = anyvalue -- remember that __setattr__ works for code that's running in methods of the object or its bases, just as well as it works for outside code. Same applies to the assignments in your own __init__ to self.sortie and self.cond, of course, and to other attributes of self you're apparently binding in other methods. The solution might be to find out what attributes DO need to be set on self rather than on the class-wide thingy, and specialcase them with a simple if at the start of __setattr__ -- starting with putting a print in the same __setattr__ may help you get ahold of all the attribute names that do need to be specialcased that way. Alex From gerson.kurz at t-online.de Mon Nov 11 14:39:04 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Mon, 11 Nov 2002 19:39:04 GMT Subject: Can python find fibonacci series in a single line of code? References: Message-ID: <3dd00718.21140890@news.t-online.de> On Mon, 11 Nov 2002 14:26:25 -0500, mwilson at the-wire.com (Mel Wilson) wrote: >Well, one-liners clearly are not your forte. > >>print reduce (lambda x,y: (x[1],x[0]+x[1], x[2]+[x[1]]), xrange(10), (0,1,[]))[2] > >Pretty lame compared to > >print reduce (lambda x,y: x + [x[-1]+x[-2]], xrange(10), [1, 1] ) > >right? Pretty lame compared to fibonacci = lambda x:map(lambda o:(map(lambda c:map(lambda l:o.__setslice__(l[0],l[1],l[2]),([o[2]+3,o[2]+4,[o[0]]],[0,3,[o[1],reduce(lambda x,o:x+o,o[:2]),o[2]+1]])),range(x)),o)[1],[[1,1,0]+range(x)])[0][3:] (that should be in one line) which you can use like this: >>> print fibonacci(10) [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] From duncan at rcp.co.uk Tue Nov 26 05:04:08 2002 From: duncan at rcp.co.uk (Duncan Booth) Date: Tue, 26 Nov 2002 10:04:08 +0000 (UTC) Subject: if : References: Message-ID: Carl Banks wrote in news:aruf6o$bd7$3 at solaris.cc.vt.edu: >> Now it's gonna be interesting to see if I ever run into a situation >> where I'd feel most comfortable doing an if :, knowing >> that there are usually better ways of solving the problem. > > Testing a bunch of regular expressions on some input and taking action > on the first match seems to do it for a lot of people.> If you have more than one or two patterns, then you should really be thinking about a loop rather than a long list of if statements: PATTERNS = [ (regex1, action1), (regex2, action2), # ... ] for regex, action in PATTERNS: match = regex.match(string) if match: action(match) break I don't see any need for assignment in an 'if' here. From gerald.hein at epost.de Sun Nov 24 01:21:21 2002 From: gerald.hein at epost.de (Gerald Hein) Date: Sun, 24 Nov 2002 07:21:21 +0100 Subject: DCOracle2 performance tuning References: <%uQD9.122449$1O2.8846@sccrnsc04> Message-ID: <3DE06FE1.3010602@epost.de> Hi Stacy, There als exists the possibility to use cx_Oracle instaed of using DCOracle. See http://py.vaults.ca/parnassus/apyllo.py/973100124 I never tried cx_Oracle, but it might be worth a try for you .. Gerald From wlfraed at ix.netcom.com Mon Nov 18 21:29:54 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 18 Nov 2002 18:29:54 -0800 Subject: Hmm... An idea: if a,b==c,d: References: Message-ID: <2n7cra.j65.ln@beastie.ix.netcom.com> Andrew Koenig fed this fish to the penguins on Monday 18 November 2002 03:37 pm: > Richard> It doesn't have ()s, so it ain't two tuples. Easy enough, da? > But, in a way, it is the COMMA that defines a tuple, not the ()s... We recently had a discussion in which it was explained that a,b = b,a in essence generates a (b,a) tuple, then unpacks it into the left-side a,b -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From anton at vredegoor.doge.nl Mon Nov 11 04:58:21 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Mon, 11 Nov 2002 10:58:21 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h3k7jlwock.fsf@pc150.maths.bris.ac.uk> <76c4da8e.0211101357.6a804d20@posting.google.com> Message-ID: On 10 Nov 2002 13:57:37 -0800, voodoo1man at hotmail.com (Vlad S.) wrote: >the language, and get a YAPFL (yet another pseudo functional >language). Last time I checked, Python fit into that category, so you >already have what you say you want. Without confirming that I want that, I would like to mention that functional languages can't have side effects. So in order to generate any output at all some concessions have to be made. Strictly speaking Lisp is not a functional language. To get at a strictly functional language - now switching into science fiction mode - a possible strategy could use an idea found in one of A.E. van Vogt's novel's. Here a description of a part of the universe is made inside a human brain which is indistinguishable from the real thing up until the twentieth's decimal. This enables the main character to effect changes in the universe because at that level of equality the description of the universe and the universe itself cannot occupy separate locations. It's an interesting read and also popularizes some ideas about identity from Korzibsky's works. Regards, Anton. From dsavitsk at e-coli.net Mon Nov 11 20:54:08 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Tue, 12 Nov 2002 01:54:08 GMT Subject: Create DLL in Python ? References: <1b318b70.0211111607.74ace07@posting.google.com> Message-ID: <4bZz9.5692$mN6.2514493@newssrv26.news.prodigy.com> "Georges Bernier" wrote in message news:1b318b70.0211111607.74ace07 at posting.google.com... > Hello, > > We have a legacy application at work written in Visual C which makes > use of a DLL for specific communication functions. Now I have to > replace this DLL (whose API is well documented) with an enhanced > version which will make use of TCP/IP instead of older protocols > without changing the original C application (or at least changing the > minimum possible). > > So does anybody have experience in such a thing, is it a bad idea (as > I'm starting to think is is) and would it better be done in C/C++ ? > I would appreciate comments from the Python community on this. The easiest thing to do is to create a COM server which is what a dll is, or rather can be. The simplest way to do this is as follows ... class MY_COM_SERVER: # change this next line. a new id can be generated with # >>> import pythoncom # >>> print pythoncom.CreateGuid() _reg_clsid_ = '{F69D8FCD-97BF-4D60-B5E5-199FC3C63172}' # list the public methods _public_methods_ = ['COM_SERVER_METHOD'] # the server's name in the registry _reg_progid_ = 'PythonCOMServer.FirstServer' def COM_SERVER_METHOD(self): return 'Hello, World!' if __name__ == '__main__': import win32com.server.register win32com.server.register.UseCommandLine(MY_COM_SERVER) Register it by running it in an ide, or by double clicking the file. It would be accessed from VBScript as Set x = CreateObject('PythonCOMServer.FirstServer') x.COM_SERVER_METHOD This creates a late bound COM server accessed like any other dll. There are many more details, and you should look in the book Python Programming on Win32 for more. if, however, the original dll is not a COM object, then I can't help. -d From dreed at capital.edu Mon Nov 25 14:31:23 2002 From: dreed at capital.edu (Dave Reed) Date: Mon, 25 Nov 2002 14:31:23 -0500 (EST) Subject: cannot import gtk In-Reply-To: <1038250593.848.6.camel@m37.net195-132-249.noos.fr> (message from Pascal Ronecker on 25 Nov 2002 19:56:33 +0100) References: <200211241734.38215.dreed@capital.edu> <1038250593.848.6.camel@m37.net195-132-249.noos.fr> Message-ID: <200211251931.gAPJVNN25597@fourier.capital.edu> > From: Pascal Ronecker > Cc: python-list at python.org > Content-Type: text/plain > Date: 25 Nov 2002 19:56:33 +0100 > Content-Length: 1651 > > Thanks ! > > but i'm still stuck. > > For example : GtkText does not exist, neither does Text alone. > > What is more, i have other problems with "from gnome.ui import GnomeApp" > and so on.Changing all the code seems a long way to me. > (it is the "eroaster" cd burning tool, a nice all-in-one) > > > Maybe the right solution is to "install the bindings" as you say, but i > do not have the slightest idea as to what it means... > > So if you could explain a bit that last bit, ... > thx !! > > Lenny You need to know if eroaster wants gtk 1.2 or gtk2. I'm guessing 1.2 for a couple reasons (gtk2 is relatively new so most older programs still use 1.2). It does appear with pygtk1.2 that the Gtk prefix is still there so "from gtk import GtkVBox" is what you want, but with pygtk2 you don't. You'll need to download the file: gnome-python-1.4.2.tar.gz which you can find on the gnome.org ftp site and install it with the usual: tar zxf gnome-python-1.4.2.tar.gz cd gnome-python-1.4.2 ./configure make make install this will put the pygtk1.2 files in /usr/local/lib/python2.2/site-packages so you'll need to add that directory to your PYTHONPATH environment variable. HTH, Dave From bondpaper at earthlink.net Sat Nov 9 17:13:02 2002 From: bondpaper at earthlink.net (Tom) Date: Sat, 09 Nov 2002 22:13:02 GMT Subject: time.sleep on linux Message-ID: Hello, Is there a special time module I need to install for a standard RH Linux 7.3 system? The reason I ask is that my installation (2.2.1) seems to be missing some time-related functions - time.sleep() for example. Thanks. Tom From mwh at python.net Thu Nov 28 05:05:31 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 28 Nov 2002 10:05:31 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3de1f902$0$695$edfadb0f@dread12.news.tele.dk> Message-ID: <7h3r8d6ovx9.fsf@pc150.maths.bris.ac.uk> Robin Munn writes: > And the reason for it is because I still don't understand how to > indent *properly* in Lisp, You use emacs (after doing (setq lisp-indent-function 'common-lisp-indent-function) in your ~/.emacs). Really. Cheers, M. -- Haha! You had a *really* weak argument! -- Moshe Zadka, comp.lang.python From wlfraed at ix.netcom.com Sun Nov 24 20:53:10 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sun, 24 Nov 2002 17:53:10 -0800 Subject: Coaxing DWORD values out of a Binary file... References: Message-ID: <6qvrra.t7d.ln@beastie.ix.netcom.com> adeptus fed this fish to the penguins on Sunday 24 November 2002 02:46 pm: > > I've tried unpacking them via the struct module, (by passing them in > as 4 byte strings) but the numbers I get don't seem to make any sense > for the file format... > > Am I making a naive assumption about how VC++ would write a DWORD to a > binary file??? > > I'm also assuming that: > (i386 centric) > 8-Bits = 1 Char = 1 Byte > 1 Word = 2 Bytes > 1 DWORD = 4 Bytes Well, from the VC++ ver5 type definitions: #ifndef _DWORD_DEFINED #define _DWORD_DEFINED typedef unsigned long DWORD; #endif // !_DWORD_DEFINED So... 4 bytes may be correct, but nothing in that controls the byte order M$ decided to use in storage -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From teaandbikkie at aol.com Wed Nov 6 17:51:02 2002 From: teaandbikkie at aol.com (TeaAndBikkie) Date: 06 Nov 2002 22:51:02 GMT Subject: Guilty secret: globals baffle me References: Message-ID: <20021106175102.10760.00000103@mb-mq.aol.com> >From: Gon?alo Rodrigues op73418 at mail.telepac.pt > >On 6 Nov 2002 17:21:46 GMT, bokr at oz.net (Bengt Richter) wrote: > >>I have an uncomfortable feeling there is unfinished >>business in the way names in nested scopes and otherwise >>related namespaces work. The global/local dichotomy doesn't >>fully express the possibilities any more. IMO it would be nice >>to have full access to accessible namespaces without magically >>determined access mode restrictions based on full-function lookahead. >> >>I.e., we have a de facto hierarchy of name spaces defined by the >>ability to nest functions. Why not have an access mechanism that >>allows rebinding as desired? E.g., you could let locals take a depth >argument, >>so locals() is equivalent to locals(0), and locals(1) is the enclosing >>name space, so locals(1)['x'] = 3 in bar above would rebind the x local to >foo. >> > >I totally agree with you. The uncomfortable feeling is underlined by the >fact that you can rebind global names through the use of global (the >only declaration in Python - ach!) but not names in the enclosing scope >- if it is not global that is. Although I do not feel that there is a >need for this feature in Python, it strikes as an ugly asymmetry - the >ugliest in fact. > >I would just change a little bit your notation. Instead of reusing >locals use something like > >enclosed() > >returning the enclosing scope. And you've guessed it - if you want to >get at the next scope just use enclosed().enclosed(). The enclosed() at >global scope should return None. > >Now if you wanted to rebind a variable in the enclosing scope you should >be able to use the notation > >enclosed().x = > >and not dict notation. globals() should follow the same rules. I would like to be able to have named scope, so you can specify precisely from which scope the variable is in. Perhaps mixed with relative scope indexing? eg: def eric(): licence='fish' def bruce(): licence='halibut' print scope(eric).licence print scope(-1).licence Or something more pythonic :-) -- Misha From fredrik at pythonware.com Tue Nov 19 07:42:33 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Nov 2002 12:42:33 GMT Subject: Tkinter/Canvas question, Please Help References: <2059908.1037644767@dbforums.com> Message-ID: "benson123456" wrote: > third question: > if I am using the grid method, does every row and column has to be the > same size? you can use the "columnspan" and "rowspan" options to create cells that span more than one column/row: http://www.pythonware.com/library/tkinter/introduction/grid.htm From cappy2112 at yahoo.com Thu Nov 7 19:00:30 2002 From: cappy2112 at yahoo.com (Tony C) Date: 7 Nov 2002 16:00:30 -0800 Subject: Newbie- how to basics Message-ID: <8d3e714e.0211071600.2a98b136@posting.google.com> I've gone through much of the documentation included with Python 2.2.2, but can find any kind of reference on how to clear the screen from a python script, or at the command line. Another useful feature would be command line history (up arrow, down arrow, etc), like in the Unix shells. Would ssomeone point me to some docs (specific locations) which descibe these features ? thanks From sholden at holdenweb.com Wed Nov 27 15:55:40 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 27 Nov 2002 15:55:40 -0500 Subject: floating point division -- question References: Message-ID: <%jaF9.16948$yk6.10839@fe03> "William Park" wrote in message news:as31ig$n7lq2$1 at ID-99293.news.dfncis.de... > Gerhard H?ring wrote: > > William Park wrote: > >> Some time ago, there was thread discussing adding a floating point division > >> operator, like //. Doing 'a//b' is certainly easier than doing 'a/float(b)', > >> and it doesn't break any existing codes. Has there been any interest from > >> the Gods of Python? > > > > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> from __future__ import division > >>>> 3 / 5 > > 0.59999999999999998 > >>>> 3 // 5 > > 0 > > > > It's been there since the original Python 2.2 release. See > > http://www.python.org/doc/current/whatsnew/node7.html for details. > > Thanks Gerhard. Although I would've have switched the two operator, so > that existing code doesn't change... > But there's simply no way you could do that. If you'd used "/" for integer division then programs that used it with float operands would have broken. Either way it's a change in semantics, and that's why Guido has decreed the change will take so long. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From bokr at oz.net Sun Nov 10 01:30:18 2002 From: bokr at oz.net (Bengt Richter) Date: 10 Nov 2002 06:30:18 GMT Subject: Determining Presence Of GUI Support References: <42aiqa.jp82.ln@boundary.tundraware.com> Message-ID: On 09 Nov 2002 17:40:11 GMT, Tim Daneliuk wrote: [...] > >Years ago, in the transition from MS-DOS to Windows, there used to be >a way to lay a DOS binary into the Windows executable file. That way, I suspect there still is, normally used for the code that tells you "This program cannot be run in DOS mode." ;-) Regards, Bengt Richter From jarek at usun.zgoda.biz Wed Nov 20 16:00:08 2002 From: jarek at usun.zgoda.biz (Jarek Zgoda) Date: Wed, 20 Nov 2002 22:00:08 +0100 Subject: Advice for using emacs python-mode References: Message-ID: <14n8la15cqnk7$.ulxse2lvi2kc.dlg@40tude.net> Dnia Wed, 20 Nov 2002 19:55:52 GMT, Andrew Koenig pisze: > Any suggestions? Use Vim. No offence, just kidding. ;) -- ~$ rm -f /bin/Laden I po k?opocie! -- Serwis Usenet w portalu Gazeta.pl -> http://www.gazeta.pl/usenet/ From rademacher at prostep.FTA-berlin.de Thu Nov 28 05:01:49 2002 From: rademacher at prostep.FTA-berlin.de (Thomas Rademacher) Date: Thu, 28 Nov 2002 11:01:49 +0100 Subject: [Tkinter] text widget update problem Message-ID: Hallo, I want to write a text widget which can be filled step by step in dependent on program sequence: ... scrollbar = Scrollbar(frameMsg, orient=VERTICAL) scrollbar.pack(fill=Y, side=RIGHT) text = Text(frameMsg, bd=0,font='courier 8', width=960, height=450, fg="black") text.pack() text.config(yscrollcommand=scrollbar.set) scrollbar.config(command=text.yview) ... The input of the text widget I create in a singleton logger class: ... Logging.__msgHandle.insert(END, logString) Logging.__msgHandle.update() <-- ... I want to see the the output step by step during program sequence. But I have following problems: 1. With Logging.__msgHandle.update() I get a program crash when all lines in the widget filled. The widget does not show the following messages. 2. Without Logging.__msgHandle.update() I get the my program output at the end of the program and not step by step. How can I resolve the problem? Who has any ideas? It is a singleton class problem? Thank's for your hints, Thomas From grante at visi.com Wed Nov 20 10:27:18 2002 From: grante at visi.com (Grant Edwards) Date: 20 Nov 2002 15:27:18 GMT Subject: Bug in Win32file WaitCommEvent ??? References: <3ddaa58d$0$4459$a1866201@newsreader.visi.com> Message-ID: <3ddba9d6$0$4464$a1866201@newsreader.visi.com> In article , Bengt Richter wrote: > On 20 Nov 2002 01:07:57 GMT, Grant Edwards wrote: > [...] >>> >>> Sounds like the mask location is safe if you don't call >>> GetOverlappedResult?? > > OTOH it looks to me pretty sure that a persistent LPOVERLAPPED > structure at least is expected for the duration of the > background operation. > > and, thinking about it, it says, > > "GetOverlappedResult reports the success or failure of the > operation, and the variable pointed to by the lpEvtMask > parameter is set to indicate the event that occurred." > > but you don't re-specify lpEvtMask with that call, so I think I > would agree with your original take on all this. Assuming the text on the MSDN page is correct. > They wouldn't just force a wait all the time, would they? I've seen plenty of apps that assume it doesn't wait all the time. If I had a C compiler and knew how to write a simple console app for Win32, it would be easy enough to figure out how it really does work. The Win32 guys I work with directly all write device drivers and none of them know how the user-land API works. > Though I can imagine that being a tempting temporary quick fix > for something, and temporariness sometimes stretches. -- Grant Edwards grante Yow! Here I am in the at POSTERIOR OLFACTORY LOBULE visi.com but I don't see CARL SAGAN anywhere!! From martin at v.loewis.de Thu Nov 14 08:52:15 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 14 Nov 2002 14:52:15 +0100 Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> <3DD36C57.8050604@trados.com> Message-ID: Zoltan Sekeres writes: > From my experience (I work for TRADOS, a translation tools provider) the > translation becomes much easier with XML. With XML it is usually > sufficient to provide a simple config file for our TagEditor product and > it just works. The problem that I still consider unsolved is how may translators can work on a single document, and how retranslation of the entire document in case of changes can be avoided. This can be solved theoretically, by assigning IDs to relevant elements (and then finding out which IDs need to change), but I'm not sure whether this would work in practice. Regards, Martin From skip at pobox.com Fri Nov 22 19:19:21 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 22 Nov 2002 18:19:21 -0600 Subject: Proposal: min(None, x) and max(None, x) return x In-Reply-To: <200211222342.PAA10255@mail.arc.nasa.gov> References: <200211222342.PAA10255@mail.arc.nasa.gov> Message-ID: <15838.51593.296849.174022@montanaro.dyndns.org> Chad> xMax = [] Chad> for -whatever-: Chad> -big calculation leading to a value of x- Chad> xMax = [max([x]+xMax)] Chad> xMax = xMax[0] Wouldn't it be better to accumulate all your x's in a list and call max once at the end: xlist = [] for -whatever-: xlist.append(big_hairy_calc) xMax = max(xlist) ? -- Skip Montanaro - skip at pobox.com http://www.mojam.com/ http://www.musi-cal.com/ From peter at silmaril.ie Fri Nov 1 18:07:35 2002 From: peter at silmaril.ie (Peter Flynn) Date: Fri, 01 Nov 2002 23:07:35 +0000 Subject: Field in SGML file References: Message-ID: Eric Brunel wrote: > Ilya Shambat wrote: > >>I need to be able to read a field in an SGML file with Python. Do you >>know how to do that? > > > What are you calling a "field"? Is it an element? An element's attribute? > And what is your SGML file like? Is it a simple, Xml-like file, or does it > uses SGML's funky features like shortref's or usemap's? > > If your file is simple enough, you may find it simpler to write your own > "micro-parser", doing exactly what you want to do. Parsing a full-featured > SGML file is *really* complicated but if the file's simple enough, writing > your own parser is probably the best solution. > > If you file is too complicated, you'd better use an external parser and > analyse the parser's results with Python. I personally used nsgmls quite a > lot (http://www.jclark.com/sp/): it's fast, easy to use (at least if you > know what SGML is about...) and its results is easy to analyse. I'd recommend using nsgmls no matter what the file size or complexity. Get it from http://www.jclark.com/sp/index.htm I don't know how you call external binaries from within Python, but you need to issue the command string nsgmls -cCATALOG [sgml-dec] filename where CATALOG is the name of a catalog file used to resolve entity references and [sgml-dec] is an optional SGML Declaration filename. You need to ask the people supplying the SGML file if you need these or not (and if you do, they must supply you with them). This will produce ESIS output (http://xml.coverpages.org/WG8-n931a.html) which is very easily usable in a scripting language, and from which you can extract the data you need. ///Peter From lehmann at puk.unibe.ch Fri Nov 29 07:40:25 2002 From: lehmann at puk.unibe.ch (christoph) Date: 29 Nov 2002 04:40:25 -0800 Subject: pyopengl install problem on redhat 8.0 Message-ID: on a redhat 8.0 system (a31p thinkpad) i ran python setup.py build and got: gcc -shared build/temp.linux-i686-2.2/GL.ARB.matrix_palette.o -L/usr/lib -L/usr/local/lib -L/usr/X11/lib -Lbuild/temp.linux-i686-2.2 -lGL -lX11 -lXext -lGLU -linterface_util -lGLE -o build/lib.linux-i686-2.2/OpenGL/GL/ARB/matrix_palette.so /usr/bin/ld: cannot find -lX11 collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 please help me!!! thanks a lot christoph From mike at skew.org Sat Nov 23 04:51:50 2002 From: mike at skew.org (Mike Brown) Date: Sat, 23 Nov 2002 02:51:50 -0700 Subject: urllib slow on FreeBSD 4.7? sockets too References: <3ddd8419_3@omega.dimensional.com> Message-ID: <3ddf4fb7$1_2@omega.dimensional.com> "Jarkko Torppa" wrote: > Seems that stdio is somehow confused, try this > > import urllib, time, os > > starttime = time.time() > u = urllib.urlopen('http://localhost/4m') > fn = u.fp.fileno() > bytea = [ ] > while 1: > bytes = os.read(fn, 16 * 1024) > if bytes == '': > break > bytea.append(bytes) > bytes = ''.join(bytea) > u.close() [...] Well, look at that... bytes: 4241.5K; time: 0.322s (13171 KB/s) That's much better. At least, it now seems to be hitting the socket speed cap. Thanks! From stuart at bmsi.com Sat Nov 9 23:27:24 2002 From: stuart at bmsi.com (Stuart D. Gathman) Date: Sun, 10 Nov 2002 04:27:24 GMT Subject: Getting SSL certificate References: Message-ID: On Sat, 09 Nov 2002 01:56:59 -0500, Martin v. Loewis wrote: >> That would make sense, but the docs say that checking the server >> certificate is not implemented. > > Did you try? Python passes the cert_file argument to > SSL_CTX_use_certificate_chain_file. It might be a problem that Python > never calls SSL_get_verify_result, though (but then, I understand that > the default verify callback will return preverify_ok, so if the server > certificate could not be verified, the TLS handshake will be > terminated). Tying doesn't tell me whether the cert was actually checked. I don't get any errors, however, poking around in the C source for socketmodule.c, I find for opening an SSL connection: if (key_file) { if (SSL_CTX_use_PrivateKey_file(self->ctx, key_file, SSL_FILETYPE_PEM) < 1) { errstr = "SSL_CTX_use_PrivateKey_file error"; goto fail; } if (SSL_CTX_use_certificate_chain_file(self->ctx, cert_file) < 1) { errstr = "SSL_CTX_use_certificate_chain_file error"; goto fail; } } SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL); /* set verify lvl */ self->ssl = SSL_new(self->ctx); /* New ssl struct */ SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ SSL_set_connect_state(self->ssl); /* Actually negotiate SSL connection */ /* XXX If SSL_connect() returns 0, it's also a failure. */ ret = SSL_connect(self->ssl); And the openssl docs have this to say about SSL_VERIFY_NONE: SSL_VERIFY_NONE Server mode: the server will not send a client certificate request to the client, so the client will not send a certificate. Client mode: if not using an anonymous cipher (by default disabled), the server will send a certificate which will be checked. The result of the certificate verification process can be checked after the TLS/SSL handshake using the SSL_get_verify_result(3) function. The handshake will be continued regardless of the verification result. socketmodule.c never calls SSL_get_verify_result() It seems that the docs are correct. The certificate is not validated and I could be talking to anybody or their dog. Furthermore, while the server and issuer are exposed through undocumented attributes, the server_cert is not. So there is no way to validate the cert manually, short of rewriting socketmodule.c. This is one case where the batteries included have been sitting on the shelf too long. If only the server_cert were available, validating it is not too much work. There is an external 'verify' program supplied with openssl that does most of the work for you. -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From hancock at anansispaceworks.com Fri Nov 15 16:08:23 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 15 Nov 2002 13:08:23 -0800 Subject: A really bad idea. In-Reply-To: <20021115180601.9454.63491.Mailman@mail.python.org> References: <20021115180601.9454.63491.Mailman@mail.python.org> Message-ID: On Friday 15 November 2002 10:06 am, Tim Peters wrote: > waiting-for-someone-to-ask-for-class-comprehensions-ly y'rs ?- tim I'm inspired. Unfortunately, I'm still using 2.1.3 -- pardon my dust: def meth1(): print 1 def meth2(): print 2 def meth3(): print 3 # Emulate 2.2 built-in? def dict(l): d = {} for pair in l: d[pair[0]] = pair[1] return d class comp: def __init__(self): self.__dict__.update(dict( [(f.__name__,f) for f in globals().values() if callable(f) ] )) >>> c = comp() >>> c.meth1() 1 >>> c.meth2() 2 ;-D Still considering whether there's a more compact (or at least clearer) way to write that. Practically, of course, using globals() is sort of dumb -- but imagine importing a module and using the module name instead. Actually I can think of one practical use for this: In a Zope product, it's quite convenient to have a separate module containing ZSQL methods defined using Zope's SQL() factory function (that way you separate SQL and Python languages for the most part). Then you could use this code with the ZSQL module to put ALL SQL methods from a given module into a class. That way you skip a whole lot of: mySQL_query = SQLmodule.mySQL_query statements in the class file that have to be updated every time you change your SQL (which is fairly frequent). This particular ugliness came up in the Zope list a few months ago, and the OP proposed writing a special parser / SQL extension language to do it. It turned out that this need to "shovel" the whole contents of an SQL module into a class was the only real problem it solved. This would be a simpler solution. There's other, perhaps better, ways to do it, of course -- it might make more sense to just use a loop and setattr(), for example. Just adding to the list comp madness. ;-) Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From martin at v.loewis.de Mon Nov 25 05:25:01 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 25 Nov 2002 11:25:01 +0100 Subject: sockets and encryption References: <8hi2uuguh0l0jlmrao1fjshle68op1kt4s@4ax.com> Message-ID: Paul Nilsson writes: > Since HTML is ascii and XML is unicode I thought this may put > some limitations on what raw data could be sent. This is a misconception. Neither is HTML ascii, nor is XML unicode. When transmitted over the wire, both are byte strings. By "XML is Unicode", people usually mean that an XML document is *conceptually* a sequence of Unicode characters. The same is true for HTML (formally atleast since HTML 3.0 or so; conceptually, you can apply this view for all HTML versions). When represented in a byte-oriented medium, an encoding has to be applied to the sequence of Unicode characters. Both HTML and XML allow usage of arbitrary encodings: "ASCII", "iso-8859-1", "utf-8", you name them, we have them. > I had suspected that SSL incorporated a unicode layer which could > cause problems if I wanted to send raw bytes (or I would have to > converrt them to CDATA). Another misconception: In a CDATA section, you cannot put arbitrary bytes. You must put characters there, according to the declared document encoding. Regards, Martin From martin at v.loewis.de Fri Nov 29 15:41:08 2002 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 29 Nov 2002 21:41:08 +0100 Subject: Parser building in Python References: Message-ID: ml writes: > I like to write a parser in Python. The language itself is > not LALR(1), but I could do some tricks to make it LALR(1). > What are the best tools to write lexers and parsers in > Python? Maybe sth. similar to ANTLR? I personally recommend YAPPS (or YAPPS2). It's only LL(1), but the generated parser is very easy to understand. Regards, Martin From akuchlin at ute.mems-exchange.org Thu Nov 7 10:37:39 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 07 Nov 2002 15:37:39 GMT Subject: A vision for Parrot References: Message-ID: In article , Steven D. Arnold wrote: > There may be difficulties like the ones you bring up, but my feeling is the > Parrot people ought to go for solving the easy 90 percent of the problem, > even if it means that little code from any language will work out of the box > (except perhaps perl6; it is their baby, after all). But then Parrot/Python becomes a variant of Python, and you have to ask why work on one variant and not another? Why work on Parrot/Python and not .NET/Python, which would also be a variant? Months ago I once predicted that Mono (the effort to write a Linux .NET implementation) would likely founder on the sheer complexity of duplicating a large and possibly-shifting standard CLR, while Parrot, which had a seemingly simpler task, would get its first usable version out more quickly. Astonishingly, just the opposite has happened; Mono has been making releases every few months and steadily writing more add-on libraries, while Parrot has advanced much more slowly. I'd like to dust off Mark Hammond's python.NET code, but unfortunately Mono doesn't yet implement enough of the necessary APIs to support it. --amk (www.amk.ca) HAMLET: Ay, madam, it is common. -- _Hamlet_, I, ii From tjreedy at udel.edu Thu Nov 14 15:29:00 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 14 Nov 2002 15:29:00 -0500 Subject: Variable names on the fly? References: <3dd3f5fd$0$28311$fa0fcedb@lovejoy.zen.co.uk> Message-ID: "e-tones.co.uk" wrote in message news:3dd3f5fd$0$28311$fa0fcedb at lovejoy.zen.co.uk... > Hi all, does python allow the creation of variable names on the fly, more > importantly lists. > > I have a stock list containing 5 elements, [0,0,0,0,0] > > Lets call it: list > > Now, via a loop, can I create list1, list2, list3 on the fly by replicting > the original list, eg > > i = 1 > for i in range(2) > list+i = list > > Whats the proper format to concatenate (sp?) variable names. I used list+i, > obviously this doesnt work, but what does :) I believe you can use setattr() with globals, but you almost certainly do not want to do this. How do you access the runtime-defined names? As suggested, an explicit dict others than globals is almost certainly better. TJR From rademacher at prostep.FTA-berlin.de Fri Nov 29 08:39:38 2002 From: rademacher at prostep.FTA-berlin.de (Thomas Rademacher) Date: Fri, 29 Nov 2002 14:39:38 +0100 Subject: [Tkinter] text widget update problem References: Message-ID: Hallo Martin, > On Thu, 2002-11-28 at 10:01, Thomas Rademacher wrote: > > Hallo, > > > > I want to write a text widget which can be filled step by step in dependent > > on program sequence: > > ... > > scrollbar = Scrollbar(frameMsg, orient=VERTICAL) > > scrollbar.pack(fill=Y, side=RIGHT) > > text = Text(frameMsg, bd=0,font='courier 8', width=960, height=450, > > fg="black") > > text.pack() > > text.config(yscrollcommand=scrollbar.set) > > scrollbar.config(command=text.yview) > > ... > > > > The input of the text widget I create in a singleton logger class: > > ... > > Logging.__msgHandle.insert(END, logString) > > Logging.__msgHandle.update() <-- > > ... > > > > I want to see the the output step by step during program sequence. But I > > have following problems: > > 1. With Logging.__msgHandle.update() I get a program crash when all lines in > > the widget filled. The widget does not show the following messages. > > 2. Without Logging.__msgHandle.update() I get the my program output at the > > end of the program and not step by step. > > > > How can I resolve the problem? Who has any ideas? It is a singleton class > > problem? > > Thank's for your hints, Thomas > > > > > > Are you calling update() from the main thread (you don't mention threads > but I am guessing you are using them) Could you post a cut down version > that demonstrates the problem? I have had problems with calling > update() from another thread..... > Yes!!! I use threads: for ii in range(maxSession): log.log(__name__, 0, "enter", "beforeThreads"); <-- logging in text widget WITHOUT problems myS = session.Session(dxmDbServer, ii+1, maxDs, lang, cpu, usr, pwd, authmode, clienttype) thread.start_new_thread(threadSession,(myS,)) def threadSession(actSession): global log log.log(__name__, 0, "enter", "threadSession") <- logging in text widget WITH problems log.log(__name__, 0, "input", actSession) actSession.testSession() log.log(__name__, 0, "leave", "threadSession") Have you an idea how can I resolve this problem? Thank's Thomas! From alanmk at hotmail.com Sat Nov 9 08:54:05 2002 From: alanmk at hotmail.com (Alan Kennedy) Date: Sat, 09 Nov 2002 13:54:05 +0000 Subject: How to spawn a program and assign its stdout to a string variable? References: Message-ID: <3DCD137D.E714C3CA@hotmail.com> "Christopher R. Culver" wrote: > I'm working on a pdf2ps frontend script that will use the *nix utility > "file" to determine a file's type without blindly trying to work on it. > I assume the best way to do this is to spawn "file", capture its stdout > to a string variable......... Or you could check this thread which discusses a python implementation of the unix "file" command:- http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=9c3f2e9c.0201150943.5e4de1fb%40posting.google.com&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3D9c3f2e9c.0201150943.5e4de1fb%2540posting.google.com regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From robin at jessikat.fsnet.co.uk Fri Nov 15 13:43:07 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 15 Nov 2002 18:43:07 +0000 Subject: wrapping all class methods In-Reply-To: References: Message-ID: ..... it seems I was asking a question that Python cannot answer as traceback.print_exc() will only print a traceback back to the point at which it's caught. The stack frames are there and can be listed further, but I don't think that the line number information is always good beyond the exception handler. ############# traceback.py def tracebackAdvice(origMethod, methodName): def wrap_traceback_method(*args, **kwargs): inst = args[0] try: origMethod(*args, **kwargs) except: print '[%s.%s]' % (inst.__class__.__name__, methodName) from traceback import print_exc print_exc() print 'stack info' import sys f = sys._getframe(1) while f: co = f.f_code print 'name:%s file:%s co_lno:%d lasti:%d f_lno:%d' % (co.co_name, co.co_filename, co.co_firstlineno, f.f_lasti, f.f_lineno) f = f.f_back return wrap_traceback_method def _allMethods(C): from inspect import ismethod, getmembers M = [] m = M.append for methodname,method in getmembers(C): if ismethod(method): m(methodname) return tuple(M) def tracebackWrap(C, *M): for m in M or _allMethods(C): setattr(C, m, tracebackAdvice(getattr(C, m), m)) if __name__=='__main__': class A(object): def f(self, x): assert x>=0 print "real f", x tracebackWrap(A, "f") def L2(): a = A() a.f(1) a.f(-1) def L1(): L2() def L0(): L1() L0() ################################# C:\Python\devel\anygui\lib\anygui\backends>tbwrap.py real f 1 [A.f] Traceback (most recent call last): File "C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py", line 5, in wrap_traceback_method origMethod(*args, **kwargs) File "C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py", line 35, in f assert x>=0 AssertionError stack info name:L2 file:C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py co_lno:38 lasti:43 f_lno:41 name:L1 file:C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py co_lno:42 lasti:9 f_lno:43 name:L0 file:C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py co_lno:44 lasti:9 f_lno:45 name:? file:C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py co_lno:1 lasti:138 f_lno:46 C:\Python\devel\anygui\lib\anygui\backends> -- Robin Becker From bswhb at 263.net Wed Nov 20 22:54:42 2002 From: bswhb at 263.net (Wang Hanbo) Date: Thu, 21 Nov 2002 11:54:42 +0800 Subject: A simple question: How to exit from a python script? Just like the exit() in C++ Message-ID: <006801c29111$bf776660$d001a8c0@dctc.cs> Hi, I have a simple question as is written in the header, how can I exit from a python program using a call such as "exit()" in C++? I am a novice on this list, and also a rookie on python language, all of you answers will be my best impetus! Thanks Hanbo 2002-11-21 -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleax at aleax.it Wed Nov 13 07:42:42 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 13 Nov 2002 12:42:42 GMT Subject: simple metaclass question References: <3DD08DC1.A4CFE557@irl.cri.nz> Message-ID: <6NrA9.4123$744.137981@news1.tin.it> Carl Banks wrote: ... > 2. Because M is not a subclass of type, instances of M are not types. > Therefore, A is not a type. (I'm not sure of this one, though. I > think in Python an object can be a type only if it is a subclass of > type; I'm not sure if this is true in other languages with I'm not exactly sure of what it is that you believe, but, for the record: objects CAN be types of other objects, in Python, without subclassing the built-in `type` -- for example: >>> class oldClass: pass ... >>> issubclass(type(oldClass), type) 0 Alex From brian at sweetapp.com Thu Nov 7 05:22:12 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 07 Nov 2002 02:22:12 -0800 Subject: Syntax Error, help a newbie In-Reply-To: Message-ID: <001101c28647$893a8930$21795418@dell1700> > self._services = [ s for s in self._services: if s._name != '$removed$' ] [sniped] > PS. Red Hat Linux 7.2 running python-1.5.2-38 Even if your syntax were correct, it wouldn't work. Python 1.52 didn't have list comprehensions. Cheers, Brian From Greg_Aumann at sil.org Mon Nov 4 08:26:39 2002 From: Greg_Aumann at sil.org (Greg Aumann) Date: Mon, 4 Nov 2002 21:26:39 +0800 Subject: file iterators and codecs, a bug? Message-ID: Recently I figured out how to use iterators and generators. Quite easy to use and a great improvement. But when I refactored some of my code I came across a discrepancy that seems like it must be a bug. If you use the old file reading idiom with a codec the lines are converted to unicode but if you use the new iterators idiom then they retain the original encoding and the line is returned in non unicode strings. Surely using the new "for line in file:" idiom should give the same result as the old, "while 1: ...." I came across this when using the pythonzh Chinese codecs but the below code uses the cp1252 encoding to illustrate the problem because everyone should have those codecs. The symptoms are the same with both codecs. I am using python 2.2.2 on win2k. Is this definitely a bug, or is it an undocumented 'feature' of the codecs module? Greg Aumann The following code illustrates the problem: ------------------------------------------------------------------------ """Check readline iterator using a codec.""" import codecs fname = 'tmp.txt' f = file(fname, 'w') for i in range(0x82, 0x8c): f.write( '%x, %s\n' % (i, chr(i))) f.close() def test_iter(): print '\ntesting codec iterator.' f = codecs.open(fname, 'r', 'cp1252') for line in f: l = line.rstrip() print repr(l) print repr(l.decode('cp1252')) f.close() def test_readline(): print '\ntesting codec readline.' f = codecs.open(fname, 'r', 'cp1252') while 1: line = f.readline() if not line: break l = line.rstrip() print repr(l) try: print repr(l.decode('cp1252')) except AttributeError, msg: print 'AttributeError', msg f.close() test_iter() test_readline() ------------------------------------------------------------------------ This code gives the following output: ------------------------------------------------------------------------ testing codec iterator. '82, \x82' u'82, \u201a' '83, \x83' u'83, \u0192' '84, \x84' u'84, \u201e' '85, \x85' u'85, \u2026' '86, \x86' u'86, \u2020' '87, \x87' u'87, \u2021' '88, \x88' u'88, \u02c6' '89, \x89' u'89, \u2030' '8a, \x8a' u'8a, \u0160' '8b, \x8b' u'8b, \u2039' testing codec readline. u'82, \u201a' AttributeError 'unicode' object has no attribute 'decode' u'83, \u0192' AttributeError 'unicode' object has no attribute 'decode' u'84, \u201e' AttributeError 'unicode' object has no attribute 'decode' u'85, \u2026' AttributeError 'unicode' object has no attribute 'decode' u'86, \u2020' AttributeError 'unicode' object has no attribute 'decode' u'87, \u2021' AttributeError 'unicode' object has no attribute 'decode' u'88, \u02c6' AttributeError 'unicode' object has no attribute 'decode' u'89, \u2030' AttributeError 'unicode' object has no attribute 'decode' u'8a, \u0160' AttributeError 'unicode' object has no attribute 'decode' u'8b, \u2039' AttributeError 'unicode' object has no attribute 'decode' ------------------------------------------------------------------------ From boud at valdyas.org Sat Nov 16 06:50:52 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Sat, 16 Nov 2002 12:50:52 +0100 Subject: keyword arguments and ** References: <3dd51831$0$13642$e4fe514c@dreader6.news.xs4all.nl> Message-ID: <3dd6324b$0$54400$e4fe514c@dreader7.news.xs4all.nl> Alex Martelli wrote: > > Usual problem: when an argument (here, fields) has a default > value that is mutable, that value is determined ONCE, when the > def statement executes -- then that single value stays around > (the function object references it), and if you mutate it you > get such a "memory effect". > > Usual fix: > >>>> def f(fields=None, **args): > ... if fields is None: fields = {} > ... print fields > ... fields.update(args) > ... print "XXX", fields > Thanks. I feel even sillier now :-). -- Boudewijn Rempt | http://www.valdyas.org From bokr at oz.net Tue Nov 5 21:59:53 2002 From: bokr at oz.net (Bengt Richter) Date: 6 Nov 2002 02:59:53 GMT Subject: [OT] You've still got an hour to vote on the (US ;-) West Coast Message-ID: Do it. I'm off... Regards, Bengt Richter From questions at smartcardware.com Sat Nov 23 10:39:14 2002 From: questions at smartcardware.com (smartcardware.com) Date: 23 Nov 2002 07:39:14 -0800 Subject: ~~~ Python Use Question ~~~ Message-ID: <2a001b6.0211230739.13aaf7c5@posting.google.com> Greetings! I am the lead developer in a upcoming game company that will start work on a new game at the beginning of 2003. We are (like everyone else in the gaming industry right now) searching for a scripting language to use in our game. I've heard that Python is a great scripting language with one downfall for game designers/programmers. That is that you must embed your code into Python, instead of convensional scripting langauges where you embed the scripting language into your code. Basically we want to use scripting languages for AI, game items stats, player stats, and a few other things. We'll use an advanced 3d engine (C++) for the rest. What we don't want to have to develope our code around Python, rather develope our code and embed Python to fit our code when and where we desire. Any and all imput would be great! Thanks! Venn Syii From tjreedy at udel.edu Mon Nov 25 14:51:25 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 25 Nov 2002 14:51:25 -0500 Subject: stupid Python/database connection References: <4cce07d5.0211250918.5c97a929@posting.google.com> Message-ID: <--idnWoJVock4n-gXTWcpw@comcast.com> "animeshk" wrote in message news:4cce07d5.0211250918.5c97a929 at posting.google.com... > So . . . how can the decision of what-database-to-use be defferred to > runtime? When writing, say, a BDE app in Delphi, it would be a simple > matter of what alias to use. How is this done in Python? For the runtime selection of what module to import: if the name of the database module you actually want is in a program variable as a string, you can write db = __import__(database_module) If database_module == 'somedbmodule', then this works just like import somedbmodule as db Terry J. Reedy From tundra at tundraware.com Sat Nov 9 18:48:05 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: 09 Nov 2002 23:48:05 GMT Subject: Tkinter listbox selection handling Message-ID: Hmmm ... I have Tkinter listbox created like this: class myUI: def __init__(self, root): # Setup the visual elements self.hSB = Scrollbar(root, orient=HORIZONTAL) self.vSB = Scrollbar(root, orient=VERTICAL) self.listbox = Listbox(root, foreground = FCOLOR, background = BCOLOR, font = (FNAME, FSZ, FWT), selectmode=SINGLE, exportselection=0, xscrollcommand=self.hSB.set, yscrollcommand=self.vSB.set, height = HEIGHT, width = WIDTH, ) self.hSB.config(command=self.y.xview) self.hSB.pack(side=BOTTOM, fill=X) self.vSB.config(command=self.DirList.yview) self.vSB.pack(side=RIGHT, fill=Y) self.DirList.pack(side=LEFT, fill=BOTH, expand=1) I instantiate it like this: root = Tk() UI = myUI(root) Then I add a handler: UI.listbox.bind('', handlerfunc) All this works fine up to a point. However, inside handlerfunc(), if I do a UI.listbox.selection_get(,) I get the *previously* selected item back, not the currently selected item. This is also the case if I try using UI.listbox.curselection(). I've worked around this by trashing the idea of an event handler and polling the widget regularly looking for changes, but that is a really ugly solution... This was suggested in some of my reading because there is no 'command' attribute for a Listbox. So, am I missing something here? *Is* there a way to use events to pickup the currently selected Listbox item, or am I stuck doing it with polling? TIA, ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From johnroth at ameritech.net Sat Nov 16 08:23:23 2002 From: johnroth at ameritech.net (John Roth) Date: Sat, 16 Nov 2002 08:23:23 -0500 Subject: My Python Editor "ActiveState Python 2.2 - Python Win IDE" does not refesh References: Message-ID: "kathik thyagarajan" wrote in message news:mailman.1037422524.22358.python-list at python.org... Hi Guys, I am having the trouble of having to exit the editor every time I make some changes to my code in order to execute the code using the "ActiveState Python 2.2 - Python Win IDE" editor. DOS work fine but the problem with DOS is that and other editors like gvim is that I am unable to debug my code with them. Is there any problem with theinstallation or is there any other patch to be added? Does any one know. Other wise I have to clos a bunch of files, open them, set break points, make changes, close them again and keep iterating the whole thing. Eagerly awaiting replies. Karthik Does that for me, too. I suspect you may have to explicitly refresh a new module, but I haven't bothered figuring out how because I tend to do XP style test first and have never bothered with the debugger. I just keep a DOS window open and have a little script that runs the test module. A couple of clicks, five keystrokes and I know whether the last change worked or not. John Roth From Paul.Moore at atosorigin.com Mon Nov 11 06:42:58 2002 From: Paul.Moore at atosorigin.com (Moore, Paul) Date: Mon, 11 Nov 2002 11:42:58 -0000 Subject: Efficient scanning of mbox files Message-ID: <16E1010E4581B049ABC51D4975CEDB88619932@UKDCX001.uk.int.atosorigin.com> I have an application which needs to scan through a number of large mbox files, preprocessing them to allow later efficient access to individual messages by index and/or message-id (I'm writing a news server which serves up mbox archives as newsgroups). I'm happy doing a preprocessing step of the file, but I want this to be reasonably efficient (it's only startup time, but I don't want it to be a *lot* of startup time), and I don't want to store masses of data in memory (some of these files are *big*). The memory constraint makes storing messages in memory a non-starter. I am currently scanning the mbox by hand, reading line by line, and storing the file offset and length of each message (detecting "From" delimiters). I can then use seek() and read() to grab messages on demand. By reading each message into an email.Message instance during the preprocessing step, I can also get the message-id for an id->index lookup dictionary, and also to get message headers for "overview" type information without needing to go back to the message. This works OK, but I wonder if it's the most effective way. I considered using the "mailbox" module, but couldn't find a way with this of getting file offsets. Also I have to do my own "while 1/ readline" loop, as "for line in file" uses buffering which makes the results of the tell() function invalid... If anyone has any suggestions for improvement, I'd love to hear them. I've considered slurping the whole file into RAM and splitting it up and analyzing like that, but I've not tried it yet. My instinct is that this would complicate the code, and could have large memory overheads (building lots of big strings) for little speed improvement. Thanks for any help, Paul. PS Here's the code. Return value is a tuple of filename, number of articles, and a list of file positions which are the start/end of articles (so there are n+1 entries in the list). This version doesn't use email to get message-id or header values, and so is simpler and more efficient than what I'll end up with... def add_group(self, id, file): print "Opening file", file, "for group", id fp = open(file, "rb") posns = [] oldpos = 0 n = 0 while 1: line = fp.readline() if not line: break if FROM_RE.match(line): n += 1 posns.append(oldpos) oldpos = fp.tell() fp.close() posns.append(oldpos) print "Group", id, "- articles(posns) =", n, len(posns) self.groups[id] = (file, n, posns) From LogiplexSoftware at earthlink.net Mon Nov 18 18:27:51 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 18 Nov 2002 15:27:51 -0800 Subject: Hmm... An idea: if a,b==c,d: In-Reply-To: References: Message-ID: <1037662070.27904.232.camel@software1.logiplex.internal> On Mon, 2002-11-18 at 14:58, Richard Dillingham wrote: > > Instead, (a, b) >= (c, d) is defined as (a>c or (a==c and b>=d)). > > I just keep reading that again and again and thinking "WTF? Why? Wha...." > > *shudders* > > Now I'm sorry I asked... Just in case it isn't clear, it isn't defined that way /in the interpreter/. Andrew was merely stating that the two statements are /equivalent/ in this particular example (otherwise, think of the mess when there are more than two elements in the tuple). Instead of thinking of a tuple as a coordinate, think of it as an immutable list (which is basically what it is). Then the comparison makes more sense. It's the same comparison used on other Python sequences (lists, tuples, strings, etc). -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 -------------- 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 paul.osman at sympatico.ca Tue Nov 5 19:16:56 2002 From: paul.osman at sympatico.ca (Paul Osman) Date: Tue, 5 Nov 2002 19:16:56 -0500 (EST) Subject: What's wrong with my for loop? In-Reply-To: <20021106000730.64582.qmail@web21208.mail.yahoo.com> Message-ID: On Tue, 5 Nov 2002, Mindy wrote: > Hey, I got such errors in runing my small program. The > attachment is my program named ld.stat.py and the > following is the error: > > % ld.stat.py > File "ld.stat.py", line 23 > for name in names > ^ > SyntaxError: invalid syntax that's because your line should read: for name in names: note the colon... > As there are no {} working as the limitators of > functions or blocks(as in C or Perl), what we can > control this is only by indentation, right? that is correct. Python uses whitespace to group statements. > > ===== > Cheers > -Mindy -- Paul Osman posman at linux.ca http://paul.codecipher.com From -$P-W$- at verence.demon.co.uk Tue Nov 12 08:02:32 2002 From: -$P-W$- at verence.demon.co.uk (Paul Wright) Date: 12 Nov 2002 13:02:32 -0000 Subject: HTML email marketing tool References: Message-ID: In article , =?big5?q?Terence=20Ng?= wrote: >I guess it cannot consider as spaming if I provide the >option to remove from the mailing list. It is spamming if you email people with whom you have no previous business relationship. It is spamming if you send mail to addresses you have collected from the web or newsgroups. It is spamming if you subscribe people to a list using a form on your web page without confirmation that they wanted to join your list (see for details of how to run a mailing list). It is still spamming even if you include a remove link, since most people know that remove links only confirm your address as "live" to a spammer, who will then spam that address even more. Doing any of these things will get you into a blacklist like the RBL or SPEWS . I'm-not-SPEWS-when-there's-an-"R"-in-the-month-ly yours, -- Paul Wright | http://pobox.com/~pw201 | From anton at vredegoor.doge.nl Mon Nov 18 14:09:33 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Mon, 18 Nov 2002 20:09:33 +0100 Subject: Berliner Python-Stammtisch 20.12.02 18:00 mit Stollen References: <2E7096CE-E74E-11D6-8765-00039345C610@darwin.in-berlin.de> <3DB915CB.5080908@tismer.com> <3DBD58CD.2080606@tismer.com> Message-ID: On Mon, 18 Nov 2002 14:12:25 +0100, Christian Tismer wrote: >... zur Ergreifung weiterer unidentifizierter Pythonen ... Ist mann im Kreis Aachen noch einigermassen sicher? :-) Anton. From dsavitsk at e-coli.net Fri Nov 1 01:26:42 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Fri, 01 Nov 2002 06:26:42 GMT Subject: Python 2.1, COM (Excel), and Threads... References: <24420294.0210311031.18f8b3e0@posting.google.com> Message-ID: "Stephen" wrote in message news:24420294.0210311031.18f8b3e0 at posting.google.com... > Hi - > > I am trying to get a threaded job server running that will thread > scripts to manipulate various MS office apps. running various MS office apps automatically can also be a recipe for disaster. Word, in particular, can only have one instance going at a time else it will do all the work into the same document. that is, if there are 2 scripts automating word they will both be automating the same document, and likely crashing it. to this end, i have been working on a spooler for word automation. you can find the gist at http://ecpspooler.sourceforge.net. contact me if you are interested. -doug From dag4004 at free.fr Tue Nov 5 12:25:03 2002 From: dag4004 at free.fr (dag4004) Date: Tue, 5 Nov 2002 18:25:03 +0100 Subject: Search a SOAP module Message-ID: <3dc7fe24$0$5127$626a54ce@news.free.fr> Hello, I search a SOAP module, does some one use some thinks which work ? Thanks From dave at boost-consulting.com Tue Nov 26 19:06:37 2002 From: dave at boost-consulting.com (David Abrahams) Date: Tue, 26 Nov 2002 19:06:37 -0500 Subject: Python - Boost - Cygwin linker error References: Message-ID: Jason Tishler writes: > St?phane, > > On Sat, Nov 23, 2002 at 07:42:28PM -0800, St?phane Vaxelaire wrote: >> I get an error at link time that appears to occur between Boost code >> and python lib. Here is the output : > The above can be solved by compiling the code that refers to > _Py_NoneStruct with -DUSE_DL_IMPORT. This will cause _Py_NoneStruct to > be declared so that it can be imported (without auto-import) from the > Cygwin Python import library. > > Note that this occurs automatically for Distutils built shared > extensions. If Boost.Python is built using a different mechanism, > then -DUSE_DL_IMPORT will have to be specified manually. Naw, Boost.Python's own build mechanism (Boost.Build) also adds -DUSE_DL_IMPORT automatically for Cygwin. This only happened because St?phane decided to build things ``manually'' in the first place ;-) -- David Abrahams dave at boost-consulting.com * http://www.boost-consulting.com Boost support, enhancements, training, and commercial distribution From anton at vredegoor.doge.nl Sun Nov 3 09:54:15 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sun, 03 Nov 2002 15:54:15 +0100 Subject: Foot in mouth disease References: Message-ID: On 1 Nov 2002 23:06:06 -0500, aahz at pythoncraft.com (Aahz) wrote: >So I've been having a friendly argument for a long time with a friend of >mine who's a real Java booster. The current iteration was sparked by a >discussion of extreme programming, where along the way I repeated what >some people here have mentioned about Python being easier to refactor >than Java. She asked me what -- if any -- Java-based tools were used by >the experienced Java programmers who made that claim. She thinks that >those tools are superior to plain text editors (which are really all >that's needed for Python). > >Anyone wanna help me out here? Three step solution: 1) Eat the food ;-) 2) Write a refactoring tool for Java using Python 3) Ask her for a date Just my idea of a cure: Do not fight the disease but concentrate on healthy activities. Anton. From ktilton at nyc.rr.com Tue Nov 19 12:09:29 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Tue, 19 Nov 2002 17:09:29 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: <3DDA7126.6090308@nyc.rr.com> A. Lloyd Flanagan wrote: >>In summary, Lisp's problem is that it had no BDFL. >> > > Exactly. BDFLs are great, but (somehow) Lispers got together and managed to carve out Common Lisp and an ANSI spec for it. That's our BDFL. > In addition, Lisp proponents have historically been > contemptous of attempts to run efficiently on available hardware, Well, the present is part of history, so this is wrong. Every CL compiles, including optimizations, and in fact some CLs /only/ compile: what seems like an interpreter hides compile-on-the-fly. > In addition, I think Common Lisp killed a lot of Lisp's momentum. No, this was important to its second life. It took many microscopic communities and made them into one tiny community (which at least has the critical mass to survive and support many vendors). And the CL spec, like I said, is our BDFL. > Much of Lisp's power comes from the application of just a few basic > language elements; True, but I am not sure I would like to do without in CL. > CL added an incredible amount of complexity in the > process of including each and every favorite feature of all the major > players in the Lisp market. well, that's how you bring divergent branches back together, but i disagree that /a lot/ translates to incredibly complex. I was very productive days after starting on CL. All that changed as I learned more and more was that my code became better and I became even more productive. > Check out Guy Steele's Common Lisp. > Python has the power but hasn't (yet at least) been drowned in > complexity. Give it time. :) btw, I am here because I just started porting a little CL hack of mine to Python, thought I'd check out clp. -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From wurmy at earthlink.net Mon Nov 4 18:32:47 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Mon, 04 Nov 2002 23:32:47 GMT Subject: Str and instance concatanation error References: Message-ID: <3DC70515.4050709@earthlink.net> Newt wrote: > File "D:\py_stuff\globals.py", line 96, in save_char > file.write('' + self.creator + '') > TypeError: cannot concatenate 'str' and 'instance' objects The error says it all: '' and '' are strings, self.creator is not. They cannot be concatenated. Use something like str(self.creator) if possible. Or, in self.creator's class, define __add__ and __radd__ methods that allow concatenating of strings. HTH, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ Kaa:: http://www.awaretek.com/nowak/kaa.html From peter at engcorp.com Sun Nov 3 15:30:01 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 03 Nov 2002 15:30:01 -0500 Subject: Parsing & question about usages off classes! References: Message-ID: <3dc58764@news.sentex.net> Frans wrote: > Hi, > > I want to put each line off a logfile in a different class. But I cant > seem to, dynamicly, create new classes. I am having problems using > variables when creating new classes. > > class TEST: > pass > > x=0 > while x < 10: > A + "" + x = TEST() > x=x+1 > > Something like that is what I want :) > > Having A1 A2 A3 A4 etc. etc. as TEST classes. Building on Alex' good advice, here's what you really wanted to do (I'm guessing) in the first place. You may need to learn more about Python to make use of these results: myObjects = {} for x in range(10): myObjects['A' + str(x)] = TEST() print myObjects print myObjects['A6'] OR this one, where they don't each get their own "name": myObjects = [] for x in range(10): myObjects.append(TEST()) print myObjects print myObjects[3] If this looks remotely like what you wanted, then you should know you are not creating new *classes*, but only new instances of the one class, or new "objects". You might also want to go back and rethink the whole approach. You say you want each line to go into a different "object" (if I may rephrase your request), but what do you plan to do with those objects? Maybe you can take a simpler approach to getting the task done. What's your goal? -Peter From skip at pobox.com Thu Nov 21 11:16:47 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 21 Nov 2002 10:16:47 -0600 Subject: Does Python (or psyco) already do this optimisation? In-Reply-To: <3DDC9BA9.9070309@rogers.com> References: <3DDC9BA9.9070309@rogers.com> Message-ID: <15837.1775.356901.890797@montanaro.dyndns.org> Mike> Any idea (anyone) whether the outlined approach has been attempted Mike> for global-variable access optimisation? i.e. is this an explored Mike> and deemed-dead path, or something new? Check PEPs 266 and 267. I don't think it's necessarily dead-end. It's proven to be a damned hard problem so far though. Jeremy and I led a developer's day session on optimization at the February 2002 Python conference. Jeremy's approach has come much farther than mine since then (as in I didn't do anything). Check the python-dev archives for the February-April 2002 timeframe for more discussion on the subject. -- Skip Montanaro - skip at pobox.com http://www.mojam.com/ http://www.musi-cal.com/ From Padraig at Linux.ie Mon Nov 11 07:59:55 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Mon, 11 Nov 2002 12:59:55 GMT Subject: referencing disjoint array indexes References: Message-ID: <3DCFA951.5030003@Linux.ie> Gerhard H?ring wrote: > In article , Padraig Brady wrote: > >>Hi, >> >>Is there any way you can do something like >> >>size, mtime = os.stat()[8,6] > > If there isn't any better way, you can easily implement a little helper function yourself: > >>>>def seqfromidxs(seq, *idxs): >>> > ... lst = [] > ... for idx in idxs: > ... lst.append(seq[idx]) > ... return lst > ... Well you should probably return a tuple rather than a list? But problems with this is that you do it manually (slow/messy). Also it doesn't support slicing. In general it would by nice (IMHO) to support: size, times = os.stat("/bin/vi")[6,7:] Maybe it's crud, but I've found myself wishing the functionality was there a few times (not just for os.stat). thanks, P?draig. From kalmas at udm.ru Sat Nov 2 01:29:56 2002 From: kalmas at udm.ru (Oleg Leschov) Date: 2 Nov 2002 06:29:56 GMT Subject: threading questions Message-ID: Using python 2.2, I am trying to implement fairly stable application in Python that is heavily relies on threads. There are currently two problems I have with this task. 1. I want to be able, using whatever the threading.get_ident() returns (perhaps), to determine the state of thread (does it still run or not), and to kill the thread, in case that it, for example, is waiting for some data from socket whose network interface has died unexpectedly. For now I rely on the behavior of linux, where when main thread quits, all its children threads are also being killed. But to me, it would be nicer to kill them by hand.. 2. I want to process user interrupt (ctrl-c), which does not work at all while running multiple threads, by setting some event so that main thread would quit. How do I register handler for this? btw, are there any signals available on windows, and if yes, where are they listed? From martin at v.loewis.de Mon Nov 4 17:18:21 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 04 Nov 2002 23:18:21 +0100 Subject: old SimpleXMLRPCLib classes References: Message-ID: Robin Becker writes: > well I'll gladly contribute testing/examples, but my documentation > skills are minimal if not negative. Also I have precisely two working > examples to boast about. > > Are there competing proposals for this kind of functionality? All that is needed is a description of what Brian's patches do, in the same style that libsimplexmlrpc.tex uses. Regards, Martin From ken at perfect-image.com Wed Nov 6 12:35:57 2002 From: ken at perfect-image.com (Ken Godee) Date: Wed, 6 Nov 2002 10:35:57 -0700 Subject: wxPython or PyQt In-Reply-To: Message-ID: <3DC8F08B.16542.D93852@localhost> Serge, I've just been going thru this same question myself trying to decide which way to go. wxPython / PyQt and have decided to go the PyQt way for my first adventures in python/GUI. I've both running on my system now Here's a couple of things I've noted..... wxPython is a wrapper around wxWindows which is a wrapper around (ie.) GTK. PyQt is a wrapper around Qt. Installing and Compiling all the way to wxPython was a pain. There's really no "free" ide like qtdesigner in wxPython. PyQt's code seems cleaner and easier to translate the c++ doc's. PyQt's (Qt) widgets seem better, ie... take a look at the "MDI" for both, opps, you can't, there isn't one for wxPython running on Linux only for win. ie. wx only takes on the native look and feel of the base system vs Qt's builtin themeable designs, etc...... I think your right, the lic. issues was the hardest thing that keep drawing me back and forth when trying to decide between the two. But.... when I really thought about it, I'll really be working only on linux anyway. The user base for wxPython is quite good and is being updating. Anyway, I'd be interested in hearing what other people thing too. > Hi, guys, > I'm a user of PyQt and I believe this library is very nice, it > supports Xft, it has very flexible signal-slots mechanism, and > enormous collection of widgets and other useful classes, but I > noticed that many projects use wxPython instead. > > What are the advantages of wxPython over PyQt or it's just a matter of > licensing policies: wxPython is free on every platform it supports, > meanwhile PyQt (or Qt) is completely free only under X? > > Looking forward to hearing from you. > > -Serge > > > -- > http://mail.python.org/mailman/listinfo/python-list > From max at alcyone.com Thu Nov 28 14:48:44 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 28 Nov 2002 11:48:44 -0800 Subject: Name of current method References: Message-ID: <3DE6731C.D989C931@alcyone.com> Thomas Guettler wrote: > How can I get the name of the method which is > executed? > > Example: > > def mymethod(self): > print self.__magic__ > > --> "mymethod" Function (and thus method) objects have a __name__ attribute (at least in Python 2.2.2) which can be used. But instead you seem to want to be inside a method inside some class and decide where you are. I'm not aware of any builtin facility for this, but obviously you could do it manually: class SomeClass: ... def myMethod(self, ...): self.where = 'myMethod' ... def myOtherMethod(self, ...): self.where = 'myOtherMethod' ... But this approach obviously isn't very elegant. It sounds like if you think you need this facility, there's probably a better way to accomplish whatever it is you're setting out to do. What exactly do you think you need this for? -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Some mistakes we must carry with us. \__/ Speaker-to-Animals Blackgirl International / http://www.blackgirl.org/ The Internet resource for black women. From markus.vonehr at ipm.fhg.de Fri Nov 29 05:48:57 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Fri, 29 Nov 2002 11:48:57 +0100 Subject: py2exe and PIL prob Message-ID: <3DE74619.497CB50C@ipm.fhg.de> Hi, I am opening an image using PIL with: from Image import * self.mi = open(filename) Everything is alright opening the images in two different programs. After using py2exe I have two cases/errors: 1. File "Tkinter.pyc", line 1285, in __call__ File "corr.pyc", line 178, in openImage File "Image.pyc", line 949, in open File "Image.pyc", line 204, in init File "ntpath.pyc", line 408, in abspath File "imputil.pyc", line 98 in _import_hook File "", line 52, in _import_top_module File "imputil.pyc", line 207, in _import_top File "imputil.pyc", line 258, in _import_one File "", line 161, in get_code File "Image.pyc", line 927, in open ValueError: bad mode 2. Another program: Exception in TKinter callback Traceback (most recent call last): File "Tkinter.pyc", line 1285, in __call__ File "BioChip.pyc", line 260, in Load File "Image.pyc", line 960, in open IOError: cannot identify image file So everything is OK with the unpacked program, but after using py2exe it doesn't work any more. What can I do then? I want to create a shipping version. Any hints? Markus From patrickw106 at yahoo.com.au Sun Nov 10 20:41:00 2002 From: patrickw106 at yahoo.com.au (Patrick W) Date: 11 Nov 2002 12:41:00 +1100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3dce5e2f$0$35917$edfadb0f@dread13.news.tele.dk> Message-ID: <87of8wkhn7.fsf@key.localdomain> Alex Martelli writes: > It's exactly BECAUSE every newcomer longs for some weird set of feechurs > that are better done without, that a language that lets such newcomers add > all the weird things, changing the language itself and turning it from a > (hopefully) well-designed whole to a hodge-podge, is not going to be > popular with the masses. Some brilliant individuals -- a tiny minority -- > are no doubt going to use such power wonderfully well, building several > different complex, specialized languages. The rest of us, the vast > majority of the human race, is BY FAR best served by having to use one > well-designed language rather than by letting each make up their own. > > *Simplicity* is an often-forgotten but nevertheless crucial criterion of > good design. A slightly harder-to-express but also important criterion is > *unity of vision* -- a system should feel like an integrated whole, not as > a disparate jumble of parts. Python meets both criteria. I believe that > introducing powerful-enough macros to Python would make it more likely than > not for most programmers to break both criteria, and thereby probably doom > Python, too, to eventual obscurity. I agree with everything you say here w.r.t. Python. I think it's a wonderfully simple and powerful language, and its design is in good hands. I don't particularly expect or want Python to acquire a macro facility. I like it just as it is. With regard to Lisp, though, I don't believe that macros preclude simplicity or unity of vision, provided they're used sparingly and intelligently. An average programmer can make a horrible mess with macros, true enough. But the other side of the coin is that an intelligent language designer (or group of designers) can design and implement new macros that blend seamlessly with the existing language. The base language can be adapted and extended to support new programming styles (or paradigms) as they arise, without the need to rewrite the core language and the guts of its implementation. These new macros can be standardised and used by mere mortals (like me) in due course. For application programmers, I don't see macros as a huge selling point. I tend to think of Lisp as an extremely powerful and pleasant high-level language, much like Python, but with a different set of strengths and weaknesses. When you say that a (Python) macro system might eventually doom Python to obscurity (too!), you may be right. I don't want to argue that. However, the implication that Lisp is (already) doomed to obscurity (if that's indeed what you meant), is very questionable. I think it's way too early to call. My own hunch is that, fifty years from now, there will be no programming language or data representation notation that closely resembles any of today's popular languages, BUT there will probably be something that resembles Lisp. That is, unless we make unexpected advances in how programming is done, there will still be a language in which code and data are interchangeable, a language that can manipulate itself in itself, and extend its core functionality without needing to be redesigned and reimplemented. I think you're absolutely right when you say that simplicity is a crucial criterion of good design. Unlike most people (it seems), I believe Lisp possesses this innate beauty and simplicity. Common Lisp is a *large* language, to be sure, but I don't believe it is complicated in the way that, say, C++ is complicated. It has a simple core, and a lot of powerful functionality flowers out from that simple core, just like an intricate mandala or fractal pattern is created out simple motifs. Lisp and Python are my two favourite languages today, by a long shot. I enjoy them both for different reasons (lots of overlapping ones too). I suspect that many Pythonistas would have a *lot* of fun with Lisp. Python fits our brains, partly because it is built on already-familiar concepts but allows us to work some black magic as well. Lisp does this too but, if you're so inclined, it's a great language for extending and maybe reconfiguring your (programming) brain in new directions. Personally: if I have a job to do, I use Python wherever possible. It's fun, convenient, easy, and it has all the libraries I need. If I have an unusual idea that I'd like to experiment with, I use Lisp or Python, depending on the idea. >From a non-personal perspective, though, I believe that Lisp offers more potential for real innovations in the way we will represent and manipulate "knowledge" in the future. From tdelaney at avaya.com Wed Nov 27 00:23:34 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 27 Nov 2002 16:23:34 +1100 Subject: Python Tutorial Was: Guido's regrets: filter and map Message-ID: > From: Grant Edwards [mailto:grante at visi.com] > > Technically, you can do everything with nothing but binary > NAND operators, > so things like addition, subraction, etc. aren't really required. That > doesn't make it a good idea to eliminate things just because > they can be > replace by more complicated sets of operations. Hey - there ain't nothin' less complicated than a binary NAND ... ;) Tim Delaney From robin at jessikat.fsnet.co.uk Fri Nov 15 11:30:03 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 15 Nov 2002 16:30:03 +0000 Subject: wrapping all class methods In-Reply-To: References: Message-ID: In message , Mark McEahern writes >[Robin Becker] >> What's the 'proper' pythonic way to do this kind of global wrapping? > Thanks very much for the pointer, I'll have a look. >Hi Robin, I don't know the answer, but I think aspect-oriented programming >provides some ideas. Pedro Rodriguez has posted working code for doing AOP >to the list: > >http://groups.google.com/groups?selm=pan.2002.01.22.15.52.49.832551.1637%40c >lub-internet.fr > >Perhaps, if nothing else, Pedro's code may give you some ideas? I'd be very >interested to hear what you come up with. > >What you're trying to do can be done with metaclasses fairly easily--but >that requires (afaik) modifying the modules you want to wrap. Which makes >it not a very good strategy for AOP (as Pedro has pointed out). See this >thread: > >http://groups.google.com/groups?selm=mailman.1025278420.26105.python-list%40 >python.org > >Cheers, > >// mark > >- > > -- Robin Becker From max at alcyone.com Wed Nov 6 14:11:15 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 06 Nov 2002 11:11:15 -0800 Subject: idiom for initialising variables References: <3dc964fa$0$12989@echo-01.iinet.net.au> Message-ID: <3DC96953.3BFF23EB@alcyone.com> Rob Hall wrote: > I'm just wondering on the correct python idiom for initialising > variables. > I see some code like this: > > class myClass: > self.a = 1 > def __init__(self): > ...more stuff here This is illegal. You probably meant: class MyClass: a = 1 def __init__(self): ... > class myClass > def __init__(self): > self.a = 1 > ...more stuff here > > Which is the correct idiom? or is there a subtle difference I am > missing? In the former corrected version, the variable a is a class variable; that is, it's shared by all instances. In the latter, it's an instance variable, and is specific only to one instance. >>> class C: ... s = 1 ... def __init__(self, x): ... self.x = x ... >>> c1 = C(2) >>> c2 = C(3) >>> c1.x 2 >>> c2.x 3 >>> c1.s 1 >>> c2.s 1 >>> C.s = 10 # note: changing the class variable, not an instance one >>> c1.s 10 >>> c2.s 10 -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ God grant me to contend with those that understand me. \__/ Thomas Fuller Polly Wanna Cracka? / http://www.pollywannacracka.com/ The Internet resource for interracial relationships. From jfontain at free.fr Tue Nov 12 07:03:39 2002 From: jfontain at free.fr (Jean-Luc Fontaine) Date: 12 Nov 2002 04:03:39 -0800 Subject: ANNOUNCE: tclpython-2.1 Message-ID: <4244613b.0211120403.3766711b@posting.google.com> ### CHANGES ### --- version 2.1 --- - tclpython2 renamed to tclpython and updated for Python 2.2.1 as found in a Redhat 8.0 distribution - tclpython (for Python 1.5) dropped - prevent automatic 'import site' on a new thread, since it makes the program hang errors from Python were not always caught and properly reported to the Tcl interpreter tclpython2 binary rpm was wrongly compiled against another installation on my computer, which caused string I/O module loading failure and a core dump ### README ### tclpython version 2.1: a Python package for Tcl This package allows the execution of Python (version 2.2) code from a Tcl interpreter, as in: package require tclpython set interpreter [python::interp new] $interpreter eval {print("Hello World")} python::interp delete $interpreter You can actually create several Python interpreters this way, if the tclpython package was linked against a Python library compiled with threads support, otherwise only 1 Python interpreter can exist at a time. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ### you may find it now at my homepage: http://jfontain.free.fr/tclpython-2.1.tar.gz http://jfontain.free.fr/tclpython-2.1-1.i386.rpm http://jfontain.free.fr/tclpython-2.1-1.spec http://jfontain.free.fr/tclpython.htm Jean-Luc Fontaine (http://jfontain.free.fr/) From rkempf at rightnow.com Fri Nov 22 12:10:43 2002 From: rkempf at rightnow.com (Kempf, Reed) Date: Fri, 22 Nov 2002 10:10:43 -0700 Subject: very large inserts Message-ID: Thanks for the input and I looked into it and I believe that the executemany basically simulates a for loop when doing inserts. It still does the inserts one by one instead of one massive insert which you can do in mysql. I do not believe this is possible in dealing with an oracle database is because of rollback segments. If you were able to do a massive insert such as: insert into table (col1, col2, col3, col4) values (1,2,3,4),(2,3,4,5),(3,4,5,6),(4,5,6,7); You would have to rollback the whole insert statement which would include all of the rows plus the mysql insert statement is not ANSI complient. The last statement problable sums up the problems I am having. oh well, I was just looking for a cheap and dirty python trick to get around this. Thanks ReedK -----Original Message----- From: Mike C. Fletcher [mailto:mcfletch at rogers.com] Sent: Tuesday, November 19, 2002 1:30 PM To: Kempf, Reed Cc: python-list at python.org Subject: Re: very large inserts Isn't that what the executemany method in DBAPI is intended to allow? *executemany*(operation,seq_of_parameters) Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence |seq_of_parameters|. Modules are free to implement this method using multiple calls to the |execute()| method or by using array operations to have the database process the sequence as a whole in one call. That is, the DB may optimise it, or it may have to go through execute, but this is where the optimisation comes if it's available. If I understand correctly, you'd create a parameterised insert: insert = """INSERT INTO table (col1, col2, col3, col4) values (%1, %2, %3, %4)""" And then call executemany( insert, my_values_list ) Good luck, Mike Kempf, Reed wrote: >Hello, > >My name is Reed and I am new to the list as of today. I have been working >with python for about 6 months and I have an issue where I am stumped. > >My background is in python, pl/sql and oracle database management with a >touch of mysql database management. > >Anyway, I know in mysql you can do a bulk insert or an insert where you can >insert many records with one insert statement like this: > >MYSQL - insert into table (col1, col2, col3, col4) > values (1,2,3,4),(2,3,4,5),(3,4,5,6),(4,5,6,7); > >In oracle, you would have to do 1 insert at a time unless you are using >pl/sql in which you can do a bulk insert (as far as I know). > >ORACLE - insert into table (col1, col2, col3, col4) > values (1,2,3,4); > insert into table (col1, col2, col3, col4) > values (2,3,4,5); and so forth....... > >My question is, can python simulate a mysql bulk insert in python? > >I am running a linux distribution 6.2 with kernel 2.4.17 and oracle 8.1.7.4 >patch set. I am also using python 2.1. Currently in my python script I >loop through a python dictionary and build an insert statement which I then >pass through a connection to update oracle and move onto the next python >dictionary key. > >This works but I would sincerely like to build one very large insert >statement and pass it to the oracle connection all at once. This is an >issue for me since I am going through sqlnet and across a VPN to update the >oracle database. The less cursors I pass through the connection, the >better. > >Thanks in advance, > >ReedK > > > > -- _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ -- http://mail.python.org/mailman/listinfo/python-list From theller at python.net Fri Nov 15 09:00:51 2002 From: theller at python.net (Thomas Heller) Date: 15 Nov 2002 15:00:51 +0100 Subject: A really bad idea. References: <7h3d6p7xelx.fsf@pc150.maths.bris.ac.uk> <7h3u1ijvv9q.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson writes: > Thomas Heller writes: > > > Michael Hudson writes: > > > > > C without it's library would get a rating of "useless"... guess this > > > is true for most languages, but C more than most. > > > > > Not at all, imo. You just have to write the library yourself, > > and you *can* do it in C. > > I guess... but not portably, surely? Ok, you need a core library of system calls, but then you go. As opposed to Pascal, for example, which I was using when I discovered C. Mainly, because 'write' is a statement (or special syntax), and cannot be written in Pascal itself. > Anyway, it meant to be a serious comment, I didn't doubt that > just the observation that C > puts very little into the language and (relatively speaking) more in > the stdlib. And this is IMO what they did right. Thomas From rmunn at pobox.com Thu Nov 14 17:43:36 2002 From: rmunn at pobox.com (Robin Munn) Date: Thu, 14 Nov 2002 22:43:36 GMT Subject: Open and reading a file... References: Message-ID: Marlon Rea wrote: > Can someone help me with opening and reading a file???? THANK YOU ALL The most common operations: file_object = file('somefile.txt', 'r') # 'r' for read, 'w' for write file_object = open('somefile.txt', 'r') # In Python 2.1 or earlier buf = file_object.read() # Slurp the whole file at once. OR... lines = file_object.readlines() # Split whole file into lines. OR... for line in file_object.xreadlines(): # Only one line at a time. OR... do_something_with(line) for line in file: # Same as above, Python 2.2 and greater do_something_with(line) More information on file objects: http://www.python.org/doc/current/lib/bltin-file-objects.html Let us know if you have any more questions that this answer didn't cover. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From jpb at ApesSeekingKnowledge.net Sat Nov 2 08:13:18 2002 From: jpb at ApesSeekingKnowledge.net (Joe Block) Date: Sat, 02 Nov 2002 13:13:18 GMT Subject: Newbie want Python CGI on Mac OS X10.2 References: Message-ID: In article , sismex01 at hebmex.com wrote: > > From: Mel Bohince [mailto:melbohince at attbi.com] > > > > I'm suspicious of the first line: > > #!/usr/lib/python I've tried #!/usr/lib/ python, #!/usr/bin/python, > > #!/usr/bin/env python > > > > what exactly is this to be? > > > > Ehh, good reason to be suspicious about it! > It's a specially-formatted comment, and it indicates > the pathname of the interpreter. You have to look > exactly where the "python" executable you need is, > and place that full pathname after the "#!". #! /usr/bin/python works fine on OS X 10.2 for me. jpb From mwh at python.net Tue Nov 5 10:49:57 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 5 Nov 2002 15:49:57 GMT Subject: Textbooks on Perl/Python References: <87b0ada6.0211011453.1df4d216@posting.google.com> Message-ID: Alex Martelli writes: > if and when a student manages to work all through it, I think the > student WILL feel pretty confident in their mastery of the subject. ("it" is Deitel & Deitel's Python : How To Program) My concern was that the student might feel confident in the subject after reading the book, but that this might not be justified. It does cover a huge amount of material, but not with enormous depth (at least, not in the chapters *I* tech reviewed). It's also expensive, if you were one of the three or four regular posters to this list who didn't get a review copy :) Cheers, M. -- [3] Modem speeds being what they are, large .avi files were generally downloaded to the shell server instead[4]. [4] Where they were usually found by the technical staff, and burned to CD. -- Carlfish, asr From shadowlord13_1 at yahoo.com Mon Nov 18 18:37:59 2002 From: shadowlord13_1 at yahoo.com (Richard Dillingham) Date: Mon, 18 Nov 2002 23:37:59 GMT Subject: Hmm... An idea: if a,b==c,d: References: Message-ID: > It's better written as: > > if coords[0]<=posx<=coords[2] and coords[1]<=posy<=coords[3]: Hmm.... I just tried that, and am quite amazed to find that it actually works. From cjw at sympatico.ca Fri Nov 22 11:34:16 2002 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 22 Nov 2002 11:34:16 -0500 Subject: Proposal: min(None, x) and max(None, x) return x References: Message-ID: <3DDE5C88.CA8E249@sympatico.ca> An HTML attachment was scrubbed... URL: From mwh at python.net Thu Nov 14 10:07:53 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 14 Nov 2002 15:07:53 GMT Subject: Python documentation in DocBook References: Message-ID: <7h3r8doxkem.fsf@pc150.maths.bris.ac.uk> anton at vredegoor.doge.nl (Anton Vredegoor) writes: > But I can't seem to get past sourceforge. > > It's not that I couldn't get past the sourceforge barrier if I would > like to do so but having to identify myself using a 128 bits security > key conflicts with my - maybe naive - notion of not looking a given > horse in the mouth. The main reason we want you to log in is so we have some chance of giving feedback. There were too many occasions (bugs in particular) where anonymous reporters were asked for more information and failed to give it. Bug reporting and patch submission is a two way process -- knowing who the other end is is a great help. Cheers, M. -- Enlightenment is probably antithetical to impatience. -- Erik Naggum, comp.lang.lisp From andre.hates.spam at ifi.uio.no Sun Nov 24 12:23:30 2002 From: andre.hates.spam at ifi.uio.no (=?ISO-8859-1?Q?Andr=E9_N=E6ss?=) Date: Sun, 24 Nov 2002 17:23:30 +0000 Subject: if : References: Message-ID: Mel Wilson wrote: > In article , > =?ISO-8859-1?Q?Andr=E9_N=E6ss?= wrote: >>When I started learning Python one of the things that surprised me was >>that you couldn't do assignments inside the if clause, e.g.: >> >>if myvar = someFunction(): >> >>My question is, what is the rationale for this? Is it a technical issue? >>Or purely a matter of language design? I'm curious because I'm interested >>in the design og programming languages, not because I want this behavior >>changed in Pyton :) > > We've just been there. groups.google.com can bring it all > back, although I don't offhand remember the subject. Ah, thanks, I found the (a?) thread, and it proved an interesting read. (The subject was: "Conditional Expressions don't solve the problem") Andr? N?ss From pyth at devel.trillke.net Sat Nov 23 12:16:48 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sat, 23 Nov 2002 18:16:48 +0100 Subject: Python IRC dictatorship In-Reply-To: ; from jdhunter@ace.bsd.uchicago.edu on Sat, Nov 23, 2002 at 10:11:30AM -0600 References: <29304.91T434T13743504threeseas@earthlink.net> <743utuoi3l31t8e8tt9v3sncosuk2gqi02@4ax.com> <1239.92T1047T4844497threeseas@earthlink.net> Message-ID: <20021123181648.M11257@prim.han.de> John Hunter wrote: > >>>>> "Timothy" == Timothy Rue writes: > [...] > "variables" in python are a little different than in other programming > languages. python has "names" for objects. This example illustrates > one of the initially surprising ways names work > > x = [] > y = [] of course you mean x = y = [] > x.append(1) > print y > > x and y are just names for the same object (the empty list). When you > change that object referring to it by the name 'x', the changes are > seen when you refer to it by it's other name 'y'. So y now equals > [1]. regards, holger From jacek.generowicz at cern.ch Thu Nov 28 03:36:40 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 28 Nov 2002 09:36:40 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3de1f902$0$695$edfadb0f@dread12.news.tele.dk> Message-ID: Robin Munn writes: > Jacek Generowicz wrote: > > > >> But what I'd really like before I try Lisp again is a special > >> color-highlighting mode [...] > >> where each indentation level would be a different color (foreground? > >> background?). > > > > ... Just curious ... have you ever felt the need for such an > > indentation-based colour-highlighting feature when programming in > > Python? > > > > If so, has the lack of it hindered you from programming in Python ? > > > > If not, what makes you think that it would be useful in Lisp? > > What I'm going off of here is my memory of having to count and re-count > parentheses as I was writing to make sure that I was putting in the > right number of closing parens to finish a structure. To me, this sounds very much like "... my memory of having to count and recount all the spaces, when programming in Python, to make sure that my blocks lined up." > With color-highlighting, I could at least be certain *at a glance* > of which paren was lining up with which. I still fail to see why you think colour highlighting is necessary, or even useful for this. Emacs highlights matching parentheses, brackets and braces for me. I would find it hard to believe that other editors do not have such capabilities. (If your editor cannot provide such a feature, well, it might be time to reconsider your choice of editor.) > Yes, I know I could use % in vi, and that there is some equivalent > function in emacs, but that would be much slower than just seeing > it. I don't understand the distinction. The cursor is at some parenthesis; the matching parenthesis is highlighted. I see it. It's immediate. I can't imagine anything faster. > And the reason for it is because I still don't understand how to > indent *properly* in Lisp, and can't find a good reference on how to > indent properly. Follow the advice you yourself gave upthread: trust the editor on indentation. > Color highlighting would at least give me the visual cues I need > until I learn to indent. Sorry, I still don't get this one. (My editor's indentation and paren matching features give me all the visual cues I need.) > Out of time. Must go. Ditto :-) From grisha at modpython.org Fri Nov 15 13:29:14 2002 From: grisha at modpython.org (Gregory (Grisha) Trubetskoy) Date: Fri, 15 Nov 2002 13:29:14 -0500 Subject: OS X/Darwin dynamic loading expert question Message-ID: <20021115132006.O75349-100000@eden.ispol.com> Hi - Perhaps some darwin/next/osx guru can answer this: Why is it that time.so loads fine when python is running from the command line, but when running from mod_python, I get this: ImportError: Failure linking new module: : dyld: /Users/grisha/www/bin/httpd Undefined symbols: /sw/lib/python2.2/lib-dynload/time.so undefined reference to _PyArg_Parse expected to be defined in the executable /sw/lib/python2.2/lib-dynload/time.so undefined reference to _PyArg_ParseTuple expected to be defined in the executable /sw/lib/python2.2/lib-dynload/time.so undefined reference to _PyDict_GetItemString expected to be defined in the executable /sw/lib/python2.2/lib-dynload/time.so undefined reference to _PyDict_ This is Python 2.2.1, but I used dynload_next.c from Python 2.3 (which has more verbose error reporting, but still doesn't work). I am using the fink distribution (which I patched with a new dynload_next.c). It creates a libpython2.2.dylib which mod_python uses. This is on OS X 10.2.2 is this matters. mod_python.so in this case is a mach-o bundle, which gets dynamically loaded by httpd. Any ideas are more than appreciated. If you need more detail, contact me off-list. Grisha From tdelaney at avaya.com Mon Nov 4 23:49:20 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 5 Nov 2002 15:49:20 +1100 Subject: bug report w\o registering Message-ID: > From: anton at vredegoor.doge.nl [mailto:anton at vredegoor.doge.nl] > > Here's a bug report. I don't want to register at SourceForge now > (browser settings etc.). Sorry for the inconvenience. If you do not submit to sourceforge, the bug report *will* be lost. In any case, this is not a bug - it is documented behaviour. The order of the parameters and return values of os.popen2 and popen2.popen2 are different. Tim Delaney From grante at visi.com Tue Nov 26 19:22:49 2002 From: grante at visi.com (Grant Edwards) Date: 27 Nov 2002 00:22:49 GMT Subject: Making termios.tcdrain() work with threads? References: <3de3c3ad$0$22225$a1866201@newsreader.visi.com> <3de3de67$0$4464$a1866201@newsreader.visi.com> Message-ID: <3de41059$0$22175$a1866201@newsreader.visi.com> In article , Donn Cave wrote: >| if (s == -1) >| return PyErr_SetFromErrno(TermiosError); [...] >| But, before I submit a patch, I've noticed that TermiosError is >| a single, static object (file scope): >| >| static PyObject *TermiosError; >| >| Is this going to cause problems if multiple threads have to >| return errors from the termios methods? > > Don't think so! > > PyEND_ALLOW_THREADS waits for the interpreter lock, so there's > only one thread at a time past that point. PyErr_SetFromErrno > should tuck that data into the thread specific state before > control gets to the ceval loop where another thread could take > over. And I wouldn't think you'd be modifying TermiosError > anyway. I wasn't sure what PyErr_SetFromErrno was doing. I was concerned that it might be modifying and returning the TermiosError object somehow. > As long as 's' is automatic (stack/register) storage, you're > fine. It is. -- Grant Edwards grante Yow! .. I see TOILET at SEATS... visi.com From gkrause at psipenta.com Wed Nov 6 03:30:10 2002 From: gkrause at psipenta.com (Gernot Krause) Date: Wed, 6 Nov 2002 09:30:10 +0100 Subject: Python 2.2.2 on AIX 4.3.3 / AIX 5.1 References: <3dc40e9c_2@news.vo.lu> <3dc6d402_1@news.vo.lu> Message-ID: Hi, you need a ANSI C compiler and the sources from python 2.2. Unpack the archive into temporary directory. Then call: % ./configure Control the output from configure. Afther this edit the File /Modules/Setup and enable/disable external packages which you need. Then call: %make and %make install MfG Gernot > anything special to do, or just the usual "dance" ? > I've never done it before, but hope to do so ASAP with a local UNIX system > engineer. From rmunn at pobox.com Sun Nov 17 14:46:03 2002 From: rmunn at pobox.com (Robin Munn) Date: Sun, 17 Nov 2002 19:46:03 GMT Subject: Reading Bluebird/Superdos Index files References: Message-ID: jmp wrote: > Hello, > > My company has a legacy application originally coded in Business Basic for > the SuperDos operating system by BlueBird. I can read the data files but > the index files are a problem. I've tried the whichdb module and got an > empty string. > > Has anyone else run up against this format or can you give me some > suggestions for deciphering the structure of these index files? > > Thanks, > > John Purser I have no personal experience with this type of file, but Wotsit's Format (http://www.wotsit.org/) often has information about obscure file types. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From Jeff.Dubois at westgroup.com Thu Nov 14 16:29:44 2002 From: Jeff.Dubois at westgroup.com (Dubois, Jeff) Date: Thu, 14 Nov 2002 15:29:44 -0600 Subject: tkinter - tk window remains Message-ID: I am using Tkinter to bring up a ScrolledText window. However, when the user closes the window by clicking on the X button in the upper right of the ScrolledText window the "tk" window remains. Based on documentation I have read I have tried using the .withdraw() method in hopes the tk window would disappear. However the tk window still remains. The code I am using is: rootWin = Tk() rootWin.withdraw() st = ScrolledText(master=rootWin) st.pack(side=TOP, expand=1, fill=BOTH) st.insert(END, "\n\n\n\n THIS IS MAIN WINDOW!\n") rootWin.mainloop() I am using python2.1 on an Windows NT operating system. Any ideas on how to fix this? Thanks! Jeff From roy at panix.com Sun Nov 10 12:30:16 2002 From: roy at panix.com (Roy Smith) Date: Sun, 10 Nov 2002 12:30:16 -0500 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h3k7jlwock.fsf@pc150.maths.bris.ac.uk> <3dce96ad$0$12451$edfadb0f@dread11.news.tele.dk> Message-ID: Jens Axel Sogaard wrote: > I can't remember a link - but if you want to Google for them, > they were calles M-expressions. Not (plus s 1) expressions? :-) From sismex01 at hebmex.com Thu Nov 7 10:21:30 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 7 Nov 2002 09:21:30 -0600 Subject: using the PSF license for one's code Message-ID: > From: David Brown [mailto:david at no.westcontrol.spam.com] > > "Anton Vredegoor" > > > Please stop trying not to start a flame war. > > Meaning please start one? > Liberally sprinkled with negatives, it gives us: "Please Don't Stop Not Trying Not To Not Start A Flame War" which is almost but not quite exactly unlike the original meaning. Sounds like a telegraph. -gustavo pd: Have a nice thursday! ;-) From martin at v.loewis.de Tue Nov 12 08:23:25 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 12 Nov 2002 14:23:25 +0100 Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> Message-ID: DaveP writes: > Is there a source form example of the py docs, > and perhaps a statement of what is required of the processing? Please have a look at http://www.python.org/doc/current/doc/doc.html for a specification of the Python documentation format. There are certainly many examples for that, see the Doc directory of the Python distibution or CVS. > Just to take a look at producing docbook from that, > and to see if XML/XSLT/XSL-FO processing chain could do the job > please? What is your question? Regards, Martin From member at dbforums.com Sat Nov 9 21:14:49 2002 From: member at dbforums.com (Tetsuo) Date: Sun, 10 Nov 2002 02:14:49 +0000 Subject: Web based interface References: <2027692.1036809220@dbforums.com> Message-ID: <2029571.1036894489@dbforums.com> Thanks for all the advise. I got Apache and that module, but Apache won't run. We had problems with Web servers, but my mom figured out that localhost got renamed to something else snd got another server to run. But Apache just won't run. My mom tried to connect and it can't. We probably didn't install it right. I'll try again tomorrow. Why, o why don't I have money for a new comp? Everything would work there... -- Posted via http://dbforums.com From aleax at aleax.it Mon Nov 4 07:48:49 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 04 Nov 2002 12:48:49 GMT Subject: Need simple algorithm for newbie References: Message-ID: Jason Tudisco wrote: > I have a list of domains... Some of the domain names in the list look > like this: > > groups.goodle.com > > The information I want is just google.com. I need to know the best way > to do this.. for .com .net .org only.. and to strip the rest of the > garbage.. like in this case.. get rid of groups in groups.google.com This is slightly underspecified. If what you want is: given a list of strings, get for each the longest trailing substring that contains just one dot, assuming each string has at least one dot: newlist = [] for item in oldlist: pieces = item.split('.') newlist.append('.'.join(pieces[-2:])) which can easily be compacted into a list-comprehension: newlist = [ ''.join(item.split('.')[-2:]) for item in oldlist ] This, however, has nothing to say about the "for .com .net .org only" clause in your specs. If that means you only want in the newlist those items which end in .com, .net, or .org, then: of_interest = dict(zip('com net org'.split(), range(3)) newlist = [] for item in oldlist: pieces = item.split('.') if pieces[-1] in of_interest: newlist.append('.'.join(pieces[-2:])) this is getting a bit too hairy for it to make sense to squash it into a list-comprehension. > I need to parse though a huge list so it has to be optimized algorithm > > No need to write complete code.. Just get me in the right direccion.. > Still learning python and I am not sure what would be the fastest way > to go about it.. I'm not sure either -- I just doubt there's much performance to be gained by any of the several other possible approaches, such as finding the second '.' from the right, RE's, and so on. No matter how huge is your list, saveing (say) 10% of runtime is no big deal, and I don't think there can be much more than this in terms of optimization one way or another. The right approach is: first, try the simplest thing that can possibly work (and things can't be much simpler than the above snippets); measure what performance you get this way; if this is unacceptable to the customer, whip out the hotshot profiler to find out where the time is going, and focus on the actual bottleneck (may not be where you'd expect it to be: always MEASURE rather than GUESS). Remember that, for just about any code, being inside a function is a substantial speedup (because local variables are looked up much faster than global ones), and so is using Python 2.3 (not acceptable for production code yet -- it's still a pre-alpha from CVS -- but, very promising for the near-future), or, if you're stuck with 2.2.2 (as you should be for production-level code), so it using -O on your command line. These are "optimization tricks" that aren't tricky, cost just about nothing, and get you a few percent speedup (up to 10% or even more in some cases) as easily as apple pie. Alex From opengeometry at yahoo.ca Fri Nov 15 18:22:58 2002 From: opengeometry at yahoo.ca (William Park) Date: 15 Nov 2002 23:22:58 GMT Subject: Permutations algoritm? References: Message-ID: sismex01 at hebmex.com wrote: >> From: William Park [mailto:opengeometry at yahoo.ca] >> Sent: Friday, November 15, 2002 3:42 PM >> >> sismex01 at hebmex.com wrote: >> > Does anybody have a clear, simple, permutations algorithm >> > in Python? >> >> Would you care to explain this? Permutation can mean >> different things. >> Concrete example might be good... >> > > Of a set of different items 'S', obtain all distinct subsets of 'n' > items where all items in the subset are different. > > So, if I have, for example: > > S = [ 0, 1, 2, 3 ] > > the universe of available subsets of 3 items would be: > > s = [ (0, 1, 2), > (0, 1, 3), > (0, 2, 3), > (1, 2, 3) ] > > the universe of available subsets of 2 items would be: > > s = [ (0, 1), > (0, 2), > (0, 3), > (1, 2), > (1, 3), > (2, 3) ] > > Any help? So, you don't want just a number (ie. P(n,k) or C(n,k)), but instead you want list of sets spat out... Well, using your example, try s, N = [], len(S) for a in range(N): for b in range(a+1, N): for c in range (b+1, N): s.append(a, b, c) -- William Park, Open Geometry Consulting, Linux solution for data management and processing. From bokr at oz.net Fri Nov 8 08:09:09 2002 From: bokr at oz.net (Bengt Richter) Date: 8 Nov 2002 13:09:09 GMT Subject: string.strip References: Message-ID: On Fri, 8 Nov 2002 10:46:32 -0000, Simon Brunning wrote: >> From: Duncan Booth [SMTP:duncan at NOSPAMrcp.co.uk] >> Gerhard H=E4ring wrote:=20 >> > In article , Stano >> > Paska wrote:=20 >>=20 >> >> in documentation: string.strip(s[, chars]) >> >> but in real life strip takes only 1 parameter >> >>=20 >> >> I have python 2.2.2 >> >=20 >> > But you've read the documentation for 2.3. (.../doc/current on >> > python.org).=20 >>=20 >> Did you check your answer before posting? >>=20 >> See >> http://www.python.org/doc/2.2.2/lib/module-string.html#l2h-698 >=20 >Ah, but this is the string *module*. The string method page - > - looks = >right. In >fact, they both do. > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import string >>> print string.strip.__doc__ strip(s) -> string Return a copy of the string s with leading and trailing whitespace removed. >>> print str.strip.__doc__ S.strip([sep]) -> string or unicode Return a copy of the string S with leading and trailing whitespace removed. If sep is given and not None, remove characters in sep instead. If sep is unicode, S will be converted to unicode before stripping >>> ' abc def '.strip() 'abc def' >>> ' abc def '.strip('fa ') 'bc de' >>> string.strip(' abc def ') 'abc def' >>> string.strip(' abc def ','fa ') Traceback (most recent call last): File "", line 1, in ? TypeError: strip() takes exactly 1 argument (2 given) >>> string.strip >>> str.strip >>> Regards, Bengt Richter From wlfraed at ix.netcom.com Wed Nov 27 16:13:26 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Wed, 27 Nov 2002 13:13:26 -0800 Subject: do you guys help newbies?? References: Message-ID: malik m fed this fish to the penguins on Wednesday 27 November 2002 03:48 am: > #chapter 3 test control structures 3.3 > print "hello, this program will tell me how many miles per gallon your > car drives by the \n amount of miles entered by the user along with > the size of his/her tank." > You probably weren't expecting an English lesson either, but that intro is running "... me ... your ... the user ... his/her ..."; implies three different people are involved You are also assuming that one always runs the tank empty before filling it, rather than using the amount of fuel needed to refill the tank. > #initialize variables > totalMilesDriven = 0 #total miles driven > > totalGallonsPerTank = 0 #total gallons per tank > > counter = 0 #bogus counter > Definitely bogus, if the only use is to see if the user entered real values you could just see if the totals are > 0. > > while gallonsPerTank or milesDriven != -1: That is equal to (gallonsPerTank) or (milesDriven != -1) Comparisons don't distribute so it is NOT (gallonsPerTank != 1) or (milesDriven !=1) which is still incorrect, since someone could enter -1 for ONE item, but the other could be a positive number, and would make the statement true. > gallonsPerTank = raw_input("Enter how many gallons your tank > holds, -1 to end:") > milesDriven = raw_input("enter how many miles driven, -1 to end:") > Forgot to convert from string to numeric. > #termination phase > if counter != 0: This looks like a homework assignment, and I'm probably going to violate conventions (don't do their homework). Of course, by the time my message shows up, you'll have seen all the line-by-line critiques. ,----[ /home/wulfraed/t.py ] | import string # probably not needed in the newest versions of Python | # strings have methods so just variable.upper() | # could replace string.upper(variable) | | #chapter 3 test control structures 3.3 | # as recreated by dlbieber/nov 20 2002 | | intro = """ | Hello. This program will tell you how many miles per gallon your | car produces by dividing the amount of miles entered by the | amount of fuel needed to refill the tank. The tank has to | be full at the start of the trip! | """ | | # initialize stuff | sumMiles = 0.0 | sumGallons = 0.0 | | def ProcessSegment(): | global sumMiles #declare the running totals as external to | global sumGallons #the function | | EOI = 0 #initialize End Of Input to false | | userin = raw_input("Enter the miles driven in this segment (Q to end) ") | if string.upper(userin) != "Q": | miles = float(userin) # note: no check for invalid input is | made | userin = raw_input("Enter the numbers of gallons needed to refill (Q to end) ") | if string.upper(userin) != "Q": | gallons = float(userin) # note: no check for invalid input | print "Miles per gallon for this segment: %s" % (miles / gallons) | sumMiles = sumMiles + miles | sumGallons = sumGallons + gallons | else: | EOI = 1 | else: | EOI = 1 #set end of input true | | return EOI #return the End Of Input flag value | | | | if __name__ == "__main__": | print intro | | while not ProcessSegment(): #loop until the function returns EOI true | print "Average miles per gallon: %s" % (sumMiles / sumGallons) | print " " | | if sumGallons and sumMiles: | print "\n\nFinal average miles per gallon: %s" % (sumMiles / sumGallons) | else: | print "*** No data entered ***" `---- -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From logistix at zworg.com Mon Nov 11 17:38:10 2002 From: logistix at zworg.com (logistix) Date: 11 Nov 2002 14:38:10 -0800 Subject: Can python find fibonacci series in a single line of code? References: Message-ID: a_human_work at hotmail.com (Pittaya) wrote in message news:... > My Perl-addicted friend shows me that he can find fibanicci series in > a single line of code. > > perl -le '$b=1; print $a+=$b while print $b+=$a' > > can python do something like this? Guys, c'mon. How are you supposed to lock up your computer when you only print the first 10 numbers? python -c "a,b=1,1;exec('while 1:\n\tglobal a,b\n\tprint a\n\ta,b=b,a+b\n\n')" From gminick at hacker.pl Sun Nov 24 07:49:07 2002 From: gminick at hacker.pl (Wojtek Walczak) Date: Sun, 24 Nov 2002 12:49:07 +0000 (UTC) Subject: rss.py for win32. References: Message-ID: Dnia 24 Nov 2002 12:24:35 GMT, Dave Pawson napisa?(a): >>> http://orchard.sourceforge.net/doc/RSS-parser.py >>> Appears to be *nix only. >> Why do you think that? > Traceback (most recent call last): > File "testrss.py", line 8, in ? > tc.parse("http://www.python.org/channews.rdf") > File "rss.py", line 207, in parse > signal.signal(signal.SIGALRM, self._timeout) > AttributeError: 'module' object has no attribute 'SIGALRM' > Looks very Un win32 like to me... > Not dissimilar to *nix C code? From: Guido van Rossum Subject: Re: Python SIGALRM on WINNT Date: 1998/07/17 Message-ID: <199807171525.LAA24284 at eric.CNRI.Reston.Va.US>#1/1 Sender: daemon at cwi.nl (0000-Admin(0000)) References: <35AF471E.263514D0 at graburn.com> Organization: CWI, Amsterdam Newsgroups: comp.lang.python > Why isn't SIGALRM supported on the WIN NT version of Python. I thought > NT is supposed to be POSIX compliant? Ha, ha, ha. There is a "POSIX subsystem" with very limited Posix compliance -- but you have to choose *either* Posix or Win32 compliance -- guess which one is more useful :-) For lots of money you can buy a much better 3rd party Posix subsystem -- but it still has that same problem. BTW. take a look at asyncore module. -- [ ] gminick (at) underground.org.pl http://gminick.linuxsecurity.pl/ [ ] [ "Po prostu lubie poranna samotnosc, bo wtedy kawa smakuje najlepiej." ] From bokr at oz.net Wed Nov 6 15:24:03 2002 From: bokr at oz.net (Bengt Richter) Date: 6 Nov 2002 20:24:03 GMT Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DC8623B.88753C16@earthlink.net> <3DC8CDDD.7050103@mindspring.com> <3pE8dhAtvNy9EwoQ@jessikat.fsnet.co.uk> <3DC943CF.84A68F32@san.rr.com> <20021106184401.X30315@prim.han.de> Message-ID: On Wed, 6 Nov 2002 18:41:52 +0000, Robin Becker wrote: >In message <20021106184401.X30315 at prim.han.de>, holger krekel > writes >..... >>I am not sure i understand this. Why does python need to enter >>restricted mode? >> >>And doesn't PSYCO also do JIT-alike compiling? That's at least how >>i understood Armin. As he also suggests to rewrite the python-core >>in python to make it faster (with psyco) maybe this could help >>with an c#-interpreter? >> >>wildly-guessing'ly yours, >> >> holger >> >I think that python allows any reference to change type dynamically. > >I don't think C# allows this, but am no expert. The implication is that >C# can be very much more agressive in its JIT compilation. When it sees >x*y for x and y known ints it can compile an integer multiply. Python >only sees x*y and without the type information it is forced to do type >lookup at run time. > >As you point out psyco can do the compilation, but only into the generic >multiply (unless psyco can be hinted in some way). > I would think you could generate machine code speculatively as cached segments based on the assumption that types for variables involved in the segment would not change after the first binding, and then dynamically check a segment cache validity flag and do what it currently does as fallback if the flag was set. The flag would of course have to be set by code that does type-changing rebindings for the particular set of variables used in a segment, so there is some overhead, but maybe not high percentagewise. I imagine you'd have to play with tuning the segment lengths and variable set sizes etc., but if the speculative assumption were right sufficiently often, especially in hot loops with function calls to builtins which would have type-signature-specific machine language variants available for common situations, you'd get a speedup with no change in semantics. Of course, this implies a pretty different VM implementation and support library, and multiple dynamically coexisting representations of code at a different granularity level. But once programmers knew that this was going on, they would watch how they bound things to take advantage. And the nice thing is the language definition would not change. I guess I would want to get some statistics on dynamic rebinding type changes before starting such a big project though. Has anyone done that already? >The pyrex project goes further and allows C style typing which makes it >very fast, but it isn't JIT. Regards, Bengt Richter From cmvb at optonline.net Fri Nov 15 20:02:15 2002 From: cmvb at optonline.net (cmvb) Date: Fri, 15 Nov 2002 20:02:15 -0500 Subject: help plz ive been to atleast 10 different faqs and guides Message-ID: <004801c28d0b$cdc93ef0$aed7bd18@mouseoh7s2nyon> um yes id like to make a program so when you ask a question it responds with a preset set of random responses is this possible? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jonas.b at home.se Thu Nov 21 21:13:22 2002 From: jonas.b at home.se (Jonas Bengtsson) Date: Fri, 22 Nov 2002 02:13:22 GMT Subject: How to access a property in Outlook using win32com? References: Message-ID: Jonas Bengtsson wrote in news:Xns92CD892C73848jonasbhomese at 195.17.59.36: > Any assistance appreciated! Please disregard my request. I managed to figure it out by myself (thanks to the test at the bottom. Works great! Thanks! Regards, Jonas From jarek at usun.zgoda.biz Wed Nov 13 14:31:04 2002 From: jarek at usun.zgoda.biz (Jarek Zgoda) Date: Wed, 13 Nov 2002 20:31:04 +0100 Subject: python gui rant References: <3dd217e2$0$231$4d4ebb8e@news.nl.uu.net> <3dd27ed6$0$4440$a1866201@newsreader.visi.com> Message-ID: <149oh3oxnl53k.1tyg3jioqd4rb$.dlg@40tude.net> Dnia 13 Nov 2002 16:33:26 GMT, grante at visi.com (Grant Edwards) pisze na grupie comp.lang.python: > One warning: there is a very special place reserved in hell for > people who design GUI dialogs with hard-wired widget locations > so that the dialogs can't be resized. One of the reasons I > really hate working with MS-Windows because of all the dialog > boxes that use 80% of the space in a dialog for useless crap, > and then show only four lines in a list-box containing 100+ > elements. A decent GUI would let you resize the dialog so you > could see more of the stuff in the list-box. But not > MS-Windows.... And here comes the Delphi's idea of using alignments and anchors. AFAIR, wxPython has also "anchors", but I didn't found any reasonable information on using it (except the demo application), so I'm forced to use sizers... -- Zdr?wko Jarek Zgoda -- Serwis Usenet w portalu Gazeta.pl -> http://www.gazeta.pl/usenet/ From e_viola at libero.it Tue Nov 19 14:45:42 2002 From: e_viola at libero.it (bart) Date: Tue, 19 Nov 2002 19:45:42 GMT Subject: URLLIB2 EXCEPTION Message-ID: <3DDA94E9.8090809@libero.it> Sometime, when I use urlopen function, happen this: Traceback (most recent call last): File "", line 2, in ? File "/usr/local/lib/python2.2/urllib2.py", line 138, in urlopen return _opener.open(url, data) File "/usr/local/lib/python2.2/urllib2.py", line 322, in open '_open', req) File "/usr/local/lib/python2.2/urllib2.py", line 301, in _call_chain result = func(*args) File "/usr/local/lib/python2.2/urllib2.py", line 790, in http_open return self.do_open(httplib.HTTP, req) File "/usr/local/lib/python2.2/urllib2.py", line 784, in do_open return self.parent.error('http', req, fp, code, msg, hdrs) File "/usr/local/lib/python2.2/urllib2.py", line 342, in error result = self._call_chain(*args) File "/usr/local/lib/python2.2/urllib2.py", line 301, in _call_chain result = func(*args) File "/usr/local/lib/python2.2/urllib2.py", line 434, in http_error_302 return self.parent.open(new) File "/usr/local/lib/python2.2/urllib2.py", line 322, in open '_open', req) File "/usr/local/lib/python2.2/urllib2.py", line 301, in _call_chain result = func(*args) File "/usr/local/lib/python2.2/urllib2.py", line 790, in http_open return self.do_open(httplib.HTTP, req) File "/usr/local/lib/python2.2/urllib2.py", line 779, in do_open code, msg, hdrs = h.getreply() File "/usr/local/lib/python2.2/httplib.py", line 1009, in getreply response = self._conn.getresponse() File "/usr/local/lib/python2.2/httplib.py", line 760, in getresponse response.begin() File "/usr/local/lib/python2.2/httplib.py", line 269, in begin version, status, reason = self._read_status() File "/usr/local/lib/python2.2/httplib.py", line 231, in _read_status line = self.fp.readline() IOError: [Errno 104] Connection reset by peer I understood that connection can be reseted but I managed this exception cases: HTTPError and URLError. I don't know another exception that can be generate in urllib2. Besides IOError exception doesn't present inside urllib2. What can I do to resolve my problem? Where I can found (web site, manual and other) a solution? Thanks to help me... - Ennio - From bokr at oz.net Thu Nov 7 14:29:33 2002 From: bokr at oz.net (Bengt Richter) Date: 7 Nov 2002 19:29:33 GMT Subject: Asking a user for the root password and executing root only c ommands... References: Message-ID: On Thu, 7 Nov 2002 18:01 +0000 (GMT Standard Time), mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) wrote: >In article , bokr at oz.net (Bengt Richter) >wrote: > >> >> but by default any doorknob rattler could kick it off with >> > ctrl-alt-del >> >> without being asked for a password. Not a cool default config IMO ;-/ >> > >> >Thus providing anyone with accesss to the console's power switch a >> more >computer-friendly way of rebooting a locked-up machine than >> power-cycling >it. >> It's a bit too friendly for my taste ;-) I accidentally did it too many >> times, >> because I am used to the the keying pattern to get past the locking >> screensaver >> on my NT box, so when I turn to the linux box I just do the same if I >> am at all >> distracted. > >Ah I thought you were arguing that the three fingered salute resetting a >linux box was a security hole. Well, yes, that too. If it's not, why would you watch 8-year-old visitors more carefully near your linux keyboard than your NT keyboard ;-) It's not that they can get root so much as the denial-of-service aspect. (Imagine that the box is just about to finish something that runs several hours ;-) Even if you don't have a lock on the physical power and reset, the social threshold for poking power/reset buttons is a little higher than fingering the keyboard. > >IMO it's at least as valid to complain about win32 changing the meaning of >C-A-D from "reset the machine" as it is to complain about linux >maintaining that meaning. > I disagree on that. I think an access-controlled machine needs a secure attention signal to start an unspoofable authentic login, and Ctrl-Alt-Del was the logical choice for PCs. I think a locking screensaver timeout is a good idea. And after the timeout, I don't think you should be able to see what was on the screen before without logging in (which should require an SAS), never mind hitting Alt-Fx and getting a root session if someone lapsed and walked away from that. But in any case, my biggest beef is with loose-access defaults. I don't think it should be possible to get past an install with insecure settings unless you chose them explicitly. However you want to choose, though, that's up to you. A reset is like rm -f on the current dynamic state of the machine. I think it's inconsistent to allow that by default from the keyboard without root, when you can't do it otherwise from the keyboard. Physical access to power/reset is a separate issue to my mind. Regards, Bengt Richter From jslmaslk at earthlink.net Mon Nov 18 23:18:16 2002 From: jslmaslk at earthlink.net (Josh) Date: Tue, 19 Nov 2002 04:18:16 GMT Subject: static variables? Message-ID: Hi guys, I am a python newbie, and I am sure there is an easy answer but, Is there any equivalent to C's static variables in Python? If not, how can you have variables inside a function, that 'remember' their values between function calls? Josh From tundra at tundraware.com Wed Nov 13 03:10:07 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: 13 Nov 2002 08:10:07 GMT Subject: Tkinter: listbox navigation Message-ID: <0v0tqa.3kf1.ln@boundary.tundraware.com> I have looked high and low but cannot find an answer to: When I give the listbox focus, I am able to navigate around it using the arrow keys. So, even if I have selected a particular item, I can move to other items *which is indicated by an underlining of the currently navigated item*. So, at any moment in time, one item may be selected and another underlined. Is there a way programmatically to force the underlining to a particular item? I have a listbox which displays directory contents. I want to reload and it periodically so it stays in sync with the directory - someone may delete a file, for example. I do this with the after() method. After the reload I want to set the navigation back to where it was before. I can set the selection with the select_set() method, but I cannot figure out how to get the underlining back to where it was - it is really annoying to see the underline move back to the first list item every polling period (1 sec)! I cannot seem to find a complete set of docs on the various methods and attributes of a listbox, so a pointer to this would also be appreciated. TIA, ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From doru-cat at ifi.uio.no Sun Nov 10 03:57:28 2002 From: doru-cat at ifi.uio.no (Doru-Catalin Togea) Date: Sun, 10 Nov 2002 09:57:28 +0100 (MET) Subject: RE - non-greedy - some greediness - complete greediness Message-ID: Hi! I am working on a little project where i need REs with a self-defined level of greediness. I am processing text in a Latex like manner, for those of you who are familiar with it. I want to be able to recognize Latex-like commands within my text. A command starts with a character, say '\' followed by the command's name and followed by the text on which the command applies enclosed in curly brackets. Examples: \footnote{some text} \cite{some referance} \section{some title} Recognizing such patterns and retriving the name of the command and the text on which the command applies is not so difficult to achieve. Things get complicated though when one encounters nested commands. Say I have the following string: "abcd \footnote{efgh \cite{myRef1} ijkl} mnop \footnote{hello there}" ^ ^ ^ closing bracket of nested \cite | | | closing bracket of first \footnote | | closing bracket of second \footnote | By using non-greedy REs, I would get recognized the following footnotes: 1) \footnote{efgh \cite{myRef1} 2) \footnote{hello there} The first matching is wrong because the first '}' encountered belongs to the nested \cite command. The second matching is correct. By using greedy REs, I would get recognized the following pattern: 1) \footnote{efgh \cite{myRef1} ijkl} mnop \footnote{hello there} This is wrong because a) there are two \footnote commands in my string, so I should get two matchings, and b) the first \footnote command should be applied only to the "efgh \cite{myRef1} ijkl" substring. In other words I need to be able to specify the level of greediness my REs should have. Is it possible? If yes, how? I have an idea of how to solve my problem without REs, by counting the opening and closing curly brackets and reasoning algorithmically about where within my text each nested command begins and ends. The question is can the above stated problem be solved elegantly by means of REs? With best regards, Catalin <<<< ================================== >>>> << We are what we repeatedly do. >> << Excellence, therefore, is not an act >> << but a habit. >> <<<< ================================== >>>> From anthony at interlink.com.au Fri Nov 8 00:53:45 2002 From: anthony at interlink.com.au (Anthony Baxter) Date: Fri, 08 Nov 2002 16:53:45 +1100 Subject: PEP 301 -- Package Index and Metadata for Distutils In-Reply-To: <200211081643.12862.rjones@ekit-inc.com> Message-ID: <200211080553.gA85rja14087@localhost.localdomain> >>> Richard Jones wrote > This PEP proposes several extensions to the Distutils packaging system. > These enhancements include a central package index server, tools for > submitting package information to the index and extensions to the > package metadata to include Trove information. The online latest version of this PEP is at: http://www.python.org/peps/pep-0301.html Catalog-sig discussion can be found at http://mail.python.org/pipermail/catalog-sig/2002-October/date.html Anthony From cnetzer at mail.arc.nasa.gov Fri Nov 22 15:27:27 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Fri, 22 Nov 2002 12:27:27 -0800 Subject: Proposal: min(None, x) and max(None, x) return x In-Reply-To: References: Message-ID: <200211222027.MAA28283@mail.arc.nasa.gov> On Friday 22 November 2002 06:25, Eric Brunel wrote: > I quite often find myself doing things like: > > xMax = None > for -whatever-: > -big calculation leading to a value of x- > if xMax is None: > xMax = x > else: > xMax = max(x, xMax) My kludgey workaround goes something like this: _xMax = [] for -whatever-: -big calculation leading to a value of x- _xMax.append( x ) _xMax = [max(xMax)] xMax = _xMax[0] Saves a line (and doesn't need to worry about None). And of course, there is always the possibly evil: _xMax = [] for -whatever-: -big calculation leading to a value of x- _xMax.append( x ) xMax = max(_xMax) # -- Bay Area Python Interest Group - http://www.baypiggies.net/ Chad Netzer cnetzer at mail.arc.nasa.gov From wlfraed at ix.netcom.com Thu Nov 21 20:40:04 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Thu, 21 Nov 2002 17:40:04 -0800 Subject: Howto wait for multiple queues (Queue.py)? References: <87bs4kxxxs.fsf@sinon.fr.de.tenovis.com> <15835.51072.893744.335565@montanaro.dyndns.org> Message-ID: Andreas Ames fed this fish to the penguins on Thursday 21 November 2002 02:01 am: > > I think this would be another possibility which would probably look > similar to alternative 3 in my post. My main concern is the > performance of this approach as the queue is one of *the* central > concepts in my server. > I suspect Alex Martelli (sp?) has the proper argument, but may have obscured it some. You seem to be asking for something similar to Ada's selective rendezvous (not actual Ada shown below): Accept EventQueue() .... or accept CommandQueue() .... Problem with Ada is that those accepts are specific to the task (thread), and not shared by a pool. In pseudo-Python you seem to want: while 1: c = Command.get_nowait() e = Event.get_nowait() if c: #command process elif e: #event process WITHOUT the busy wait. So... Rather than use two queues, on for each type of data, why not pass the data type as the first item of the entry? while 1: d = CEQueue.get() #use the blocking mode if d[0] == "COMMAND": #command process elif d[0] == "EVENT": #event process All the "writers" use: CEQueue.put(("COMMAND, data)) or CEQueue.put(("EVENT, data)) IOWs; just take your current queue data, and make a tuple with that data AND a determinant for the type of data. Ada would need the selective accept because of its strict static type checking. Python Queues can accept any data with each entry. -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From alanmk at hotmail.com Tue Nov 19 07:43:09 2002 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 19 Nov 2002 12:43:09 +0000 Subject: COM interfaces and inheritance References: Message-ID: <3DDA31DD.35E676C0@hotmail.com> Rob Sykes wrote: > I'm having a problem with a (3rd party) IDispatch interface > I need to create a new bar object but the 3rd party interface gives > me a method which returns foo objects Thw win32 extensions provide explicitly for this situation, i.e. where the returned COM object implements several different interfaces, but functions return the interface that you don't want. First, you've got to run the win32 utility script Lib/site-packages/win32com/client/makepy.py on the library you're using. This will create a pure python module that interfaces to your COM library. These generated python modules are stored in the directory Lib/site-packages/win32com/gen_py Inside this generated file appears all of the code that you need to turn an object implementing one interface into an object implementing another interface (assuming, of course, that it does actually implement that interface). The first step is to get a handle on the module for your COM library, like so from win32com.client.gencache import GetModuleForProgID myModule = GetModuleForProgID('your.com.library.name.here') Each possible interface in that module will have a class to represent it. Each of the "constructors" for those classes will recognise if you have passed it an instance of an object that implements a related interface. If you have, then it will return to you an instance that implements the interface you need. So some code might look like this objA = createObjA() # Returned object implements interface A objB = myModule.IInterface2(objA) # Bingo! At least, that works for me :-) I hope this helps, and that I've explained it clearly enough. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From mwh at python.net Sat Nov 9 08:24:27 2002 From: mwh at python.net (Michael Hudson) Date: Sat, 9 Nov 2002 13:24:27 GMT Subject: [OT] Cameras (was Re: Why is Python popular, while Lisp and Scheme aren't?) References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: <7h3wunmx4j7.fsf@pc150.maths.bris.ac.uk> Totally off-topic, but hey... Fernando P?rez writes: > If you just want convenience for 4x6 prints from negative, a P&S is > fine. But even a basic SLR like a Canon Rebel is about as easy to > use as a P&S, while allowing you to 'go manual' when you feel like > it. What strikes me is that with modern, decent print film, going manual -- at least wrt. exposure -- makes next to now difference. I don't know enough about the area to say what's going on, but I was surprised. Cheers, M. -- > Why are we talking about bricks and concrete in a lisp newsgroup? After long experiment it was found preferable to talking about why Lisp is slower than C++... -- Duane Rettig & Tim Bradshaw, comp.lang.lisp From ktilton at nyc.rr.com Sat Nov 23 10:58:10 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Sat, 23 Nov 2002 15:58:10 GMT Subject: Newbie Q on searching lists References: <3DDF1673.4020203@nyc.rr.com> <3DDF3C32.4060205@nyc.rr.com> <87wun4wnv0.fsf@key.localdomain> Message-ID: <3DDFA5F5.2070005@nyc.rr.com> Patrick W wrote: > Kenny Tilton writes: > > >>>>1. Am I missing something? >>>> >>> >>>if calculators.count(thisCalculator): # returns zero if not found >>> raise CircularDependency, thisCalculator >> >>oops :) thx! > > > Try this: > > if thisCalculator in calculators: > do_stuff() > > Tests of the form ' in ' work for dictionaries > (hashtables), strings and tuples as well as lists. ah, that was my problem. i had looked only at list operations, not yet grokking the umbrella sequence quality. thx much. -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From zhitenev at cs.vsu.ru Tue Nov 26 11:12:51 2002 From: zhitenev at cs.vsu.ru (Lexy Zhitenev) Date: Tue, 26 Nov 2002 19:12:51 +0300 Subject: A bug or a feature: how to avoid? Message-ID: My code has to react on many exceptions. I use ActivePython 2.2.1 with stackless 2.2.2 DLL. The problem is that I can't write a handler for more than two exceptions at once. My program can throw a lot of exceptions, and I can't react on them simultaneously! This code doesn't work, it raises SyntaxError >>> try: ... pass ... except IndexError, ValueError, NameError: Traceback ( File "", line 3 except IndexError, ValueError, NameError: ^ SyntaxError: invalid syntax >>> I don't want to write the code under try statement twice! What's the solution? Or it should be reported as a bug? From martin at v.loewis.de Tue Nov 12 09:53:47 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 12 Nov 2002 15:53:47 +0100 Subject: Cyrillic letters in 'Entry' widget References: Message-ID: "Denis S. Otkidach" writes: > This helps for output only. To recieve input you need patching > Tkinter: http://prefnews.ru/forum/viewtopic.php?t=19 This information is outdated; changing FixTk is not necessary anymore in Python 2.2.1 and later, since Kirill's patch has been applied. Regards, Martin From grante at visi.com Tue Nov 19 19:18:39 2002 From: grante at visi.com (Grant Edwards) Date: 20 Nov 2002 00:18:39 GMT Subject: Bug in Win32file WaitCommEvent ??? References: <3ddaa58d$0$4459$a1866201@newsreader.visi.com> Message-ID: In article , Mark Hammond wrote: >> I'm trying to figure out how WaitCommEvent() works in Python, and it looks >> like there's a problem when it's used in overlapped mode. >> >> My understanding is that (in C) you: >> >> 1) Call WaitCommEvent() and give it three parameters: >> * File handle >> * a pointer to where the output mask value is to be stored >> * a pointer to an overlapped struct >> >> 2) WaitCommEvent() returns immediately. >> >> 3) Call one of the WaitXXX() functions to wait on the event in >> the overloapped struct. >> >> 4) When the event is triggered WaitXXX() returns. Check the >> value stored via the output mask pointer passed in 1) >> above. >> >> [I've gleaned most of this from >> http://msdn.microsoft.com/library/en-us/devio/base/waitcommevent.asp] > > I don't think this last step is correct. Perhaps. If it isn't correct, where does the event mask get returned? [I'd try to generate a test case in C, but I don't have a Win32 C compiler.] Remember that in overlapped mode, the call to WaitCommEvent() can return _before_ the event actually happens, just as a call to ReadFile() or WriteFile() can return before data has been transferred. > Certainly the link you posted doesn't say this is true. Here's the part I was reading: Remarks The WaitCommEvent function monitors a set of events for a specified communications resource. To set and query the current event mask of a communications resource, use the SetCommMask and GetCommMask functions. If the overlapped operation cannot be completed immediately, the function returns FALSE and the GetLastError function returns ERROR_IO_PENDING, indicating that the operation is executing in the background. This means to me that WaitCommEvent can return immediately (before the event has happened). Therefore, the "mask" variable can not contain valid info upon return from WaitCommEvent. IOW, the event which "mask" is to identify hasn't happened yet. When this happens, the system sets the hEvent member of the OVERLAPPED structure to the not-signaled state before WaitCommEvent returns, and then it sets it to the signaled state when one of the specified events or an error occurs. The calling process can use one of the wait functions to determine the event object's state Since WaitCommEvent returned immediately (none of the masked events has happened yet) you have to use WaitXXX() if you want to know when one of the selected events does happen. and then use the GetOverlappedResult function to determine the results of the WaitCommEvent operation. To me the phrase "and then use the GetOverlappedResult function" implies that this happens _after_ WaitXXX() has returned. The reasons for calling GetOverlappedResult are unclear. The docs for GetOverlappedResult state explicitly that the "lpNumberOfBytesTransferred" return value is undefined, so the call appears to be useless in this context. [Indeed I've never seen it used following WaitCommEvent()/WaitForXXX()]. GetOverlappedResult reports the success or failure of the operation, and the variable pointed to by the lpEvtMask parameter is set to indicate the event that occurred. lpEvtMask was the pointer passed to WaitCommEvent(). This last sentance says to me that the variable to which lpEvtMask points isn't written to until _after_ WaitForXXX() has returned. > Looking further, I can't find *anything* that implies this is true. I don't see how the above section can be interpreted any differently, and I don't see how WaitCommEvent() can return a mask value describing an event that hasn't happened yet. > KB Q175551 has sample code for Windows CE that uses overlapped IO, and it > examines the mask immediately after the call. FWIW, The WinCE serial driver doesn't work the same way as serial devices on other Win32 platforms. Notice that this example doesn't pass an overlapped structure pointer to WaitCommEvent(). One of my companies projects had to use Embedded NT rather than WinCE due to the differences in I/O on WinCE. At least that's what the Win32 guys claimed. > Further, if what you say is correct, I would expect Python COM port > based programs to regularly crash! In your scenario, by the time the > overlapped function ended up writing to our mask variable, that address > would be invalid. I don't see any other interpretation. If WaitCommEvent() can return immediately, the mask variable obviously isn't valid at that point. Perhaps in the overlapped case, the output mask value information is discarded, but that's not what the above text says. > However, it would be pretty close to the top of the stack, so I would expect > it to corrupt whatever was running when the mask was actually written. I > know a number of people have used these APIs to do serious serial port > control - either directly, or via another wrapper. I would be very > surprised we survived this long. > > Can you find an explicit reference to this? I think the text quoted above is pretty explicit. It's from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/devio/base/waitcommevent.asp Overlapped read/write work in similar ways, you pass a pointer to the source/destination when you initiate the operation, then after doing WaitForXXX(), you check the contents of the destination or the byte count. Here's the example program from the Win32All Demo directory: 88 89 def _ComPortThread(self): 90 overlapped = OVERLAPPED() 91 overlapped.hEvent = CreateEvent(None, 1, 0, None) 92 while 1: 95 rc, mask = WaitCommEvent(self.handle, overlapped) If WaitCommEvent() always waits for the event to happen so that mask is valid, then we know that receive data is ready. Why not just call ReadFile() at this point? Because the WaitCommEvent is overlapped, the WaitCommEvent returns immediately whether or not data is ready, and we have to do the WaitForXXX() below: 96 if rc == 0: # Character already ready! 97 SetEvent(overlapped.hEvent) 98 rc = WaitForMultipleObjects([overlapped.hEvent, self.eventStop], 0, INFINITE) 99 if rc == WAIT_OBJECT_0: 100 # Some input - read and print it 101 flags, comstat = ClearCommError( self.handle ) 102 rc, data = ReadFile(self.handle, comstat.cbInQue, overlapped) 103 WaitForSingleObject(overlapped.hEvent, INFINITE) 104 sys.stdout.write(data) -- Grant Edwards grante Yow! I represent a at sardine!! visi.com From cnetzer at mail.arc.nasa.gov Thu Nov 14 15:28:18 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Thu, 14 Nov 2002 12:28:18 -0800 Subject: How to write Inline Functions in Python? In-Reply-To: References: Message-ID: <200211142028.MAA25626@mail.arc.nasa.gov> On Thursday 14 November 2002 04:47, David Brown wrote: > The question then is when will gcc support such > link-time code generation, because until then, inlined functions in headers > will remain an issue. I'm guessing there may be patent issues in this particular area, which could restrict gcc's ability to implement some of these features. -- Bay Area Python Interest Group - http://www.baypiggies.net/ Chad Netzer cnetzer at mail.arc.nasa.gov From fperez528 at yahoo.com Mon Nov 11 13:38:50 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 11 Nov 2002 11:38:50 -0700 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: Jacek Generowicz wrote: [snip] >> I'd very much appreciate an overview of this by you or anyone else >> with a good lisp background. > > I would not consider myself to have a "good lisp background". But I'd > be happy to try to make constructive suggestions, and maybe give you > some pointers ... but please allow me to postpone this for a week or > so, as I would not be able to make a sensible contribution with my > current time constraints. Thanks a lot for the information you did give. And yes, I'm still interested, so whenever you find a spare moment (next week, next month, it doesn't really matter), I'd still appreciate more details. If you want, you can CC me privately at , my work email (not used on Usenet normally for spam reasons). Thanks again for your time. Cheers, f. From loewis at informatik.hu-berlin.de Thu Nov 7 04:11:10 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 07 Nov 2002 10:11:10 +0100 Subject: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up References: Message-ID: "Fredrik Lundh" writes: > > You can if you want. The PEP continues to allow it until Python 3.0. > > According to the PEP, Python 2.5 will print warnings whenever you use > long literals. If the OP doesn't want warnings, he'll have to change his > code for 2.3, and change it back for 2.5. It is quite difficult to predict the future, and I would suggest that the OP ignores predictions that the PEP makes about what phases will be implemented in what Python version. My personal prediction is that Python 2.5 will not warn about long literals. > Looks like the only portable way to use large "unsigned" constants is to > use long("0x80000000")... You mean, long("80000000",16)? Python 1.5.2 (#4, Jul 4 2000, 19:57:05) [GCC 2.95.2 19991024 (release)] on sunos5 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> long("80000000",16) Traceback (innermost last): File "", line 1, in ? TypeError: long requires exactly 1 argument; 2 given Regards, Martin From djc at object-craft.com.au Fri Nov 29 18:53:32 2002 From: djc at object-craft.com.au (Dave Cole) Date: 30 Nov 2002 10:53:32 +1100 Subject: Threading problems at program exit Message-ID: The following program demonstrates a problem I am experiencing with the threading module. I have an object (A) which holds a lock on another object (B). When object A is deleted I want it to release any lock it may still be holding on object B. Everything works fine except when the program terminates. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - import sys import threading class Locked: def __init__(self, lock): self._lock = lock self._lock_count = 0 self._thread = None self._log = sys.stderr.write self._current_thread = threading.currentThread self.lock() def lock(self): self._log('locked in %s\n' % self._current_thread()) self._lock.acquire() self._lock_count += 1 def unlock(self): self._log('unlocked in %s\n' % self._current_thread()) self._lock_count -= 1 self._lock.release() def __del__(self): while self._lock_count: self.unlock() obj = Locked(threading.RLock()) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - When I run this program I get the following: locked in <_MainThread(MainThread, started)> unlocked in <_DummyThread(Dummy-1, started daemon)> Exception exceptions.AssertionError: in > ignored It looks like interpreter is deleting thread objects before objects which hold locks in those threads. Is there any kosher way I can avoid the problem? The only way I can think to fix it is a bit non-kosher: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - import sys import threading class Locked: def __init__(self, lock): self._lock = lock self._lock_count = 0 self._thread = None self._log = sys.stderr.write self._current_thread = threading.currentThread self.lock() def lock(self): self._log('locked in %s\n' % self._current_thread()) self._lock.acquire() self._lock_count += 1 def unlock(self): self._log('unlocked in %s\n' % self._current_thread()) self._lock_count -= 1 self._lock.release() def __del__(self): if self._lock_count: count, owner = self._lock._release_save() self._log('owner was %s\n' % owner) owner = self._current_thread() self._log('owner is now %s\n' % owner) self._lock._acquire_restore((count, owner)) while self._lock_count: self.unlock() obj = Locked(threading.RLock()) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This prints the following: locked in <_MainThread(MainThread, started)> owner was <_MainThread(MainThread, stopped)> owner is now <_DummyThread(Dummy-1, started daemon)> unlocked in <_DummyThread(Dummy-1, started daemon)> The trouble is that it requires the use of private methods of the RLock class. Is there a better or more kosher way? - Dave -- http://www.object-craft.com.au From pan-newsreader at thomas-guettler.de Fri Nov 15 14:02:26 2002 From: pan-newsreader at thomas-guettler.de (Thomas Guettler) Date: Fri, 15 Nov 2002 20:02:26 +0100 Subject: bind problem References: Message-ID: On Fri, 15 Nov 2002 18:40:13 +0100, Dan Stromberg wrote: > I'm still having my previously-mentioned problem binding sockets in > python 2.2. Things are fine on linux, but they don't work on solaris - > some solaris hosts, not all, I think. > > I'm approaching the group again about it, because I've run across > another, much smaller program with the same problem - in fact it's so > small, but I think it'll be ok to post it here in its entirety. > > The error I get with 2.2.1 is: > > Traceback (most recent call last): > File "/tmp/packetpasser", line 108, in ? > main() > File "/tmp/packetpasser", line 60, in main > sockin.bind(('',read_from)) > socket.gaierror: (3, 'getaddrinfo failed') "getaddrinfo failed" sounds like you can't resolve the dns-name of a machine to its ip-address. does "nslookup machine" work? Does it work if you use ip-adresses instead? thomas -- Thomas Guettler http://www.thomas-guettler.de From mcfletch at rogers.com Wed Nov 13 18:50:05 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 13 Nov 2002 18:50:05 -0500 Subject: property problems References: Message-ID: <3DD2E52D.8080309@rogers.com> Okay, there's a number of things going on here: * properties only work (properly) with new-style classes, new-style classes derive from other new-style classes, normally "object". Your class GlobalVars is an old-style class. Derive from object to prevent problems which _will_ come up later on. * you are accessing a property which stores a list as if it was the setter method of that property. You want to do: gv.stats = [['Height',self.height],['Build',self.build],['Strength',str]] * gv.stats( ... ) is actually accessing the property value, which is currently a list object, and then trying to call it as if it were a function/method/callable object (it isn't one). HTH, Mike Newt wrote: > Hi, > > I've got a problem trying to use a property in a class module. The > class module is listed below (it's called globals.py): > > class GlobalVars: > > def __init__(self): > self.l_stats = [] > return > > def set_stats(self,val): > self.l_stats = val[:] > return > > def get_stats(self): > return self.l_stats > > stats = property(get_stats, set_stats) > gv = GlobalVars() > > I've got a further module which does the following: > > from globals import gv > gv.stats([['Height',self.height],['Build',self.build],['Strength',str]]) > However, I get the following error: > > Exception in Tkinter callback > Traceback (most recent call last): > File "C:\Python22\lib\lib-tk\Tkinter.py", line 1292, in __call__ > return apply(self.func, args) > File "D:\py_stuff\curry.py", line 14, in __call__ > return self.fun(*(self.pending + args), **kw) > File "D:\py_stuff\chaz.py", line 223, in shownext > SelectStats(self) > File "D:\py_stuff\stats.py", line 46, in __init__ > self.do_widgets() > File "D:\py_stuff\stats.py", line 208, in do_widgets > > gv.stats([['Height',self.height],['Build',self.build],['Strength',str]]) > TypeError: 'list' object is not callable > > Could somebody explain to mw what this means, and how to fix it please! > > Thanks, > > Newt -- _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From SBrunning at trisystems.co.uk Thu Nov 28 08:52:45 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Thu, 28 Nov 2002 13:52:45 -0000 Subject: Distributing python applications for Windows users Message-ID: <31575A892FF6D1118F5800600846864D01200318@intrepid> > From: martyn_quick at yahoo.co.uk [SMTP:martyn_quick at yahoo.co.uk] > > What's the best way to distribute an application written in Python > (consisting of quite a few modules and using Tkinter/Pmw for GUI) so > that it can be used by someone who is using MS Windows without > requiring them to install Python itself? > > What's the easiest way also? (I ask this because many of you have > considerably more knowledge than me, and I might well find the best > way is way beyond what I can currently handle.) I like py2exe - . Others prefer Installer - . Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From pinard at iro.umontreal.ca Fri Nov 15 08:36:10 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 15 Nov 2002 08:36:10 -0500 Subject: A really bad idea. In-Reply-To: <3DD47156.683F18B3@alcyone.com> References: <3DD47156.683F18B3@alcyone.com> Message-ID: [Erik Max Francis] > "Simon Wittber (Maptek)" wrote: > > I disagree. C is a very simple language. > The C language itself is a fairly straightforward language, but > summarizing that in eight pages does not do it much justice. [...] > Comparing a Python reference of 120 or so pages to a "C/C++" reference > of 16 pages is comparing apples and oranges, and says absolutely nothing > about the relative size or complexity of any of these languages. I might not be fully singing with the choir here, but I do not find that C is a simple language. It has fairly intricate points here and there, and I guess there are very, very few people in this crowd, and in many other crowds as well, truly able to reply correctly to any question about C, the language, not even considering its libraries. C++ as a language is a slightly more regular than C, so it might be slightly easier in that respect, but it is also much more complex, so all summed, C++ is undoubtedly a difficult language. No doubt to me that Python is an easier language, one can learn most of it quickly, and run quite a long while on that knowledge. But really knowing Python, deeply, inside out, is a challenge in itself: there is a great deal of details to know. So, despite Python allows us to be much more efficient and productive than with other languages, I would never go as far as saying that Python is fully easy. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From max at alcyone.com Sat Nov 23 17:54:54 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 23 Nov 2002 14:54:54 -0800 Subject: reliable tcp server holding multiple connections References: <3DDFAEB4.1040506@nospam.attbi.com> Message-ID: <3DE0073E.25EE8B9E@alcyone.com> Wojtek Walczak wrote: > Dnia Sat, 23 Nov 2002 16:37:07 GMT, djw napisa?(a): > > > Do you know about Medusa? > > Yes, but Medusa it a little bit large. I want to create small code, > proof of concept. An educational example, nothing more. The two primary modules in Medusa -- asyncore and asynchat -- are already standard in the Python distribution. For simple client-server stuff, they're very lightweight and require no additional installation to use. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Said it? yep / Regret it? nope \__/ Ice Cube EmPy / http://www.alcyone.com/pyos/empy/ A system for embedding arbitrary Python in template text as markup. From pearu at cens.ioc.ee Sun Nov 10 03:25:02 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Sun, 10 Nov 2002 10:25:02 +0200 (EET) Subject: Numarray append In-Reply-To: <1ggz9.11678$Zn2.332778@twister1.libero.it> Message-ID: On 9 Nov 2002, Fabrizio wrote: > Hi, > > Is there a quick way to append elements to a Numarray array ? > > I could not find any. Using Numeric.concatenate should be the quickest way to achieve that. E.g. >>> a=Numeric.arange(5) >>> a=Numeric.concatenate((a,range(4))) >>> a array([0, 1, 2, 3, 4, 0, 1, 2, 3]) Pearu From klaatu at evertek.net Fri Nov 15 21:16:30 2002 From: klaatu at evertek.net (Mike Dean) Date: Fri, 15 Nov 2002 20:16:30 -0600 Subject: list.reverse() Message-ID: I think I recall seeing a reasonable explanation for this earlier (probably referring actually to list.sort()), but I'm wondering - what was the rationale for making list.reverse() reverse a list in-place rather than return a new, reversed list? I'm sure there's a good reason, but what might that be? -Mike From mcfletch at rogers.com Thu Nov 21 03:39:05 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 21 Nov 2002 03:39:05 -0500 Subject: Does Python (or psyco) already do this optimisation? References: Message-ID: <3DDC9BA9.9070309@rogers.com> Okay. That answers whether base Python (non-psyco) currently does this. Thank-you for confirming what I'd assumed regarding the current operation. Any idea (anyone) whether the outlined approach has been attempted for global-variable access optimisation? i.e. is this an explored and deemed-dead path, or something new? Enjoy, Mike Martin v. Loewis wrote: >"Mike C. Fletcher" writes: > > > >>Anyway, would be interested to know if someone C-knowledgable has done >>this already and 1) integrated it into Python or psyco already, or 2) >>decided it just isn't a feasible approach? >> >> > >Local namespaces are accessed by integer index only, global namespaces >are accessed by dictionary only; object attribute lookup uses complex >procedures. > >Regards, >Martin > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From LogiplexSoftware at earthlink.net Wed Nov 6 14:03:53 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 06 Nov 2002 11:03:53 -0800 Subject: Emacs and Indentation In-Reply-To: References: Message-ID: <1036609434.23122.111.camel@software1.logiplex.internal> On Wed, 2002-11-06 at 07:37, Michael Tiller wrote: [snip] > does nothing in Emacs (v21.4, windows). So, I have to go and indent using > the TAB key. The problem there is that Emacs doesn't really understand the > block structure so I get: > > for x in mylist: > if not x in filled: > foo[x] = x[1] > bar[x] = x[2] > y = x # Yikes! > [snip] > > Surely I can't be the only person who is bugged by this? Are there ways > around this? You can also put a "pass" at the end of a block and emacs will treat that as a block delimiter (at least in python-mode). Sort of ugly IMO but if this really bothers you it may be worth a try. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From jacek.generowicz at cern.ch Wed Nov 27 12:28:11 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 27 Nov 2002 18:28:11 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3de1f902$0$695$edfadb0f@dread12.news.tele.dk> Message-ID: Robin Munn writes: > So we were learning a new style of programming, functional > programming, which we had to wrap our brains around. > Now that I've gotten productive in Python, I may give Lisp another > try, although I think I'll study Haskell first as a kind of > stepping-stone (functional programming without the parentheses-heavy > syntax). You do realize that funcitonal programming is just one of the programming paradigms that Lisp supports ? (But I understand where you're coming from: I followed a small Lisp course about a decade ago, and the Lisp that was presented there bears very little resemblance to what I have since discovered Lisp to be, in reality.) > But what I'd really like before I try Lisp again is a special > color-highlighting mode that would distinguish between deeply-nested > parentheses, either coloring the parentheses themselves or else all > the text between said parentheses. Something like this: > > (first > (second > (third > (fourth > ) > ) > ) > ) (Point of information: dangling parentheses are most definitely NOT good Lisp code layout style.) > where each indentation level would be a different color (foreground? > background?). ... Just curious ... have you ever felt the need for such an indentation-based colour-highlighting feature when programming in Python? If so, has the lack of it hindered you from programming in Python ? If not, what makes you think that it would be useful in Lisp? From aleax at aleax.it Sun Nov 3 11:51:21 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 03 Nov 2002 16:51:21 GMT Subject: Python 2.2.2 on OS/390 V2R10 References: <3dc40ef1_1@news.vo.lu> <3dc50045_2@news.vo.lu> Message-ID: John Roth wrote: ... >> our three teams (Windows, AIX and OS/390). I doubt that it will be an ... > Also, I believe REXX is availible for all three environments. AFIC, it's > a typical kludge scripting language, but it does work. Me, I remember Rexx as a pretty good scripting language back from the '80s, when I worked for IBM -- Rexx is what first gave me the taste for using "scripting" languages wherever feasible. I hear it also took roots in the Amiga world, and I assume it must have grown and developed in the 14 years since I last used it, but I haven't kept track. But what do you think is "a typical kludge" about it? Alex From fredrik at pythonware.com Tue Nov 5 16:41:15 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 05 Nov 2002 21:41:15 GMT Subject: how to import References: Message-ID: <%VWx9.2705$h%5.96261@newsb.telia.net> Fedor wrote: > [test1.py] > #This setup doesn't work: > import mx.DateTime > class A: > def __init__(self): > print mx.DateTime.now() > def test(self): > print mx.DateTime.now() > import mx.ODBC > a=A() > #Results in: 2002-11-06 19:22:14.49 > a.test() > #Results in: UnboundLocalError: local variable 'mx' referenced before > assignment full story: http://www.python.org/doc/current/ref/naming.html http://www.python.org/doc/current/ref/import.html summary: "import" behaves like any other assignment statement. inside the test method, the "import mx.ODBC" statement attempts to assign a value (the module object) to the "mx" variable. the compiler notices this, and flags "mx" as a local variable. since "mx" is a local variable, you cannot refer to it before it has been assigned a value. to fix this, either add a "global mx" statement to the method, or move the import statement to the top of the method. From wlfraed at ix.netcom.com Sat Nov 23 21:14:25 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sat, 23 Nov 2002 18:14:25 -0800 Subject: Newbie Q on searching lists References: <3DDF1673.4020203@nyc.rr.com> <3DDF3C32.4060205@nyc.rr.com> <87wun4wnv0.fsf@key.localdomain> <3DDFA5F5.2070005@nyc.rr.com> Message-ID: <1mcpra.0o4.ln@beastie.ix.netcom.com> Kenny Tilton fed this fish to the penguins on Saturday 23 November 2002 07:58 am: > > ah, that was my problem. i had looked only at list operations, not yet > grokking the umbrella sequence quality. thx much. > Relax, I was about to suggest something on the order of: if thisCalculator < len(calculators): #len=4 means 0..3 are valid, #hence the < -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From fperez528 at yahoo.com Sun Nov 3 17:57:45 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Sun, 03 Nov 2002 15:57:45 -0700 Subject: Numerical & FFT References: Message-ID: David Siroky wrote: > Hi! > > Functions "fft" and "real_fft" returns some array. What those numbers > exactly mean? Especially the first one (DC or what)? > > Thank you! > > David In [3]: fft? Type: function Base Class: String Form: Namespace: Interactive File: /usr/lib/python2.2/site-packages/Numeric/FFT/FFT.py Definition: fft(a, n=None, axis=-1) Docstring: fft(a, n=None, axis=-1) Will return the n point discrete Fourier transform of a. n defaults to the length of a. If n is larger than a, then a will be zero-padded to make up the difference. If n is smaller than a, the first n items in a will be used. The packing of the result is "standard": If A = fft(a, n), then A[0] contains the zero-frequency term, A[1:n/2+1] contains the positive-frequency terms, and A[n/2+1:] contains the negative-frequency terms, in order of decreasingly negative frequency. So for an 8-point transform, the frequencies of the result are [ 0, 1, 2, 3, 4, -3, -2, -1]. This is most efficient for n a power of two. This also stores a cache of working memory for different sizes of fft's, so you could theoretically run into memory problems if you call this too many times with too many different n's. In [4]: real_fft? Type: function Base Class: String Form: Namespace: Interactive File: /usr/lib/python2.2/site-packages/Numeric/FFT/FFT.py Definition: real_fft(a, n=None, axis=-1) Docstring: real_fft(a, n=None, axis=-1) Will return the n point discrete Fourier transform of the real valued array a. n defaults to the length of a. n is the length of the input, not the output. The returned array will be the nonnegative frequency terms of the Hermite-symmetric, complex transform of the real array. So for an 8-point transform, the frequencies in the result are [ 0, 1, 2, 3, 4]. The first term will be real, as will the last if n is even. The negative frequency terms are not needed because they are the complex conjugates of the positive frequency terms. (This is what I mean when I say Hermite-symmetric.) This is most efficient for n a power of two. cheers, f From graik at web.de Wed Nov 6 17:43:02 2002 From: graik at web.de (Raik Gruenberg) Date: Wed, 06 Nov 2002 23:43:02 +0100 Subject: segmentation fault when unpickling an object in another Python instance References: <3DC96AAD.9090503@web.de> Message-ID: <3DC99AF6.2030906@web.de> It's not cPickle specific - I got the same segmentation fault when using normal pickle. Getting a minimum example will take some time and it can get quite long. I can switch off the error by deleting a line in the constructor of the pickled object... Summary so far, I can not unpickle my object if: - The constructor of this object called (before pickling) a certain method of an internally referenced object - this internal object encapsulates an Numeric array - the certain method deletes parts of this array (via Numeric.compress ) Rings a bell for someone?? Anyway, I'll see what I can do. All comments are welcome ! Raik Terry Reedy wrote: > "Raik Gruenberg" wrote in message > news:3DC96AAD.9090503 at web.de... > > >>I have got some home-made class. From within the same Python > > interpreter > >> I can create, dump and load it back without any problem. But, if I > > try > >>to load it after re-starting the interpreter, I end up with a >>segmentation fault. >> > >>Obviously, it is also somewhat the fault of this >>particular class. I narrowed down the problem somewhat. But, before >>bothering you with all the details, perhaps anyone knows this > > problem or > >>has some promising idea??? > > > There have been some known problems with CPickle and some patches, but > in the absence of keyword searching of the SourceForge database, I > won't guess as to specifics and relation to your problem. You may be > asked for minimum example that exhibits problem. > > TJR > > From richard.mertens at wolfi.org Mon Nov 4 10:43:25 2002 From: richard.mertens at wolfi.org (Richard Mertens) Date: 4 Nov 2002 15:43:25 GMT Subject: problem's with strings Message-ID: first problem: I'd like to convert a text-file von unix to windows and vice versa Do you know a solution for this When the python script is reading the text-file i have always the Nextline - Character on the end. How do you I remove it? From sholden at holdenweb.com Mon Nov 25 10:37:18 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 25 Nov 2002 10:37:18 -0500 Subject: if : References: Message-ID: Interesting that none of the responders referenced a FAQ article ... though since it refers to 2.0 as a future release it's clearly in some need of updating! http://www.python.org/cgi-bin/faqw.py?req=show&file=faq06.030.htp regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- "Andr? N?ss" wrote in message news:arqm0r$s6f$1 at maud.ifi.uio.no... > When I started learning Python one of the things that surprised me was that > you couldn't do assignments inside the if clause, e.g.: > > if myvar = someFunction(): > > My question is, what is the rationale for this? Is it a technical issue? Or > purely a matter of language design? I'm curious because I'm interested in > the design og programming languages, not because I want this behavior > changed in Pyton :) > > Thanks. > Andr? N?ss > > > From tjreedy at udel.edu Fri Nov 29 15:33:58 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 29 Nov 2002 15:33:58 -0500 Subject: Newbie Question, list = list + x VS append (x) References: Message-ID: Seq + seq (of same type) is sequence concatenation: len(r+s) = len(r)+len(s) >>> 'a'+'b' 'ab' >>> (1,)+(2,) (1, 2) >>> [1]+[2] [1, 2] >>> (1,)+[2] Traceback (most recent call last): File "", line 1, in ? TypeError: can only concatenate tuple (not "list") to tuple While not commutative, seq + is associative with identity (empty seq of type) and is thus a reduction operator. Ie, reduce(tuple.__add__, tuples, ()) => tuple, etc list.append(object), specific to lists, simply tacks object on to the end of list. It never looks at the type of object. If it is a list, that is irrelevant. list.extend(seq) is similar to list+seq but is more general. Terry J. Reedy From pyth at devel.trillke.net Mon Nov 11 11:13:31 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 11 Nov 2002 17:13:31 +0100 Subject: something like "if" that returns a value? In-Reply-To: ; from Paul_Rudin@scientia.com on Mon, Nov 11, 2002 at 03:18:52PM +0000 References: Message-ID: <20021111171331.V30315@prim.han.de> Paul Rudin wrote: > >>>>> "hk" == holger krekel writes: > >> - there's a degree of obfuscation here, the code is less > >> comprehensible than something like: if x then y else z. > > hk> IMO it's not overly hard to get used to it. It certainly isn't as > hk> evident (as has the aforementioned pitfall) as in some other > hk> languages. Funny enough, i don't need this ternary operation > hk> often. > > hk> And if one the expressions is more complex i use a proper > hk> if-clause. > > I guess these things depend on what you're used to - I now program > mostly in lisp; I used to program mostly in c++; I'm very used to > using such a construct. Using an if-then-else type construct without a > return value makes some code rather inelegant, it seems to me. But no > doubt one can get used to it. yes. But i also said that with python i don't need this ternary operator often (usually in cases where applying the 'x and y or z' is no problem). It happend to me that instead of using a ternary operator i cut simplify, shorten *and* enhance my program by not doing so. Is there an obvious killer use case? IOW can you state a problem where the use of a ternary operator comes in really handy? Sorry if this sounds dumb to you but i am interested. regards, holger From tundra at tundraware.com Mon Nov 11 19:20:07 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: 12 Nov 2002 00:20:07 GMT Subject: Tkinter listbox selection handling References: Message-ID: <05hpqa.vpi.ln@boundary.tundraware.com> Martin Franklin wrote: > There must be something else in the code your not showing (the code you > posted did not work out of the bx...) This works:- > > #### start > > from Tkinter import * > > class myUI: > def __init__(self, root): > self.listbox = Listbox(root, > selectmode=SINGLE, > exportselection=0) > self.listbox.pack() > root = Tk() > UI = myUI(root) > > > def handlerfunc(event): > print event.widget.get(first=event.widget.curselection()[0]) > > UI.listbox.insert("end", "1") > UI.listbox.insert("end", "2") > UI.listbox.insert("end", "3") > UI.listbox.insert("end", "4") > > > UI.listbox.bind('', handlerfunc) > > root.mainloop() > > #### end > > > Tested just a few seconds ago on a RedHat Linux 8.0 Python 2.2.2 > Tk 8.4 and Python 2.2.2 Tk 8.3 > > > Cheers, > Martin. I must have had some other artifacts that were breaking things when I tried previously. It now works fine, exactly as you suggest... Thanks, all, for taking the time to help ... -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From johnroth at ameritech.net Fri Nov 22 17:32:43 2002 From: johnroth at ameritech.net (John Roth) Date: Fri, 22 Nov 2002 17:32:43 -0500 Subject: Proposal: min(None, x) and max(None, x) return x References: Message-ID: "Eric Brunel" wrote in message news:arle6m$aa9$1 at news-reader11.wanadoo.fr... > In > addition, today, min(None, x) and max(None, x) work, but have strange > results: as far as I can see, min(None, x) is always None and max(None, x) > is always x, but this behaviour isn't documented. It's not documented *separately.* It's a consequence of the documented fact that comparisons between objects that don't have an obvious ordering will always have a consistent, although arbitrary order. This behavior is documented to be changable between releases, however. See the Python Library Reference, 2.1.3 (Comparisons) for Release 2.1. It's right under note 1. That's section 2.2.3 for Python 2.2.2. One consequence of this is that in another release, None might compare high rather than low. I rather doubt that it ever would, but the possibility is there. John Roth From ELabuschane at gmsonline.co.za Tue Nov 12 02:49:28 2002 From: ELabuschane at gmsonline.co.za (Etienne Labuschagne) Date: Tue, 12 Nov 2002 09:49:28 +0200 Subject: p2exe and ZODB Message-ID: Hi there, First, an apology, my M$ Outlook INSISTS on sending HTML-spew, even though I have all settings I can find on Text only and the status bar says Plain Text :( I gather from the context of my message that you also only have this problem under Py2EXE (does Py2EXE work at all on *Nix?). If not, it's quite strange as ZODB works perfectly in a normal Python environment for me - it's just doing strange things when working in a py2exe environment. I have just started investigating McMillan's installer product, but have had no luck so far in getting it to wrap ZODB. If I can get it to work, I'll post the solution. Regards Etienne -----Original Message----- From: Harry George [mailto:hgg9140 at seanet.com] Sent: Tuesday, November 12, 2002 4:05 AM To: python-list at python.org Subject: Re: p2exe and ZODB Etienne Labuschagne writes: > Content-type: text/html ; charset = "iso-8859-1" > > > > > > > p2exe and ZODB > > > >

Hi there, >

> >

I am using stand-alone ZODB (Zope Object Database) in a applica > tion written in Python.  The platform I am targeting is Windows 2000 and W > indows XP.  So far I had no luck  py2exe'ing the product with ZODB in > cluded.  What I have done is to exclude ZODB (-e flag for py2exe) and crea > te an install without the stand-alone ZODB.  I then manually copy the ZODB > and all files needed by it (eg. base64) into the dist created by py2exe. >

> >

This works, but I sometimes get (seemingly) random pickling err > ors when calling get_transaction().commit() on the ZODB database.  This ca > uses a lot of havoc as the transaction then also seems to be lost, which is VER > Y bad!

> >

Anyone had any luck with py2exe and apps using ZODB? >

> >

If I can't get this to work, are there any other "python n > ot needed for install" methods to package my product in? >

I'm having trouble using standalone ZODB, with ramdom pickling errors on commit as well. I'm running on Linux, not Win**. Maybe there is a problem in ZODB? My next attempt is to do the pickling directly, and just make a database to store those strings. > >

Regards >
Etienne Labuschagne >

> > > -- Harry George hgg9140 at seanet.com -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Nov 15 13:09:58 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 15 Nov 2002 13:09:58 -0500 Subject: keyword arguments and ** References: <3dd51831$0$13642$e4fe514c@dreader6.news.xs4all.nl> Message-ID: "Alex Martelli" wrote in message news:w68B9.12486$744.448146 at news1.tin.it... > Usual problem: when an argument (here, fields) has a default > value that is mutable, that value is determined ONCE, when the > def statement executes -- then that single value stays around > (the function object references it), and if you mutate it you > get such a "memory effect". I would just add that if def occurs within a function called multiple times, then default args are alse evaluated multiple times, but just once for each execution of the def statemeant -- which is just once for each function object produced. (And if outer function is never called, defaults are never evaluated.) Terry J. Reedy From bokr at oz.net Wed Nov 13 12:02:42 2002 From: bokr at oz.net (Bengt Richter) Date: 13 Nov 2002 17:02:42 GMT Subject: pythonic way to optimize access to imported value? References: <3DD1AB92.3030409@something.invalid> Message-ID: On Wed, 13 Nov 2002 14:32:02 +1300, Greg Ewing wrote: >Bengt Richter wrote: > >> >>> def mkfoo(): >> ... from math import pi >> ... def foo(): >> ... return pi >> ... return foo >> ... >> >> What would be best Pythonic practice for getting a foo2? It seems like if there were >> a way to say "do this part once at compile time" > > >It's not really compile-time that we want to do it, >but module load time, or perhaps function definition >time. > Well, ok, I was speaking loosely of compile-time as the time between reading source and when final executable byte codes are laid down, but of course it's more complex than that (especially with Python), as mkfoo incidentally demonstrates. But the general idea is to find points in the sequence where one could intercede with some meta-operations to modify code that gets executed at the end of the cascade. You mention load time and function definition time. (Class definition time would seem to similar, with metaclasses aready providing much control). Also, execfile time has some things in common with module load time. Is there a unified "-time" concept re both? Are there different possibly useful intercession points in loading .py vs .pyc? What other "-times" can be clearly identified? If we had macros, I'm sure there would be a "macro-interpretation time" (read-time?) associated with that. (BTW, how about times associated with encoding transformations of source and i/o?) But, getting back to foo/mkfoo, the intent was to set up values for efficient access and to release unneeded references as soon as possible, compiling (in a narrower sense) the source effectively partitioned into code and metacode for execution at appropriate separate times to yield a clean foo function. >One way would be to use a default-argument hack: > Which would be a definition-time binding, I guess you would say? > import math > > def foo(m = math): > return m.pi > >but this has all the usual drawbacks of the default-argument >hack. Plus that version retains a reference to math, where I'd like to think that I would wind up with just a reference to a double with the 3.14.. value. I.e., def foo(pi = math.pi): return pi (not that I want to pursue the default-argument hack, just to indicate that whatever the methodology, I don't think the generated code should be forcing persistence of anything it doesn't really need). > >This suggests that perhaps there should be a way >of getting something that is just like a default >argument, except that it's not part of the argument >list. Maybe > > def foo(): > const m = math > return m.pi > >The "const" statement would be evaluated when >the "def" was executed, and "m" would appear in the >local namespace when the function was called. > >Although "const" might not be the best name for >it, since it's not really a constant, more like >a local with an initial value. > Yes. Also I think I would like a keyword that governs a block scope instead of just the scope of an assignment. E.g., (resisting the temptation of discovering a general mechanism here ;-) def foo(): predef: import math pi = math.pi del math seven = 7 return pi, seven meaning the predef block would be done once at define-time, and you could do whatever you wanted to predefine the local environment that would be seen at the first call (execution-time). You could also delete unneeded bindings as above. This kind of flexibility would be hard if not impossible to get with 'const' & such. I'm not sure whether a postdef: section would be of use, but if so these things should probably be subsumed under a single keyword (e.g. "meta" for "meta predef: and "meta postdef" ?) especially if one anticipated other contexts of use as well. The predef block looks like a kind of meta-code, and I would think the compiler could generate a code block for that separate from the code of the function body that defines what is called at execution time (foo), loosely corresponding to mkfoo and foo code in the example, not a single body with a special conditional part and references hanging on to things beyond their intial and only use. Regards, Bengt Richter From mgilfix at eecs.tufts.edu Fri Nov 29 15:20:59 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Fri, 29 Nov 2002 15:20:59 -0500 Subject: How to install with -O? In-Reply-To: References: Message-ID: <20021129202059.GC13460@eecs.tufts.edu> Hi Aahz. So, I can just set the PYTHONOPTIMIZE variable in my setup.py and python will take care of itself (both in unix n' windows)? Perhaps I should work on a distutils patch... -- Mike On Thu, Nov 28 @ 19:56, Aahz wrote: > In article , > Michael Gilfix wrote: > > > > Hi all. I've been using __debug__ in my python programs with the > >hope to byte-compile my programs with -O on install and remove the > >__debug__ code. However, I haven't figured out quite how to do this > >with distutils, and some searching through the documentation didn't > >reveal anything. Has anyone solved this problem? > > Unfortunately, there are only two ways to force optimized mode: running > "python -O" and setting PYTHONOPTIMIZE. -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From gminick at hacker.pl Wed Nov 13 11:32:02 2002 From: gminick at hacker.pl (Wojtek Walczak) Date: Wed, 13 Nov 2002 16:32:02 +0000 (UTC) Subject: os.system and wget References: <7d728336.0211130756.3e39a748@posting.google.com> Message-ID: Dnia 13 Nov 2002 07:56:48 -0800, zunbeltz napisa?(a): > I've download a web in a python script with > os.system('wget -q -O foo.txt http://foo.html') > but later (in same script) i can't open foo.txt > When the script finished the foo.txt is there, correctly donwloaded. > What is wrong? 1. Use full/absolute paths: os.system('/usr/local/bin/wget -q -O/tmp/foo.txt http://URL') 2. Use exceptions: import sys, os try: os.system('command') except: print sys.exc_info()[1] sys.exit() HTH. -- [ Wojtek gminick Walczak ][ http://gminick.linuxsecurity.pl/ ] [ gminick (at) hacker.pl ][ gminick (at) underground.org.pl ] From eddie at holyrood.ed.ac.uk Mon Nov 11 12:32:01 2002 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Mon, 11 Nov 2002 17:32:01 +0000 (UTC) Subject: [OT] Cameras (was Re: Why is Python popular, while Lisp and Scheme aren't?) References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: Fernando =?ISO-8859-1?Q?P=E9rez?= writes: >ps. The above doesn't quite apply to 'prosumer' digital P&S like the Canon >G2/G3. Because the sensor is so small, those cameras actually have decent >zooms. And they also have all the manual controls typical of an SLR. That's >because it's the only way the companies can sell to the market who wants >manual control but can't afford a 2k-8k true digital SLR. The G2 was what I went for in the end. I'm happy and fairly impressed. Time to learn a bit about photography I suppose. Eddie From mchermside at ingdirect.com Thu Nov 14 13:03:33 2002 From: mchermside at ingdirect.com (Chermside, Michael) Date: Thu, 14 Nov 2002 13:03:33 -0500 Subject: Unit testing - Using Java Mock Objects in Python? Message-ID: <902A1E710FEAB740966EC991C3A38A8903C35B10@INGDEXCHANGEC1.ingdirect.com> > > It would be great to have available the Java Mock classes available to > > be used from Python. > > Could you describe shortly what makes Mock valuable for you? > I wasn't able understand the distinct features of Mock Objects from > the web site. Is it that the framework manage deploying stubs rather > than the real code? Short answer: yes. Long explanation for those not familiar with it: JUnit, and it's close partner, Python's unittest module, are both tools that help you to EXECUTE your unit tests. They handle issues like how to run a bunch of tests at once, how to set up for and clean up after the tests, how to declare that you expect a certain result during a test, or that you expect an exception to be thrown. JUnit and unittest have lots of things that they DON'T do. For instance, they DON'T automagically write the tests for you (you have to actually write some lines of code to specify each test you want to run). They don't track coverage (to ensure every line of code or every possible code branch gets executed), although this might be possible with ADDITIONAL libraries. One other problem they don't solve is that of simulating external services. Suppose you write a program (in Java OR Python... the principle is the same) which reads from and writes to an Oracle database. Now, your unit tests need to test out code like "FindUserInDb()", and "DeleteAllUsersFromDB()". But if you REALLY invoke DeleteAllUsersFromDB on the real DB instance, it could be disasterous. The ideal solution might be to set up a separate instance of the database just for testing, but that makes for AWEFULLY slow setup()/teardown() methods and may be downright impossible (Oracle licenses aren't cheap!). You can easily see that the same problem extends to other external services besides Oracle databases. The usual design pattern for addressing this is called "mock objects". Basically, instead of using a REAL database connection object, you use a "fake" object, which simply remembers the arguments passed to it (so you can check to make sure they are what was expected by the test) and returns "rigged" outputs (so you can make the test go the way you wanted it to go). This kind of thing is actually QUITE EASY to do in Python, because the design of the language makes it easy to write generic handlers (using __getattr__, __setattr__, and friends). In Java it's a bit harder, but the folks at www.mockobjects.com have written some fairly good ones and they accept contributions. As for the original question, I don't know of a way to use java mock objects to debug Jython (or python) code. But there are a few places it could still be useful. One example would be the above... if your Jython code is accessing a database via JDBC, you could stub it out using the mockobjects JDBC mock classes. But to create a mock of a Python class, you're better off writing it in Python... it'll be easier to write, and more powerful to boot (better introspection and flexibility via __getattr__ & friends). -- Michael Chermside From exarkun at meson.dyndns.org Sun Nov 24 14:36:14 2002 From: exarkun at meson.dyndns.org (Jp Calderone) Date: Sun, 24 Nov 2002 14:36:14 -0500 Subject: Guido's regrets: filter and map In-Reply-To: References: <9PvekLArvL49Ewa2@jessikat.fsnet.co.uk> Message-ID: <20021124193614.GA19543@meson.dyndns.org> On Sun, Nov 24, 2002 at 03:40:09PM +0000, maney at pobox.com wrote: > Robin Becker wrote: > > I repeatedly get > > > > for loop took 5.81 > > list comprehension took 8.16 > > map took 4.23 > > > > with 2.2.2 win32 on a 1GHz pentium. > > [snip setup, timings] > > ### revised test with filtering > from time import time > > n = 1000000 > N = xrange(n) > > t0 = time() > S=[] > a = S.append > for x in N: > if x % 2 == 1: > a(str(x)) > print 'for loop took %.2f to make a list of %d items' % ((time()-t0), len(S)) > > del S > t0 = time() > S = [str(x) for x in N if x % 2 == 1] > print 'list comprehension took %.2f to make a list of %d items' % ((time()-t0), len(S)) > > del S > t0 = time() > S = map(str,filter(lambda x: x % 2 == 1, N)) > print 'map took %.2f to make a list of %d items' % ((time()-t0), len(S)) > ### > On my P2 Linux machine w/ Python 2.2.2: for loop took 17.74 to make a list of 500000 items list comprehension took 17.24 to make a list of 500000 items map took 12.72 to make a list of 500000 items However, changing the last filter to: S = map(str,filter((2).__rmod__, N)) (which is equivalent) improves the final time to 7.74 seconds. > Interesting chages when the filter is changed to select every seventh > item (s/x % 2/x % 7/ in three places): > > maney at wheel2:~$ python sorry.py > for loop took 2.57 to make a list of 142857 items > list comprehension took 2.57 to make a list of 142857 items > map took 2.94 to make a list of 142857 items > > maney at wheel2:~$ python2.2 sorry.py > for loop took 2.58 to make a list of 142857 items > list comprehension took 2.46 to make a list of 142857 items > map took 3.24 to make a list of 142857 items Adding this 4th test: def seventh(n): for e in n: if e % 7 == 1: yield e del S t0 = time() S = map(str, seventh(N)) print 'mapping generator took %.2f to make a list of %d items' % ( (time()-t0), len(S)) (and reverting the map/filter, since the trick doesn't work for 7 ;) gave me... for loop took 7.48 to make a list of 142857 items list comprehension took 7.37 to make a list of 142857 items map took 8.80 to make a list of 142857 items map took 6.68 to make a list of 142857 items showing us once again that function calls are slow, and to be avoided where ever possible! ;) I did notice one other solution that is orders of magnitudes faster than the above, it involves passing a couple extra parameters to range(). I'll leave determining exactly what it is as an exercise for the reader... Jp > > Okay, that's enough for now. > -- > http://mail.python.org/mailman/listinfo/python-list -- In the days when Sussman was a novice Minsky once came to him as he sat hacking at the PDP-6. "What are you doing?" asked Minsky. "I am training a randomly wired neural net to play Tic-Tac-Toe." "Why is the net wired randomly?" asked Minsky. "I do not want it to have any preconceptions of how to play." Minsky shut his eyes. "Why do you close your eyes?" Sussman asked his teacher. "So the room will be empty." At that moment, Sussman was enlightened. -- 2:08am up 22 days, 13:02, 6 users, load average: 0.08, 0.10, 0.09 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From tundra at tundraware.com Sat Nov 9 01:40:07 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: 09 Nov 2002 06:40:07 GMT Subject: Determining Presence Of GUI Support Message-ID: <42aiqa.jp82.ln@boundary.tundraware.com> Is there a portable method of determining whether the current runtime environment supports a GUI or text-based interface? I would like to write a single program which autosenses the presentation environment and works accordingly. -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From dave at pythonapocrypha.com Mon Nov 11 11:52:12 2002 From: dave at pythonapocrypha.com (dave at pythonapocrypha.com) Date: Mon, 11 Nov 2002 08:52:12 -0800 (PST) Subject: PEP #99484663 In-Reply-To: <1036990754.1525.123.camel@dsl-65-184-205-5.telocity.com> Message-ID: On 10 Nov 2002, Ian Bicking wrote: > On Sun, 2002-11-10 at 21:48, Dave Brueck wrote: > > You don't hear of long-time Python users complaining about the indentation > > thing; > > As an exception, anyone who uses or implements Python-embedded-in-HTML > style systems wants (and usually adds) an explicit block delimiter. > It's essential in that domain. That's one way to look at it, sure, but I'd argue that either (1) Python is the wrong tool in that circumstance or (2) it's an un-Pythonic approach to solving that problem. Setting aside the issue of whether or not it's a good idea to mix logic and presentation that closely anyway, the fact that Python + HTML (with OR without a delimiter) is so ugly should be a strong indication that there's something wrong. ISTM that using a block delimiter is a band-aid fix to a symptom where the real problem is that you're trying to do something in Python a certain way because that's the way it's done in other languages, rather than it being the best approach to the problem. FWIW, I don't find the blocks-of-code-embedded-in-HTML to work that well in other languages, either. :) It has always felt like such a hack and the result is unreadable and thus tough to maintain. -Dave From LogiplexSoftware at earthlink.net Wed Nov 13 19:03:16 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 13 Nov 2002 16:03:16 -0800 Subject: Presenting Data neatly... how :) In-Reply-To: <3dd2dd57$0$28316$fa0fcedb@lovejoy.zen.co.uk> References: <3dd2dd57$0$28316$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <1037232196.22832.18.camel@software1.logiplex.internal> On Wed, 2002-11-13 at 15:15, e-tones.co.uk wrote: > Hi all, im wring a command line python app that outputs 5 lines of data to > the user in the forum > > Name1 votes %votes > > so, an example output might be > > Dell 45 40% > Microsoft 60 56% > IBM 4 5% > > Is there anyway to format it like this: > > Dell 45 40% > Microsoft 60 56% > IBM 4 5% Sounds suspiciously like homework, so here's what you should turn in: votes = {'Dell': 45, 'Microsoft':60, 'IBM': 4} columns = { 'Company': max([len(n) for n in votes.keys() + ['Company']]), 'Votes': 3, 'Percent': 4 } format = "%%-%(Company)ss %%%(Votes)sd %%%(Percent)s.0f%%%%" % columns totalVotes = float(reduce(int.__add__, votes.values())) for company in votes: percent = votes[company] / totalVotes * 100 print format % (company, votes[company], percent) Be prepared to give a detailed explanation regarding how each line works to your instructor ;) -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 -------------- 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 Hobbes2176 at yahoo.com Fri Nov 22 09:35:07 2002 From: Hobbes2176 at yahoo.com (Mark) Date: Fri, 22 Nov 2002 14:35:07 GMT Subject: Boost.Python sans Jam References: Message-ID: I have this horrible tendency to work on something for awhile, post about it, go to bed, wake up, look for an answer to the post, spend another hour working on it, and produce the answer to my own question! In short, I wanted to compile a Boost.Python python extension without doing it from within the boost code hierarchy (as the boost examples and tutorial do). I set up ~/include/boost and ~/include/boost/python with all of boost's include files [although I don't believe they are all needed ... I only think ~/include/boost/python.hpp and ~/include/boost/python/* are necessary]. I set up ~/lib/ with libboost_python.so*, libboost_python_debug.so* libboost_python.so.1.29.0*, and libboost_python_debug.so.1.29.0* . Now, I realized I needed to do one thing before running [not necessarily before compiling my "boostable" extension]: export LD_LIBRARY_PATH=~/lib To compile, I used the following command line [there may be some unnecessary stuff in here]: g++ hello.cpp -I/home/mfenner/include -I/usr/include/python2.2/ -L/usr/lib/python2.2/config -L/home/mfenner/lib -lpython2.2 -lboost_python -o hello.so -shared Basically, I needed to specify the include files for boost and python, the library paths for both the python2.2 and boost_python libraries, and specify shared so g++ produces an shared object file. Now I can just type, in python: >>>import hello >>>hello.greet() Regards, Mark From mgarcia at cole-switches.com Fri Nov 15 18:40:44 2002 From: mgarcia at cole-switches.com (Manuel M. Garcia) Date: Fri, 15 Nov 2002 23:40:44 GMT Subject: Permutations algoritm? References: Message-ID: On Fri, 15 Nov 2002 15:51:04 -0600, sismex01 at hebmex.com wrote: (edit) >Of a set of different items 'S', obtain all distinct subsets of 'n' >items where all items in the subset are different. > >So, if I have, for example: > > S = [ 0, 1, 2, 3 ] > >the universe of available subsets of 3 items would be: > > s = [ (0, 1, 2), > (0, 1, 3), > (0, 2, 3), > (1, 2, 3) ] > >the universe of available subsets of 2 items would be: > > s = [ (0, 1), > (0, 2), > (0, 3), > (1, 2), > (1, 3), > (2, 3) ] import pprint def _subsets_ofsize_help(n, m): if m == 0: return [ [] ] elif n == 0: return [] elif m == 1: return [ [i] for i in range(n) ] else: s0 = _subsets_ofsize_help(n-1,m) s1 = _subsets_ofsize_help(n-1,m-1) for i in range(len(s1)): s1[i].append(n-1) s0.extend(s1) return s0 def _subsets_help(n): s = [ [] ] if n == 0: return s for i in range(n): s0 = _subsets_ofsize_help(n,i+1) s0.sort() s.extend(s0) return s def DistinctSubsets(set): return [ tuple([set[i] for i in s]) for s in _subsets_help(len(set)) ] pprint.pprint( DistinctSubsets( ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday')) ) ----Output----- [(), ('Sunday',), ('Monday',), ('Tuesday',), ('Wednesday',), ('Thursday',), ('Sunday', 'Monday'), ('Sunday', 'Tuesday'), ('Sunday', 'Wednesday'), ('Sunday', 'Thursday'), ('Monday', 'Tuesday'), ('Monday', 'Wednesday'), ('Monday', 'Thursday'), ('Tuesday', 'Wednesday'), ('Tuesday', 'Thursday'), ('Wednesday', 'Thursday'), ('Sunday', 'Monday', 'Tuesday'), ('Sunday', 'Monday', 'Wednesday'), ('Sunday', 'Monday', 'Thursday'), ('Sunday', 'Tuesday', 'Wednesday'), ('Sunday', 'Tuesday', 'Thursday'), ('Sunday', 'Wednesday', 'Thursday'), ('Monday', 'Tuesday', 'Wednesday'), ('Monday', 'Tuesday', 'Thursday'), ('Monday', 'Wednesday', 'Thursday'), ('Tuesday', 'Wednesday', 'Thursday'), ('Sunday', 'Monday', 'Tuesday', 'Wednesday'), ('Sunday', 'Monday', 'Tuesday', 'Thursday'), ('Sunday', 'Monday', 'Wednesday', 'Thursday'), ('Sunday', 'Tuesday', 'Wednesday', 'Thursday'), ('Monday', 'Tuesday', 'Wednesday', 'Thursday'), ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday')] Manuel From tim.one at comcast.net Sun Nov 17 18:48:23 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 17 Nov 2002 18:48:23 -0500 Subject: What is the best way to merge two lists? In-Reply-To: Message-ID: [John Hunter, explains stability in sorting] > ... > Incidentally, the efficiency of sort in the yet-to-be-released > python2.3 is rumored to be substantially improved. For random data, it seems platform-dependent which wins, with more platforms seemingly giving the edge to the 2.3 sort due to cache effects. Both methods do very close to the theoretical minimum # of compares on randomly ordered data, so there was no room for "deep" improvement on random data (and I'm just talking about CPython there; Jython's sort was a variant of CPython's much older quicksort, and Jython benefited a lot even on random data when Finn Bock ported the new sort to Java). Where the 2.3 sort kicks ass is in exploiting many more kinds of partial pre-existing order. Lots of real data *is* partially ordered already, and the algorithm discovers that and adapts to it, saving mountains of comparisons when possible. BTW, the 2.3 sort is stable, although the language specification doesn't guarantee that. From abidnego25 at yahoo.com Thu Nov 14 14:29:18 2002 From: abidnego25 at yahoo.com (les) Date: 14 Nov 2002 11:29:18 -0800 Subject: parsing python code Message-ID: <653cf871.0211141129.681e5dd7@posting.google.com> Hi, i would like to find out the function call tree of a python code. i.e. say i have a code like this: def fun111(): .. def fun11(): fun111() def fun1(): fun11() fun12() if __name__ =='__main__': fun1() then i would like to build a dictionary like this d ={ 'root': '__name__', '__name__': ['fun1'] 'fun1': [ 'fun11','fun12'], 'fun11': [ 'fun111'] } it is easy to parse out function names from the code, but not so easy to jump around to figure the tree structure. is there a module which exports some function when given a functionname returns all the functions it calls? (only those functions that are in the source code) so far i have something like this that removes the function names but before i try the brute force way,i wanted to ask if there is already a module that does what i want ###################################### from sys import argv,exit,stdin if __name__ == '__main__': try: codefile = argv[1] except IndexError: print 'USAGE %s ' % argv[0] exit(-1) #pull out function names fp = open(codefile) fun_names=[] for x in fp: if x[0:3]=='def': fun_names.append( x.split()[1].split('(')[0]) print fun_names fp.close() # go thought the file again and build nested list nested={} fp = open(codefile) ################ I NEED HELP HERE fp.close() thanks From rjkuhns at geetel.net Wed Nov 27 10:53:31 2002 From: rjkuhns at geetel.net (Richard Kuhns) Date: Wed, 27 Nov 2002 10:53:31 -0500 Subject: Tkinter scrolling canvas questions Message-ID: <20021127105331.7368a20c.rjkuhns@geetel.net> I'd appreciate any comments or suggestions on the best way to proceed with a problem. I'm fairly new to GUI programming, and I'd appreciate some pointers. I have a list of lists of (name, variable) tuples I'd like to display. In addition, I want to allow the variable's value to be changed/editted. It looks something like: li = [ [("a", a), ("b", b), "c", c)], [("d", d), ("e", e), "f", f)] ] There's no limit on how many elements li can have, but each element will be the same size. What I have in mind right now is to create a Frame for each element of the toplevel list. Each Frame would contain Label and Entry widgets for each tuple in that element. After each Frame is created I would then append it to the end of a vertically scrollable Canvas. Does this sound reasonable? If so, is there a good way to determine a good size for the canvas? Each frame in the canvas will be a single line; how do I query the Label and Entry widgets to determine the size of the font being used? I've been studying the Tkinter section of Programming Python 2E but I haven't been able to track down what I need. The word "font" doesn't even appear in the index :(. Are there any other "gotchas" I should watch out for? Thanks... - Dick -- Richard Kuhns rjkkuhns at geetel.net From tudisco at sexmagnet.com Mon Nov 4 16:08:01 2002 From: tudisco at sexmagnet.com (Jason Tudisco) Date: 4 Nov 2002 13:08:01 -0800 Subject: Need simple algorithm for newbie References: Message-ID: Thanks everyone for you help... I also got this in my email.. Wanted to post it here also.. just in case somebody else was interested. thanks.. you guys have been lots of help ------------------ Note if the list origonally came from a file (one per line), then: sed 's/^[^.]*\.\([^.]*\)\.\([^.]*\)/\1.\2/' ... > I have a list of domains... Some of the domain names in the list look > like this: > > groups.goodle.com > > The information I want is just google.com. I need to know the best way > to do this.. for .com .net .org only.. and to strip the rest of the > garbage.. like in this case.. get rid of groups in groups.google.com > > I need to parse though a huge list so it has to be optimized algorithm > > No need to write complete code.. Just get me in the right direccion.. > Still learning python and I am not sure what would be the fastest way > to go about it.. From mwh at python.net Wed Nov 20 07:57:38 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 20 Nov 2002 12:57:38 GMT Subject: need help porting ctypes to Linux References: <8yzp5pgv.fsf@python.net> <7h3zns4tpqr.fsf@pc150.maths.bris.ac.uk> <1y5g2z6r.fsf@python.net> Message-ID: <7h3vg2stna5.fsf@pc150.maths.bris.ac.uk> Thomas Heller writes: > Michael Hudson writes: > > > Try executing > > > > ulimit -c unlimited > > > > before running your program. > > Yup, works now. Cool. > > > Do I have to enable this? Or is it possible to configure gdb so > > > that it will automatically pop up to examine the program's state? > > > > If you run your program under gdb (i.e. execute > > > > $ gdb python > > > > and type "run") then any signal -- including sig 11 -- will dump you > > into gdb. > > Ok, so I'll have to put a 'rawinput()' before the crashing code, > and then press ^C, and set my breakpoints. Usually I let gdb start python up as far as the interactive prompt, use ^Z to get back to gdb, set breakpoints, use 'c' to continue my program and run the problem code interactively. In particular, using ^Z may be less confusing than using ^C. Not sure, though. Cheers, M. -- Premature optimization is the root of all evil. -- Donald E. Knuth, Structured Programming with goto Statements From lawrence_jesse at yahoo.ca Thu Nov 21 10:28:12 2002 From: lawrence_jesse at yahoo.ca (Jesse Lawrence) Date: Thu, 21 Nov 2002 10:28:12 -0500 (EST) Subject: Problem with list assignment Message-ID: <20021121152812.80906.qmail@web11306.mail.yahoo.com> I'm using the following function to retrieve the headers from my mysql columns. I want to shed the extra info, and just maintain the name of the column. This might be really simple, but I can't seem to figure out why the assigment of the headers to the list header[] in my for loop isn't working. Here's the function: def mysqlFieldNames(conn): cursor = conn.cursor() cursor.execute ("DESCRIBE guestbook") row = cursor.fetchall() cursor.close() # here's the problem area: header = [] i = 0; for r in row: header[i] = r[0] i = i + 1 return header Now, when I just do a print r[0] in the for loop, I'm getting exactly what I want, it's just that when I try to assign it to header, that I get a "list assignment index out of range" error. Am I overlooking something? Thanks very much, Jesse Lawrence ______________________________________________________________________ Post your free ad now! http://personals.yahoo.ca From slawus at imf.au.dk Sat Nov 9 09:17:23 2002 From: slawus at imf.au.dk (Slawus) Date: Sat, 09 Nov 2002 15:17:23 +0100 Subject: MS Windows + Python + VTK -- how to install? References: Message-ID: Ok. This time I will try to ask better question: I can not run VTK with my Python 2.2.2 on Win2k. First: I have got Python for Windows and some libraries for it working very well: - Python 2.2.2 - binaries for win32 - Numeric 22 - binaries for win32 - numarray 0.3.6 - binaries for win32 - SciPy 2.0 alpha 145.4398 - binaries for win32 - wxPython 2.3.3 - binaries for win32 - PyOpenGL 2.0.0.44 - binaries for win32 - Python Imaging Library 1.1.2 - also binaries for win32 I test some examples from wxPython and I extensively use SciPy and Numeric for some calculations. As I said all above works very well. Now, I want to use Visualization Toolkit (vtk) library. I download this files: - vtkNightlyCore.exe (ver. 11/9/2002) - vtkNightlyPython.exe (ver. 11/9/2002) and I have installed it in default directory: c:\Program Files\vtkNightly I have also add to windows PATH variable this directory: c:\Program Files\vtkNightly\bin I tried to add directories: c:\Program Files\vtkNightly\bin c:\Program Files\vtkNightly\Wrapping\Python to PYTHONPATH in windows registry but it seems not work becouse: >>> import sys >>> print sys.path do not show them. But I add this two vtk directories by hand by sys.path.append() command. Command: >>> import vtk when I put them first show: --- Traceback (most recent call last): File "", line 1, in ? import vtk File "C:\PYTHON22\Lib\site-packages\vtk_python\vtk\__init__.py", line 7, in ? from common import * File "C:\PYTHON22\Lib\site-packages\vtk_python\vtk\common.py", line 9, in ? from vtkCommonPython import * ImportError: No module named vtkCommonPython --- but when I repeat this twice it looks ok: >>> import vtk #second time >>> But I still can not use vtk: --- >>> cone = vtkConeSource() Traceback (most recent call last): File "", line 1, in ? cone = vtkConeSource() NameError: name 'vtkConeSource' is not defined --- Please direct me what should I do to make VTK working? Ps. I also try use setup.py from vtk python package. -- Greetings. Slawomir Razniewski. From kemu at sdf-eu.org Sat Nov 23 11:47:48 2002 From: kemu at sdf-eu.org (Jonas Geiregat) Date: Sat, 23 Nov 2002 17:47:48 +0100 Subject: ~~~ Python Use Question ~~~ In-Reply-To: <2a001b6.0211230739.13aaf7c5@posting.google.com> References: <2a001b6.0211230739.13aaf7c5@posting.google.com> Message-ID: <3ddfb0be$0$86556$ba620e4c@news.skynet.be> smartcardware.com wrote: > Greetings! I am the lead developer in a upcoming game company that > will start work on a new game at the beginning of 2003. We are (like > everyone else in the gaming industry right now) searching for a > scripting language to use in our game. I've heard that Python is a > great scripting language with one downfall for game > designers/programmers. That is that you must embed your code into > Python, instead of convensional scripting langauges where you embed > the scripting language into your code. Basically we want to use > scripting languages for AI, game items stats, player stats, and a few > other things. We'll use an advanced 3d engine (C++) for the rest. > What we don't want to have to develope our code around Python, > rather develope our code and embed Python to fit our code when and > where we desire. > > Any and all imput would be great! Thanks! > > Venn Syii And what is your question or point by posting this ? From SBrunning at trisystems.co.uk Mon Nov 4 04:49:21 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Mon, 4 Nov 2002 09:49:21 -0000 Subject: Foot in mouth disease Message-ID: <31575A892FF6D1118F5800600846864DCBDA85@intrepid> > From: Derek Thomson [SMTP:derek at wedgetail.com] > Aahz wrote: > > She asked me what -- if any -- Java-based tools were used by > > the experienced Java programmers who made that claim. She thinks that > > those tools are superior to plain text editors (which are really all > > that's needed for Python). > > Eclipse ... for about one day. Far too painful, (snip) Hmm. Well, Java is my day job, and I've been using Eclipse for a year or so. For me, the refactorings work just fine. Now, I've not used EMACS, so I can't do a comparison, but Eclipse's refactorings are a *whole* lot better that doing refactoring with a 'dumb' text editor. The auto-completion and so on are also great. If you work with Java, and aren't hairy-chested enough for EMACS, give Eclipse a try. You won't regret it. Unless you have less than 256MB, that is. ;-) Reasonable-men-can-differ,-but-not-with-me-ly y'rs, Simon B ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From jdhunter at nitace.bsd.uchicago.edu Fri Nov 15 20:23:18 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Fri, 15 Nov 2002 19:23:18 -0600 Subject: help plz ive been to atleast 10 different faqs and guides In-Reply-To: <004801c28d0b$cdc93ef0$aed7bd18@mouseoh7s2nyon> (cmvb's message of "Fri, 15 Nov 2002 20:02:15 -0500") References: <004801c28d0b$cdc93ef0$aed7bd18@mouseoh7s2nyon> Message-ID: >>>>> "cmvb" == cmvb writes: cmvb> um yes id like to make a program so when you ask a question cmvb> it responds with a preset set of random responses is this cmvb> possible? Yep. I just hope you aren't trying to write one of those spam bots trying to imitate a person while advertising in a chat room. import random answers = ['Are you crazy?', 'Exactly.', 'Are you through yet?', 'Yeah, I remember when I had my first beer', ] # ind is a random index into the answers list ind = random.randrange(len(answers)) print answers[ind] This is sampling with replacement. If you want sampling without replacement, there are other options.... Here is a link to the library documentation for the random module http://www.python.org/doc/lib/module-random.html Cheers, John Hunter From jdhunter at ace.bsd.uchicago.edu Mon Nov 18 10:22:35 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 18 Nov 2002 09:22:35 -0600 Subject: popkey() method for dictionaries? In-Reply-To: (Fernando =?iso-8859-1?q?P=E9rez's?= message of "Mon, 18 Nov 2002 02:18:50 -0700") References: Message-ID: >>>>> "Fernando" == Fernando P?rez writes: Fernando> Sure. First, on principle: the exception option is still Fernando> there, if no default is provided. What giving a default Fernando> buys you is not having to trap the exception Fernando> yourself. If you want a missing key to generate an Fernando> exception, simply don't give a default and that's Fernando> it. But then you break the symmetry with get, which provides None as a default if no default is provided. Aren't you now back in danger of violating the principle of least surprise? John Hunter From markus.vonehr at ipm.fhg.de Tue Nov 26 11:23:51 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Tue, 26 Nov 2002 17:23:51 +0100 Subject: wxPython Prob Message-ID: <3DE3A017.AEE4CE2B@ipm.fhg.de> Hi, I worte a small sample app using wxToolBar. There occurs the error that the bitmaps used in: images.getNewBitmap() images.getOpenBitmap() etc. are not found. (I imported images in the beginning.) Anyone knows the answer? Markus From jkraska at san.rr.com Mon Nov 18 23:45:07 2002 From: jkraska at san.rr.com (Courageous) Date: Tue, 19 Nov 2002 04:45:07 GMT Subject: static variables? References: Message-ID: >I am a python newbie, and I am sure there is an easy answer but, Is there >any equivalent to C's static variables in Python? If not, how can you have >variables inside a function, that 'remember' their values between function >calls? Usually this is done as a member on the Class and not on in the Instance. Like this: >>> class MyClass: myStatic=0 def f(self): MyClass.myStatic+=1 print `MyClass.myStatic` >>> c = MyClass() >>> c.f() 1 >>> c.f() 2 >>> From Padraig at Linux.ie Tue Nov 26 11:39:34 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Tue, 26 Nov 2002 16:39:34 GMT Subject: How to convert ASCII-number => HEX -number => string of numbers in HEX ? References: <3de39ca8$1@news.vip.fi> Message-ID: <3DE3A33E.3050505@Linux.ie> Pekka Niiranen wrote: > Hi, > > I looked thru modules binascii and struct but not found a way to > convert hexadecimal value to a string of hex values according to ascii > table. > > Example: > > number = 6673 (max is 0xFFF) > hex -value = '0x1a11' > string value = "\x31\x61\x31\x31" (31 is one, 61 is 'a') > > or: > > number = 333 (max is 0xFFF) > hex -value = '0x14d' string value = "\x30\x31\x34\x64" > (30 is zero, 31 is one, 34 is four, 64 is "d") > > I have got this far: > > x="" > a = hex(333) > for byte in a[2:].zfill(4): # Number is allways presented with 4 > hex values (filling missing values with zeros) > x = "%s%s" % ( WHAT HERE ) > > Anybody, is there a build in function or shortcut that does this ? x='' for byte in string.zfill(hex(6673)[2:],4): x=x+ r'\x%02x' % ord(byte) Hmm ''.zfill() isn't present on python 2.2 at least? (string.zfill() is?) P?draig. From phil at river-bank.demon.co.uk Mon Nov 4 04:03:05 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Mon, 4 Nov 2002 09:03:05 +0000 Subject: pyqt rules In-Reply-To: <2Dkx9.42039$Lg2.11444432@news2.news.adelphia.net> References: <3dc550fb$0$9008@echo-01.iinet.net.au> <2Dkx9.42039$Lg2.11444432@news2.news.adelphia.net> Message-ID: <200211040903.05315.phil@river-bank.demon.co.uk> On Monday 04 November 2002 2:06 am, Bob X wrote: > "Phil Thompson" wrote in message > news:mailman.1036370164.21605.python-list at python.org... > On Sunday 03 November 2002 9:33 pm, Bob X wrote: > > > >The binary of Qt NC is at > >http://www.trolltech.com/developer/download/qt-win-noncomm.html > > Under the requirement it states that Visual Studio 6 is required. Does that > mean only for integration into the IDE or does that mean I have to compile > the download with it? I guess I am just confused about the lingo they are > using. I have been to that page several times and always thought they meant > here is the Qt stuff BUT you have to compile it with VC6. They mean that you need VC6 to write C++ apps with Qt NC. > >The binary of PyQt for Qt NC is at > >http://www.riverbankcomputing.co.uk/pyqt/download.php > > So I get the binary (exe's) for both...run 'em and now I can do PyQt? Correct - so long as you conform to the license conditions. Phil From e_viola at libero.it Thu Nov 21 12:18:31 2002 From: e_viola at libero.it (bart) Date: Thu, 21 Nov 2002 17:18:31 GMT Subject: variable scope Message-ID: <3DDD157D.3090609@libero.it> Could I modify variable present inside an object's method from external module without override method of this class? Example: -->Module A class Person(): def __init__(self): variable=value -->Module B Person.__init__.variable=value (it's surely mistake!!!) Another question is: can I override an object's method locate in modeule B from module A when this object is created from another functions presents inside module B? Example: Module A ----> Module B ---> function A ---> function B ---> object A thanks for yours attention... - Ennio - From SBrunning at trisystems.co.uk Wed Nov 27 11:20:13 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Wed, 27 Nov 2002 16:20:13 -0000 Subject: do you guys help newbies?? Message-ID: <31575A892FF6D1118F5800600846864D01200302@intrepid> > From: Wojtek Walczak [SMTP:gminick at hacker.pl] > Dnia Wed, 27 Nov 2002 15:53:20 GMT, Robin Munn napisa?(a): > > You could also do this in one step, like: > > gallonsPerTank = int(raw_input("Enter how many gallons...")) > It of course works, but there's a large amount of situations to think of. > > --- > import sys > try: > while 1: > a = raw_input("Put a digit here: ") > if not a.isdigit(): > a = raw_input("Put a digit here: ") > else: > a = int(a) > break > except: > print sys.exc_info()[1] > sys.exit() > > print a > --- > > Any ideas to make it more reliable ? See . Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From irmen at NOSPAM-REMOVETHIS-xs4all.nl Fri Nov 8 21:22:29 2002 From: irmen at NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 09 Nov 2002 03:22:29 +0100 Subject: socket.py and 2.2.1 In-Reply-To: References: Message-ID: <3dcc7165$0$46608$e4fe514c@news.xs4all.nl> Susan Williams wrote: > We're finally getting around to upgrading from 1.5.2 to 2.2.1... ;-) Why not upgrade to 2.2.2? It's been available for several weeks now... Irmen From nas at python.ca Thu Nov 14 16:36:48 2002 From: nas at python.ca (Neil Schemenauer) Date: Thu, 14 Nov 2002 13:36:48 -0800 Subject: My (late) beef with Simple Generator syntax (PEP 255) In-Reply-To: References: Message-ID: <20021114213647.GA32110@glacier.arctrix.com> Just wrote: > IMO the best idiom for this currently is > > def foo(): > while 0: > yield "whatever" This whole discussion is silly, IMHO. The best idiom is: def foo(): return [] If you really want an interator, then: def foo(): return iter([]) Requiring that the type returned by foo be is un-Pythonic and silly. If you do want that, the best solution would be the very clever suggestion of: def foo() if 0: yield None Neil From costanza at web.de Mon Nov 11 05:33:43 2002 From: costanza at web.de (Pascal Costanza) Date: Mon, 11 Nov 2002 11:33:43 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCD8571.6CACEA04@alcyone.com> <3DCF2127.8080602@something.invalid> Message-ID: <3DCF8787.9000607@web.de> Greg Ewing wrote: > Pascal Costanza wrote: > >> In Common Lisp, you can have: >> >> (paint circle :on canvas :at point) >> >> Given that you have defined paint as follows: >> >> (defun paint (&key on at) >> ...) > > Python still goes one better, because (for user-defined > methods at least) you can supply arguments by keyword even > if they *haven't* been declared that way! No problem. (defun paint (&key on at &allow-other-keys) ...) ;-) Lisp's argument options are rather complete. Here's another nice example. (defun test (&key (arg nil arg-supplied)) (if arg-supplied (format t "The argument was ~A.~%" arg) (format t "No argument was supplied."))) > (test :arg 5) The argument was 5. > (test :arg nil) The argument was nil. > (test) No argument was supplied. Pascal -- Pascal Costanza University of Bonn mailto:costanza at web.de Institute of Computer Science III http://www.pascalcostanza.de R?merstr. 164, D-53117 Bonn (Germany) From dgemic at nospam.net Fri Nov 15 18:22:57 2002 From: dgemic at nospam.net (Drazen Gemic) Date: Sat, 16 Nov 2002 00:22:57 +0100 Subject: Serial Port References: Message-ID: <3DD581D1.1080303@nospam.net> Luca Bruderer wrote: > Hello > > How can I read and send information through a serial port for a custom > keyboard I would like to build. > > Under UNIX-like OS's it is posible to start an aplication with serial line as standard input & output. Serial port can be configured with stty command. Aplication can read and write standard input and output without knowing anything about serial port. DG From bokr at oz.net Tue Nov 26 12:28:50 2002 From: bokr at oz.net (Bengt Richter) Date: 26 Nov 2002 17:28:50 GMT Subject: Coaxing DWORD values out of a Binary file... References: <0pGE9.6590$1r1.259632@newsc.telia.net> Message-ID: On Tue, 26 Nov 2002 08:37:16 GMT, "Fredrik Lundh" wrote: >adeptus wrote: > >> I've tried unpacking them via the struct module, (by passing them in as 4 >> byte strings) but the numbers I get don't seem to make any sense for the >> file format... >> >> Am I making a naive assumption about how VC++ would write a DWORD to a >> binary file??? >> >> I'm also assuming that: >> (i386 centric) >> 8-Bits = 1 Char = 1 Byte >> 1 Word = 2 Bytes >> 1 DWORD = 4 Bytes >> >> What I'm asking is, what is proper officially pythonic way of accessing >> DWORD values stored in a binary file by a VC++ program??? > >for some reason, there seem to be a new trend on this newsgroup >where people post lame replies without even attempting to answer >the original question. sorry for that. here's the correct answer: In this case "people" was me, I think. I could have made the same guess you did, but I chose not to. > > struct.unpack(" >From what the OP says, he already tried some version of this, perhaps exactly this. We don't know. >(little-endian, four-byte unsigned integer) > >to avoid problems on non-Unix platforms, also make sure you open >the file in binary mode: > > f = open(filename, "rb") > data = f.read(4) Presumably the OP tried some code close to this also. I guessed that the OP had read the struct module docs, and not opening in binary was the most likely problem, which I mentioned, albeit in the context of a complaint. > >to debug, use "print repr(data)" or "print data.encode('hex')" and >make sure the data is what you expect it to be. > This is good specific advice, which I also suggested in a general way. I am a bit chastened, and will try to improve my tone, but I think I will continue to noodge people about posting snippets of actual interactive experiments demonstrating their problems instead of creating unnecessary ("lame" ;-) guesswork. Regards, Bengt Richter From bokr at oz.net Thu Nov 21 15:38:06 2002 From: bokr at oz.net (Bengt Richter) Date: 21 Nov 2002 20:38:06 GMT Subject: Gnuplot on Windows References: Message-ID: On Thu, 21 Nov 2002 15:11:32 +0000, "Paul Simmonds" wrote: [...] >Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 >Type "help", "copyright", "credits" or "license" for more information. >>>>import Gnuplot >>>>a=Gnuplot.Gnuplot() >>>>a.plot('1.dta') # A simple data file >Traceback (most recent call last): > File "", line 1, in ? > File "F:\SIMMONDS\python22\Lib\site-packages\Gnuplot\_Gnuplot.py", line >281, in plot > self.refresh() > File "F:\SIMMONDS\python22\Lib\site-packages\Gnuplot\_Gnuplot.py", line >222, in refresh > self(self.plotcmd + ' ' + string.join(plotcmds, ', ')) > File "F:\SIMMONDS\python22\Lib\site-packages\Gnuplot\_Gnuplot.py", line >206, in __call__ > self.gnuplot(s) > File "F:\SIMMONDS\python22\Lib\site-packages\Gnuplot\gp_win32.py", line >122, in __call__ > self.write(s + '\n') >IOError: [Errno 22] Invalid argument >>>># Working through the hierarchy gives me >>>>a.gnuplot.gnuplot > ^^^ ^^^ Why would a .exe file be opened with mode 'w'?? Or at all? Creating or modifying exe's on the fly could be not so nice for your system ;-/ I would want to check that out carefully. >>>>a.gnuplot.gnuplot.write("hello") >Traceback (most recent call last): > File "", line 1, in ? >IOError: [Errno 22] Invalid argument > >I had a check through the Gnuplot-py project page, and there was another >support request describing the same thing, but no answer was given. > >I'd be grateful for any comments. No experience with Gnuplot, sorry. But that open file caught my eye. Hope it's a useful clue. Regards, Bengt Richter From tim at frontier.net Fri Nov 8 01:11:42 2002 From: tim at frontier.net (Tim H) Date: 7 Nov 2002 22:11:42 -0800 Subject: PySol Windows binaries, anyone? References: Message-ID: <5453f6e4.0211072211.2480c257@posting.google.com> Christian Tismer wrote in message news:... > Dear Python Community, > > my wife is unhappy. She used to play PySol for years. > Recently, I tried to install the latest version, > but didn't get it to work. Unfortunately, I wiped > the old installation before. :-( > > It is known that Markus lost his Windows stuff, there is > no more an installer (no problem), and a couple of > Windows specific functions are missing. That's the problem. > > Does somebody have a working PySol for me? > Or maybe one of the last working installers is still > around? I'd also put this on my website for people > to download. Markus seems to be no longer reachable > by email. > > As the last resort, I also could write the missing C functions, > but I really hope somebody has them still around. I'm also > not sure what else is missing. > > many thanks in advance - chris Hey Christian, The latest pysol Windows installer I have found is 4.60, if you google for pysol460.exe you will find a couple places to get it. As a last resort, reply to me and I will send it. Good luck, Tim H From andymac at bullseye.apana.org.au Mon Nov 18 16:57:36 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Tue, 19 Nov 2002 07:57:36 +1000 (est) Subject: python-dev Summary, 2002-11-01 through 2002-11-15 In-Reply-To: Message-ID: On 17 Nov 2002, Brett C. wrote: > The majority of the thread was spent trying to get FreeBSD 4.4 to > compile Python and trying to work out a possible bug in pymalloc. Sorry I didn't pick this up before, but that FreeBSD thread was about FreeBSD-CURRENT (what will shortly become FreeBSD 5.0), and not FreeBSD 4.4. The -CURRENT issue has to do with the FreeBSD developers taking a more stringent view of the interpretation of certain standards related symbols, which affects what libc symbols are visible in the standard C headers. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From see_reply_address at something.invalid Wed Nov 27 23:57:48 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 28 Nov 2002 17:57:48 +1300 Subject: floating point division -- question References: <%jaF9.16948$yk6.10839@fe03> Message-ID: <3DE5A24C.8060606@something.invalid> Steve Holden wrote: > But there's simply no way you could do that. If you'd used "/" for integer > division then programs that used it with float operands would have broken. > Either way it's a change in semantics, and that's why Guido has decreed the > change will take so long. The only way to avoid breakage altogether would have been to introduce *two* new operators, one for integer-only division and one for float-only, and leave / alone completely. Then we would have had a situation where the most obvious symbol for division was the one least recommended for use. That would have been very ugly. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From idoerg at burnham.org Fri Nov 8 22:52:39 2002 From: idoerg at burnham.org (Iddo) Date: 8 Nov 2002 19:52:39 -0800 Subject: Using bsddb with Berkeley DB 3.3 Message-ID: <5361ecc1.0211081952.6158b00c@posting.google.com> Hi, I am using the Python2.2 bsddb interface with a BerkeleyDB 3.3.11, on Linux RH7.3 As I was unaware that there are more updated packages not in the standard python distribution (just found out), I have written quite a bit of code using bsddb.I am pretty much the newbie to this aspect of Python (basically, I needed some good serialization, I do not know much about the Berkeley DB). 1) Is this really bad? If so, is there an easy way to "upgrade". 2) My databases seem to be terribly large. For example, I converted a 2.6GB hashdb (created with Python too) to BTree, and it blew up to ~10GB. Is it the old interface? Something else? Where to I start checking? Thanks, any additional info given would be appreciated. Iddo From tjreedy at udel.edu Thu Nov 21 12:40:56 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 21 Nov 2002 12:40:56 -0500 Subject: static variables? References: <3DDAFA97.92B70465@alcyone.com> <3DDB3373.2578CEC0@alcyone.com> <3DDC1874.F72E2B35@alcyone.com> Message-ID: "Erik Max Francis" wrote in message news:3DDC1874.F72E2B35 at alcyone.com... > Terry Reedy wrote: > > > If I understand this, you are proposing that if a default is > > 'mutable', then extra magic be added to re-initialized (somehow) on > > every call. > > I am doing no such thing. Ok, you are 'proposing' that extra magic is *possible*, that it *could* be added, or rather, have been added from the beginning. > I am simply stating that there is no a priori > reason why it _couldn't_ have been done that way. Given that we all know that anything programmable could be done, the above does not say anything. I thought you were saying something more (ie, that there is a plausibly good and not just possible alternative). > It wasn't done that way, and I am not suggesting it be changed, OK, actual change of the language is a non-issue. > just justifying my position that the way it's done right now is an arbitrary choice I presume you mean 'was', referring to the original choice rather than 'is', referring to the continual choice not to change, which we agree on as rational (and to me, therefore, non-arbitrary). To make a concrete choice, there must be a concrete alternative. As I explained in my previous post, your other 'way' that defaults could have been handled covers many possibilities. I interprete you as saying that at least one of the underspecified alternatives would have been just as rational a choice, had GvR but thought of it and considered it. 'Arbitrary' has a range of meanings and connotations from discretionary, according to preference, through whimsical, capricious, or random, to despotic or dictatorial. I'll let you clarify which you mean, if you wish, before arguing this point much further. > (simply because it is the easiest to implement). If arbitrary means random (not based on rational consideration, could just as well have been decided by a coin flip), then this is a denial of arbitrariness 8-) > Whether the way it's currently done is a good idea is another question; 'Good' on some absolute scale, or as compared to your underspecified alternative? > it seems from the constant confusion that this issue causes, it doesn't > seem so to me: It causes confusion for newbies, We agree that confusion is not good. Whether any particular (hypothetical) alternative would be (would have been) better or worse in this respect is a different question. I see three possible responses to the current situation: 1. Let the confusion continue, with or without occasional bitching. (2. Change the language, but this is off the table.) 3. Improve the presentation of what is so it is somehow less confusing. Here is why I am bothering to discuss and dispute your claim. Presenting something as capricious or despotic is unlikely to disperse confusion. Explaining why is it as it is and some of the problems of doing it differently might. Terry J. Reedy From thanks200 at hotmail.com Thu Nov 21 18:47:22 2002 From: thanks200 at hotmail.com (Tom Hanks) Date: 21 Nov 2002 15:47:22 -0800 Subject: [Boost.Python] Printed documentation available? Message-ID: <6152d0a0.0211211547.2afdb8df@posting.google.com> I hope the subject says it all. I'd like a printout of the Boost.Python documentation (found at http://www.boost.org/libs/python/doc/index.html) for my daily train trips. Unfortunately for me the available documentation is not printer-friendly. Instead it is browser-friendly, organised into an html tree 3-4 pages deep. I've googled for a couple of hours but can't find a more suitably formatted document. Can someone recommend a way to get a printable version? Thankyou for your help in reading this far, Tom Hanks. From martin at v.loewis.de Wed Nov 13 14:31:40 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 13 Nov 2002 20:31:40 +0100 Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> Message-ID: Fernando P?rez writes: > Good luck. Writing such a tex<->xml converter is an insanely > non-trivial task, and I know a few bright people who have tackled > it. Python does have one. > If you do succeed, _please_ let the Lyx team know about it. I don't think that the Lyx team would like to use it, though, since it is specific to the Python documentation. > Latex is very hard to parse correctly, from what I've seen. In the general case, yes. Not when it is Python documentation. > Considering it's basically a full-blown programming language, > short of rewriting TeX itself, this won't be a simple task... If you can enforce constraints on the constructs used, parsing it is a manageable task. Regards, Martin From imbosol at vt.edu Tue Nov 26 05:45:16 2002 From: imbosol at vt.edu (Carl Banks) Date: Tue, 26 Nov 2002 05:45:16 -0500 Subject: if : References: Message-ID: Duncan Booth wrote: > Carl Banks wrote in news:aruf6o$bd7$3 at solaris.cc.vt.edu: > >>> Now it's gonna be interesting to see if I ever run into a situation >>> where I'd feel most comfortable doing an if :, knowing >>> that there are usually better ways of solving the problem. >> >> Testing a bunch of regular expressions on some input and taking action >> on the first match seems to do it for a lot of people.> > > If you have more than one or two patterns, then you should really be > thinking about a loop rather than a long list of if statements: > > PATTERNS = [ > (regex1, action1), > (regex2, action2), > # ... > ] > > for regex, action in PATTERNS: > match = regex.match(string) > if match: > action(match) > break > > I don't see any need for assignment in an 'if' here. Other people often clamor for assignment if here, because the way you did is an unnatural and circumlocative way to do something most people, myself included, want to do as a sequential piece of code. I don't want an assignment if because I have a great distaste for it, so I usually use other workarounds whenever I want to do something like this. But I don't blame anyone who doesn't want to break up their code the way you did, making it less straightforward in the process. -- CARL BANKS From bogusdrop at myself.com Sat Nov 2 03:28:32 2002 From: bogusdrop at myself.com (TuxTrax) Date: 2 Nov 2002 00:28:32 -0800 Subject: Protect Python Source References: Message-ID: <30770aa4.0211020028.1434bd34@posting.google.com> "David Brown" wrote in message news:... > "TuxTrax" wrote in message > > > > > Your comments reveal a thoughtful and curious approach that is quite > healthy. > > It also reveals a world view that has in large part been shaped by the > > philosophies of proprietary software companies. > > > > Is a python compiler available for linux? I don't know. I do know that no > > Linux users I know would even consider using one. It would never cross our > > minds to make our source closed to others. This is where the whole open > source > > software movement takes a completely different world view. In open source > > software, you retain the right to make a profit from your work, while > still > > granting others the right to copy, distribute, modify and view the source > > code. Just a year ago, this whole concept was horrifying to me. I could > > not concieve of allowing others to have free access to my source code. As > > a Long time windows user, I had some un-learning to do. But unlearn I did. > > I started thinking in terms of the advantages of open source. First, it > keeps > > you honest; you write your best code because you know that your peers are > > going to be seeing it all over the world. Second, with open source, once > > you release it, other programmers may modify it helping it to become more > > than you ever could have made it on your own (unless you choose to forbid > > the modification of your code, but that's another subject). Third, the > > distribution of your product using the open source community, has no > equal, > > and will cost you nothing. You can provide support to your users via > > that same community at little or no cost to you, and support is the number > > one ongoing cost that software developers get saddled with. You can use > > the resources of such organizations as the free software foundation to > > defend your copyright (don't let the "free" in FSF throw you; you can > still > > market your product using the GPL licence). > > > > And finally, you get to give something back. This is a philosophical point > > for me, but giving something back to the community that you benefit from, > > whether it be your local community, or the computer community, is very > > important for us as people. It is a common and refreshing view that you > > will find in the open source world, and one reason that I left the > > windows world for good. But thats a soapbox for another time. > > > > Cheers, > > > > Mathew > > > > I think you are making the mistake many "born again" open-source advocates > make, and one that many anti-open-source people also make. There is plenty > of place in the world for both open and closed source software. Indeed this is true. Did I leave you with the impression that I was saying anything against closed source? The fact is I happen to agree with you, but shamelessly took an oppotunity to pitch the case for open source since the OP seemed not to have considered it. > In some situations, one is far better than the other OK. > in some cases either will do > the job. Saying that everything should be open source is as bad as saying > everything should be closed source. It's a common misunderstanding about > Linux ("Software companies should not write for Linux because then they > would have to give away all their source code..."). And it is a common misconception (perpetuated by some proprietary software houses) that open_source == zero_profit. The fact is, open sourcing the program will not negatively impact the profitablility of the product. This flies in the face of conventional wisdom, but such companies as red hat have proven the business model. At any rate, I don't believe I said everything should be open source. I did not intend to imply it. > Consider, for example, the program I am writing at the moment. It is in > Python - a language whose licence is very clear in stating that all > Python-licenced code can be used in open and closed source software (keeping > copyright messages intact). The program provides a gui for an embedded > motor controller card, and our customer is paying good money for me to write > the program. He intends to sell the cards on to his customers, with this > controller program to go with it. In the future, he will want a bigger > version of the program (supporting several cards simultaneously). He may > well want to charge his customers for that software upgrade. He certainly > won't want his customers to have full access to the code - they may modify > it for use with other supplier's motor cards. fine. Then make a license agreement that forbids the modification of the code for use with other brands of motor control equipment. That has nothing to do with open sourcing it. When you open source your code, you provide greater value to your customers, because you give them the power to meet future needs as they expand, by applying the same codebase to new hardware/software platforms. They can also see and verify that the code is not filled with bugs/backdoors. > This is not a program for > which either myself or my customer will gain any benifits from releasing it > as open source - no one is going to be making improvements to it that will > benifit us. see above > However, there are certainly *parts* of the program that could > be released seperately. For example, I may seperate out the graphing parts > of the gui into a nice, modular graph widget. That could easily be released > as open source (Python licence), for the benifit of others and for our own > benifit - if people like it, they will contribute improvements which I can > then use. If I make any changes or improvements to the pyserial module that > I am using, then I certainly will pass those changes back to the community. > But by the time I get as far as making distribution copies of the program, > I'll be making two sorts of packages - py2exe packages for easy installation > on Windows machines, and .pyc byte-code files for use on Linux (and for > Windows users who already have Python). > > I fully agree that there are often direct benifits from making your own > software open source. There is also the personal satisfaction factor - I > have not written much that could be of direct benifit to others (my job is > embedded systems development - you need our company's hardware to run our > software), but I have enjoyed the feeling I get from the few direct > contributions I have made. But there are many reasons to write closed > source code as well. You do not speak for the Linux-using community when > you say that writing closed source is against your principles. From a > user's viewpoint, open source is definitely an advantage - just like lower > cost, better documentation or more functionality is an advantage. But from > the writer or sellers viewpoint, it is a mixed blessing which must be > considered sensibly - just like the selling price, the level of > documentation and the functionality of the software. The aim of all > businesses is to make money - preferably by providing good products and > services to their customers. If that end can be best achieved by openning > their software, great. If it is best achieved by closing their software, > then that's the way it is. Thank you for your thoughts. The OP was asking about securing code and I wanted to impress two things: 1) you can't secure your code 2) open source is not a bad thing, it is, in fact, a very good option. cheers, Mathew From tjreedy at udel.edu Wed Nov 20 16:51:36 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 20 Nov 2002 16:51:36 -0500 Subject: Python as first language (Re: static variables?) References: <3DDAFA97.92B70465@alcyone.com> <3DDB3373.2578CEC0@alcyone.com> <8ef9bea6.0211201119.2f846d0c@posting.google.com> Message-ID: "Hung Jung Lu" wrote in message news:8ef9bea6.0211201119.2f846d0c at posting.google.com... >Sorry for digressing, but this reminds me of an old debate on whether >Python is suitable as the first language to teach. > Well, the thing is that Python works with "name binding". And the > concepts of name spaces, name binding, objects, mutability, etc. are > just a bit non-obvious. I somewhat disagree. An object is something with identify, generic type, and specific value. Binding names to objects is common in everyday life. We also name slots and refer to objects by the name of the slot where currently located, but this is probably less common and less obvious. For instance, your parents (I presume) bound the name Hung Jung to you shortly after birth. On the other hand, if you stay in a hotel, you might be 'the person in Room 223'. If you moved up several floors, you could be 'the person in Room 1287'. In school, you might have been either 'Hung Jung' or 'the child in row 4 seat 3', but I suspect you would have been more comfortable with the former. Namespace is just a fancy (but specific) word for context. A particular name may be bound to different objects in different contexts. For instance, 'John' may be bound to one child in one classroom and another child in another. So namespaces are a way to reuse names within an information processing language. How is mutability non-obvious? You change location. You get sick and then healthy (I hope). You learn. We put things into containers and take them out. On the other hand, words are fixed sequences of letters. But sealed containers may be less obvious. > Once a person understands these things, or if > a person knows about pointers, hashmaps and memory structure, > everything becomes clear. One of the things I like about Python as an *information* processing language is that it is *not* defined in terms of computer hardware. This means that humans can interprete Python code *without* mentally simulating a computer. This should mean that people should be able to learn Python without learning a machine model. I would think that this should make Python easier to learn than languages which are defined in terms of a machine. > After many years in the Python world and having seen so many debates, > I still have to say that Python is not good as the first programming > language to teach. Not as good as what? Assembler? Basic? Fortran? C?, C++?, CommonLisp? ... Whether or not Python is suitable as a first language (your original question), which I would expect it to be by some criterion until evidence showed otherwise, is quite different from 'is it as good (or even the best)?', which would be much toughter to show. Rather than debate, I would like see evidence. A real trial would pit Python against one or more specific other languages. There would need to be a language-neutral test. Students should be randomly assigned to classes after being disabused of preconceptions and prejudices. There would need to be multiple teachers so the trial was not just a trial of teaching ability. Such trials are now routine in medicine but not yet in pedegogy. >Maybe it's just > me, but I have been horrified by programmers writing a few lines of > code, without realizing their few lines of code can actually have > severe impact on the RAM or the harddrive. Impact on the RAM? Are you talking about merely filling things up with data (easily reversible) or something possibly more damaging, like thrashing a drive for hours on end? Or erasing unbacked data? Certainly, people should not learn to open a file (open() or file()) or access the os (os.system()) without also being taught the possible dangers. But this is true for any language and nothing, that I can see, to do with Python as a first language. In any case, one of the nice things about learning to program is that sandbox programs restricted to keyboard input, RAM memory, and screen output really cannot really hurt anything (on a single user system). Quite different from, for instance, learning to drive. > I still feel more > comfortable if the new generation of programmers starts with a > language closer to the machine level, where one can kind of "feel" the > bits and bytes. Just my 2 cents. :) Having starting with 1620 assembler (and paper tape input) and later 'graduated' to Fortran and punched cards, I think people might better start by learning about functions and algorithms with an modern interactive language like Python. > Hung Jung Terry J. Reedy From sanjay2kind at yahoo.com Fri Nov 8 10:54:15 2002 From: sanjay2kind at yahoo.com (sanjay) Date: 8 Nov 2002 07:54:15 -0800 Subject: SGMLParser problem Message-ID: <63170f57.0211080754.4d398296@posting.google.com> Hi, Any one has suggestion for following problem. Some word documents have been converted to HTML page in Ms-Word. Want to filter html tags like.. ,  , etc. I couldn't solve using SGMLParser. Shows error like.. raceback (most recent call last): File "D:\Python21\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "C:\Program Files\test\msword_html_parser_1.py", line 166, in ? s = get_parsed_content1() File "C:\Program Files\test\msword_html_parser_1.py", line 71, in get_parsed_content1 mk.feed(obj.read()) File "D:\Python21\lib\sgmllib.py", line 91, in feed self.goahead(0) File "D:\Python21\lib\sgmllib.py", line 158, in goahead k = self.parse_declaration(i) File "D:\Python21\lib\sgmllib.py", line 238, in parse_declaration raise SGMLParseError( SGMLParseError: unexpected char in declaration: '<' Thanks, Sanjay From loewis at informatik.hu-berlin.de Mon Nov 4 07:47:24 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 04 Nov 2002 13:47:24 +0100 Subject: old SimpleXMLRPCLib classes References: Message-ID: Robin Becker writes: > Under 2.2 it seems that SimpleXMLRPCServer has gone into the library, > but the CGI support classes are gone. Anyone know of a replacement? This > feature was really useful. See python.org/sf/473586. Comments are appreciated (in this patch submission). Regards, Martin From jbublitzNO at SPAMnwinternet.com Wed Nov 6 19:19:50 2002 From: jbublitzNO at SPAMnwinternet.com (Jim) Date: Thu, 07 Nov 2002 00:19:50 GMT Subject: pyqt threading problems unstable References: <3dc95b0b$0$12984@echo-01.iinet.net.au> Message-ID: <3DC9B188.6010101@SPAMnwinternet.com> Rob Hall wrote: > Is this a flakey way of going about things? as I am getting pretty > frustrated. Or is the pyqt threading flakey? You might want to repost your question to the PyKDE mailing list, which also covers PyQt and sip. You can sign up at: http://mats.gmd.de/mailman/listinfo/pykde Jim From camhorn at mac.com Wed Nov 13 17:38:25 2002 From: camhorn at mac.com (Cameron Horn) Date: Wed, 13 Nov 2002 14:38:25 -0800 (PST) Subject: My (late) beef with Simple Generator syntax (PEP 255) Message-ID: <6435449.1037227105210.JavaMail.camhorn@mac.com> On Wednesday, Nov 13, 2002, at 02:26PM, wrote: >> From: Cameron Horn [mailto:camhorn at mac.com] >> Sent: Wednesday, November 13, 2002 4:26 PM >> >> On Wednesday, Nov 13, 2002, at 02:19PM, wrote: >> >> >> From: Cameron Horn [mailto:camhorn at mac.com] >> >> Sent: Wednesday, November 13, 2002 4:20 PM >> >> >> >> On Wednesday, Nov 13, 2002, at 02:16PM, David Eppstein >> >> wrote: >> >> >> >> >On 11/13/02 2:11 PM -0800 Cameron Horn wrote: >> >> >>> What I wonder is, why does it need to be a generator? >> >> What's wrong with >> >> >>> def foo(): return ( ) >> >> >>> ? >> >> >> >> >> >> You're right if it's a one-time thing. However, if I've got a >> >> >> scaffolding like this, then it matters. >> >> >> >> >> >> def process_generator(function): >> >> >> for x in function(): >> >> >> print x >> >> > >> >> >How does the function foo() I defined above fail to work in this >> >> >scaffolding? >> >> >> >> In the "TypeError: iteration over non-sequence" sort of way. >> >> >> > >> >An empty tuple is a sequence also; >> > >> >the "return ( )" thing is returning an empty tuple, >> >not "None". You can make it clearer by using >> >"return tuple()" rather than "return ()". >> >> Oops. Missed those parentheses. Then it is completely >> useful, unless you end up using the "next" method. >> > >In that case, if you reckon you're going to use .next() >directly, then you should change 'foo' to something like >the following: > >def foo(): return iter(tuple()) > >It's going to return a valid iterator which is going to >try to iterate through an empty tuple, so it's going >to raise StopIteration the first time you call .next(). > > Which is the obvious, clear and consistent way to create a generator that doesn't do anything. Unless you're checking types or doing any other low-level things that you probably oughtn't. I return to my original point. And then, since everything works and I'm just complaining about a tiny bit of syntax, I shut up. From ronecker at noos.fr Sun Nov 24 15:59:22 2002 From: ronecker at noos.fr (Lenny) Date: Sun, 24 Nov 2002 21:59:22 +0100 Subject: cannot import gtk Message-ID: Hi, I've just installed a RH 8.0, and while trying to use python programs from my previous linuxbox, i encounter the following problems with python : > from gtk import GtkVBox >ImportError: cannot import name GtkVBox this is just an example. I have the same errors with many widgets, but also, with GDK, etc.etc... I tried with python (that is python1.5), python2 and python2.2 I really have gtk+- installed (/usr/include/gtk-1.2 AND gtk-2.0) with (for the example above) a nice gtkvbox.h I think python does not know where to look for modules or something like that, but I'm new to this, and do not know what to do. Thanx a lot for your help, From m.faassen at vet.uu.nl Thu Nov 28 18:06:00 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 28 Nov 2002 23:06:00 GMT Subject: do you guys help newbies?? References: <31575A892FF6D1118F5800600846864D01200302@intrepid> Message-ID: Brad Hards wrote: > On Thu, 28 Nov 2002 03:20, Simon Brunning wrote: >> > Any ideas to make it more reliable ? >> >> See . > Reading this pointed out the value of a validator. If you want input in a > particular form, it is probably better to not let the user do anything else, > rather than let them do an entry, then explain what they did wrong, then let > them try again. > > Anyone got a class that can do generic validation, without using one of the > GUIs? [going more offtopic] Zope 3 has something in the works called 'Schema'. It's probably more than you're asking for as it is a special kind of interface, but it can do generic validation. Conversion of user input is however left to the 'Forms' package as different UI systems (web, various GUIs, text) have different widgets that deliver results of a different type (web form input is typically string data, while a GUI toolkit may have special widgets for inputting integers or dates). Schema only do validation. Anyway, while there's code this is hard to use in isolation right now and mostly vaporware. But I just felt like rambling. :) http://cvs.zope.org/Zope3/lib/python/Zope/Schema/ http://cvs.zope.org/Zope3/lib/python/Zope/App/Forms/ Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From brian at sweetapp.com Wed Nov 20 14:13:53 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 20 Nov 2002 11:13:53 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? In-Reply-To: <3DDBD838.10406@nyc.rr.com> Message-ID: <00ae01c290c8$f7803a30$21795418@dell1700> Kenny Tilton wrote: > documentation available at a keystroke, and apropos to search for > stuff you suspect is in the language Python has several nice help tools. Try typing "help()" at an interactive shell. > true garbage collection (I am /not/ looking forward to reference > counting or the hoops one has to jump thru to handle cyclic refs) Python does not require any such hoops. Python uses a generational garbage collector to deal with circular references. Cheers, Brian From slaven.rezic at berlin.de Fri Nov 8 04:53:14 2002 From: slaven.rezic at berlin.de (Slaven Rezic) Date: 08 Nov 2002 10:53:14 +0100 Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DCB7D3D.B2EAAB0F@earthlink.net> Message-ID: <878z04mlpx.fsf@vran.herceg.de> Benjamin Goldberg writes: > Walter Roberson wrote: > > [...] > > Speaking of layers: I take it that some thought has been put into > > how to do operating-system escapes? So that one can (for example) > > handle graphics? Or even just sockets? Seeing as some of the most > > popular interpreted languages are by no means restricted to text-only > > and have networking capabilities? > > Remember, the parrot interpreter is written in C... it has to be. > Obviously, one would have parrot opcodes which result in calls to C > functions, which perform socket operations or graphics or whatever. > I dont't think it will be opcodes, but rather a combination of loadlib (load a DLL) and dlfunc (create a parrot-callable subroutine from a DLL function). See core.ops. Regards, Slaven -- Slaven Rezic - slaven.rezic at berlin.de Visualize Makefiles with GraphViz: http://user.cs.tu-berlin.de/~eserte/src/perl/GraphViz-Makefile/ From Patrick.Carabin at MyRealBox.COM Tue Nov 12 08:31:04 2002 From: Patrick.Carabin at MyRealBox.COM (Patrick.Carabin at MyRealBox.COM) Date: 12 Nov 2002 05:31:04 -0800 Subject: Can python find fibonacci series in a single line of code? References: Message-ID: <44ee1dc2.0211120531.10574867@posting.google.com> If You change : print reduce (lambda x,y: (x[1],x[0]+x[1], x[2]+[x[1]]), xrange(10), (0,1,[]))[2] into : print reduce (lambda x,y: (x[1],x[0]+x[1], x[2]+[x[1]]), xrange(99), (0,1L,[]))[2] it should remain working without overflow... From shadowlord13_1 at yahoo.com Mon Nov 18 19:09:02 2002 From: shadowlord13_1 at yahoo.com (Richard Dillingham) Date: Tue, 19 Nov 2002 00:09:02 GMT Subject: Hmm... An idea: if a,b==c,d: References: Message-ID: What's top-posting? Also, I knew that a,b normally evaluates to a tuple, but it already doesn't in an if-statement. I get a syntax error instead. From charles at pentek.com Thu Nov 7 14:01:39 2002 From: charles at pentek.com (Charles Krug) Date: Thu, 07 Nov 2002 19:01:39 GMT Subject: Making a better textbook (was Re: The Deitel book) References: <87b0ada6.0211011453.1df4d216@posting.google.com> <815e8a38.0211071038.208c7577@posting.google.com> Message-ID: On 7 Nov 2002 10:38:44 -0800, CShannon wrote: > I am a college professor and use Python as the language in our first > course -- designed for both majors and non-majors alike. There are a > number of good python reference books around. Most of them are not > appropriate as text books however because they have few examples and > often no exercises. I like a book that is moderate in size. Books > often have more material than can be covered in a single semester but > it shouldn't be so large (or expensive) as to intimidate all but the > bravest of souls. In my course, students are also expected to buy a > text dealing with social/ethical issues. > Interesting. I doubled in both Math and CS. Half of the CS courses had an ethics component, while none of the maths did. Which only makes sense. I've never heard of a fudged mathmatical model used to support the desired conclusion of a sponsor with deep pockets. Have you? From tdelaney at avaya.com Sat Nov 23 19:36:38 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Sun, 24 Nov 2002 11:36:38 +1100 Subject: Python IRC dictatorship Message-ID: He's back! He's back! [rest of thread deleted manually] Damn - guess my filters are playing up :( Tim Delaney From answer at tnoo.net Mon Nov 11 12:16:52 2002 From: answer at tnoo.net (=?iso-8859-1?q?Martin_L=FCthi?=) Date: 11 Nov 2002 18:16:52 +0100 Subject: How to create and interactive, distributable program? References: <3dcfa0e3.921157@news.jaring.my> Message-ID: Great task.... I am not shure about creating a FE package from scratch in three months. There is plenty of very good, fast and tested code around to build upon: Check for example http://sal.kachinatech.com/B/2 http://www.engr.usask.ca/~macphed/finite/fe_resources/fe_resources.html Two free codes that I can recommend (but there are many, many others): Tochnog (http://tochnog.sourceforge.net): Does about everything, 2D, 3D, remeshing, coupled analysis, easy to use (no graphical frontend) GPL Deal.II (http://www.dealii.org/): Very fast C++ library, but you have to code the equations yourself in C++ QT-style license With such a bullet-proof backing you only have to write the frontend that generates inputfiles and reads outputfiles. I wrote a small GPL'd library in Python for the task of FE-file conversion that could be useful (http://www.sourceforge.net/projects/feval, no project page yet). Hope this of help for you Martin -- Martin L?thi answer at tnoo.net From dave at pythonapocrypha.com Fri Nov 22 11:41:33 2002 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 22 Nov 2002 08:41:33 -0800 (PST) Subject: Proposal: min(None, x) and max(None, x) return x In-Reply-To: Message-ID: On Fri, 22 Nov 2002, Eric Brunel wrote: > So I told myself: wouldn't it be great if max(None, x) or min(None, x) > always simply returned x? So I could just write: > > xMax = None > for -whatever-: > -big calculation leading to a value of x- > xMax = max(x, xMax) > > Okay, it only saves 3 lines, but I personally find it quite natural... In > addition, today, min(None, x) and max(None, x) work, but have strange > results: as far as I can see, min(None, x) is always None and max(None, x) > is always x, but this behaviour isn't documented. > > Opinions anyone? Sure! Write two functions, and put them in your sitecustomize.py file. No PEPs to write, no patches to submit, no battles to win, and you get all the functionality you want _today_. -Dave From goldbb2 at earthlink.net Fri Nov 8 05:26:54 2002 From: goldbb2 at earthlink.net (Benjamin Goldberg) Date: Fri, 08 Nov 2002 05:26:54 -0500 Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DCB7D3D.B2EAAB0F@earthlink.net> <878z04mlpx.fsf@vran.herceg.de> Message-ID: <3DCB916E.76E55334@earthlink.net> Slaven Rezic wrote: > > Benjamin Goldberg writes: > > > Walter Roberson wrote: > > > > [...] > > > Speaking of layers: I take it that some thought has been put into > > > how to do operating-system escapes? So that one can (for example) > > > handle graphics? Or even just sockets? Seeing as some of the most > > > popular interpreted languages are by no means restricted to > > > text-only and have networking capabilities? > > > > Remember, the parrot interpreter is written in C... it has to be. > > Obviously, one would have parrot opcodes which result in calls to C > > functions, which perform socket operations or graphics or whatever. > > I dont't think it will be opcodes, but rather a combination of loadlib > (load a DLL) and dlfunc (create a parrot-callable subroutine from a > DLL function). See core.ops. Ok, so loadlib is one op, and dlfunc is another op :) -- my $n = 2; print +(split //, 'e,4c3H r ktulrnsJ2tPaeh' ."\n1oa! er")[map $n = ($n * 24 + 30) % 31, (42) x 26] From anton at vredegoor.doge.nl Sun Nov 10 05:36:11 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sun, 10 Nov 2002 11:36:11 +0100 Subject: Tkinter listbox selection handling References: Message-ID: On 09 Nov 2002 23:48:05 GMT, Tim Daneliuk wrote: >class myUI: > > def __init__(self, root): > > # Setup the visual elements > self.hSB = Scrollbar(root, orient=HORIZONTAL) > self.vSB = Scrollbar(root, orient=VERTICAL) > self.listbox = Listbox(root, > foreground = FCOLOR, > background = BCOLOR, > font = (FNAME, FSZ, FWT), > selectmode=SINGLE, > exportselection=0, > xscrollcommand=self.hSB.set, > yscrollcommand=self.vSB.set, > height = HEIGHT, > width = WIDTH, > ) > > self.hSB.config(command=self.y.xview) > self.hSB.pack(side=BOTTOM, fill=X) > self.vSB.config(command=self.DirList.yview) > self.vSB.pack(side=RIGHT, fill=Y) > self.DirList.pack(side=LEFT, fill=BOTH, expand=1) Here self.Dirlist is used, but where is it bound to an object? Anton. From pete at shinners.org Fri Nov 1 12:04:48 2002 From: pete at shinners.org (Pete Shinners) Date: Fri, 01 Nov 2002 17:04:48 GMT Subject: Wrapping a .dll under windows with SWIG References: <8beb91f5.0210312226.7eb08c08@posting.google.com> Message-ID: Ben C wrote: > I want to wrap a .dll under windows and have access to it's functions > etc. The problem is that all I have is the .dll and header file ... no > source ... and as all the examples that I have seen for swig seem to > need the original source ... I was wondering if it is still possible > to get access to the functions stored in the dll? Would anyone be able > to point me in the write direction, docs examples etc if this can be > done at all? sorry if this is no help at all. I believe there are tools to produce a .LIB file from a .DLL. I think that is all you should need. Then the generated SWIG code could be properly linked the the LIB/DLL. Hopefully that's all it takes, unfortunately you are on your own for figuring out the DLL to LIB thing. From jonas.b at home.se Thu Nov 21 07:29:09 2002 From: jonas.b at home.se (Jonas Bengtsson) Date: Thu, 21 Nov 2002 12:29:09 GMT Subject: How to access a property in Outlook using win32com? References: Message-ID: Tim Peters wrote in news:mailman.1037849249.16795.python-list at python.org: > Heh. I doubt it, but we can *show* you: check out the Outlook2000 > directory in the spambayes project: > > http://tinyurl.com/2vt5 > > and especially MAPIMsgStoreMsg._GetMessageText() in msgstore.py there. > > PR_TRANSPORT_MESSAGE_HEADERS is a MAPI property (not part of the > *Outlook* object model), and it even took Mark Hammond several days to > figure out how to access it without going thru CDO (Collaboration Data > Objects -- yet another API-on-an-API-on-an-...). Thanks! But I have a hard time to realize how to use that code to extract that data from a MailItem object. I guess I need some assistance. One alternative is to rewrite the code from msgstore.py to just extract the PR_TRANSPORT_MESSAGE_HEADERS provided a specific MailItem object. The other alternative is to use parts of msgstore.py directly. What I want is to get the headers and the body of all mails in a specific folder. How should I use msgstore.py to be able to do that? Any assistance appreciated! > Be forewarned that the exact meaning of PR_TRANSPORT_MESSAGE_HEADERS > isn't defined by MAPI, may contain lines that aren't valid SMTP > headers, and can ne downright strange when looking at msgs handled by > an Exchange server. For msgs delivered via POP3, they're what you > expect. Mostly. I can live with that :-) Regards, Jonas From andreas at andreas-jung.com Mon Nov 4 11:47:53 2002 From: andreas at andreas-jung.com (Andreas Jung) Date: Mon, 04 Nov 2002 17:47:53 +0100 Subject: Encoding of String In-Reply-To: References: Message-ID: <3333943.1036432073@[192.168.0.3]> No, since a unicode string is unicode does not depend on the encoding it was encoding in. -aj --On Montag, 4. November 2002 17:40 +0100 Thomas Guettler wrote: > Hi! > > Is there a way to get the encoding of a string? > > Suppose I do: > > mystring="blu" > ustring=unicode(mystring, "utf-8") > > later I want to know which encoding ustring has: > ustring.getEcoding() --> "utf-8" > > Is there something like "getEcoding()"? > > thomas > > > -- > http://mail.python.org/mailman/listinfo/python-list --------------------------------------------------------------------- - Andreas Jung http://www.andreas-jung.com - - EMail: andreas at andreas-jung.com - - "Life is too short to (re)write parsers" - --------------------------------------------------------------------- From gminick at hacker.pl Sat Nov 23 11:44:12 2002 From: gminick at hacker.pl (Wojtek Walczak) Date: Sat, 23 Nov 2002 16:44:12 +0000 (UTC) Subject: reliable tcp server holding multiple connections References: <3DDFAEB4.1040506@nospam.attbi.com> Message-ID: Dnia Sat, 23 Nov 2002 16:37:07 GMT, djw napisa?(a): > Do you know about Medusa? Yes, but Medusa it a little bit large. I want to create small code, proof of concept. An educational example, nothing more. -- [ ] gminick (at) underground.org.pl http://gminick.linuxsecurity.pl/ [ ] [ "Po prostu lubie poranna samotnosc, bo wtedy kawa smakuje najlepiej." ] From gminick at hacker.pl Wed Nov 27 14:29:09 2002 From: gminick at hacker.pl (Wojtek Walczak) Date: Wed, 27 Nov 2002 19:29:09 +0000 (UTC) Subject: re.DOTALL References: Message-ID: Dnia Wed, 27 Nov 2002 13:46:56 -0500, Irina Szabo napisa?(a): > What is wrong? Nothing :) Your code works for me. --- html.html --- line 1 line 2 line 3 line 4 ----------------- --- py.py --- import re w = open("html.html") a = w.read() w.close() matchstr = re.compile(r'''<.*?>''',re.DOTALL|re.MULTILINE) print matchstr.sub(" ", a) ------------- % python py.py line 1 line 2 line 3 line 4 % _ Tested on Linux with: % python -c "print getattr(__import__('sys'),'version')" 2.2.2 (#1, Oct 16 2002, 18:08:06) [GCC 2.95.3 20010315 (release)] % _ -- [ ] gminick (at) underground.org.pl http://gminick.linuxsecurity.pl/ [ ] [ "Po prostu lubie poranna samotnosc, bo wtedy kawa smakuje najlepiej." ] From mwh at python.net Tue Nov 12 10:47:58 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 12 Nov 2002 15:47:58 GMT Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> Message-ID: <7h3lm3y23of.fsf@pc150.maths.bris.ac.uk> DaveP writes: > Is there a source form example of the py docs, You meant like the Doc/ directory in the source distribution? [...] > Just to take a look at producing docbook from that, > and to see if XML/XSLT/XSL-FO processing chain could do the job > please? I still don't grok the advantages of a "XML/XSLT/XSL-FO processing chain", except that Milan has said info production would be easier... Cheers, M. -- Whaaat? That is the most retarded thing I have seen since, oh, yesterday -- Kaz Kylheku, comp.lang.lisp From see_reply_address at something.invalid Tue Nov 12 20:32:02 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 13 Nov 2002 14:32:02 +1300 Subject: pythonic way to optimize access to imported value? References: Message-ID: <3DD1AB92.3030409@something.invalid> Bengt Richter wrote: > >>> def mkfoo(): > ... from math import pi > ... def foo(): > ... return pi > ... return foo > ... > > What would be best Pythonic practice for getting a foo2? It seems like if there were > a way to say "do this part once at compile time" It's not really compile-time that we want to do it, but module load time, or perhaps function definition time. One way would be to use a default-argument hack: import math def foo(m = math): return m.pi but this has all the usual drawbacks of the default-argument hack. This suggests that perhaps there should be a way of getting something that is just like a default argument, except that it's not part of the argument list. Maybe def foo(): const m = math return m.pi The "const" statement would be evaluated when the "def" was executed, and "m" would appear in the local namespace when the function was called. Although "const" might not be the best name for it, since it's not really a constant, more like a local with an initial value. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From abuse at nospam.riot.com.au Thu Nov 21 23:41:24 2002 From: abuse at nospam.riot.com.au (Glen Murphy) Date: Fri, 22 Nov 2002 15:41:24 +1100 Subject: Web Tracking in Python References: Message-ID: Get a copy of winrar (free) - does .tar files fine. I tested it on follow, and all I had to do was open the .tar, then open the file contained within (which spawned another winrar window with the necessary files) -- http://glenmurphy.com/ "Paul Sage" wrote in message news:mailman.1037912231.7883.python-list at python.org... > My wife has a family webpage that is pretty active. She uses site > tracking, but has never been happy with the lack of certain features. > Can anyone recommend a good Python website tracking package? > I looked at Follow, but the .TAR doesn't expand properly on Windows > platforms. I might be inclined to use it, if I find a more friendly > version for Windows. Windows needed as main development platform. The > Web server is UNIX based. From jon at csh.rit.edu Sun Nov 17 19:57:40 2002 From: jon at csh.rit.edu (Jon Parise) Date: Sun, 17 Nov 2002 19:57:40 -0500 Subject: Calling local functions from the C API In-Reply-To: References: Message-ID: <20021118005740.GA19299@csh.rit.edu> On Sun, Nov 17, 2002 at 09:02:17AM +0100, Martin v. Loewis wrote: > Jon Parise writes: > > > def SomeFunction(): > > pass > > > > ... gets evaluated by PyRun_RunString(). Later on, I'd like to call > > SomeFunction from C (embedded Python interpreter). > > > > Is that still not possible without playing with stack frames and such? > > Ah, so you have a char* that has Python source code, and you want to > run a specific function in it. > > For such questions, always ask yourself how you would achieve this > effect in pure Python, and then you'll see how to do it in C. > > In Python, you could write > > d = {} > exec sourcecode in d > func = d['SomeFunction'] > func() > > Now just do the same in C. Which of the four steps is unclear to you? Thinks makes sense, I think (although I may have more questions when I work on my actual implementation). The one thing I note, however, is that I just can't execute arbitrary blocks of code via PyRun_SimpleString() and expect to be able to execute a function defined in one of those blocks of code again. Instead, it looks like I'll need to use Py_CompileString() or similar to maintain a code object. Is that correct? (This is the first time I've actually used this aspect of the Python C API, so I thank you for your patience.) -- Jon Parise (jon at csh.rit.edu) :: http://www.csh.rit.edu/~jon/ From max at alcyone.com Sat Nov 30 17:53:49 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 30 Nov 2002 14:53:49 -0800 Subject: Python exceptions: is there a way to find the exception attributes? References: <3DE8F629.4080108@attglobal.net> Message-ID: <3DE9417D.4A736D68@alcyone.com> Pierre Rouleau wrote: > Is there a way to find out about the existence of these attributes > without having to read the documentation, using the dir() function or > something else? > > It would be nice to be able to do that from the interpreter. The only > thing i have found using dir() is shown below and it does not give me > the attributes. ... > Of course, I could force an exception and print it like: ... > Is this the only way ? Without inspecting the code, probably. The details about the exception are instance attributes, not class attributes, so you won't find them by simple inspection of the class type; you'd have to look at the actual code of the exception's __init__ method. Especially in the face of user-defined exceptions, the best way to proceed is by inspecting the instance attributes of an actual exception object after the fact. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ You are the lovers rock / The rock that I cling to \__/ Sade Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From tjreedy at udel.edu Wed Nov 27 12:50:56 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 27 Nov 2002 12:50:56 -0500 Subject: Python Tutorial Was: Guido's regrets: filter and map References: <698f09f8.0211261046.582254a5@posting.google.com> <3DE40E21.A547F49E@alcyone.com> <698f09f8.0211270143.5a3b9f0f@posting.google.com> Message-ID: "Jeremy Fincher" wrote in message news:698f09f8.0211270143.5a3b9f0f at posting.google.com... > But I think it would be more appropriate for map/filter to return > sequences of the same type as their argument sequences, not just > return lists blindly. And that requires that map/filter be methods, > not functions over sequences. There is some sense to this, but: 1. Does not apply to reduce, which produces summary that depends on type of contents, not container. 2. When map and filter were added with reduce, strings and tuples did not have methods. Now that they do, we can, I believe, derive a subtype with added methods. 3. One can easily convert list output to desired sequence type by feeding it back through the constructor of the desired type. String and tuple constructors need a sequence of fixed length. Thus, tuple.filter(f), for instance, would have to scan the tuple twice anyway. 4. tuple(filter(f,seq)) is much more general than tuple.filter(f). 5. Map can be a function of multiple sequences (iterables), possibly of multiple types, including generators. It is then not sensibly a method of any one. Terry J. Reedy From mwh at python.net Thu Nov 7 12:39:29 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 7 Nov 2002 17:39:29 GMT Subject: Making a better textbook (was Re: The Deitel book) References: Message-ID: <7h365v9z3hf.fsf@pc150.maths.bris.ac.uk> Dave Brueck writes: > I mean, what first year (or any year, for that matter!) languages > force people to [snip] stay away from creating 1000-line functions? If any language does this, it would be Python... Cheers, M. -- MGM will not get your whites whiter or your colors brighter. It will, however, sit there and look spiffy while sucking down a major honking wad of RAM. -- http://www.xiph.org/mgm/ From skip at pobox.com Fri Nov 15 15:08:58 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 15 Nov 2002 14:08:58 -0600 Subject: A really bad idea. In-Reply-To: References: <4STA9.9987$744.345722@news1.tin.it> <3DD44152.69795B9F@alcyone.com> Message-ID: <15829.21594.896779.746111@montanaro.dyndns.org> Manuel> I will plead that the metric I should used was the ratio of Manuel> daily referenced documentation versus productivity in varied Manuel> programming tasks. Python's ratio is pretty darn good, the best Manuel> I have found. Indeed. With very rare exception, the only documentation tools I need are the builtin help() function and the global module index: http://www.python.org/doc/current/modindex.html Fred Drake and his minions do a wonderful job keeping the documentation within spitting distance of the source code. I don't use any of those fancy-schmancy IDEs, though I do use python-mode, which has F1 bound to call help() on the dotted attribute expression under the cursor. -- Skip Montanaro - skip at pobox.com http://www.mojam.com/ http://www.musi-cal.com/ From jryan at rackspace.com Fri Nov 15 07:13:00 2002 From: jryan at rackspace.com (Justin Ryan) Date: 15 Nov 2002 06:13:00 -0600 Subject: changing unix password with python Message-ID: <1037362380.9533.126.camel@justin> Heya all.. Is there a python module that would facilitate changing a unix system user's password (preferably via PAM rather than directly modifying /etc/shadow)? Thanks! -Justin -------------- 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 max at alcyone.com Wed Nov 20 02:05:50 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 19 Nov 2002 23:05:50 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: <3DDB344E.2E2B7658@alcyone.com> Robin Munn wrote: > Out of curiosity, do you think a response like: "That's covered in the > Python tutorial -- look at [URL]" will strike a newbie as friendly or > not? Unless insults are thrown into the response, I don't see why not -- or at the very least, if a newbie concludes that an answer to his question is rude simply because the responder didn't spend fifteen minutes crafting a reply to a question that has already been answered so many times that it is included in a FAQ, that newbie needs to learn a little more about Usenet, not just Python. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Seat thyself sultanically among the moons of Saturn. \__/ Herman Melville Official Omega page / http://www.alcyone.com/max/projects/omega/ The official distribution page for the popular Roguelike, Omega. From david at no.westcontrol.spam.com Tue Nov 26 04:43:09 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Tue, 26 Nov 2002 10:43:09 +0100 Subject: Python Tutorial Was: Guido's regrets: filter and map References: Message-ID: "Courageous" wrote in message news:sss5uus0o18jtdi2lcpp3605vfgscmvmum at 4ax.com... > On 25 Nov 2002 18:56:10 GMT, Grant Edwards wrote: > > >In article , David Brown wrote: > > > >>> I never liked filter, map and reduce. > > > >So don't use them. ;) > > Lambda is an abortion, imo. It should be deprecated, and eventually > removed from the language. It doesn't do what it set out to do particularly > well, and suffers from the double sin of being a construct that is > inherently anti-pythonic. The subset of list comprehensions that can > be used to do what map/reduce-lambda do are an example of something > that does what it was intended, is clear, and pythonic. > > Just an opinion, > Everyone is entitled to their opinion - I happen to like lambda. I am comfortable with map(lambda ... ) expressions, but I suppose I should really use list comprehensions more for that sort of thing. It depends on whether I am thinking that I am applying a function to each element in a list, or I am wanting a new list based on another list with a function applied to each element. It amounts to the same thing, but it is viewing it from a different angle. But I use lambda functions regularly outside of that. The alternative is either far more small functions cluttering the source code and namespace, or making function-construction functions. There are definitely some uses for that sort of thing (lambda has its limitations), but there is no point in removing a feature that many people find useful just because some people find it a little odd and out-of-place. From aleax at aleax.it Sat Nov 9 09:49:17 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 09 Nov 2002 14:49:17 GMT Subject: Point an MS Access / VB developer in the right direction... References: <3dcb9830$1@duster.adelaide.on.net> <3dccd9eb@dnews.tpgi.com.au> Message-ID: Ben C wrote: > ... SQLite is typless and doesn't have ODBC connectivity as far as I > know?? (though someone might have written an ODBC driver for it) ... http://www.ch-werner.de/sqliteodbc/ Alex From loewis at informatik.hu-berlin.de Mon Nov 4 03:21:57 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 04 Nov 2002 09:21:57 +0100 Subject: Tkinter disregards font encoding References: <6e990e29.0211040009.33127f7@posting.google.com> Message-ID: hjwidmaier at web.de (Hans-Joachim Widmaier) writes: > My code's like this: > Font = '-*-helvetica-bold-r-normal-*-12-*-*-*-*-*-iso8859-15' > > w = Label(master, font=Font, textvariable=self.priceVar, > justify=RIGHT) > > But I do not get the expected Euro sign; Tk uses definitely the > *-iso8859-1 variant. The -15 is installed, I can use it with other > applications and look at it with xfd. What is the value of self.priceVar? > Does anyone have an idea how I might circumvent that problem? Here is my theory: you are using a Latin-1 locale, and use a byte string for the priceVar, where you use '\xe4' to denote the EURO SIGN. However, in Latin-1, '\xe4' denotes the CURRENCY SIGN. Tk tries to convert the local encoding (latin-1) into the font encoding (latin-9); since latin-9 does not support the CURRENCY SIGN, this conversion fails. Instead, you should use a Unicode string to denote the EURO SIGN, which would be u'\u20ac'. HTH, Martin From gustav at morpheus.demon.co.uk Thu Nov 7 16:17:10 2002 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: Thu, 07 Nov 2002 21:17:10 +0000 Subject: "Universal Gateway" References: <1y63gc02.fsf@morpheus.demon.co.uk> Message-ID: Thomas Heller writes: > Ok, it seems I cannot escape, now that ctypes also was mentioned in > the Daily Python-URL, so I will also announce it here, after some > cleanup. Having looked at this, I'm very impressed. calldll did the job, but I was never completely happy with its interface. Your code is far nicer, and makes things very clean. I was interested in the support for callbacks, and as there wasn't a sample script in the distribution, I had a go at writing one. Took me no more than a few minutes (most of which was looking up prototypes in MSDN!) and worked straight off. It was a very nice experience :-) In case you're interested, here's the code (just lists the window titles of all the windows in the system). ---- cut here ---- from ctypes import windll, CFunction, c_string user32 = windll.user32 class EnumWindowsProc(CFunction): _types_ = "ii" _stdcall_ = 1 def DisplayWindow(hwnd, lparam): title = c_string('\000' * 256) user32.GetWindowTextA(hwnd, title, 255) print title.value enumproc = EnumWindowsProc(DisplayWindow) user32.EnumWindows(enumproc, 0) ------------------ Paul. -- This signature intentionally left blank From jbublitzNO at SPAMnwinternet.com Tue Nov 5 15:16:06 2002 From: jbublitzNO at SPAMnwinternet.com (Jim) Date: Tue, 05 Nov 2002 20:16:06 GMT Subject: pyqt rules References: <3dc550fb$0$9008@echo-01.iinet.net.au> <2Dkx9.42039$Lg2.11444432@news2.news.adelphia.net> <3DC6E304.6070507@SPAMnwinternet.com> <3DC7B220.BF77CADB@philips.com> Message-ID: <3DC826E2.9070207@SPAMnwinternet.com> Gerrit Muller wrote: >>from: http://www.trolltech.com/developer/faqs/noncomm.html >>"What is the Qt Non-Commercial Edition for Microsoft Windows? >>----------------------------------------------------------- >>You may freely use Qt Non-Commercial Edition for: >>* Running software legally developed by others >>* Developing non-commercial software" > I am creating a freely accessible website > http://www.extra.research.philips.com/natlab/sysarch/index.html at home > as well as during working hours. At both places I work with Windows > (strongest dependency is the use of Visio). I maintain the site by means > of Python scripts. Taking the above license literal I might use Qt at > home for free, but not at work. Yes that is clear, but not stimulating > to dive in :-( You should be able to run eric (which I believe was the main complaint). I would think that falls in the category "Running software legally developed by others" It doesn't seem like you really need Qt for development, but if the website is non-commercial, the second category above should apply as well. I haven't read the license in a long time, but it sounds like restrictions are related to development only, not use. However, I don't know if the non-commercial version of Qt is recent enough to support all of the new features coming in the next eric release. Jim From ktilton at nyc.rr.com Thu Nov 21 02:47:17 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Thu, 21 Nov 2002 07:47:17 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DDA7260.4050905@nyc.rr.com> <3DDBD838.10406@nyc.rr.com> Message-ID: <3DDC8FEE.7090904@nyc.rr.com> Dennis Lee Bieber wrote: > Alexander Schmolck fed this fish to the penguins on Wednesday 20 > November 2002 04:40 pm: > > >>macros would make it feasible to write extremely readable code (even >> > > Forgive my intrusion but... > > Macros have always seemed to me to be a means of implementing > work-arounds for what a language lacks in its native definition. Not a workaround, but a way to embed a domain-specific language within Lisp. Or just to hide a lot of plumbing that would otherwise clutter up the code. But, hey, there is at least one CL venerable who does not think macros are necessary. > Granted, the only languages I've been exposed to with macros are the C > family,... That one I know, and it just substitutes tokens. In CL a macro is CL code which than rewrite its input (the "body" argument) to generate new code actually seen by the compiler. > Macros in LISP may make it possible to write "extremely readable code" > -- but what level of LISP expertise is required to write those macros? Not much. It's just that you are writing code which takes apart the client code and reassembles it to suit some package, saving the client all that trouble. (That sounds like a function, hence the opposition to macros by the fellow i mentioned before.) I can macroexpand code to check what form the compiler will see, but when I screw up I usually find out at compile or runtime. > > If you have to supply the macros ahead of time, the users aren't > learning LISP, they are learning "MacroExtendedLISP"... Yes, macros could be abused that way. but key is to produce a /different/ domain-specific language, say a 3d-animation "language" which swims with the host code. kenny clinisys From skip at pobox.com Mon Nov 18 15:56:06 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 18 Nov 2002 14:56:06 -0600 Subject: changing the Python grammar ? In-Reply-To: <2259b0e2.0211181221.2eab9db7@posting.google.com> References: <2259b0e2.0211181221.2eab9db7@posting.google.com> Message-ID: <15833.21478.461611.451833@montanaro.dyndns.org> Michele> Suppose for instance I want to make able Python to recognize Michele> identifiers starting with some funny symbol, say "@". All I Michele> must do is to modify the first line of the grammar as Michele> identifier ::= Michele> ["@"] (letter|"_") (letter | digit | "_")* Sure, take a look at the file Grammar/Grammar in the source distribution. -- Skip Montanaro - skip at pobox.com http://www.mojam.com/ http://www.musi-cal.com/ From magnus at thinkware.se Fri Nov 1 17:11:06 2002 From: magnus at thinkware.se (=?ISO-8859-1?Q?Magnus_Lyck=E5?=) Date: Fri, 01 Nov 2002 23:11:06 +0100 Subject: HTMLgen replacment module References: <3dc0f443$0$4714@echo-01.iinet.net.au> Message-ID: Nicholas Yue wrote: > Given that the last update of HTMLgen is 1998, is there any update or a > replacement package? A few... Maybe there should be one in the standard lib? This is a common enough task, not a big module to maintain, and less duplication and more focused maintenance could be good. This module could cover the (X)HTML standard, and then people could make their own modules for document types and other higher level constructs. Today, you have a few choices, for instance: http://dustman.net/andy/python/HyperText/ and http://www.livinglogic.de/Python/xist/ See also http://www.thinkware.se/cgi-bin/thinki.cgi/PythonForInternet From wlfraed at ix.netcom.com Sun Nov 3 17:26:06 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sun, 03 Nov 2002 14:26:06 -0800 Subject: Parsing & question about usages off classes! References: <0efx9.175905$Mf5.8592441@Flipper> Message-ID: Frans fed this fish to the penguins on Sunday 03 November 2002 11:58 am: Yes, it's me again... > I want to create several new list. The name off the new lists will > come from another list. That way I can create several lists, depending > on the data received from logfiles. Is that possible ? > > Or isnt that a good idea either ? :) > > So basicly: > my_list['some','data'] > variable = my_list[0] > variable = list > > Now this doesnt work, but the result I want is a new list with the > name 'some'. > NOT recommended but seems to work on my system... >>> globals() {'__builtins__': , '__name__': '__main__', '__doc__': None} >>> alist = ['log1', 'log3', 'log2', 'logn'] >>> i = 0 >>> for lg in alist: ... globals()[lg] = [i,'log data', i*20] ... i = i+1 ... >>> globals() {'lg': 'logn', 'log2': [2, 'log data', 40], 'log3': [1, 'log data', 20], 'log1': [0, 'log data', 0], 'i': 4, 'alist': ['log1', 'log3', 'log2', 'logn'], '__builtins__': , 'logn': [3, 'log data', 60], '__name__': '__main__', '__doc__': None} >>> log1 [0, 'log data', 0] >>> log2 [2, 'log data', 40] >>> log3 [1, 'log data', 20] >>> logn [3, 'log data', 60] But again, you have the problem that you either have to KNOW the name to code it (as in the last displays), OR you need to access it by using: globals()[string_containing_name] If you have to use that reference anyways, why hassle with modifying the global scope -- just create your own dictionary and reference it (as my prior post does). -- -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From hancock at anansispaceworks.com Tue Nov 26 07:00:11 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 26 Nov 2002 04:00:11 -0800 Subject: Python Tutorial Was: Guido's regrets: filter and map In-Reply-To: <20021126101601.3518.73128.Mailman@mail.python.org> References: <20021126101601.3518.73128.Mailman@mail.python.org> Message-ID: On Tuesday 26 November 2002 02:16 am, David Brown wrote: > Good names are the key to readable and maintanable programming. ?But there > are plenty of cases where no name is better than some dummy name. ?If you > have to refer to something, it should have a good, sensible name. ?If you > don't have to refer to it, then it is an advantage to have no name - it > saves cluttering namespaces, and it makes dir() more useful. Yes, I agree. I think lambda does the same thing for functions that literals do for basic variable types: # Using a temporary variable... a = 2 myfunc(a) # ... is analogous to defining a single-use function ... def a(): return 2 mydispatch(a) # ... whereas using a literal ... myfunc(2) # ... is like using lambda mydispatch(lambda x: 2) These are not only shorter than the temporary variable/named-function versions, they are clearer -- since the name "a" doesn't carry any meaning. It's only conceivable meaning is transparently what it does (i.e. return a 2), so it serves no documentation purpose to name it. In this case, defining it in place really makes more sense. Of course if the function did something complicated, I'd far rather have a descriptive name attached to it, and it would require more than a simple expression (probably) to define it. The same thing applies to variables -- if you must do some complex arithmetic to figure it out, it probably makes sense to do the math, name it something appropriate to indicate conceptually what the quantity is, and then pass it on to the function. The existing lambda seems appropriate for encouraging this behavior, since it's difficult to express any function complicated enough to confuse the reader as a simple expression (I've seen it done for show -- but it doesn't seem like it would happen much in practice). Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From gerhard.haering at opus-gmbh.net Fri Nov 8 06:17:46 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 8 Nov 2002 11:17:46 GMT Subject: string.strip References: Message-ID: In article , Duncan Booth wrote: > Gerhard H?ring wrote in > news:slrnasn36r.tk.gerhard.haering at haering.opus-gmbh.net: > >> In article , Stano >> Paska wrote: >>> Hi, >>> >>> in documentation: string.strip(s[, chars]) >>> but in real life strip takes only 1 parameter >>> >>> I have python 2.2.2 >> >> But you've read the documentation for 2.3. (.../doc/current on >> python.org). > > Did you check your answer before posting? > > See > http://www.python.org/doc/2.2.2/lib/module-string.html#l2h-698 Only with the 2.2.1 docs from ActivePython. Sorry about that. -- Gerhard From gumuz at looze.net Wed Nov 13 04:21:33 2002 From: gumuz at looze.net (Gumuz) Date: Wed, 13 Nov 2002 10:21:33 +0100 Subject: python gui rant Message-ID: <3dd217e2$0$231$4d4ebb8e@news.nl.uu.net> sorry guys/girls, but i had to vent this :) i am using wxPython at the moment as my python gui. Coming from a nice IDE like Delphi it's really frustrating to get a nice layout together. I tried some tools. The one i liked most, because of it's simplicity was wxGlade, but still... it's not there yet. I might have missed something here and I don't want to complain, but I think that a good, robust gui-designer will open up a lot of posibilities for python. i might give it a shot! thanks, guyon From threeseas at earthlink.net Sat Nov 23 16:28:11 2002 From: threeseas at earthlink.net (Timothy Rue) Date: Sat, 23 Nov 2002 21:28:11 GMT Subject: Python IRC dictatorship References: <29304.91T434T13743504threeseas@earthlink.net><743utuoi3l31t8e8tt9v3sncosuk2gqi02@4ax.com><1239.92T1047T4844497threeseas@earthlink.net> Message-ID: <4992.92T2618T9825720threeseas@earthlink.net> On 23-Nov-02 11:11:30 John Hunter wrote: >>>>>> "Timothy" == Timothy Rue writes: > Timothy> they exist here too. >They are everywhere > Timothy> so what the fuck don't you understand about a named > Timothy> container that can hold changable information? Like a > Timothy> variable or a file. >If you say named container, to a python coder, they will think list, >tuple, dict and maybe string. They definitely would not initially >think about a 'variable or file'. >"variables" in python are a little different than in other programming >languages. python has "names" for objects. This example illustrates >one of the initially surprising ways names work [snip - see thread] John, thank you for your effort to describe some of the differences. Correction to your example, by another, noted. In summary what you are saying is that there is a tower of babel between not only client and coder but between languages as well. The result of this is that anyone in the position of a client really needs to learn the details of whatever specific language, including any other specifics of the use of a language, such as platform dependant issues, before they consider hiring a coder to produce, what the client designs. Otherwise how the hell is the client to communicate to the coder what the fuck they want? This to me is a clear indication of what can only be described as a serious failure of the software industry to properly take into consideration client perspective and client communication vocabulary and dictionary set. It further opens the door up for deception of the coders side, as they can always play vocabulary trip up games to drag things out and cost up. Currently the only notable effort there is to improve this failing is the ECMA-335 document on Common Language Infrastructure done unfortunately by Microsoft, as they are criminal regardless of getting off the hook. It is however a task anyone could have done, as it is more a matter of man hours rather than genius, to collect it all up, sort it all out and then integrate it into a non-conflicting manner. What the CLI is, is a sum total of programming concepts and datatypes, integrated in a non-conflicting manner. This of course having it's own Common Intermediate Language.... and run time engine. With this why would anyone continue to need language specific complexity, not to mention other dependant issues, when all they really need to do is speak concepts and datatypes to a translator that generates bytecode? But the problem is that we are no there yet and Microsoft has every intention of using such "common" to corner the next step or stage of software industry development.... autocoding. Now if I have a choice to go and use MS coders using CLI to speak with me in, that I can use that as a vocabulary set of concepts to communicate what I want.... or play the tower of babeling BS and drain of my bank account due it... which way do you think I or anyone being given that choice, would go? The real problem is the tower of babel. OBVIOUSLY! I believe you understand that.Unfortunately there are those who also understand that but use it dishonestly. The apex of the problem I seek a solution to is one of providing sharable resources of the type known in the language of shell speak.... Variables. Variable_name ; tag ; value variable_name ; tag ; value etc... placed in a file, so that the resource is available to any number of possible read and write accesses, as well as stored for later use, even after the system is turned off. Not to mention being in a directly human readable and editable format (i.e. the above) All is fine untill you have concurrent accesses that include at least one write. Unfortunately in python there is no platform independant way to apply locks and unlocks. There are a number of ways to handle the data, dictionary, dbm, Shelves, pickle, etc.. But these still don't handle the concurrent access problem in a platform independant manner. Now it is possible that concurrent access problems would be rare, and there is a way to intentionall force sequence of accesses when it is known in advance but I hate lose strings that when pulled causes alot to come undone. Interesting enough the Hurd servers comes to mind, as in a custom filehandeling server that handles concurrent accesses to prevent such problems. But the Hurd is a platform yet to have a production release, and such a solution is dependant upon the platform being used and such a custom filehandler being written. any suggestions? --- *3 S.E.A.S - Virtual Interaction Configuration (VIC) - VISION OF VISIONS!* *~ ~ ~ Advancing How we Perceive and Use the Tool of Computers!* Timothy Rue What's *DONE* in all we do? *AI PK OI IP OP SF IQ ID KE* Email @ mailto:timrue at mindspring.com >INPUT->(Processing)->OUTPUT>v Web @ http://www.mindspring.com/~timrue/ ^<--------<----9----<--------< From tjreedy at udel.edu Tue Nov 5 12:33:37 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 5 Nov 2002 12:33:37 -0500 Subject: How does Python handle probing to see if a file already exists? References: Message-ID: wrote in message news:mailman.1036508171.27010.python-list at python.org... > > From: Christopher R. Culver [mailto:Kricxjo.neniuspamajxo at yahoo.com] > > However, translating that directly into Python doesn't work because > > if Python can't find a file to open, it doesn't just return 0, it > > gives an error and exits. How can I write this functionality in Python > > so that it returns 0 and continues, or does Python have a totally > > different way of handling this problem than C? > Others have talked about the goodness of using try/except, I'll > say to use os.access(), which is precisely for what you're asking, > if you can read or write a file. > > -- check if writeable -- > > import os > if os.access("some-filename", os.W_OK): > # neat, I can write to the file. But only IF nothing happens to the file between the before-leap look and the leap itself. If another process deletes the file, changes permissions, or opens it for writing in between, then the OP is back where he started -- getting an uncaught, program-crashing exception. Or opening could fail for lack of OS open-file slots, buffers, whatever or writing could fail for lack of disk space. Whether or not this is a serious concern depends on the system and enironment the program runs in. TJR From imbosol at vt.edu Wed Nov 13 13:41:00 2002 From: imbosol at vt.edu (Carl Banks) Date: Wed, 13 Nov 2002 13:41:00 -0500 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3dce5e2f$0$35917$edfadb0f@dread13.news.tele.dk> <7h3smy5zj8k.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson wrote: > Carl Banks writes: > >> do_A() >> if test_based_on_A(): >> take_action_A() >> else: >> do_B() >> if test_based_on_B(): >> take_action_B() >> else: >> do_C() >> if test_based_in_C(): >> take_action_C() >> else: >> ... > > *This* is asking to be written as a loop: Not for me. I wouldn't use a loop in this situation, unless the operations in the loop were dynamic. The loop interrupts the logical flow and makes it a chore for a human reader to track down what's happening. I'll probably just factor the whole sequence into a function and use return when I got a match. I guess some people have hissyfits if they have to use break or return; I don't. and-if-I-were-programming-in-C-I'd-just-use-goto-ly yr's -- CARL BANKS From Robert_NJ_Sykes at msn.co.uk Tue Nov 19 12:16:50 2002 From: Robert_NJ_Sykes at msn.co.uk (Rob Sykes) Date: 19 Nov 2002 17:16:50 GMT Subject: COM interfaces and inheritance References: Message-ID: Alex Martelli wrote in news:kRqC9.27602$744.1004200 at news1.tin.it: >> >> class foo(): >> pass >> >> class bar(foo): >> self.stuff = 7 > > Invalid Python on several scores. Apologies. More haste less speed... class foo: pass class bar(foo): def __init__(self): self.stuff = 7 but you *knew* what I meant :-). I've had Delphi and VB in my head today There's COM stuff else-thread. I'll have a read -- Rob Sykes Born again Bairn | 'The despair I can live with. rob at john-richard dot co dot uk | It's the hope I can't stand' (header email for spambots) | (Anon.) From ktilton at nyc.rr.com Wed Nov 20 14:37:16 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Wed, 20 Nov 2002 19:37:16 GMT Subject: gc (was Re: Why is Python popular, while Lisp and Scheme aren't?) References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <3DDBD838.10406@nyc.rr.com> Message-ID: <3DDBE4C7.6060308@nyc.rr.com> Kenny Tilton wrote: > true garbage collection (I am /not/ looking forward to reference > counting or the hoops one has to jump thru to handle cyclic refs) Someone was kind enough to email me that the above is mistaken. I just revisited the page where I got that info, turns out it was 2000. My correspondent did not specify, but is this provided by the optional GC module, or is it now just part of core Python? Either way, great news. -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From rmunn at pobox.com Wed Nov 13 01:59:25 2002 From: rmunn at pobox.com (Robin Munn) Date: Wed, 13 Nov 2002 06:59:25 GMT Subject: newbie question: how to get directory of script? References: <4cce07d5.0211120957.6d4934@posting.google.com> <3DD1B65D.AE624740@cisco.com> Message-ID: Tom McDermott wrote: > djw wrote: >> >> os.getcwd() >> > No such luck. This (at least on linux) returns the directory from which > the script is invoked, rather than the directory of the script. > > I use sys.path[0], but that doesn't seem to be the official method. I don't know why Windows is putting the name of the script in sys.argv[1] instead of sys.argv[0] -- that bothers me. But if you know the name of the script, then you can do: script_dir = os.path.dirname(os.path.abspath(script_name)) Or: script_dir, script_basename = os.path.split(os.path.abspath(script_name)) -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From martti.halminen at kolumbus.fi Sat Nov 9 14:05:20 2002 From: martti.halminen at kolumbus.fi (Martti Halminen) Date: Sat, 09 Nov 2002 21:05:20 +0200 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h31y5uyj81.fsf@pc150.maths.bris.ac.uk> Message-ID: <3DCD5C70.1981C152@kolumbus.fi> Robin Munn wrote: > I think I was weirded out by Python's indentation like just about > everyone else who was coming from something like C -- but I quickly grew > used to it. > > Lisp's parentheses, OTOH, I never got used to. Having to constantly stop > and count parentheses to remember where I was in my program structure > quickly went from novel to irritating and never recovered. Most of the > other students in my CS class agreed with me about the Lots of > Irritating Superfluous Parentheses. > > The only thing that could make me at all comfortable with using Lisp > would be if I had an editor that would color-highlight not keywords or > strings, as color-highlighting usually goes, but levels of parenthesis > indentation. So that this: > > (a (b (c (d e)))) > > would have 'a' in one color, 'b' in a second, 'c' in a third, and 'd e' > in a fourth. The secret in programming in Lisp is not to count the parentheses. After a few months, they pretty much disappear from sight. Counting parens is for the compiler and editor, the humans read Lisp code based on indentation (and the editor (emacs, mostly) takes care of that, so the programmer doesn't have to bother...). This should be rather easy for Python programmers to understand :-) -- From bdash at gmx.net Mon Nov 11 02:41:04 2002 From: bdash at gmx.net (Mark Rowe) Date: Mon, 11 Nov 2002 20:41:04 +1300 Subject: Reusing Address with Sockets In-Reply-To: Message-ID: On Monday, Nov 11, 2002, at 14:58 Pacific/Auckland, Kuros wrote: > Hello, > > I am writing a TCP server program, and everything is working fine, > except > for one minor problem. When I close the program, I cannot reuse the > same > address, I have to change the port it runs on. Now, I've tried to do > this: > > sock.setsockopt(SO_REUSEADDR, SO_LINGER, 1) Hello, That line should be sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) The setsockopt man page details this and other socket options. Mark From theller at python.net Tue Nov 19 14:28:16 2002 From: theller at python.net (Thomas Heller) Date: 19 Nov 2002 20:28:16 +0100 Subject: need help porting ctypes to Linux Message-ID: <8yzp5pgv.fsf@python.net> I recently announced ctypes, see http://starship.python.net/crew/theller/ctypes.html I've got some enthusiastic responses, and also some requests to port this to other systems. So I'm currently porting it to Linux. I have an early version running, but I have some questions for experienced linux people. Certainly off-topic here, but I hopefully I get bright answers fast also to these questions. Here we go: Section A: libffi 1. I use Anthony Green's libffi. I subscribed to the mailinglist at redhat and asked questions there, but no response so far. This list seems pretty dead. From what I found on the web, libffi is included in gcc starting with 3.0 or so. I cannot check this myself, I use an oldish suse 7.0 linux here. Is it correct that libffi is still covered by the MIT license, and not GPL or LGPL? 2. I would like to throw away some of my own code and use libffi instead also for Windows. Since libffi uses gnu's assembler syntax, it would be easiest to crosscompile the library under linux for Windows, at least for starting. I've heard this is possible using MingW, is this correct? (Ahem) In this case, would some kind soul be willing to do it? Section B: general linux questions 3. When my extension does something wrong, I see 'Speicherzugriffsfehler' ('access violation' or so) printed on the console. Why isn't a core dump (for examination) created? Do I have to enable this? Or is it possible to configure gdb so that it will automatically pop up to examine the program's state? 4. When I have undefined symbols in my shared extension module, I get an 'ImportError: /.../_ctypes.so: undefined symbol: blabla' when the module is loaded. Is this normal? Why doesn't the linker complain? Section C (and now we're on-topic again): understanding the Python interpreter lock 5. I got crashes when using callbacks, they vanished when I called PyEval_InitThreads(). This was unneeded on Windows, I assume because on Windows PyEval_InitThreads() has been called before. My question is: why do I have to call this function on Linux, but not on Windows? Does it do any harm if I call the function when the ctypes module is loaded, or should I wait until the callbacks are actually needed? Thanks for any advice, Thomas From see_reply_address at something.invalid Wed Nov 27 23:45:03 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 28 Nov 2002 17:45:03 +1300 Subject: Implementation of the global statement References: <8ef9bea6.0211270526.5a1278c5@posting.google.com> Message-ID: <3DE59F4F.1090004@something.invalid> Mikael Olofsson wrote: > Is that behaviour intended? > Is it likely to stay that way? Yes and yes. Consider that when you do from A import f you probably want f to still work properly even if it calls other functions defined in A or otherwise relies on things living in A. If it didn't work this way, you'd have to not only import f but all the things that f relied on as well! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From LogiplexSoftware at earthlink.net Mon Nov 18 18:31:22 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 18 Nov 2002 15:31:22 -0800 Subject: Hmm... An idea: if a,b==c,d: In-Reply-To: References: Message-ID: <1037662282.27904.237.camel@software1.logiplex.internal> On Mon, 2002-11-18 at 14:59, Richard Dillingham wrote: > It doesn't have ()s, so it ain't two tuples. Easy enough, da? Incorrect. Consider: Python 2.2.1 (#1, Aug 30 2002, 12:15:30) [GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> t = 1, 2 >>> t (1, 2) >>> type(t) >>> No parentheses, yet still a tuple. At this point perhaps you should RTFM ;) Also, please don't top-post. Regards, > "Carl Banks" wrote in message > news:arbqp2$rkb$1 at solaris.cc.vt.edu... > > Richard Dillingham wrote: > > > Kind of like we have multiple assignments in a line (oldx,oldy=x,y), > what do > > > you think of the ability to have multiple tests in an if statement with > only > > > one == or >=. > > > > > > This would mean that lines like the following: > > > if posx>=coords[0] and posy>=coords[1] and posx<=coords[2] and > > > posy<=coords[3]: > > > > > > Could be rewritten like so: > > > if posx,posy>=coords[0],coords[1] and posx,posy<=coords[2],coords[3] > > > > How would you disambiguate that from a comparison of two tuples? > > > > > > -- > > CARL BANKS -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 -------------- 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 kennedy.bill at freeuk.com Wed Nov 20 08:19:07 2002 From: kennedy.bill at freeuk.com (William Kennedy) Date: 20 Nov 2002 07:19:07 -0600 Subject: Pickles Message-ID: **** Post for FREE via your newsreader at post.usenet.com **** How big can a pickled object be. I am looking at an index 800 records long, should I be using a database -- --- william kennedy remove .nospam from email address -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= *** Usenet.com - The #1 Usenet Newsgroup Service on The Planet! *** http://www.usenet.com Unlimited Download - 19 Seperate Servers - 90,000 groups - Uncensored -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= From psage at ncaustin.com Fri Nov 8 11:02:15 2002 From: psage at ncaustin.com (Paul Sage) Date: Fri, 8 Nov 2002 10:02:15 -0600 Subject: Why is Python popular, while Lisp and Scheme aren't? Message-ID: <03F53405C6ED434A986221919785A6A70154F5E3@nca-postal.ncaustin.com> Having worked a bit with LISP, in college, and Python, as a scripting language for computer game work, my feelings about the two are very different. I remember LISP was cool in that we could do some neat math proofs with it, and it had applications that made formula translation (textbook to code) quick and nifty. However, LISP also was not obvious to me as a 'real-world' language because it just always felt like I had to recreate the wheel when I used it for anything applicable to a real world application. We also nicknamed LISP - Little, Insignificant, Stupid Parentheses. Maybe that holds as my most common complaint, it was darn hard to read someone else's LISP code quickly. Python on the other hand has been pretty easy to pick up for the tasks I need it to do. I have been surprised at just how easy I can do something useful quickly. The other night I wrote a quick few lines of code to move files around without even thinking about it. In all fairness, my impression of LISP was based around a language I had to learn in college and the tasks that were assigned to me. Python is a language we are using at work, so I spend more time trying to figure out what it can do in the real world. Note, by no means am I a software engineer. I'm just an average Joe who is mucking around, so that is my average Joe impression. > -----Original Message----- > From: Oleg [mailto:oleg_inconnu at myrealbox.com] > Sent: Friday, November 08, 2002 6:54 AM > To: python-list at python.org > Subject: Why is Python popular, while Lisp and Scheme aren't? > > Hi > > I don't know much about Python, but I looked at this comparison > between Python and Common Lisp ( > http://www.norvig.com/python-lisp.html ), and I couldn't help but > wonder why Python is popular, while Common Lisp and Scheme aren't? > > Oleg > -- > http://mail.python.org/mailman/listinfo/python-list From ulbi at ivs.tu-berlin.de Mon Nov 11 05:25:38 2002 From: ulbi at ivs.tu-berlin.de (Andreas Ulbrich) Date: Mon, 11 Nov 2002 11:25:38 +0100 Subject: [Jython] out of memory during jythonc compilation References: Message-ID: Robert Oschler wrote: > I tried to compile a python file using the following options: > > jythonc --deep --jar new.jar new.py > > After cranking away for several minutes, it terminated with an "out of > memory" message, and suggested increasing the heap size with the "-mx" > option. I then tried: > > jythonc -J-mx1000000 --deep --jar new.jar new.py > > And got the same error. I then tried 50M instead of 1M for the heap size > and still go an "out of memory" error. new.py pulls in the Jython XML > package structure, and the memory error always occurs right after > "processing codecs". Anybody know what I might be able to do about this? > > thx I've had similar problems quite a while ago when Jython was called JPython and had version numbers less than two. Increasing the heap size helped, but you may want to try something more substantial than 50 MB. Give it everything your machine has. I managed to compile everything when the heapsize was at least 256 MB. A fast machine comes handy, too :-) From robin at jessikat.fsnet.co.uk Sat Nov 2 10:00:02 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 2 Nov 2002 15:00:02 +0000 Subject: Using windll with complex data types References: <8beb91f5.0211020556.30107507@posting.google.com> Message-ID: <0qxMNUAyh+w9EwJw@jessikat.fsnet.co.uk> In article <8beb91f5.0211020556.30107507 at posting.google.com>, Ben C writes .... I use the structob module to create structured things as for pointers they are the address of something. so for example a lasterror function looks like def _lastErrorMessage(n=None): msg = windll.cstring('',512) kernel32.FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, n is None and GetLastError() or n, 0, msg.address(), len(msg)-1, 0 ) return repr(msg)[1:-1] we create the buffer and pass its address to the FormatMessage function. If you really need pointer to pointer you need to create a buffer that holds the real address eg class pointer(structob.struct_object): oracle = structob.Oracle ( 'pointer', 'Nl', ('ref',) ) then you can do msg = windll.cstring('',512) p=pointer() p.ref = msg.address so p points to msg and p.address() is a pointer to a pointer > >How does one pass reference to a pointer in a function? > >How does one retrieve data back from that pointer? > >How does one retrieve data back from aggregate data types such as >structures and arrays? > >Thanks in advance > >Ben -- Robin Becker From bloke at ii.net Thu Nov 7 05:54:13 2002 From: bloke at ii.net (Rob Hall) Date: Thu, 7 Nov 2002 02:54:13 -0800 Subject: idiom for initialising variables Message-ID: <3dc964fa$0$12989@echo-01.iinet.net.au> I'm just wondering on the correct python idiom for initialising variables. I see some code like this: class myClass: self.a = 1 def __init__(self): ...more stuff here I also see: class myClass def __init__(self): self.a = 1 ...more stuff here Which is the correct idiom? or is there a subtle difference I am missing? Rob From jorgencederberg at hotmail.com Thu Nov 7 02:02:46 2002 From: jorgencederberg at hotmail.com (=?Windows-1252?Q?J=F8rgen_Cederberg?=) Date: Thu, 7 Nov 2002 08:02:46 +0100 Subject: Placing Tkinter objects in a dictionary References: <3dc9fa87$1_4@nopics.sjc> Message-ID: "Adonis" wrote in message news:3dc9fa87$1_4 at nopics.sjc... > I have a loop creating Tkinter objects (an Entry text box) all with the same > name and placing its instance in a dictionary: i.e: > > for x in range(10): > myEntry = Entry(frame) > myEntry.grid(row=x, column=0) > > someDict['%s'%x] = myEntry > > now I have another function which will modify myEntry: > > def someFunc(x, data): > someDict[str(x)].config(text=data) # here is my error; the config does > not work; > # no error is raised. hi The problem is that there is no 'text' option for the Entry widget, you can see the options here: http://www.pythonware.com/library/tkinter/introduction/x4447-options.htm Here is an example where I use a StringVar to update the contents of the entry. >>> from Tkinter import * >>> root = Tk() >>> s = StringVar() >>> Entry(root, textvariable=s).pack() >>> d = {} >>> d['test'] = s >>> d['test'].set('Hello World') Instead of saving the Entry in a dictionary, I save the StringVar, which is accessed with get and set methods. Hope this helps. /Jorgen From mfranklin1 at gatwick.westerngeco.slb.com Mon Nov 11 07:06:27 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 11 Nov 2002 12:06:27 +0000 Subject: Efficient scanning of mbox files In-Reply-To: <16E1010E4581B049ABC51D4975CEDB88619932@UKDCX001.uk.int.atosorigin.com> References: <16E1010E4581B049ABC51D4975CEDB88619932@UKDCX001.uk.int.atosorigin.com> Message-ID: <1037016388.1101.5.camel@m-franklin> On Mon, 2002-11-11 at 11:42, Moore, Paul wrote: > > def add_group(self, id, file): > print "Opening file", file, "for group", id > fp = open(file, "rb") > posns = [] > oldpos = 0 > n = 0 > while 1: > line = fp.readline() > if not line: break > if FROM_RE.match(line): > n += 1 > posns.append(oldpos) > oldpos = fp.tell() > fp.close() > posns.append(oldpos) > print "Group", id, "- articles(posns) =", n, len(posns) > self.groups[id] = (file, n, posns) > > -- > http://mail.python.org/mailman/listinfo/python-list Paul, I ran the above example on my Python folder (7000+ messages...) it took 12 seconds to process. Then I changed the if FROM_RE.match(line): to if line.startswith("From "): And got a 2 second speed up.... Then I slurped the file into a cStringIO.StringIO object and got it down to 5 seconds..... Just some thoughts Martin From csshi99 at yahoo.com Mon Nov 4 22:40:34 2002 From: csshi99 at yahoo.com (xinghua shi) Date: Mon, 4 Nov 2002 19:40:34 -0800 (PST) Subject: simple question In-Reply-To: <20021105010502.7943.81810.Mailman@mail.python.org> Message-ID: <20021105034034.20792.qmail@web21204.mail.yahoo.com> Hey, I am new to Python world. I wrote a simple program but got error. Could someone help me fix this? Thanks. import sys,os,string pid = os.getpid() filename = ".ld.mon." + str(pid) print filename ^^^^^^^^^^Name error: name "filename" is not defined. Do I really need to define "filename" before use it? I tried char *filename but still didn't work. Thanks for the help. --------------------------------- Do you Yahoo!? HotJobs - Search new jobs daily now -------------- next part -------------- An HTML attachment was scrubbed... URL: From ubecher at gmx.de Wed Nov 13 14:09:11 2002 From: ubecher at gmx.de (Uwe Becher) Date: Wed, 13 Nov 2002 20:09:11 +0100 Subject: Local drives on Win32 with win32api Message-ID: <3DD2A357.4000308@gmx.de> Hi. I'm trying to get information about local drives on a win32 box. Using win32api.GetLogicalDriveStrings() and win32api.GetDiskFreeSpace(drive) works nearly perfect - except: I get all the network drives mapped to a drive letter too! Is there a way to get information, if a drive is local or remote? May be I missed the point reading the documentation. Uwe From tjreedy at udel.edu Mon Nov 25 14:57:42 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 25 Nov 2002 14:57:42 -0500 Subject: Strange's exception :-) References: <3DE2453B.9030002@libero.it> Message-ID: > IOError: [Errno 104] Connection reset by peer This is pretty common with telnet sessions kept open long enough and occasional with long file downloads. Happened to me just last night with Yahoo. > What can I do to manage this exception? Basicly, try again later. From jdhunter at nitace.bsd.uchicago.edu Fri Nov 15 15:24:21 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Fri, 15 Nov 2002 14:24:21 -0600 Subject: A really bad idea. In-Reply-To: <15829.21594.896779.746111@montanaro.dyndns.org> (Skip Montanaro's message of "Fri, 15 Nov 2002 14:08:58 -0600") References: <4STA9.9987$744.345722@news1.tin.it> <3DD44152.69795B9F@alcyone.com> <15829.21594.896779.746111@montanaro.dyndns.org> Message-ID: >>>>> "Skip" == Skip Montanaro writes: Skip> I don't use any of those fancy-schmancy IDEs, though I do Skip> use python-mode, which has F1 bound to call help() on the Skip> dotted attribute expression under the cursor. Hey ... emacs IS fancy-schmancy! What is the python-mode function that you bind F1 to? That sounds useful. John Hunter From whisper at oz.net Sun Nov 17 03:06:51 2002 From: whisper at oz.net (David LeBlanc) Date: Sun, 17 Nov 2002 00:06:51 -0800 Subject: Windows Nt directory names In-Reply-To: <20021117073039.31348.qmail@web14507.mail.yahoo.com> Message-ID: CMD=r'"c:\program files\action.exe"' Note the double quotes inside the single quotes. What you are doing is passing a quoted string to the OS and that's legal (and required as you have found out when there are spaces in the path) :) David LeBlanc Seattle, WA USA -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org]On Behalf Of asdfasd asdfasdf Sent: Saturday, November 16, 2002 23:31 To: python-list at python.org Subject: Windows Nt directory names hi i wanted to execute a command somewhere in "program files" directory but can't seem to do it as it says : "c:\program" is not recognized as an internal command i have used : import os CMD = r'c:\program files\action.exe' os.system(CMD) how do i code so that the space in "program files" is recognized? thanks ---------------------------------------------------------------------------- -- Do you Yahoo!? Yahoo! Web Hosting - Let the expert host your site -------------- next part -------------- An HTML attachment was scrubbed... URL: From SBrunning at trisystems.co.uk Mon Nov 4 10:38:29 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Mon, 4 Nov 2002 15:38:29 -0000 Subject: Foot in mouth disease Message-ID: <31575A892FF6D1118F5800600846864DCBDA99@intrepid> > From: aahz at pythoncraft.com [SMTP:aahz at pythoncraft.com] > In article , > Simon Brunning wrote: > >> From: aahz at pythoncraft.com [SMTP:aahz at pythoncraft.com] > >>> > >>>3) Ask her for a date > >> > >> She lives in Toronto (I'm in California) and I'm not her > type. > > > >Yeah, but asking her out would put her on the back foot, and you can win > the > >Java vs. Python argument for once and for all. > > Um.... How do you think I know I'm not her type? What does "back foot" > mean, anyway? Funny - I often know that I'm not a woman's type without having to ask - it's usually bleedin' obvious. ;-) The 'back foot' thing - sorry, it's an idiom in use in cricket playing nations only. I should have thought about my audience a little more. If someone is on the back foot, they are uncomfortable and on the defensive. Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From trentm at ActiveState.com Wed Nov 6 14:06:52 2002 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 6 Nov 2002 11:06:52 -0800 Subject: idiom for initialising variables In-Reply-To: <3dc964fa$0$12989@echo-01.iinet.net.au>; from bloke@ii.net on Thu, Nov 07, 2002 at 02:54:13AM -0800 References: <3dc964fa$0$12989@echo-01.iinet.net.au> Message-ID: <20021106110652.D18006@ActiveState.com> [Rob Hall wrote] > I'm just wondering on the correct python idiom for initialising variables. > I see some code like this: > > class myClass: > self.a = 1 > def __init__(self): > ...more stuff here > I suspect you quoted that one incorrectly. It should be: class myClass: a = 1 def __init__(self): ...more stuff here > I also see: > > class myClass > def __init__(self): > self.a = 1 > ...more stuff here > > > Which is the correct idiom? or is there a subtle difference I am missing? Either works. Which one you chose probably depends more on your preference for aethetics than anything else. There *is* a slight difference in when the 'a' variable gets created. With the former, you can access 'a' on the class object. With the latter you have to create a class instance (i.e. the __init__() method has to run) before 'a' is available. >>> class TopLevel: ... a = 1 ... def __init__(self): ... pass ... >>> class InInit: ... def __init__(self): ... self.a = 1 ... >>> >>> >>> t = TopLevel() >>> t.a 1 >>> i = InInit() >>> i.a 1 >>> >>> TopLevel.a 1 >>> InInit.a Traceback (most recent call last): File "", line 1, in ? AttributeError: class InInit has no attribute 'a' >>> Trent -- Trent Mick TrentM at ActiveState.com From derek at wedgetail.com Sat Nov 2 09:08:01 2002 From: derek at wedgetail.com (Derek Thomson) Date: Sun, 03 Nov 2002 00:08:01 +1000 Subject: Foot in mouth disease References: Message-ID: <3dc3dc4e$0$12762$afc38c87@news.optusnet.com.au> Aahz wrote: > She asked me what -- if any -- Java-based tools were used by > the experienced Java programmers who made that claim. She thinks that > those tools are superior to plain text editors (which are really all > that's needed for Python). Eclipse ... for about one day. Far too painful, so it was back to Emacs. Really, I've yet to see any IDE that I liked, or did anything but limit my productivity. They have the same problems all GUI's have - you can only do what the designers *thought* you might want to do. And when coding, that's a serious limitation. I use Emacs, because it's basically just a Lisp interpreter with some built-in functions for text editing. I can therefore program it do do *anything*. [And sometimes I have to use Visual Studio when porting. I can't understand how anyone puts up with it. Aside from being unusable, it's full of bugs] As for refactoring, Python's advantage here are it's dynamic typing, and run-time flexibility. Try altering a Java application on the fly. It can't be done. In Python you can, for example, muck about with a GUI as it's running, to see what works and what doesn't. This is *great*. Then there's the fact that it takes between 5-10 lines of Java to do the same thing in Python, depending on what you're doing. Having a very high level language, as opposed to a high level one, definitely helps refactoring in that there's much less code to refactor. Look at the size of Fnorb (*), compared to Java ORBs. Or just look at the size of the Fnorb IDL compiler ... and it's even readable. I know which I'd like to be refactoring. (*) http://fnorb.org As for the "tools" refactoring IDEs provide, I can get more powerful results with the Perl "-i" option, which lets you modify files in-place. I could rename a method to anything I pleased, consistently, just to name a trivial example. But since I'm using a *language* to specify my changes, I can do literally anything. You can't do that in an IDE, unless the IDE authors create a Turing-complete language to specify changes with. (Yes, I know people are going to say I should use Python, but Perl's honestly better for pattern matching and substitution from the command line, mainly because regexes are always immediately available and for all the neat command line switches. Like "-i" itself ...) -- D. From quadric at primenet.com Mon Nov 18 14:14:42 2002 From: quadric at primenet.com (quadric at primenet.com) Date: Mon, 18 Nov 2002 12:14:42 -0700 Subject: Fast construction of Python list from large C array of int's - Extension Module Message-ID: <5.1.1.6.2.20021118111217.019a74d0@pop3.norton.antivirus> Hi, I'm a bit of a Python newbie and I've written a C extension module. One of the functions must return a Python list whose source is a large (5000 - 6000) C array of integers. I need a fast way of constructing the Python list. I was planning on something like: PyObject * CreateListFromArray( int * array , int array_length) { PyObject * list = PyList_New( array_length); for int i = 0 ; i < array_length ; i++ ) { PyList_SetItem( list , i , Py_LongFromLong( (long) array[i] ) ); } return list; } Is this the fastest way to do this? Any inherent dangers here? Any issues with memory shortage etc... in Python interpreter. In other words should I do thusly: PyObject * list = PyList_New( array_length); if (list != NULL) { for int i = 0 ; i < array_length ; i++ ) { PyList_SetItem( list , i , Py_LongFromLong( (long) array[i] ) ); } } Thanks for your help. quadric at primenet.com From scheff at bigfoot.de Tue Nov 5 06:22:06 2002 From: scheff at bigfoot.de (Tim Scheffler) Date: 5 Nov 2002 03:22:06 -0800 Subject: GUI with blocking database access Message-ID: <5ec37a54.0211050322.e663b54@posting.google.com> Dear all, I would like to construct a GUI to access an external database. Unfortunately I have to use a (non-opensource) python dll (WIN32) module provided by the database to write/read from/to it. If I/O is done via this module all execution is stopped if I try to run it in a separate thread in the GUI. Does somebody have an idea how to construct a GUI, that can trigger such an I/O module? I thought about to run two separate processes on WIN-NT one that provides the GUI and one that runs the I/O and let them communicate through a pipe or something like that. But here I dont know how to start two processes from one python script as fork() wont work on WIN-NT. Any help is deeply appreciated. Thanks in anticipation Tim From bvdpoel at kootenay.com Fri Nov 8 11:50:43 2002 From: bvdpoel at kootenay.com (Bob van der Poel) Date: Fri, 08 Nov 2002 09:50:43 -0700 Subject: Optik long help strings References: <3DC9CDAD.91A42BDB@kootenay.com> Message-ID: <3DCBEB63.794C000C@kootenay.com> David Goodger wrote: > > Bob van der Poel wrote: > > I'm trying to use the Optik package for parsing command line options. > > However, I'm running into a problem overriding its line warping > > routines. I'd like the help to print something like: > > > > options: > > -p, --pattern Set pattern > > 'xx' use the xx pattern > > 'yy' use the yy pattern > > ... more list of pattern options > > > > Seems that optik thinks it knows better where the new lines should go. > > Suggestions? > > It's not really clear what you intend. Either you're using hard tabs or > single spaces for indents; in any case, it's very subtle here. Sorry. Was using real tabs. Dumb me. options: -p, --pattern Set pattern 'xx' use the xx pattern 'yy' use the yy pattern ... more list of pattern options Hopefully this doesn't get munged. > Optik isn't currently set up to handle complex option descriptions (where > complex means anything other than a single flexible paragraph). I suggest > you post to . If this feature is really > important to you, delve into the code and submit a patch. I didn't know there was a optik list. Guess I'll have to subscribe. Thanks. -- Bob van der Poel ** Wynndel, British Columbia, CANADA ** EMAIL: bvdpoel at kootenay.com WWW: http://www.kootenay.com/~bvdpoel From bokr at oz.net Tue Nov 12 07:47:57 2002 From: bokr at oz.net (Bengt Richter) Date: 12 Nov 2002 12:47:57 GMT Subject: Can python find fibonacci series in a single line of code? References: <6q7kfjau4f.fsf@salmakis.intevation.de> Message-ID: On Tue, 12 Nov 2002 12:09:56 +0000 (UTC), Duncan Booth wrote: >Bernhard Herzog wrote in >news:6q7kfjau4f.fsf at salmakis.intevation.de: >> >> python -c "a = b = 1L; exec('while 1: print a; a,b=b,a+b')" >> >> It would be nice to get rid of that exec, too... > >You could get rid of the unnecessary parentheses after the exec. And as for >the whitespace, are you trying to make it readable or something?: > > python -c "a=b=1;exec'while+1:print+a;a,b=b,a+b'" > >Who ever said Python programs need whitespace! I didn't know exec would parse semicolons that way (I hardly ever use it). But is that new with 2.2? Does that mean it effectively assumes a semicolon is the same as a newline and indent to the same level as the previous statement, until it finds an actual newline? Regards, Bengt Richter From max at alcyone.com Mon Nov 11 22:34:09 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 11 Nov 2002 19:34:09 -0800 Subject: newbie Q: shortcuts for long module names? References: Message-ID: <3DD076B1.B0A5CA12@alcyone.com> Robert Oschler wrote: > Let's say I import a module with a long name: > > import com.long.module.name > > Now every time I access a function in com.long.module.name I have to > prepend > "com.long.module.name" to the member function. Is there generally > accepted > and safe way to "alias" the module name or bring it into the local > namespace > so I can either omit or alias the module name with something much > shorter? Try import this.is.a.long.module.name as name or import this.is.a.long.module.name as somethingElse -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ There are defeats more triumphant than victories. \__/ Montaigne Polly Wanna Cracka? / http://www.pollywannacracka.com/ The Internet resource for interracial relationships. From DaveP at NEARLYdpawson.freeserve.co.uk Fri Nov 15 03:11:08 2002 From: DaveP at NEARLYdpawson.freeserve.co.uk (DaveP) Date: Fri, 15 Nov 2002 08:11:08 -0000 Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> Message-ID: martin at v.loewis.de (Martin v. Loewis) wrote in news:m3u1ilqic9.fsf at mira.informatik.hu-berlin.de: > DaveP writes: > >> > However, it is not clear to what the value would be of completing the >> > circle, given that the XML is of no use. >> >> Martin, your prejudice is showing; very badly :-) > > That might be the case. However, as a question, I meant it seriously: > What do I gain from converting the Python documentation to XML? In an earlier mail you mentioned the toolset for XML. Saves a lot of work. > Longer-term, I have been considering that using XML might help > translating the Python documentation to French and German, but I'm > certain that nobody else has that usage in mind. So I'm wondering what > other people expect from this, apart from buzzword compliance. OK, the last bit rings true. Docbook has a significant multi-lingual element for boiler plate, the techniques are re-usable though. Norm Walsh did a talk on it at a conference I hosted in 2001 if you are interested. Regards DaveP. From alanmk at hotmail.com Wed Nov 20 07:03:10 2002 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 20 Nov 2002 12:03:10 +0000 Subject: Deep XML modification.. References: <3ddb6d4f$0$18869$afc38c87@news.optusnet.com.au> Message-ID: <3DDB79FE.8D1CDC41@hotmail.com> nobody wrote: > Whats the best way to modify deep branches of XML? The tree is eight > levels deep, so I have a forrest of cloneNode and replaceChild, to > propogate changes from the leaves back to the root Document. Hmm, why would you want to "propagate changes back to the root"? You give the impression that you want to change some nodes 8 levels down. That shouldn't necessitate any changes to the root. > There has got to be a > better way? I also want to avoid pre-sorting the data into a list, > and keep it entirely XML if possible. Methinks you have some application specific requirements that you're not sharing with us. Why would want to transfer the data into a list? Is the data sorted in some way? Perhaps it would better if you either A: Told us the nature of your data and the constraints you have placed on it? B: Posted one of your XML document structures, with perhaps before and after examples to tell us what you're trying to achieve. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From carlca at dircon.co.uk Wed Nov 13 17:48:23 2002 From: carlca at dircon.co.uk (Carl Caulkett) Date: Wed, 13 Nov 2002 22:48:23 +0000 Subject: python gui rant References: <3dd217e2$0$231$4d4ebb8e@news.nl.uu.net> Message-ID: On 13 Nov 2002 09:47:16 GMT, bokr at oz.net (Bengt Richter) wrote: Hi Bengt, ---8<--- >Your mention of Delphi made me recall that you can right click on a gui form >and select 'view as text' from the popup menu, and you get to see all the >parameters that define your layout. E.g. a default form with one button dropped >on it near the top left: > >object Form1: TForm1 > Left = 200 > Top = 108 > Width = 544 ---8<--- Hmmm. It occurs to me that the items that appears in a Delphi form (including events) are published properties of the visual controls on that form. This means that they can be traversed using RTTI (Run Time Type Information) and could be used to dynamically build a Python/wx script. As you mention elsewhere, Delphi supports the use of Anchors which, along with Constraints and the Align property, should provide the kind of resiable forms that decent thinking people expect . My only problem is that, while I'm pretty good at the Delphi side of things, my wx knowledge is limited at the moment. It would be a good incentive to improve, though. I think I feel a little project coming on ... -- Carl From achim.domma at syynx.de Thu Nov 14 10:50:45 2002 From: achim.domma at syynx.de (Achim Domma) Date: Thu, 14 Nov 2002 16:50:45 +0100 Subject: A really bad idea. References: Message-ID: "M" wrote in message news:c0abefc3.0211140738.635c0e6d at posting.google.com... > Just a few examples... > The new enumerate or zip function. If you look at the code using this function > it is not at all obvious what the code does. Let say a programmer that knows > 10 other languages looks at this code. I don't think he would right away > understand what this function does. This construct is not obvious. Generators > are another thing that are just horrible. They just don't work in a way > that one would expect from previous experience. [...] > I hope this is not a start of adding powerfull and hard to understand > features to Python. As mentioned in other threads one should learn python if one would like to develop in python. I think you should make a difference between features which are hard to understand and features which are usually not found in other languages. In my opinion enumerate, zip and generators are not hard to understand, but they might be uncommon. But they give you the power to express concepts in their natural way. Another example is list comprehension: If you are used to it, they are nearly plain english, but I know people who prefer writing loops over multiple lines, only because they are used to do it this way and don't want to learn something new. regards, Achim From phil at river-bank.demon.co.uk Sun Nov 3 19:35:24 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Mon, 4 Nov 2002 00:35:24 +0000 Subject: pyqt rules In-Reply-To: <7Dgx9.41909$Lg2.11396126@news2.news.adelphia.net> References: <3dc550fb$0$9008@echo-01.iinet.net.au> <3dc571d0$0$63818$e4fe514c@dreader1.news.xs4all.nl> <7Dgx9.41909$Lg2.11396126@news2.news.adelphia.net> Message-ID: <200211040035.24941.phil@river-bank.demon.co.uk> On Sunday 03 November 2002 9:33 pm, Bob X wrote: > "Boudewijn Rempt" wrote in message > news:3dc571d0$0$63818$e4fe514c at dreader1.news.xs4all.nl... > > > Not too mention buying the book -- don't try Amazon, > > they seem to have problems delivering, but at > > http://www.opendocs.org/pyqt :-). > > -- > > Boudewijn Rempt | http://www.valdyas.org > > I would love to use PyQt but it seems I have to have the Qt NC version to > make it run but I cannot find a Windows binary anywhere. I do not have VC++ > to compile the beast either. The binary of Qt NC is at http://www.trolltech.com/developer/download/qt-win-noncomm.html The binary of PyQt for Qt NC is at http://www.riverbankcomputing.co.uk/pyqt/download.php Phil From gerrit.muller at philips.com Tue Nov 5 06:57:20 2002 From: gerrit.muller at philips.com (Gerrit Muller) Date: Tue, 05 Nov 2002 12:57:20 +0100 Subject: pyqt rules References: <3dc550fb$0$9008@echo-01.iinet.net.au> <2Dkx9.42039$Lg2.11444432@news2.news.adelphia.net> <3DC6E304.6070507@SPAMnwinternet.com> Message-ID: <3DC7B220.BF77CADB@philips.com> <...snip...> > If "openness" is the controlling factor, you can run the > GPL'd versions of Qt/PyQt on any open OS (*BSD, Linux) > free of charge. > > from: http://www.trolltech.com/developer/faqs/noncomm.html > > "What is the Qt Non-Commercial Edition for Microsoft Windows? > ----------------------------------------------------------- > > The Non-Commercial Edition is the Qt for Windows toolkit, > licensed for private development of non-commercial software > in a non-commercial setting. > > A non-commercial setting means that you must not use the > package in the course of your employment or whilst engaged > in activities that will be compensated. > > A non-commercial application is an application that cannot > be sold, leased, rented or otherwise distributed for > recompense. > > You may freely use Qt Non-Commercial Edition for: > > * Running software legally developed by others > * Developing non-commercial software" > > It doesn't look that complicated to me. > > Jim I am creating a freely accessible website http://www.extra.research.philips.com/natlab/sysarch/index.html at home as well as during working hours. At both places I work with Windows (strongest dependency is the use of Visio). I maintain the site by means of Python scripts. Taking the above license literal I might use Qt at home for free, but not at work. Yes that is clear, but not stimulating to dive in :-( regards Gerrit -- -------------------------------------------------------------------- Gerrit Muller Philips Research Laboratories Eindhoven Building: WDC 2 - 007 Prof. Holstlaan 4 Phone: +31 40 27 45242 5656 AA Eindhoven Fax: +31 40 27 45033 The Netherlands mailto:gerrit.muller at philips.com http://www.extra.research.philips.com/natlab/sysarch/index.html From jdhunter at ace.bsd.uchicago.edu Fri Nov 22 00:35:53 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 21 Nov 2002 23:35:53 -0600 Subject: Boost.Python sans Jam In-Reply-To: (Mark's message of "Fri, 22 Nov 2002 04:31:27 GMT") References: Message-ID: >>>>> "Mark" == Mark writes: Mark> Hello all, I'd like to use the product of Boost.Python (ie Mark> libboost_python and the necessary header files) without Mark> resorting to using jam as my comilation system (why? I want Mark> to learn one thing at a time ... right now I'll focus on Mark> Boost.Python ... when I want to learn jam, I'll look at it). Not the answer to you question -- but, I had the same philosophy when I first encountered bjam. I wanted to go it along with the tools I was familiar with. When I was unsuccessful, I went back to bjam and after about 15 minutes of RTFM-ing, I was successful. So I suggest you do it the way the library developers suggest. it worked better for me that way. As a starting point, here is the beginning of my compile notes of a (dated) python version specific build of boost::python with bjam: # Build the libs: cd ~/c/lib/boost_1_28_0 bjam -sPYTHON_VERSION=2.1 clean bjam -sPYTHON_VERSION=2.1 -d2 >& bjam.out cd libs/python/build bjam -sPYTHON_VERSION=2.1 # the rest is a platform specific description of how I installed the # libs for my platform (red hat linux) Sorry for the OT post :-). JDH From jepler at unpythonic.net Tue Nov 12 19:10:58 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 12 Nov 2002 18:10:58 -0600 Subject: Q: Name of a arbitary variable as a string? In-Reply-To: <3DD15E18.F5A8905B@ilt.fhg.de> References: <3DD15E18.F5A8905B@ilt.fhg.de> Message-ID: <20021112181057.A2000@unpythonic.net> On Tue, Nov 12, 2002 at 09:01:28PM +0100, username wrote: > I am searching for a function (call it: var_name) that do something like > this: > > >>> V="Hello World" > >>> var_name(V) > 'V' Here's a very nasty little piece of work which makes a few assumptions about the kindly nature of the caller and the structure of Python bytecodes. I recommed that you not use this code. You should probably find another way to do whatever it is you're trying to do. For instance, you could replace var_name(V) with "V" BTW, this code is broken at least for LOAD_DEREF and probably for LOAD_NAME. # IF YOU USE THIS CODE YOU WILL DIE def var_name(arg): f = sys._getframe(1) c = f.f_code.co_code ip = f.f_lasti i = ord(c[ip-3]) o = ord(c[ip-2]) + 256*ord(c[ip-1]) r = [] while dis.opname[i] == 'LOAD_ATTR': r.append(f.f_code.co_names[o]) ip=ip-3 i = ord(c[ip-3]) o = ord(c[ip-2]) + 256*ord(c[ip-1]) if dis.opname[i] == 'LOAD_FAST': r.append(f.f_code.co_varnames[o]) r.append(f.f_code.co_names[o]) r.reverse() print r return ".".join(r) From tim.one at comcast.net Wed Nov 6 22:19:02 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 06 Nov 2002 22:19:02 -0500 Subject: power TypeErrors In-Reply-To: <7h3adkn0yyl.fsf@pc150.maths.bris.ac.uk> Message-ID: [Michael Hudson] > ... > It's a bit odd that there's no cmath.pow(). But not surprising: a good-quality pow() is difficult to code even for reals, and numerical analysts had nothing to do with Python's cmath. If "most" vendors bother to implement C99 (I'm afraid that's not a certainty), Python can borrow its cpow() to plug this hole. Short of that, exp(y*log(x)) makes users responsible for their own numeric screwups. From sross at connectmail.carleton.ca Mon Nov 4 13:44:42 2002 From: sross at connectmail.carleton.ca (Sean Ross) Date: 4 Nov 2002 18:44:42 GMT Subject: Tkinter problem References: <369fc45d.0211031751.7ad1276@posting.google.com> Message-ID: Hi. If you go to http://www.manning.com/getpage.html?project=grayson&filename=Source.html you can download the example code from John E. Grayson's "Python and Tkinter Programming". In the examples for chapter 8, you will find code for making "about..." boxes using Pmw or "Python MegaWidgets" (http://pmw.sourceforge.net/). Pmw provides a ready-made AboutDialog class, so, if you're not required to roll your own, you can just use theirs. Hope this was helpful, Sean Ross From jepler at unpythonic.net Sat Nov 23 21:32:32 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 23 Nov 2002 20:32:32 -0600 Subject: Repost: Tkinter Checkbox Question In-Reply-To: References: Message-ID: <20021123203221.A1515@unpythonic.net> On Sat, Nov 23, 2002 at 06:18:27PM -0800, Josiah wrote: > What am I doing wrong in this sample? When I press the "status" > button, the printout shows that "self.var.get()" returns a "0" weather > the box is checked or not! Is this a Bug in Tkinter? Help please. > Thanks! > josiah It looks fine to me. If you have created more than one Tk(), then the IntVar may be in a different interpreter than the checkbutton (for instance, by adding the following two lines above 'root = Tk()' not_root = Tk() not_root.wm_withdraw() I can get the behavior your describe) You can make sure your variable is in the right interpreter by using < self.var = IntVar(master) just as you do for widgets. That change makes your script work whether or not 'non_root' was created at startup. Jeff From wlfraed at ix.netcom.com Thu Nov 14 22:45:52 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Thu, 14 Nov 2002 19:45:52 -0800 Subject: lists changed to tuples unexpectedly! References: Message-ID: Chris Fonnesbeck fed this fish to the penguins on Thursday 14 November 2002 06:44 am: > > Why did I make lists, and get tuples? > Those aren't tuples... Tuples display with (...). They /are/, however, a list containing lists of lists... What you *initially* made (actions) is a LIST of TUPLES: >>> actions = [(((i,0),),((j,j),)) for i in (0,1,2,3,4) for j in ... (0.0,0.1,0.2)] >>> import pprint >>> pprint.pprint(actions) [(((0, 0),), ((0.0, 0.0),)), (((0, 0),), ((0.10000000000000001, 0.10000000000000001),)), (((0, 0),), ((0.20000000000000001, 0.20000000000000001),)), (((1, 0),), ((0.0, 0.0),)), (((1, 0),), ((0.10000000000000001, 0.10000000000000001),)), (((1, 0),), ((0.20000000000000001, 0.20000000000000001),)), (((2, 0),), ((0.0, 0.0),)), (((2, 0),), ((0.10000000000000001, 0.10000000000000001),)), (((2, 0),), ((0.20000000000000001, 0.20000000000000001),)), (((3, 0),), ((0.0, 0.0),)), (((3, 0),), ((0.10000000000000001, 0.10000000000000001),)), (((3, 0),), ((0.20000000000000001, 0.20000000000000001),)), (((4, 0),), ((0.0, 0.0),)), (((4, 0),), ((0.10000000000000001, 0.10000000000000001),)), (((4, 0),), ((0.20000000000000001, 0.20000000000000001),))] >>> a = actions[0] >>> a (((0, 0),), ((0.0, 0.0),)) We'd have to see the full definition of your QOptimizer class, AND the invocation, to make any guess as to what happened inside it. -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From ktilton at nyc.rr.com Wed Nov 20 14:34:03 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Wed, 20 Nov 2002 19:34:03 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <3DDBB8BD.6020806@web.de> Message-ID: <3DDBE406.6030803@nyc.rr.com> Courageous wrote: >>Common Lisp is not designed for newbies but for experts. > > > This little oft-repeated meme is exactly what has consigned > Common Lisp to the dust bin of programming history. > It's not in the dust bin, there are four (or more?) commercial vendors and several free. It's just not widely used. But when I look at why Java and Perl and Python and Ruby are so well-received, I get the feeling evolution is headed for where CL already is. Time will tell. -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From brian at sweetapp.com Mon Nov 18 16:02:54 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 18 Nov 2002 13:02:54 -0800 Subject: redirecting cgi error to browser In-Reply-To: Message-ID: <003401c28f45$dd2ec360$21795418@dell1700> Barghest wrote: > import Pyana > def formatRef(): > return "Hello %s " % 'foo' > ... > Pyana.installGlobalExtension( 'pyNS', formatRef, 'formatRef' ) > data = Pyana.transform2String( source = readData( "fichier.xml" ), style = > readData( "test3.xsl" ) ) > => Hello <b> foo </b> > Just a simple question. > Why all my tags returned from my functions are always converted to > entities ?? How can I obtain "Hello foo " ? Sorry for the delayed reply but I just found this post today. The problem is that you are returning a string from your extension function. So the XSLT processor is going its job and converting into a safe XML string. What you probably want to return is a result tree fragment. Unfortunately, Pyana does not currently support extension functions returning result tree fragments. In the example that you gave, you could modify your XSL and extension function to get the results that you expect: test3.xsl --------- ... Hello ... test.py ------- ... def formatRef(): return 'foo' ... Of course, you may not be able to do what you want to do in a non-trivial example. If this is really hurting your development, let me know and I might be able to help you devise a work-around. Cheers, Brian From fellowsd at cs.man.ac.uk Fri Nov 15 06:52:11 2002 From: fellowsd at cs.man.ac.uk (Donal K. Fellows) Date: 15 Nov 2002 03:52:11 -0800 Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DCFCC3E.204D9B45@man.ac.uk> <3DCFEF06.9E74A794@earthlink.net> <3DD12795.23E2F02F@man.ac.uk> <3DD1770F.4FEAB063@earthlink.net> <3DD27F67.AA0247FA@man.ac.uk> <3DD2A0A2.CB933D95@earthlink.net> Message-ID: <74aa6858.0211150352.8418b96@posting.google.com> Benjamin Goldberg wrote: > Donal K. Fellows wrote: >> OK, what sequence of bytecodes would instantiate and invoke those >> layers? The expositions I've found online so far have been rather too >> dry for me to actually see how such a thing could be done. > > Umm, err, I don't know... I've merely looked (briefly) at the docs and > source of Parrot, and never programmed for it. But I'm sure > that it *can* be done. I'm *fairly* sure it can be done. I was just trying to evaluate whether it could be done with a reasonably small input of effort or whether it was going to be a really big porting job. (Everything I've seen so far makes me think that it will be enough effort that I'll leave it to someone with a commercial interest in having things work together.) >> Donal (fed up of hand-waving, particularly in his day job. Must write >> code...) > > Sorry about the handwaving, but it's the best I can offer. If it can't > be done now, someone will add it in the future. It's just that given the size of the semantic disconnect between Tcl and Parrot, it's pretty clear to me that there's going to be great amounts of C code (or some other language, I suppose) involved in building a bridge between the two. Hence my intense interest in seeing how this might be done, and my irritation at someone saying "oh, it must be possible". And I was feeling frustrated at cow-orkers that day too... ;^) Donal (posting through Google due to sucky local news-server.) -- [This space unintentionally left blank.] From anton at vredegoor.doge.nl Mon Nov 11 07:46:04 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Mon, 11 Nov 2002 13:46:04 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: On Mon, 11 Nov 2002 11:15:22 +0100, "Johannes Gr?dem" wrote: >* anton at vredegoor.doge.nl (Anton Vredegoor): > >> Maybe it's better to take a shortcut and to directly say what I >> *think* I was implying: The perceived difficulty of the parens (and >> it doesn't matter at all if this difficulty is real or imagined) >> increased Lisp's popularity in the early days because at that time >> it was thought that a programming language worth its wits had to be >> difficult to read. > >So you're saying that people use Lisp because they're elitists? I >fail to see how that is not trolling. There's a subtle difference, since this thread is about popularity one has to accommodate for the fact that popularity can result from factors that have little to do with factors internal to that which is popular. For example I studied social psychology, and because of the intellectual status that the exact sciences had (and maybe still have) at that time a great part of my studies was taken up by studying methodology, statistics and, yes informatics (also Lisp). Later on I have had extensive experience with informaticians and mathematicians and I have more or less reached a conclusion that although these disciplines have some value, the usability of isolated sciences is severely limited. Still some sciences are popular, highly rated, have a lot of authority in governmental decision making, get the largest funding, while there is really nothing to gain from single discipline approaches. There has been some effort to create multidisciplinar approaches in my country but as soon as they were created they fell apart between the usual dividing lines of the existing established faculties. So this is my take: Its a crazy ball game, some win some loose, but none of them have any impact on the real world unless there's some unified approach which doesn't preclude *any* opinion from being investigated. > >> I would like to add at this stage that "ad hominem" attacks like >> suggesting that I have been smoking - peculiar things maybe? - are >> also considered to be bad form. > >Quite, but what is the appropriate response for an obvious troll? There's no need for type checking! If someone tries to initiate the troll protocol: don't comply. Even a troll might support useful protocols and what's to be gained by initiating the troll protocol oneself anyway? Anton. From dnew at san.rr.com Mon Nov 11 15:39:50 2002 From: dnew at san.rr.com (Darren New) Date: Mon, 11 Nov 2002 20:39:50 GMT Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DCFCC3E.204D9B45@man.ac.uk> <3DCFEF06.9E74A794@earthlink.net> <3DCFF6FB.40426F8E@san.rr.com> <3DD00595.B2905D8E@earthlink.net> <3DD00B63.EC604897@san.rr.com> <3DD0113D.79EC23F6@earthlink.net> Message-ID: <3DD01596.A3420862@san.rr.com> > So? Pass these in as arguments. There's no need to recompile a > procedure for each and every different set of arguments that might be > passed to it. That would defeat the point of having procedures in the > first place. A binding isn't a procedure. Indeed, I'm pretty sure that [eval] doesn't cache bytecode in bindings because it's more inefficient than regenerating the bytecodes each time. It's good style to invoke a procedure, but hardly necessary. And indeed, putting something like "break" or "continue" inside a procedure called by a binding doesn't have the same effect as putting it in the binding. From max at alcyone.com Thu Nov 7 13:43:06 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 07 Nov 2002 10:43:06 -0800 Subject: power TypeErrors References: <7h3ptthzlf0.fsf@pc150.maths.bris.ac.uk> Message-ID: <3DCAB43A.6EFA9A25@alcyone.com> Fernando P?rez wrote: > Well, other than the fact that not having them is pretty much a slap > in the > face of everybody who does scientific computing, I guess it doesn't > matter. > The fact that C lacks native complex numbers is one of the reasons > many hard > core numerical computing people still frown upon it (not the only > one). Note that in the interests of nitpickery, C99 does have a builtin complex type. > The most trivial numerical problem with _real_ numbers can generate > complex > numbers in its solution (think any random polynomial root finding > problem, or > just about any eigenvalue problem you can write). Therefore we *NEEED* > good > complex number support in any language that is going to be taken > seriously > for scientific computing. I'm not sure what your background is, but I > can > tell you that python is gaining _very_ stronng support in scientific > computing. That's probably the best rationalization I've seen for including complex number support in the language itself. Implementing a complex number class oneself is pretty straightforward, and the vast majority of non-scientific users will never have a need for it, but when you want to do scientific work and the builtins don't play nice with complex numbers, it's a huge inconvenience. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ War is like love, it always finds a way. \__/ Bertolt Brecht Erik Max Francis' bookmarks / http://www.alcyone.com/max/links/ A highly categorized list of Web links. From leazen at uol.com.ar Fri Nov 1 10:25:40 2002 From: leazen at uol.com.ar (Leazen) Date: Fri, 01 Nov 2002 12:25:40 -0300 Subject: Wrapping a .dll under windows with SWIG References: <8beb91f5.0210312226.7eb08c08@posting.google.com> Message-ID: <3DC29CF4.2060606@uol.com.ar> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 You could use calldll to make the function calls. You can get it at http://www.nightmare.com/~rushing/dynwin/index.html. Leazen Ben C wrote: > Hi there, > > I want to wrap a .dll under windows and have access to it's functions > etc. The problem is that all I have is the .dll and header file ... no > source ... and as all the examples that I have seen for swig seem to > need the original source ... I was wondering if it is still possible > to get access to the functions stored in the dll? Would anyone be able > to point me in the write direction, docs examples etc if this can be > done at all? > > thanks in advance > > Ben C -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.0 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQE9wpzmhcKLjUu3XMkRAuz0AJ9TSRc7saEs+AYf2XwZXE4mGESeSQCgsR/R o3UV9hWZkfjvEcEKMUvyFjM= =50Zh -----END PGP SIGNATURE----- From jepler at unpythonic.net Tue Nov 5 14:59:45 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 5 Nov 2002 13:59:45 -0600 Subject: sre_constants.error: bogus escape In-Reply-To: <3DC81B1F.C367AB25@crary.com> References: <3DC81B1F.C367AB25@crary.com> Message-ID: <20021105195926.GC21221@unpythonic.net> On Tue, Nov 05, 2002 at 01:25:19PM -0600, Bradley D. Larson wrote: > What is the best method of changing a \ character to something else > > I'm trying to use re.... > > pat = re.compile('\\'); ts = pat.sub(':',ts) > > which produces.... > > File "C:\PYTHON21\Lib\sre.py", line 90, in compile > return _compile(pattern, flags) > File "C:\PYTHON21\Lib\sre.py", line 136, in _compile > raise error, v # invalid expression > sre_constants.error: bogus escape > > It is bogus. If you want to match a literal backslash, the regular expression '\\\\', also writable as r'\\' is what you're looking for. '\\' (a 1-character string containing a single backslash) is not a valid regular expression, much as '%' (a 1-character string containing a single percent sign) is not a valid format string (i.e., don't try to do "%" % (...)) Jeff From eugene1977 at hotmail.com Tue Nov 26 01:37:56 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Tue, 26 Nov 2002 06:37:56 +0000 Subject: variable name and type confusion... Message-ID: after table_name = Graph(table), graphs.append(table_name) appends string type not Graph type if i do exec "table_name = Graph(table)" graphs.append(table_name) appends Graph type.. is this expected behavior? i'm using python 2.2.1 table_list = ['abc', 'def'] tables['abc'] = Table(a) tables['def'] = Table(b) graphs = [] def tests(Graph): for table_name in table_list: table = tables[table_name] table_name = Graph(table) <--------------here graphs.append(table_name) From gmduncan at netspace.net.au Thu Nov 21 03:34:19 2002 From: gmduncan at netspace.net.au (Gary Duncan) Date: Thu, 21 Nov 2002 19:34:19 +1100 Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> Message-ID: <3DDC9A8B.8050801@netspace.net.au> David Mertz, Ph.D. wrote: > Carl Banks wrote previously: > |Try two or three months [to learn Common Lisp], at worst. A competent > |and experienced programmer can probably learn a language like Common > |Lisp in a couple weeks in their spare time. > > There's a strange phenomenon with programmers, especially (but not > exclusively) ones who are attached to one or a couple favorite > langauges. They claim--rather persistently--that someone/anyone can > learn their language in an absurdly short time period. > > Sometimes it is "a few hours to pick up the basics of Python;" other > times "a couple weeks to master CL;" or occasionally "a few months to > become an expert in X." All these claims are quite literally > unbelievable... and yet they come up over and over from every advocate. > > The funny thing about all the claims is that they are enthymatic > contrasts with all "those other languages." The writers apparently > expect readers to have a realistic sense about how long it takes to > learn most programming languages (months or years), so the silly claim > about is then drawn as such a strong contrast with > that. But as soon as anyone explicitly STATES the claim that > actually takes -many- months to learn, the > optimistic "days" for appears as an absurdity rather > than a language advantage. > > It's a funny structure... sort of like what ordinary language > philosophers (Grice or Dummett, I think) call "essentially accidental" > events. But this is "essentially implicit." > > Yours, David... > > P.S. I'm a pretty smart guy, btw. From kindergarten through doctorate, > I always learned things faster than just about everyone around me. I > remember more than almost anyone I know. Everywhere I've worked as a > programmer, I've been pretty much the best one at the site. Hmm, David - if I can interject a joke, at your expense :- "I'm not conceited although I have reason to be" :) [ Btw, I thought that only insecure Germans appended Ph D to their name :) Well I'm a modest person ("have a lot to be modest about" :) but after 15 yrs + of real-time C-programming (from about the time, mid-70s that Timbot wrestled with Crays and f/p) I thought I knew it well. Then I picked up some specialized ref books (Jaeschke: "Solutions in C", "Portability and the C-language" ) and realised how superficial my understanding of the language and its surrounding environment was. Some previous work colleagues have said (enviously/spitefully) about my C-knowledge:- "You know fuck-NOTHING", to which my reply was :- "Yeah; but I know fuck-ALL!". - Gary (who just fondled a real 10ft Python at the Bairnsdale Vic Australia show; - forgot to get its Version number :) P.S. Browsing c.l.p is like spending quiet time in the British Museum. So civilized. (Most Trans-Atlantic readers will not comprehend ...) > > And you know what: I CANNOT learn CL in a couple weeks of my spare > time. I've spent more than that, and understand little about it, > really. When I first learned Python, it took me much longer than a few > hours to pick up even the barest essentials. And when I have programmed > with languages fulltime for several years, I continued to learn new > things about them after those years. > > -- > _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/ > _/_/ ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~ _/_/ > _/_/ The opinions expressed here must be those of my employer... _/_/ > _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/ > > From a.schmolck at gmx.net Sat Nov 23 12:43:23 2002 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 23 Nov 2002 17:43:23 +0000 Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <2259b0e2.0211210838.7647301a@posting.google.com> <093kra.3n3.ln@beastie.ix.netcom.com> Message-ID: "Donn Cave" writes: > If there's one thing that makes Python a bad choice for me, that's it. > During development, static type systems save me a lot of trouble. Have you tried pychecker? I'm not sure what sort of troubles static type systems save you from, but at least for the relatively trivial but common cases like typos, pychecker seems to do quite a good job. On the whole, I think compulsory static typing is a bad idea. It invariably seems to lead to spurious warnings and unnecessary code (partly because typecheckers are usually quite daft and complain about correct code and partly because it causes less flexible code) and longer development times. It would seem to me that most or all of the benfits of static typing can be obtained from tools. alex From gerhard.haering at opus-gmbh.net Tue Nov 12 06:09:23 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 12 Nov 2002 11:09:23 GMT Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> <87y98f566d.fsf@zamazal.org> Message-ID: In article , DaveP wrote: > Gerhard H?ring wrote in > >> Of course I agree that the standard Docbook DTD wouldn't be sufficient >> and would need to be extended. >> > > Could you be more specific on this please? > Docbook's purpose is to document software, so if you've > found a shortfall, I'm sure the docbook group would be interested in > filling any such gaps? As far as I understand, it is quite normal to extend Docbook to meet specific needs. It's specifically designed to be easily extensible. > What sort of extensions? See MvL's message in this thread: http://groups.google.de/groups?selm=m3bs5fbi7l.fsf%40mira.informatik.hu-berlin.de or, shorter URL: http://tinyurl.com/2mhm many of these aren't supported by the Docbook DTD, yet. \seerfc, for example. -- Gerhard H?ring OPUS GmbH M?nchen Tel.: +49 89 - 889 49 7 - 32 http://www.opus-gmbh.net/ From theller at python.net Fri Nov 15 09:22:25 2002 From: theller at python.net (Thomas Heller) Date: 15 Nov 2002 15:22:25 +0100 Subject: A really bad idea. References: <7h3u1ijvv9q.fsf@pc150.maths.bris.ac.uk> Message-ID: roy at panix.com (Roy Smith) writes: > Thomas Heller wrote: > > Ok, you need a core library of system calls, but then you go. > > Depends on what you're trying to do. If you're writing an application > to run on top of an operating system, then yes, you need a library of > system calls. But, even at that, most system call libraries are a > very thin layer which do little more than put arguments on the stack > in the right format and execute some flavor of trap instruction. > > But, there are plenty of things you might want to do with C which do > not involve any sort of system call library at all. You might be > writing an embedded system which runs directly on top of the hardware. > Or, you might be writing an operating system itself, or a device > driver. It's a pity that most people don't ever get to do either of > those. You miss out on some good experiences by never getting to > touch the hardware directly. Hehe. Absolutely correct! If the hardware supports memory-mapped I/O, nothing is needed except C itself. Thomas From josiah7 at hotmail.com Tue Nov 19 19:29:20 2002 From: josiah7 at hotmail.com (Josiah) Date: 19 Nov 2002 16:29:20 -0800 Subject: Updating A Tkinter Window every 100 ms? Message-ID: I would like to create the TK dialog with a "Update" function that will run every 100 ms. A self calling function. Inside this fuction, I want to call "lift()" to keep the window on top of all the others, and I want to call another function that will update other things. Could some look at my sample code and please give me some feedback? Is there a better way? Why does the "lift()" function not work with "self.master.lift()"? Thanks for any help with this. Josiah ############################################################## from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.grid() def Do_Stuff(self): pass def Update(self): self.Do_Stuff() root.lift() root.after(100, self.Update) root = Tk() app = App(root) app.Update() root.mainloop() ############################################################### From davecook at nowhere.net Thu Nov 14 00:14:21 2002 From: davecook at nowhere.net (David M. Cook) Date: Thu, 14 Nov 2002 05:14:21 GMT Subject: python gui rant References: <3dd217e2$0$231$4d4ebb8e@news.nl.uu.net> Message-ID: In article <3dd217e2$0$231$4d4ebb8e at news.nl.uu.net>, Gumuz wrote: > i am using wxPython at the moment as my python gui. Coming from a nice IDE > like Delphi it's really frustrating to get a nice layout together. I tried > some tools. The one i liked most, because of it's simplicity was wxGlade, Thanks! I didn't know about wxGlade. That's very cool that someone is working on this. I think XML is the way to go, and I don't like code generators or integrated environments. I'm currently using glade + pygtk, but it would be nice to have access to something more crossplatform. Dave Cook From grante at visi.com Tue Nov 26 16:01:29 2002 From: grante at visi.com (Grant Edwards) Date: 26 Nov 2002 21:01:29 GMT Subject: Why not a, b += i, j? (augmented assignment via tuple unpacking) References: Message-ID: <3de3e129$0$4437$a1866201@newsreader.visi.com> In article , Steven Rumbalski wrote: > In python I can write: > > a, b = i, j > > but the following is not legal: > > a, b += i, j > > Is there a reason that allowing this would be bad? If it were allowed, what do you propose it would do? > Why does Python forbid this? First tell us what you think it would do were it legal. :) -- Grant Edwards grante Yow! Now, I think it would at be GOOD to buy FIVE or SIX visi.com STUDEBAKERS and CRUISE for ARTIFICIAL FLAVORING!! From kbass1 at nc.rr.com Tue Nov 5 17:53:58 2002 From: kbass1 at nc.rr.com (Kevin Bass) Date: Tue, 05 Nov 2002 22:53:58 GMT Subject: Newbie Question: Sockets Message-ID: I am attempting to process data within a socket. The socket establishes communications on both servers but the data does not come out the way that I want it. How do I store the retrieved data into an array or another value? If there are multiple values, how can I store this information? Thanks! client.py ======= import sys from socket import * HOST = '127.0.0.1' PORT = 8080 var_name = 'Mousey Moo' sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect((HOST, PORT)) for line in message: sockobj.send(var_name) data = sockobj.recv(1024) print 'Client Received', 'data' sockobj.close() Server.py ======== from socket import * HOST ='127.0.0.1' PORT = 8080 date="" sockobj = socket(AF_INET, SOCK_STREAM) sockobj.bind((HOST, PORT)) sockobj.listen(5) while 1: conn, addr = sockobj.accept() print 'Server Connected by', addr data = conn.recv(1024) print 'The received data is ', data print 'Closing conn' conn.close() print 'Shutting down' -------------- next part -------------- An HTML attachment was scrubbed... URL: From johnroth at ameritech.net Mon Nov 25 10:45:55 2002 From: johnroth at ameritech.net (John Roth) Date: Mon, 25 Nov 2002 10:45:55 -0500 Subject: Problem with paths on Win 9x Message-ID: I'm trying to invoke a package, and I'm not getting very far. Nothing I do works. Here's the printout from the command line that shows the problem: C:\Python22\MyStuff\AstroPy3>civact C:\Python22\MyStuff\AstroPy3>python fit\FileRunner.py CivilDateAT.htm CivATOut.htm C:\PYTHON22\PYTHON.EXE: can't open file 'fit\FileRunner.py' C:\Python22\MyStuff\AstroPy3>python Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> print sys.path ['', 'C:\\PYTHON22\\lib\\site-packages\\win32', 'C:\\PYTHON22\\lib\\site-package s\\win32\\lib', 'C:\\PYTHON22\\lib\\site-packages', 'C:\\PYTHON22\\lib\\site-pac kages\\Pythonwin', 'C:\\PYTHON22\\DLLs', 'C:\\PYTHON22\\lib', 'C:\\PYTHON22\\lib \\lib-tk', 'C:\\PYTHON22', 'C:\\PYTHON22\\MyStuff\\AstroPy3', 'C:\\PYTHON22\\MyS tuff\\TestTools', 'C:\\PYTHON22\\Lib\\site-packages\\fit', 'C:\\PYTHON22\\AddedS tuff\\pycover'] >>> The path to FileRunner.py is: c:\Python22\Lib\site-packages\fit\fit\FileRunner.py The OS is win98se. The files referenced by the parameters are in the current directory, but it isn't getting that far. John Roth From dvass at felis.uni-freiburg.de Tue Nov 5 07:52:48 2002 From: dvass at felis.uni-freiburg.de (Joerg Woelke) Date: Tue, 05 Nov 2002 13:52:48 +0100 Subject: More about simple question References: Message-ID: <3DC7BF20.95768C4@felis.uni-freiburg.de> Bengt Richter wrote: > > On Mon, 4 Nov 2002 21:11:52 -0800 (PST), xinghua shi wrote: > > >--0-1493159574-1036473112=:21756 > >Content-Type: text/plain; charset=us-ascii > > > > > >> > >> import sys,os,string > >> > >> pid = os.getpid() > >> > >> filename = ".ld.mon." + str(pid) Maybe you are interested in os.tempnam, os.tmpfile or os.tmpnam? [ snip ] > Regards, > Bengt Richter HTH, J"o! -- sigfault From bokr at oz.net Tue Nov 5 21:57:37 2002 From: bokr at oz.net (Bengt Richter) Date: 6 Nov 2002 02:57:37 GMT Subject: power TypeErrors References: <200211052054.PAA05238@nealtech.net> <200211060810.28875.bhards@bigpond.net.au> Message-ID: On Tue, 5 Nov 2002 16:39:44 -0500, anton wilson wrote: [...] > >It actually causes an error from a source file, only if i use a variable >argument to **. > >so this fails: > >x = -1 >x ** 0.5 > >but > >-1 ** -0.5 doesn't. operator precedence makes that -(1 ** -0.5) whereas using x is like (-1) ** 0.5 Regards, Bengt Richter From martin at v.loewis.de Thu Nov 7 10:12:35 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 07 Nov 2002 16:12:35 +0100 Subject: where could we find PMW package ? References: Message-ID: black writes: > I'm practice Tkinter these days and my book told me PMW provided > many nicely GUI components, I checked python.org but find nothing, > where is it ??? or it is not free ??? Anwsering the question in the subject: Use Google. Regards, Martin From kemu at sdf-eu.org Wed Nov 27 06:07:55 2002 From: kemu at sdf-eu.org (Jonas Geiregat) Date: Wed, 27 Nov 2002 12:07:55 +0100 Subject: what does is ? Message-ID: <3de4a6dd$0$86531$ba620e4c@news.skynet.be> I saw something import string string._StringType is str what does this specially that IS or in 2.2.2 string._StringTypes is str From brian at sweetapp.com Wed Nov 20 18:12:19 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 20 Nov 2002 15:12:19 -0800 Subject: Python as first language (Re: static variables?) In-Reply-To: Message-ID: <00c201c290ea$466dc060$21795418@dell1700> John Roth wrote: > > I think that the conceptual problem that people have with > > assignment being a binding operation is that they are used > > to names labeling some sort of memory mailbox. > > If you take the word "memory" out of there, that does describe > Python. I think this is a false distinction. No it doesn't. In C or Java, when you write: int a = 5; you are, conceptually, saying: stick a 5 in the "a" mailbox. In Python, when you write: a = 5 you are, conceptually, saying: 5 is in a mailbox somewhere, make "a" know the address of that mailbox. I wouldn't use the mailbox analogy with Python though. Cheers, Brian From karl at elemtech.com Wed Nov 13 18:27:19 2002 From: karl at elemtech.com (Karl G. Merkley) Date: Wed, 13 Nov 2002 16:27:19 -0700 Subject: python, Qt and HOOPS 3D References: <3DD2A05D.5050007@elemtech.com> <3DD2B4C2.3060507@SPAMnwinternet.com> Message-ID: <3DD2DFD7.8040204@elemtech.com> HOOPS is a 3D graphics engine built on top of OpenGL. They provide a Qt widget that is derived from QWidget called HQWidget. In many ways this widget is analagous to QGL widget but with high level functions like orbit_camera(). See http://www.hoops3d.com/downloads/linux/linux.htm for the details including a free linux version. So, what I want to do is create a wrapper for this HQWidget so that I can create one in python. I've switched from swig to sip, but I'm still struggling with figuring it out. Any pointers would be appreciated! Karl Jim wrote: > Karl G. Merkley wrote: > >> I am looking for the python bindings for the HOOPS-Qt widget. >> Has anybody done this? Is anyone willing to share? If not >> does someone have any pointers on how to go about doing this? > > >> I've been playing around with swig but haven't had any luck making >> it work yet. > > > > I'm not familiar with HOOPS-Qt at all, so this is somewhat > speculative. There is a complete set of Python bindings > for PyQt (http://www.riverbankcomputing.co.uk) using > sip. If HOOPS-Qt depends on other Qt widgets, this would > probably be your best starting point, as you can import > the bindings for the rest of Qt and wouldn't have to > redo them. > > There isn't any complete documentation for doing bindings > with sip. I'm working on some stuff to make sip bindings > easier to do (along with docs hopefully), but it'll be > a while before I have anything to release (if ever). If > HOOPS-Qt isn't an extremely large set of files, you can > use PyQt or PyKDE as examples of how to do bindings with > sip manually. > > You can get help with sip and PyQt on the PyKDE mailing > list at: > > http://mats.gmd.de/mailman/listinfo/pykde > > If you're interested, email me directly and I'll try to give > you some more info. > > > Jim > From maxmcorp at worldonline.dk Fri Nov 29 02:52:12 2002 From: maxmcorp at worldonline.dk (Max M) Date: Fri, 29 Nov 2002 08:52:12 +0100 Subject: Sending group mails from Python Message-ID: <3%EF9.47641$HU.3271416@news010.worldonline.dk> I am writing a small web based groupware program, and is often in the situation where I want to send mails out to an add hoc created group of user. Ie. calendar notifications, information subscriptions etc. Sort of an "embedded" list server. Writing a program that sends out mail in Python is trivial, but my worries are that the server will be bogged down if there is problems with the mail server. Does anybody have a clue/pointer as to the best approach or most common pittfalls for this? I considdered using mailman, but think that it is a bit overkill. Especially if I want to make distribution of my app simple. regards Max M From dwelch91 at nospam.attbi.com Sat Nov 23 11:37:07 2002 From: dwelch91 at nospam.attbi.com (djw) Date: Sat, 23 Nov 2002 16:37:07 GMT Subject: reliable tcp server holding multiple connections References: Message-ID: <3DDFAEB4.1040506@nospam.attbi.com> Wojtek Walczak wrote: > Hi, > > I'm trying to write a skeleton of a TCP server able to hold multiple > connections. The code is here: > > It works nice, but I'm sure, there're dozens of small, hard to see > and to think about bugs, and I want you to help me in tracing them ;) > Why I'm doing this? Since it's hard to find such an example in > c.u.py archives. In howtos and documentation you'll find nothing > but some simple single server examples. I want to create a point of > reference to well-written TCP server (holding multiple connections), > but it's almost impossible without your participation :) > > ps. I know about SocketServer ;) > Do you know about Medusa? http://oedipus.sourceforge.net/medusa/ /d/ From robin at jessikat.fsnet.co.uk Sun Nov 17 05:56:39 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 17 Nov 2002 10:56:39 +0000 Subject: wrapping all class methods References: <7HAfWUAhuj19EwTr@jessikat.fsnet.co.uk> Message-ID: In article , Bengt Richter writes ...... >>..... no I hadn't used that, but then I don't want a trace I want to >>discover which tracebacks are being detected and trapped. > >I thought you might be able to do a silent trace and see the exceptions >before they're "trapped". (The hook doesn't do any output or force you to. >You choose what to do if/when you see something of interest). > this is probably a good way to go as it is non-invasive, but it's a new technology for me so I'd need to wrap my decreasing neurones around it before use. The wrapping approach applies itself to all classes and all method members, but in my example I see base class methods are also being wrapped which may or may not be desired. I suppose a global tracefunc could check at each 'call' whether the currently entered scope is wanted and then set a local trace. I wonder how fast this is compared to the wrapping approach. >E.g., this is what my tracewatch does being told to watch only calls >and returns from foo and bar, but incidentally reporting on exceptions: > > >>> from ut.tracewatch import TraceWatch as TW > >>> def foo(n): > ... if n>4: raise StopIteration # or whatever > ... bar(n+1) > ... > >>> def bar(n): > ... if n>3: foo(n+1) > ... try: > ... foo(n+1) > ... except StopIteration: > ... print 'Caught stopiter with n = %s' % n > ... > >>> tw=TW() > >>> tw.addwatch('foo','#f') > >>> tw.addwatch('bar','#f') > >>> tw.on() > >>> foo(2) > -------------------------------------------------------------------- > File: "" > Line [scope] C:all, R:eturn eX:cept S:tack N:ew M:od E:quiv U:nbound > ---- ------- ------------------------------------------------------- > 1 [foo]: C: foo(n=2) > 1 [bar]: C: bar(n=3) > 1 [foo]: C: foo(n=4) > 1 [bar]: C: bar(n=5) > 1 [foo]: C: foo(n=6) > 2 [foo]: X: StopIteration() > S: < bar:2 < foo:3 < bar:4 < foo:3 < ?:1 > 2 [bar]: X: StopIteration() > S: < foo:3 < bar:4 < foo:3 < ?:1 > 3 [foo]: X: StopIteration() > S: < bar:4 < foo:3 < ?:1 > 4 [bar]: X: StopIteration() > S: < foo:3 < ?:1 > Caught stopiter with n = 3 > 6 [bar]: R: bar(...) => None > 3 [foo]: R: foo(...) => None > >Whereas if we start off with foo at 3, bar won't set the trap, so we get >the full unwind and no returns (R:): > > >>> foo(3) > 1 [foo]: C: foo(n=3) > 1 [bar]: C: bar(n=4) > 1 [foo]: C: foo(n=5) > 2 [foo]: X: StopIteration() > S: < bar:2 < foo:3 < ?:1 > 2 [bar]: X: StopIteration() > S: < foo:3 < ?:1 > 3 [foo]: X: StopIteration() > S: < ?:1 > Traceback (most recent call last): > File "", line 1, in ? > File "", line 3, in foo > File "", line 2, in bar > File "", line 2, in foo > StopIteration > >Regards, >Bengt Richter -- Robin Becker From martin at v.loewis.de Fri Nov 29 18:12:29 2002 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 30 Nov 2002 00:12:29 +0100 Subject: Embedding Python and built-in types References: Message-ID: "Mickael Putters" writes: > Well, I was talking about the assignment operator, maybe it's not =. > Yeah well guess I'll have to modify the source, I thought maybe there would > be a way to do that already present in Python/C. Ah, that's not an operator: assignment is not an expression; it is a statement (but it is =). Controlling assignment is even more difficult. Assignments usually results in a dictionary operation. Intercepting all kinds of assignment won't be easy. If you are just looking for assignments to global variables, you might intercept the dictionary write operation. Using non-dictionary objects to keep global variables (so that you can intercept writes and reads) is a long-standing wish; it hasn't been granted because there is no efficient implementation for it that doesn't cause significant penalties if there is no interception. Regards, Martin From jepler at unpythonic.net Mon Nov 4 09:08:41 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 4 Nov 2002 08:08:41 -0600 Subject: Tkinter File Dialog Question In-Reply-To: <6747bc9d.0211040501.2e8000b5@posting.google.com> References: <6747bc9d.0211021953.4fd02462@posting.google.com> <6747bc9d.0211040501.2e8000b5@posting.google.com> Message-ID: <20021104140830.GA15752@unpythonic.net> When the tk file dialog window is closed, the window is not actually destroyed. If you don't mind being a little bit dirty, you can peek in and see what text was displayed in the 'file type' when it was dismissed. Of course, this doesn't work on Windows (where the dialog is native, not constructed from Tk widgets) and the paths may change from version to version. If 'w' is some widget, just run label = w.tk.call(".__tk_filedialog.f3.menu", "cget", "-text") m = re.search("\(\*\.([^,]*)", label) extension = m.group(1) print extension this worked for me. I think that my python is using tk8.3 for Tkinter. The OS is Linux. Jeff From maney at pobox.com Wed Nov 27 00:55:40 2002 From: maney at pobox.com (maney at pobox.com) Date: Wed, 27 Nov 2002 05:55:40 +0000 (UTC) Subject: if : References: Message-ID: Paul Wright <-$P-W$- at verence.demon.co.uk> wrote: > This is a regular question on comp.lang.python. Yes, it does seem to cause new-to-Python programmers a fair bit of confusion, doesn't it? Everything is going along so nicely, then you hit a block of code where you want to do this really very simple thing, and all of a sudden Python is being less helpful than C. Of course tou find this worthy of comment: it's so unusual! > There's another thread on this where I've posted some statistics from > a study which found that that feature caused errors roughly once in > every 3000 lines of code: > You might want to read Hatton's description of that again - the accurate one in chapter four, not the wooly one earlier on. He makes it quite clear that the statistics merely count the occurences of patterns he considers error-prone, not actual errors per se. Some of the occurences may be errors, but Hatton provides fuck-all in the way of hard data on that score. That lack was, I think, the main reason _Safer C_ has been stuck on a back shelf all these years... though the fact that I've been moving away from using C so much over those years must be a factor as well. :-) None of which should deter anyone who has to use C from reading _Safer C_, for there is a great deal of merit to it. From e_viola at libero.it Mon Nov 25 10:43:15 2002 From: e_viola at libero.it (bart) Date: Mon, 25 Nov 2002 15:43:15 GMT Subject: Strange's exception :-) Message-ID: <3DE2453B.9030002@libero.it> When I run urlopen function to connect, sometimes, happen that its performance is stopped in this way: Traceback (most recent call last): File "newspider.py", line 78, in ? File "MyParser.py", line 201, in connect File "MyParser.py", line 28, in urlopen File "/usr/local/lib/python2.2/urllib2.py", line 322, in open '_open', req) File "/usr/local/lib/python2.2/urllib2.py", line 301, in _call_chain result = func(*args) File "/usr/local/lib/python2.2/urllib2.py", line 790, in http_open return self.do_open(httplib.HTTP, req) File "/usr/local/lib/python2.2/urllib2.py", line 779, in do_open code, msg, hdrs = h.getreply() File "/usr/local/lib/python2.2/httplib.py", line 1009, in getreply response = self._conn.getresponse() File "/usr/local/lib/python2.2/httplib.py", line 760, in getresponse response.begin() File "/usr/local/lib/python2.2/httplib.py", line 269, in begin version, status, reason = self._read_status() File "/usr/local/lib/python2.2/httplib.py", line 231, in _read_status line = self.fp.readline() IOError: [Errno 104] Connection reset by peer What can I do to manage this exception? Thanks... - Ennio - From mike at skew.org Fri Nov 22 00:26:06 2002 From: mike at skew.org (Mike Brown) Date: Thu, 21 Nov 2002 22:26:06 -0700 Subject: urllib slow on FreeBSD 4.7? sockets too References: <3ddd8419_3@omega.dimensional.com> Message-ID: <3dddbfef_1@omega.dimensional.com> "Skip Montanaro" wrote: > What happens if you reach into the file wrapper and grab the raw socket? How do I do that? u.fp is as close as I seem to be able to get. u = urllib.urlopen('http://localhost/4MBfile') print u print print dir(u) print print u.fp print print dir(u.fp) u.close() ', mode 'rb' at 0x8191900>> ['__doc__', '__init__', '__module__', '__repr__', 'close', 'fileno', 'fp', 'geturl', 'headers', 'info', 'read', 'readline', 'readlines', 'url'] ', mode 'rb' at 0x8191900> ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__repr__', '__setattr__', '__str__', 'close', 'closed', 'fileno', 'flush', 'isatty', 'mode', 'name', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines'] > Again, what happens if you read from the socket instead of the file object > returned by makefile()? Maybe 2 KB/s improvement: read 501760 bytes in 0.041s (11923 KB/s) read 512000 bytes in 0.043s (11671 KB/s) read 522240 bytes in 0.045s (11214 KB/s) read 532480 bytes in 0.093s (5609 KB/s) read 542720 bytes in 0.046s (11633 KB/s) read 552960 bytes in 0.047s (11459 KB/s) read 563200 bytes in 0.048s (11392 KB/s) read 573440 bytes in 0.072s (7725 KB/s) read 583680 bytes in 0.090s (6304 KB/s) read 593920 bytes in 0.052s (11241 KB/s) read 604160 bytes in 0.054s (11022 KB/s) > Also, what happens if you break the read up in to a > loop, reading smaller chunks? No change. bytes: 4343332; time: 9.064s (467 KB/s) using u.read(1024) bytes: 4343332; time: 9.050s (468 KB/s) using u.read(2048) bytes: 4343332; time: 9.050s (468 KB/s) using u.read(4096) > Did you build Python with or without pymalloc? I installed it from the FreeBSD packages collection. If pymalloc is not normally built-in, then it's probably not in the package. > Can you try the opposite? I'd rather not obliterate my current installation, no. From see_reply_address at something.invalid Wed Nov 27 21:40:54 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 28 Nov 2002 15:40:54 +1300 Subject: Python Tutorial Was: Guido's regrets: filter and map References: <698f09f8.0211261046.582254a5@posting.google.com> <698f09f8.0211270155.207f81e@posting.google.com> Message-ID: <3DE58236.1020305@something.invalid> Jeremy Fincher wrote: > Reduce (which I so wish was called foldl, leaving the oppurtunity open > for a symmetric foldr) Well, you could always call it ecuder(). :-) -- Gerg Gniwe, Retupmoc Ecneics Tnemtraped, Ytisrevinu fo Yrubretnac, Hcruhctsirhc, Wen Dnalaez gerg~\zn.ca.yrubretnac.csoc.www\\:ptth From mfranklin1 at gatwick.westerngeco.slb.com Thu Nov 7 04:59:50 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 07 Nov 2002 09:59:50 +0000 Subject: Python and Tktable In-Reply-To: <20021106205856.7de663f9.tim_sleptsov@fromru.com> References: <20021106205856.7de663f9.tim_sleptsov@fromru.com> Message-ID: <1036663193.1161.24.camel@m-franklin> On Wed, 2002-11-06 at 17:58, Timofey Sleptsov wrote: > Hello All! > > I am try to use Tktable library with python, but without any result ;( > For example, i type it: > > Python 2.2 (#1, Mar 29 2002, 17:58:00) > [GCC 2.95.3 20010315 (release)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import Tkinter > >>> root = Tkinter.Tk() > >>> root.tk.eval('package require Tktable') > Traceback (most recent call last): > File "", line 1, in ? > TclError: couldn't load file "/usr/lib/Tktable2.7/Tktable.so.2.7": > /usr/lib/Tktable2.7/Tktable.so.2.7: undefined symbol: tclStubsPtr > >>> > And get error message. > class Table(Widget): """table widget.""" def __init__(self, master=None, cnf={}, **kw): ## hack to load a dynamic.so into tk..... try: master.tk.call('package', 'require', 'Tktable') except TclError: try: master.tk.call('load', '', 'Tktable') except TclError: pass Widget.__init__(self, master, 'table', cnf, kw) This is taken from the Tk Table/Tkinter module (still working on it!) I hope to finish it later this year! I found when google'ing a couple of TkTable.py modules perhaps you would be happy using them... http://tix.sourceforge.net/Tixapps/ Seems to be the most up to date.... Oh and looking at the Tktable sourceforge page it seems to be up to version 2.8 Martin From see_reply_address at something.invalid Wed Nov 27 23:52:45 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 28 Nov 2002 17:52:45 +1300 Subject: Why is Python popular, while Lisp and Scheme aren't? References: Message-ID: <3DE5A11D.5090207@something.invalid> Brian Quinlan wrote: > Holger wrote: > >>How does the introduction of 'yield' break old code? > > Because someone, somewhere was almost certainly using yield as an > identifier. Hey, I'm that person! I used yield as a method name in early versions of Plex. I'm not complaining -- I was quite happy to change it. Just offering evidence that this sort of breakage does actually happen, and isn't just a theoretical possibility. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From aleax at aleax.it Fri Nov 22 17:57:12 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 22 Nov 2002 22:57:12 GMT Subject: Proposal: min(None, x) and max(None, x) return x References: Message-ID: Chad Netzer wrote: ... > _xMax = [] > for -whatever-: > -big calculation leading to a value of x- > _xMax.append( x ) > _xMax = [max(xMax)] > xMax = _xMax[0] perhaps a slightly better expression of the same idea might be... _xMax = [] for -whatever-: -big calculation leading to a value of x- _xMax = [max([x]+_xMax)] xMax = _xMax[0] Alex From sholden at holdenweb.com Mon Nov 25 09:30:09 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 25 Nov 2002 09:30:09 -0500 Subject: Multi Recipients With smtplib? References: Message-ID: "John Abel" wrote in message news:mailman.1038231874.18339.python-list at python.org... > Hi, > > I am trying to send a mail, to multiple recipients, without much > success. A single mail address works fine, but when I add another, > using a comma to separate the addresses, the second address fails to > receive the mail. Any ideas? Here's the code I am using: > > mailMessage = "From: %s \r\nTo: %s\r\n" % (self.mailFrom, > self.mailTo) > mailMessage += "Subject: %s\r\n%s" % (mailSubject, mailBody) > try: > self.MailConn.sendmail( self.mailFrom, self.mailTo, mailMessage) > except (smtplib.SMTPRecipientsRefused, > smtplib.SMTPSenderRefused), ErrorMsg: > print "There Was A Problem Sending The Mail. Reason: %s" % > ErrorMsg > > Any help would be appreciated, as this is driving me mad! > Given that yout code is arranged to print an error message it's a pity you didn't give us the benefit of its output so we knew a little more about the erre that's occurring. The arguments to the .sendmail() method should be: a string containing the sender's address a list of strings containing an address for each recipient, and an RFC822-formatted mail message I am guessing that when you say "but when I add another, using a comma to separate the addresses, the second address fails to receive the mail" you are setting the self.mailTo attribute to be a comma-separated list ot recipients? Frankly I'm not sure how you are managing to get this mail formatted. What you really want for multiple recipients is something like the following: self.mailFrom = me at mydomain.com self.mailTo = ["him at hisdomain.com", "her at herdomain.com", "it at itsdomain.net"] ... mailMessage = "From: %s \r\nTo: %s\r\n" \ % (self.mailFrom, ", ".join(self.mailTo)) mailMessage += "Subject: %s\r\n%s" % (mailSubject, mailBody) try: self.MailConn.sendmail( self.mailFrom, self.mailTo, mailMessage) except (smtplib.SMTPRecipientsRefused, smtplib.SMTPSenderRefused), ErrorMsg: print "There Was A Problem Sending The Mail. Reason: %s" \ % ErrorMsg In other words, use a comma-separated list of recipients in the message body, but a list of email addresses as the second argument to .sendmail(). regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From maney at pobox.com Wed Nov 27 13:17:40 2002 From: maney at pobox.com (maney at pobox.com) Date: Wed, 27 Nov 2002 18:17:40 +0000 (UTC) Subject: if : References: Message-ID: Dave Brueck wrote: > IMO the desire for if-assignment in C is driven in part by a desire > to fit more on the screen; Python code is more vertically compact so > I don't miss that feature as much. On the contrary, the only time the lack of (explicit) assignment in expression has bothered me the issue was *horizontal* space. It also sounds as though you could be confusing a desire for concise expression with a much sillier objective - at least it seems so entirely silly to me that I can't really take it seriously. Of course it's much easier to defeat a silly, contrived argument. :-/ From jacek.generowicz at cern.ch Thu Nov 28 09:56:16 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 28 Nov 2002 15:56:16 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3de1f902$0$695$edfadb0f@dread12.news.tele.dk> <3de62746$0$71652$edfadb0f@dread11.news.tele.dk> Message-ID: "Anders J. Munch" writes: > "Jacek Generowicz" wrote: > > > > I still fail to see why you think colour highlighting is necessary, or > > even useful for this. Emacs highlights matching parentheses, brackets > > and braces for me. > > It should be noted that in a vanilla configuration Emacs only blinks > parens as they are typed. This does tend to be true for FSF Emacs ... for which the magic incantation is (show-paren-mode 1). On XEmacs it happens by default. > But thanks for mentioning this, you prompted me to go discover > mic-paren, which is sweet. Hmm ... not convinced about it. My initial reaction is that it flashes up too much stuff, and therefore seems a bit annoying ... but I'll work with it for a while and see if I get used to it. > >I would find it hard to believe that other editors > > do not have such capabilities. (If your editor cannot provide such a > > feature, well, it might be time to reconsider your choice of editor.) > > Sometimes my editor of choice is a printout with handwritten annotations. But then you will not be concerned with inserting the correct number of parentheses to close an expression which you are typing ... at which point indentation gives pretty much all the clues you need. (I sometimes use "]" as a superbracket, is such situations.) My biggest problem with reading lisp on hard copy is when a bit of code is split on two pages ... then I get lost _very_ easily, because I lose much of the indentation related information. From erno-news at erno.iki.fi Thu Nov 21 12:25:09 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 21 Nov 2002 19:25:09 +0200 Subject: Advice for using emacs python-mode References: Message-ID: In article , Andrew Koenig writes: | problem: It appears that if I change code in foo.py, and type C-c C-c, | that change is not necessarily reflected in the program's execution. | I am guessing that under some circumstances, what is happening is that | the code is not getting re-imported. the import statement only goes out and loads the code the first time it asked for a module, then it gets cached in sys.modules. you can manually reload a module with the reload builtin function, you might want to use that in your __main__ block. reloading gets hairy fast in more complicated setups (see eg ), but should work with no trouble for this case. -- erno From ronecker at noos.fr Mon Nov 25 13:56:33 2002 From: ronecker at noos.fr (Pascal Ronecker) Date: 25 Nov 2002 19:56:33 +0100 Subject: cannot import gtk In-Reply-To: <200211241734.38215.dreed@capital.edu> References: <200211241734.38215.dreed@capital.edu> Message-ID: <1038250593.848.6.camel@m37.net195-132-249.noos.fr> Thanks ! but i'm still stuck. For example : GtkText does not exist, neither does Text alone. What is more, i have other problems with "from gnome.ui import GnomeApp" and so on.Changing all the code seems a long way to me. (it is the "eroaster" cd burning tool, a nice all-in-one) Maybe the right solution is to "install the bindings" as you say, but i do not have the slightest idea as to what it means... So if you could explain a bit that last bit, ... thx !! Lenny On Sun, 2002-11-24 at 23:34, Dave Reed wrote: > On Sunday 24 November 2002 15:59, Lenny wrote: > > Hi, > > > > I've just installed a RH 8.0, and while trying to use python programs > from > > my previous linuxbox, i encounter the following problems with python : > > > > > from gtk import GtkVBox > > >ImportError: cannot import name GtkVBox > > > The GTK prefix is removed: > > try: > from gtk import VBox > > > > this is just an example. I have the same errors with many widgets, but > > also, with GDK, etc.etc... > > > > I tried with python (that is python1.5), python2 and python2.2 > > > Red Hat 8.0 doesn't include python 1.5 (just python 2.2.1). > > > > I really have gtk+- installed (/usr/include/gtk-1.2 AND gtk-2.0) > > with (for the example above) a nice gtkvbox.h > > > Red Hat 8.0 comes with the libraries for gtk 1.2, but only the python > bindings for gtk 2.0. If you want to use python with gtk 1.2 you'll > have to install those bindings yourself. > > > > I think python does not know where to look for modules or something > like > > that, but I'm new to this, and do not know what to do. > > Nope, see above. > > HTH, > Dave > From costanza at web.de Sat Nov 9 19:49:33 2002 From: costanza at web.de (Pascal Costanza) Date: Sun, 10 Nov 2002 01:49:33 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCD8571.6CACEA04@alcyone.com> Message-ID: Syver Enstad wrote: > On another note, I think the Smalltalk method call (keyword message send) > syntax is fabulously readable, why haven't anybody picked that up? > Code like this is marvelously more understandable than the usual > position based argument list that one uses in Lisp and C. > > Ex: > > aCircle paintOn: aCanvas at: aPoint > > Where aCircle, aCanvas and aPoint are variable names, and what is > happening is that one is calling the method paintOn: at: where aCircle > is self. The alternative: > > aCircle.paint(aCanvas, aPoint) > > is okay for this example but the smalltalk way lets you convey much > more. Python has a kind of middle ground with its keyword messages, > which is good but not quite as nice as Smalltalk. In Common Lisp, you can have: (paint circle :on canvas :at point) Given that you have defined paint as follows: (defun paint (&key on at) ...) You can also have default values. (defun paint (&key (on default-canvas) (at '(0 0))) ...) So you can have all of the following. (paint circle :on canvas) (paint circle :at '(5 5)) (paint circle) If you define circle to be a class, you can have the usual overriding of methods as follows: (defmethod paint ((object circle) &key (on default-canvas) (at '(5 5))) ...) (defmethod paint ((object rectangle) &key (on default-canvas) (at '(10 10)) ...) (paint (make-instance 'rectangle) :on my-canvas :at '(150 10)) ...which is to show that you can mix positional and keyword parameters. In the latter examples, circle and rectangle are classes defined as follows. (defclass circle (graphical-object) (radius)) (defclass rectangle (graphical-object) (width height)) ...where graphical-object is the common superclass, and radius, width and height are slots (instance variables). etc., etc. ;) Pascal -- Given any rule, however ?fundamental? or ?necessary? for science, there are always circumstances when it is advisable not only to ignore the rule, but to adopt its opposite. - Paul Feyerabend From hancock at anansispaceworks.com Thu Nov 7 22:46:44 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 7 Nov 2002 19:46:44 -0800 Subject: Newbie: needs help with ... In-Reply-To: <20021108032601.4438.75566.Mailman@mail.python.org> References: <20021108032601.4438.75566.Mailman@mail.python.org> Message-ID: On Thursday 07 November 2002 07:26 pm, python-list-request at python.org wrote: > I'm trying to print the contents of a list. > > Python displays "..." until I press enter. Why is it waiting for me to press enter ? > > >>>?for x in l2[:5] : print x > ... I'm not exactly sure whether: for x in l2[:5]: print x print x, x would be legal (it's certainly bad style), so maybe the interpreter ought to figure out that there won't be anything more in the loop. But what the "..." is about is the way the interactive interpreter decides when a loop is actually complete: >>> if x in l2[:5]: ... print x ... print "x = %d" % x ... That last "..." with no content tells the interpreter you're done so it can actually run the loop. (So you can't have any blank lines when you're pasting code into the interpreter to test it, and each loop must have a blank line as well as a dedent). This is a difference between the interactive and script modes of operation of python. You see the same thing with tcsh and bash, BTW (though the prompt symbols are different). Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From claird at lairds.com Tue Nov 5 08:36:51 2002 From: claird at lairds.com (Cameron Laird) Date: Tue, 05 Nov 2002 13:36:51 -0000 Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> Message-ID: In article , Frodo Morris <""> wrote: . . . >How cool would it be to just set up a computer with a listening parrotd >and DHCP client, plug it in to the Beowulf and have it automagically >recognised as a node and delegated tasks? >I have been thinking quite a bit about cross-platform Beowulfing >recently. My initial idea was to set up an rlogin or something on the >node machines, and have the Apple (that's what I call the conducting >machine: "Apple" because it sends Jobs away, does nothing for a while >then gets Jobs back :-) distribute the source code for the node service >and job processor, configure and build the code, then log out and use >the new node as normal. This would be faster (provided the building >didn't fall over) as Beowulfs go, but less secure and probably harder to >set up. . . . Work on such schemes is already underway. Security is a *hard* problem. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From david at no.westcontrol.spam.com Fri Nov 22 10:25:42 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Fri, 22 Nov 2002 16:25:42 +0100 Subject: Proposal: min(None, x) and max(None, x) return x References: Message-ID: "Andrew Koenig" wrote in message news:yu99bs4hlkp5.fsf at europa.research.att.com... > Eric> So I told myself: wouldn't it be great if max(None, x) or > Eric> min(None, x) always simply returned x? > > My first thought was that this was an excellent idea. > > Then I thought again. > > Here's the problem: The notion that max(None, x) and min(None, x) > should both return x is one of three desirable properties that cannot > all be true at once. Here are the other two: > > 1) Whenever x < y, min(x, y) is x and max(x, y) is y. > > 2) < is an order relation over all types. > > The desirability of (1) should be obvious. (2) is more subtle, but > it is necessary for it to be possible to sort a vector of heterogenously > typed objects. > > Now, if max(None, x) and min(None, x) both yield x, and (1) is true, > then x > None and x < None must both be true. But then (2) cannot > be true. > "None > x" or "x > None"doesn't really make sense: Nothing is better than complete happiness. A cheese sandwich is better than nothing. Ergo, a cheese sandwich is better than complete happiness. -- David "I love deadlines. I love the whooshing noise they make as they go past." Douglas Adams From hancock at anansispaceworks.com Thu Nov 7 16:08:47 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 7 Nov 2002 13:08:47 -0800 Subject: power TypeErrors In-Reply-To: <20021107192126.26346.92569.Mailman@mail.python.org> References: <20021107192126.26346.92569.Mailman@mail.python.org> Message-ID: On Thursday 07 November 2002 11:21 am, python-list-request at python.org wrote: > Fernando P?rez writes: > >?Michael Hudson wrote: MH> For all my mathematical leanings, I still don't really see the point MH> of having complex numbers native to a language. FP>?Well, other than the fact that not having them is pretty FP> much a slap in the face of everybody who does scientific FP> computing, I guess it doesn't matter. ?The fact that C lacks native FP> complex numbers is one of the reasons many hard FP>?core numerical computing people still frown upon it (not the FP> only one). MH> Really? ?OK. ?I was under the impression that while one used complex MH> numbers heavily in deriving one algorithms, that when it came to MH> implementing them they weren't an overwhelmingly helpful abstraction MH> -- that it was often easier to split things up into arrays MH> real_values, imag_values or something. ?Maybe this is just ignorance, MH> though. Scientific packages that use Fourier transforms, frequently rely on arrays of complex numbers. The general Fourier transform of a real array is complex-valued. We sometimes throw away the complex part (the real part, is, I believe called a "power spectrum"), but without it, you cannot correctly recover the original array. Fourier space calculations are frequently used in image processing, enhancement, and tomography. It's also important to realize that in a rapid-prototyping tool (which is arguably what Python is best at), the abstract conception is the thing to support. A real number-crunching application will use a faster, compiled language to implement the "actual algorithms' you're talking about. You see that in Numeric or SciPy (which uses LAPACK, still implemented in Fortran!). But the user/programmer doesn't think that way -- they use the complex-valued math which is the way the textbook describes it, and the way you talk about the problem (because that's how you're trained). It's the human-readable version. This is true in IDL, too -- users frequently use horribly memory- or CPU- intensive operations simply because it is *conceptually* simpler to do it that way. The attitude is that the saved development time is worth the extra run time, and you can always throw a more expensive computer at it, whereas trained scientists are a limiting reagent. ;-) Of course, eventually that goes sour and you need to use an optimized solution, but when you're read to make that decision, you're probably ready to switch languages anyway (and you can use a hybrid of languages as with Numeric or Scipy). FP > I'm not sure what your background is, MH> Algebraic geometry, mainly, plus a little theoretical physics & number MH> theory. Yep. It's ironic that mathematicians hardly ever "do math" (by which I mean calculations)! It's scientists that do that -- mostly applied physics folks: astronomers, chemists, geologists, engineers, and some biologists. Mathematical and theoretical physics applications tend to stay very conceptual. They manipulate equations, but they hardly ever have to actually plug in numbers and solve them (especially in droves). And sometimes, it's not pretty. So we have scientific computing. FP >?but I can tell you that python is gaining _very_ strong support in FP >?scientific computing. I also observe this. MH > Given what I hear of IDL, this doesn't surprise me :) That isn't pretty, either. ;-) Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From bushbo at attbi.com Sat Nov 9 13:37:15 2002 From: bushbo at attbi.com (Brian O. Bush) Date: 9 Nov 2002 10:37:15 -0800 Subject: indexed looping, functional replacement? Message-ID: <3fe406f0.0211091037.2795e538@posting.google.com> I currently have a list of functions and a list of arguments to the functions (n to n). Is there a way I can get around having to keep an index into the arguments as I loop through the functions. Below is my imperative approach: def f1(str): print "f1:", str def f2(str): print "f2:", str def f3(str): print "f3:", str str = ["bbb", "sdf", "sdw"] fn = [f1, f2, f3] i = 0 for f in fn: f(str[i]) i = i + 1 I would like a simpler approach to avoid having to manually maintain an index, maybe functional if possible. Thanks, Brian From jbperez808 at yahoo.com Mon Nov 4 12:40:57 2002 From: jbperez808 at yahoo.com (Jonathan P.) Date: 4 Nov 2002 09:40:57 -0800 Subject: getting status of SHIFT and CTRL key under Python curses Message-ID: Is it possible to get the status of the SHIFT and CTRL keys under the python curses API? Both getch() nor getkey() return the same values for SHIFT-'some key' and just 'some key' - no differentiation. From jdhunter at ace.bsd.uchicago.edu Wed Nov 27 16:35:36 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 27 Nov 2002 15:35:36 -0600 Subject: do you guys help newbies?? In-Reply-To: <200211280809.01424.bhards@bigpond.net.au> (Brad Hards's message of "Thu, 28 Nov 2002 08:09:01 +1100") References: <200211280809.01424.bhards@bigpond.net.au> Message-ID: >>>>> "Brad" == Brad Hards writes: Brad> How far is a mile? How much is a gallon? A mile is approx 1.7048275260088487e-13 light years. A gallon is a half a peck. The units aren't terribly important for this problem. Cheers! John Hunter From trapforcannedmeatproduct at hotmail.com Sat Nov 9 23:45:21 2002 From: trapforcannedmeatproduct at hotmail.com (R. Charles Henry) Date: 9 Nov 2002 20:45:21 -0800 Subject: Image merging within python - based tool (maybe OT) Message-ID: <8ed56b42.0211092045.1e833602@posting.google.com> I'd like to ask the group's advice. My situation: I have two separate document images, both of the same format .png, .bmp, .jpg, or .tif. They are otherwise identical in size and file characteristics, having been produced from a larger-than-A4 document using an A4 flatbed scanner. Each image contains a region of 'overlap' with the other. I need to find an open-source 'mosaicking' or 'blending' codebase, which will be capable of accepting both input images, and merging them to reproduce an image of the original larger-than-A4 document. This code is to be used within a tool I am creating using python, & I'd like to avoid the neccessity of having to manually set reference points on the input images. The code itself that I'm searching for doesn't need to be python, just accessible from it. Since the input images are 'flat', I don't require such features as projection adjustment etc, I just need some form of basic automatic 'merging'. Would anyone have any suggestions? Any pointers at all would be very gratefully received. TIA From mhammond at skippinet.com.au Tue Nov 19 16:56:55 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 19 Nov 2002 21:56:55 GMT Subject: COM interfaces and inheritance In-Reply-To: <3DDA31DD.35E676C0@hotmail.com> References: <3DDA31DD.35E676C0@hotmail.com> Message-ID: Alan Kennedy wrote: > So some code might look like this > > objA = createObjA() # Returned object implements interface A > objB = myModule.IInterface2(objA) > # Bingo! > > At least, that works for me :-) > > I hope this helps, and that I've explained it clearly enough. The next version of win32all will have win32com.client.CastTo() - then you can simply give the interface by name. Eg, the SpamBayes outlook addin uses this now: popup = CastTo(popup, "CommandBarPopup") To "cast" a "CommandBar" object to "CommandBarPopup" (where the latter derives from the former). Mark. From jdhunter at nitace.bsd.uchicago.edu Wed Nov 13 15:55:26 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Wed, 13 Nov 2002 14:55:26 -0600 Subject: [regexp] Where's the error in this ini-file reading regexp? In-Reply-To: <3dd2a254@news.swissonline.ch> ("F. GEIGER"'s message of "Wed, 13 Nov 2002 20:05:15 +0100") References: <3dd2a254@news.swissonline.ch> Message-ID: >>>>> "F" == F GEIGER writes: F> rex = re.compile(r"(\s*(\[.+\])(\s*((.+)=(.+)))+?)", F> re.MULTILINE|re.IGNORECASE) L = rex.findall(s) This is a little messier than necessary. If the config file is really as simple as the example, how about a dictionary of dictionaries? import re s = \ '''[Section 1] Key11=Value11 Key12=Value12 Key13=Value13 [Section 2] Key21=Value21 Key22=Value22 Key23=Value23''' rgx = re.compile('^\[Section (\d+)\]$') config = {} for line in s.split('\n'): m = rgx.match(line) if m: secNum = int(m.group(1)) continue try: secNum except NameError: raise RuntimeError, 'Improper config file, no section defined' else: key, val = line.split('=') config.setdefault(secNum, {})[key] = val print config The key value pairs in each section are calling for a string split. All you have to do is keep tabs on the section number by updating it when you see a match for a section regex. The section numbers are keys for the dictionary, and each key points to a dictionary of key/value pairs for that section. Simple, clean, easy to read and it works. You can get the vals with, eg, config[1]['Key11'] JDH From max at alcyone.com Sat Nov 9 05:49:12 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 09 Nov 2002 02:49:12 -0800 Subject: zip/unzip pictures doesn't work References: <3DCCE633.5040301@gamebox.net> Message-ID: <3DCCE828.E8F646DD@alcyone.com> A Nilsson wrote: > I've been messing around with the zipfile module and discovered > something strange. > When I zip/unzip ordinary text files there's no problem but when i use > pictures (JPG and GIF) they get corrupted. I believe it is during the > unzip operation they get messed up. Sniff, sniff. I smell a text/binary distinction (and I see you're on Windows). Make sure you open the relevant files in binary mode by appending a 'b' character to the mode string. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Success and failure are equally disastrous. \__/ Tennessee Williams The laws list / http://www.alcyone.com/max/physics/laws/ Laws, rules, principles, effects, paradoxes, etc. in physics. From un36523f at blue-seal.com Sat Nov 16 10:37:29 2002 From: un36523f at blue-seal.com (Alexander Meins) Date: Sat, 16 Nov 2002 16:37:29 +0100 Subject: Python als PHP ersatz? References: Message-ID: <1176026.fauViv82ue@blue-seal.com> Marten Bauer wrote: > Kann mir da jemand weiterhelfen? comp.* newsgroups are usually english speaking.... A. From rnd at onego.ru Fri Nov 1 05:55:19 2002 From: rnd at onego.ru (Roman Suzi) Date: Fri, 1 Nov 2002 13:55:19 +0300 (MSK) Subject: problem with calendar Message-ID: I have the following problem: Python 2.2.2 (#1, Oct 18 2002, 11:40:02) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import calendar >>> calendar.month_abbr >>> calendar.month_abbr() Traceback (most recent call last): File "", line 1, in ? AttributeError: _localized_month instance has no __call__ method What's up? Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - not to mailto:aaro at onego.ru From shalehperry at attbi.com Sat Nov 23 02:32:10 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 22 Nov 2002 23:32:10 -0800 Subject: Newbie Q on searching lists In-Reply-To: <3DDF1673.4020203@nyc.rr.com> References: <3DDF1673.4020203@nyc.rr.com> Message-ID: <200211222332.10353.shalehperry@attbi.com> On Friday 22 November 2002 21:45, Kenny Tilton wrote: > I see the index method on lists throws an error if the element sought is > not found. I was hoping it would return None. > > The semantics I am coding happen to throw an error if a certain element > is found in a list, so i want to code: > > if calculators.index[thisCalculator]: > raise CircularDependency, thisCalculator > > 1. Am I missing something? > if calculators.count(thisCalculator): # returns zero if not found raise CircularDependency, thisCalculator print count.__doc__ count(value) -> integer -- return number of occurrences of value > 2. Can I add a method to List that has the behavior I am after? > in the new python 2.2 code base you can derive from list and add a new method > 3. Should I just start a module of my favorite utilities and create there: > > def find( item, list): > try: yada yada... > not always a bad option either From tundra at tundraware.com Wed Nov 6 18:50:07 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: 06 Nov 2002 23:50:07 GMT Subject: Grabbing Keystrokes Within A GUI Application Message-ID: <3f9cqa.8e61.ln@boundary.tundraware.com> It has been several centuries since I last wrote GUI code, so I stipulate that the following question may be Moronic, however ... --------------------------------------------------------------------- Part of Python's appeal for me was the lower ramp-up time to getting GUI applications to work. In an effort to retrain my command line brain to think GUI-ly again, I decided to start with 'anygui' as a learning exercise. [I am unclear on just how good/stable the current 'anygui' code actually is, but, for the moment, it serves my purposes.] I now have the skeleton of a GUI-driven utility which allows me to navigate through a file system. When I select a directory, it moves there. When I click on a file, I do nothing (for now). Now, here's the part my elderly brain does not get. During all this mousing, suppose I want to capture keystrokes. In my case, I want to first select a file visually, and then use a single letter to perform an operation on it - 'e' for emacs, 'm' for more, and so on. I am hacking my way to some visual composite of mc, less, and MS Winders Explorer, I guess. In the Bad Old Days, I recall hooking into the GUI message handling loop and looking for messages indicating keyboard input. There appears to be no such animal, at least in 'anygui'. Does anyone have suggestions on how this might be accomplished. I am willing to learn that 'anygui' is not yet stable/feature-laden enough to do the trick, in which case I will go learn Tkinter as needed. Similarly, responses in the form of, "You big dummy, this is Soooo, easy to do..." are fine, but hopefully a pointer to someplace which 'splains it to me will also be included in that case... TIA, -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From mstenner at phy.duke.edu Mon Nov 18 09:36:09 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Mon, 18 Nov 2002 09:36:09 -0500 Subject: How to write Inline Functions in Python? In-Reply-To: <001e01c28ee0$93ddf290$21795418@dell1700>; from brian@sweetapp.com on Mon, Nov 18, 2002 at 12:57:52AM -0800 References: <2L2C9.22705$744.831937@news1.tin.it> <20021117221910.A3360@phy.duke.edu> <001e01c28ee0$93ddf290$21795418@dell1700> Message-ID: <20021118093609.A4968@phy.duke.edu> On Mon, Nov 18, 2002 at 12:57:52AM -0800, Brian Quinlan wrote: > Michael Stenner wrote: > > I feel like we're going around in circles here. I'm talking about > > python. It looks like 'inline' would produce serious speedups in some > > cases. Therefore, it looks like an inline command would not be > > useless. > > Doing this would be almost impossible because Python name binding is > done at runtime. For example, how would you compile this? < excellent examples snipped > Your point is well made. It looks like one would have to deviate extremely far from the "python feel". It could be done in an extremely restrictive way, of course, but (as you point out) inline function objects would not (COULD not) behave like every other python object does. They would probably have to be treated like macros and only have meaning at compile-time. > Not that an inline keyword should be added to the language even if it > were possible... Never said they should :) On Mon, Nov 18, 2002 at 09:51:58AM +0000, Alex Martelli wrote: > Michael Stenner wrote: > ... > > I'm not convinced that it would be "worth it" to have "inline > > functions" or "auto-inlined code" or whatever you want to call it. > > That's what I'm trying to discuss. I'm interested in your (and > > others') thoughts on the matter. So far though, I find your claims > > that they would be useless unconvincing. > > Let's try another tack -- how would it work? > > def f(x): > return g(x+1) < snip > Summary: g can be anything, and change each time f is called > OK so far? This is where we're starting from. Now, what black magic > would you be willing to put up with, to enable the user to state that > g should not be called (despite the presence of the call-operator > "open and close parens":-) but rather "expanded"? That's the issue > as I see it. > > If g is a qualified name, as it often will be when using functions > defined in another module: > > def ff(x): > return gmod.gfun(x+1) > > it becomes even murkier. Do you think the huge irregularity > involved in "inline is only allowed for functions whose def > statement precede the inline-use in this very module" would be > an acceptable price to pay, for whatever modest benefits you > think having the compiler inline things rather than having to > do that yourself might bring? The discussion needs to be split > in two alternative threads depending on this crucial decision. < snipped further discussion of the possible degrees of ugliness > OK, I'm pretty convinced. It could by "simple" (as I imagined it) such that inline functions are like macros. In this case, they behave nothing like regular objects (only really existing at compile-time) and are only usable in very restricted ways. Or... It could be "complex" and totally rework the concept of compilation. I hadn't fully appreciated the complexities introduced by modules. Basically, I think it comes down to the fact that there _is_ no single "compile time". I feel silly for not realizing that. I've extolled the benefits of that model many times :) > Summarizing, my working hypothesis is NOT "inline would be > TOTALLY useless"; rather, it is, for either possible choice > regarding what functions inlining could apply to, the costs > and complications would be SO huge compared with the possible > benefits that it almost defies belief that somebody would > propose such changes in earnest. Well, I want to repeat that I _didn't_ propose such changes. I merely sought enlightened opinions on the matter. I saw modest benefit in the idea, and was curious about _why_ people thought it was a bad one. You (and Daniel) have given me precisely what I asked for. < snipped analogy explaining absolute vs. relative merit > > So, I would not feel moved to criticize somebody who described such a plan > as "useless", even though the term is not strictly and literally applicable. My objection to the word "useless" was not linguistic nit-picking. Timothy was not (as I understood him) saying that the drawbacks far outweighed the benefits. He did not discuss drawbacks at all. He said that the benefits were insignificant. You have said something very different (and the sort of thing I was asking for). You have said that the modest benefits are dwarfed by the costs of implementation and the "ugliness" (for lack of a better word) introduced. I find your argument quite persuasive. Thank you all for the discussion. That's all I was after. I apologize if it ever seemed otherwise. -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From see_reply_address at something.invalid Mon Nov 25 23:30:13 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Tue, 26 Nov 2002 17:30:13 +1300 Subject: Borgengi (Re: Perl to python convertor) References: <3dd94531$1@news.mt.net.mk> <3DDA5765.F0DA8132@spam.no.volvo.com> Message-ID: <3DE2F8D5.6040101@something.invalid> ?????? ?. wrote: >>-- >>?????? >> >> Actually, Microsoft is sort of a mixture between the Borg and the Ferengi. First rule of assimilation: You will be acquired! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From eric.brunel at pragmadev.com Wed Nov 13 04:18:24 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 13 Nov 2002 10:18:24 +0100 Subject: Tkinter: listbox navigation References: <0v0tqa.3kf1.ln@boundary.tundraware.com> Message-ID: Tim Daneliuk wrote: > I have looked high and low but cannot find an answer to: > > When I give the listbox focus, I am able to navigate around it using the > arrow keys. So, even if I have selected a particular item, I can move to > other items *which is indicated by an underlining of the currently > navigated item*. So, at any moment in time, one item may be selected > and another underlined. > > Is there a way programmatically to force the underlining to a particular > item? Yep: use listbox.activate(index) and make sure your listbox keeps the keyboard focus (via focus_set I suppose...). To know where the active line is, use listbox.index(ACTIVE). > I cannot seem to find a complete set of docs on the various methods > and attributes of a listbox, so a pointer to this would also be > appreciated. The most complete set of docs you'll ever find is the tk documentation in your man pages if you're on Un*x, or @ http://www.tcl.tk/man You'll have to know how to translate tcl commands to Python methods, but that's not the toughest part of the job, especially if you already know the basics of Tkinter. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From costanza at web.de Fri Nov 22 14:49:57 2002 From: costanza at web.de (Pascal Costanza) Date: Fri, 22 Nov 2002 20:49:57 +0100 Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <2259b0e2.0211210838.7647301a@posting.google.com> <093kra.3n3.ln@beastie.ix.netcom.com> Message-ID: Donn Cave wrote: > The procedural aspect of Python is also natural but not necessarily > benign. This is basically the linear descendent of assembly language, > with variables for registers and other superficial differences; the > alternative (or one of them, anyway) is the equational reasoning you > find in functional and logic programming languages. It's arguably > true that the normal programmer can more easily conceive a procedural > solution to a problem, but it is not true that this solution will > naturally be robust and maintainable. [...] That's even true for code that superficially looks like OOP. An extremely well-presented example and discussion of this can be found at http://csis.pace.edu/~bergin/patterns/ppoop.html Pascal -- Given any rule, however ?fundamental? or ?necessary? for science, there are always circumstances when it is advisable not only to ignore the rule, but to adopt its opposite. - Paul Feyerabend From tismer at tismer.com Thu Nov 21 09:09:48 2002 From: tismer at tismer.com (Christian Tismer) Date: Thu, 21 Nov 2002 15:09:48 +0100 Subject: SHA-2 state of the art? Message-ID: <3DDCE92C.70803@tismer.com> Hi friends, I am looking for implementations of SHA-256 and SHA-512, and I found CryptKit so far. http://eevolved.com/cryptkit/ Does anybody know of alternative activities? Does somebody plan to include sha-2 into the Python standard? thanks for any info - 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 pager +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 lvirden at yahoo.com Thu Nov 7 08:26:48 2002 From: lvirden at yahoo.com (lvirden at yahoo.com) Date: 7 Nov 2002 13:26:48 GMT Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DC8623B.88753C16@earthlink.net> Message-ID: According to Wojciech Kocjan : :But not quite more secure. Imagine userX running a script that does :something nasty - like replace some command and then wait for root to :call it. This was a very simple example, since probably parrot would :recreate interpreters per script, but I guess it still could be possible :since it would be the same process... Each script would need to be done in a seperate safe interpreter which goes away at the end of the script, so there was no cross process pollination. -- Tcl - The glue of a new generation. Even if explicitly stated to the contrary, nothing in this posting should be construed as representing my employer's opinions. From aleax at aleax.it Mon Nov 18 18:38:55 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 18 Nov 2002 23:38:55 GMT Subject: popkey() method for dictionaries? References: Message-ID: Fernando P?rez wrote: ... > key _will_ trigger an exception, I'd argue that the default behavior of > all these functions (get, pop, popitem) should be to raise an exception. Practicality beats purity, and it would be no use for somedict.get(key) to be just alternative syntax for somedict[key]; while having it return None when key not in somedict is useful to enable, for example, such use as map(somedict.get, potentialkeys). > Unfortunately these functions (get/pop/popitem) have already been written > with (it seeems to me) inconsistent interfaces, and we'll just get used to Yes, somewhat, but I think they're each pragmatic enough that keeping track is no major chore (IMHO). Alex From ajw126NO at SPAMyork.ac.uk Wed Nov 20 07:26:31 2002 From: ajw126NO at SPAMyork.ac.uk (Andrew Wilkinson) Date: Wed, 20 Nov 2002 12:26:31 -0000 Subject: Subscript AST Node Message-ID: <3ddb7f77$0$113$1b0f2dd5@mercury.nildram.co.uk> Hi, I'm working with the Python syntax tree as returned by compiler.parseFile(). Looking at the documentation the subscript node has three attributes, expr, flags and subs. 'expr' is obvious and does exactly what I'd expect it to do, 'flags' seems to be undocumented (it probably is the source code, but I'd prefer not go that deep...) - what does it do? I expected 'subs' to be a single AST node, but instead it's a list - under what circumstances would this have more than one element in the list? Any help in understanding this would be greatly appreciated, Cheers, Andrew Wilkinson --- You tried your best and you've failed miserably. The lesson is, never try. From nelson at crynwr.com Sun Nov 10 01:34:40 2002 From: nelson at crynwr.com (Russell Nelson) Date: 10 Nov 2002 01:34:40 -0500 Subject: PEP #99484663 Message-ID: Suggested PEP: Treat { and } when encountered at the end of a statement like this: When you see a {, generate an error if the next statement is not indented more than the previous statement. When you see }, generate an error if the next statement is not indented less than the previous statement. In this manner, people who are unable to wean themselves from silly syntactic block structure tokens will be happy with Python, rather than continually whinging about how horrible it is that indentation is meaningful to the program. -- -russ nelson http://russnelson.com | Crynwr sells support for free software | PGPok | it's better to be free 521 Pleasant Valley Rd. | +1 315 268 1925 voice | than to be correct. Potsdam, NY 13676-3213 | +1 315 268 9201 FAX | From i.steinhardt at web.de Fri Nov 1 05:05:49 2002 From: i.steinhardt at web.de (x-herbert) Date: 1 Nov 2002 02:05:49 -0800 Subject: py2exe and COM32 Message-ID: Hi, I will build an .exe of my python script... I have the follow header: import win32com, sys, string, win32api, re, os import win32com.client.gencache from os import spawnv, P_WAIT, unlink from Tkinter import Tk, Button, Frame, Label from Tkconstants import * from win32com.client import gencache from win32com.client.gencache import EnsureDispatch and during the "compilation" i have the follow failure-message: creating dist\Outlook_COM_05\Outlook_COM_05.exe warning: py2exe: could not parse version number '' No VersionInfo will be created copying C:\PYTHON22\DLLs\tk83.dll -> dist\Outlook_COM_05 copying C:\PYTHON22\DLLs\tcl83.dll -> dist\Outlook_COM_05 copying C:\PYTHON22\DLLs\_tkinter.pyd -> dist\Outlook_COM_05 copying C:\Python22\Lib\site-packages\win32\win32trace.pyd -> dist\Outlook_COM_05 copying C:\WINDOWS\SYSTEM\python22.dll -> dist\Outlook_COM_05 copying C:\WINDOWS\SYSTEM\PyWinTypes22.dll -> dist\Outlook_COM_05 copying C:\Python22\Lib\site-packages\Pythonwin\win32ui.pyd -> dist\Outlook_COM_05 copying C:\PYTHON22\DLLs\_sre.pyd -> dist\Outlook_COM_05 copying C:\Python22\Lib\site-packages\win32\win32api.pyd -> dist\Outlook_COM_05 copying C:\WINDOWS\SYSTEM\pythoncom22.dll -> dist\Outlook_COM_05 warning: py2exe: ************************************************************************* warning: py2exe: * The following modules were not found: warning: py2exe: * win32dbg.dbgcon warning: py2exe: * win32dbg warning: py2exe: * win32com.client.Dispatch warning: py2exe: * win32com.client.NeedUnicodeConversions warning: py2exe: ************************************************************************* removing 'build\bdist.win32\winexe\collect\Outlook_COM_05' (and everything under it) Built File dist\Outlook_COM_05\Outlook_COM_05.exe removing 'build\bdist.win32\winexe' (and everything under it) Have anybody an solution?? my script works o.k. .... Thanks Ingolf From sismex01 at hebmex.com Tue Nov 12 13:43:28 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 12 Nov 2002 12:43:28 -0600 Subject: Optimisation problem Message-ID: > From: gabor [mailto:gabor at realtime.sk] > Sent: Tuesday, November 12, 2002 12:44 PM > > On Tue, 2002-11-12 at 19:30, sismex01 at hebmex.com wrote: > > > From: gabor [mailto:gabor at realtime.sk] > > > > > > On Tue, 2002-11-12 at 16:50, Michael Hudson wrote: > > > > anton at vredegoor.doge.nl (Anton Vredegoor) writes: > > > > > m,x,y,z = self.matrix,self.x,self.y,self.z > > > > > > > > > > This is faster > > > > > > > > Don't be so sure: this creates a tuple. > > > > > > > > > > > this is interesting.... > > > > > > you're saying that for example > > > > > > x,y = 2,4 > > > > > > creates a tuple? > > > > > > i thought thatr x,y=2,4 is the same as x=2;y=4 > > > > > > bye, > > > gabor > > > > Nope; when declaring tuples, unless stated otherwise, > > using parenthesis is optional; so you are in fact creating > > a tuple on both sides of the assignment, and unpacking > > it into variables on the left side. > > ok, so it creates temporary tuples.. i didn't know that... > > but the end result would be the same? > > bye, > gabor In this case which is quite simple, yes, it's the same result; but others might enlighten us on other cases where the "obvious" result isn't the one we'd get. Any suspects, anyone? -gustavo From robin at jessikat.fsnet.co.uk Wed Nov 20 05:54:16 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 20 Nov 2002 10:54:16 +0000 Subject: Understanding PyEval_InitThreads References: <7kf83526.fsf@python.net> Message-ID: In article <7kf83526.fsf at python.net>, Thomas Heller writes >Gernot Hillier writes: ...... >> void call_back_into_python(PyThreadState *s) >> { >> PyEval_PyEval_RestoreThread(s) >> // do your work >> PyEval_SaveThread(); >> } > >Unfortunately it won't work this way. > >Think of call_some_c_code() being the C standard library's qsort >function, and call_back_into_python() is the function pointer I gave >qsort to do the comparison. There's no way to pass the thread state to >the callback function! > >Storing the thread state in a global variable would be possible, but >in this case it wouldn't be thread safe, I assume, and *only* work if >the callout into C is done by my extension module. .... I think there's an issue here though. If the ctypes call is started in thread A then it makes sense to ensure that thread A receives the callback. Of course this is moot when only one python thread is running. Perhaps this is the mainthread only issue with tkinter and the like. -- Robin Becker From Paul.Casteels at ua.ac.be Wed Nov 6 02:29:48 2002 From: Paul.Casteels at ua.ac.be (Paul.Casteels at ua.ac.be) Date: 6 Nov 2002 08:29:48 +0100 Subject: win32com / Dispatch References: <3dc6c2ad@news.uia.ac.be> <6dXx9.15577$5u4.50589@news-server.bigpond.net.au> Message-ID: <3dc8c4ec@news.uia.ac.be> Mark Hammond wrote: : Paul.Casteels at ua.ac.be wrote: :> When I use win32com.client.Dispatch I get a CDispatch object with an :> oleobj inside and I have direct access to all methods/attributes. :> How can I obtain the same result when I get the IDispatch pointer from :> an external application (as an argument from another COM method). :> The type of this pointer is PyIDispatch but I am unable to invoke any :> methods on it. : Simply pass the PyIDispatch object to win32com.client.Dispatch() - it : detects this case and creates a wrapper around it. : Mark. Thanks a lot, this works fine. Paul Casteels From joe+usenet at sunstarsys.com Mon Nov 11 10:54:08 2002 From: joe+usenet at sunstarsys.com (Joe Schaefer) Date: 11 Nov 2002 10:54:08 -0500 Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DCFCC3E.204D9B45@man.ac.uk> Message-ID: "Donal K. Fellows" writes: [Scary ... worrying ... security ... suspicious ... pipe-dream] Brazil (1985). -- Joe Schaefer "The eternal mystery of the world is its comprehensibility." --Albert Einstein From ark at research.att.com Fri Nov 22 09:53:42 2002 From: ark at research.att.com (Andrew Koenig) Date: Fri, 22 Nov 2002 14:53:42 GMT Subject: Proposal: min(None, x) and max(None, x) return x References: Message-ID: Eric> So I told myself: wouldn't it be great if max(None, x) or Eric> min(None, x) always simply returned x? My first thought was that this was an excellent idea. Then I thought again. Here's the problem: The notion that max(None, x) and min(None, x) should both return x is one of three desirable properties that cannot all be true at once. Here are the other two: 1) Whenever x < y, min(x, y) is x and max(x, y) is y. 2) < is an order relation over all types. The desirability of (1) should be obvious. (2) is more subtle, but it is necessary for it to be possible to sort a vector of heterogenously typed objects. Now, if max(None, x) and min(None, x) both yield x, and (1) is true, then x > None and x < None must both be true. But then (2) cannot be true. So the cost of your proposal would be either to break the consistency between max/min and >/<, or to render unsortable vectors of values that include None. I don't think it's worth it. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From zhitenev at cs.vsu.ru Mon Nov 25 12:19:57 2002 From: zhitenev at cs.vsu.ru (Lexy Zhitenev) Date: Mon, 25 Nov 2002 20:19:57 +0300 Subject: Problem with paths on Win 9x References: Message-ID: > I'm trying to invoke a package, and I'm not getting very far. > C:\Python22\MyStuff\AstroPy3>python fit\FileRunner.py CivilDateAT.htm CivATOut.htm > C:\PYTHON22\PYTHON.EXE: can't open file 'fit\FileRunner.py' > ... > The path to FileRunner.py is: > > c:\Python22\Lib\site-packages\fit\fit\FileRunner.py > Probably, you have forgotten one 'fit' dir. Your running path should look: C:\Python22\MyStuff\AstroPy3>python fit\fit\FileRunner.py CivilDateAT.htm CivATOut.htm or C:\Python22\MyStuff\AstroPy3\fit>python fit\FileRunner.py CivilDateAT.htm CivATOut.htm Also, your package should meet certain requirements: 1) it must have __init__.py in its dir. 2) it must be a subdir of your running script or be present in your sys.path ALL subpackages should have a __init__.py file. If you wish to run your script from a package, you have to create a 'run' script, something like #!/usr/bin/env python import fit fit.fit.FileRunner.main() or something like that. Good Luck! Lexy. From fredrik at pythonware.com Sun Nov 17 10:07:02 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 17 Nov 2002 15:07:02 GMT Subject: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up References: Message-ID: Aahz wrote: > >> Write it in a platform-independent way. If you *intended* this literal to > >> mean "a 1 bit followed by 31 zero bits", then stick an L on the end of the > >> literal. > > > >...and remove it again when you get to Python 2.5. > > Why? hint: *** pep-0237.txt 12 Aug 2002 00:55:43 -0000 1.15 --- pep-0237.txt 7 Nov 2002 15:41:19 -0000 1.16 *************** *** 213,217 **** option, but it is off by default. ! B2. The warning for long literals is turned on by default. B3. The warnings about operations that give different results than --- 213,217 ---- option, but it is off by default. ! B2. (This stage is deleted.) B3. The warnings about operations that give different results than From robin at jessikat.fsnet.co.uk Wed Nov 6 11:40:57 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 6 Nov 2002 16:40:57 +0000 Subject: A vision for Parrot References: <20021105221004.339206f3.occitan@esperanto.org> <3DC8623B.88753C16@earthlink.net> <3DC8CDDD.7050103@mindspring.com> <3pE8dhAtvNy9EwoQ@jessikat.fsnet.co.uk> <3DC943CF.84A68F32@san.rr.com> Message-ID: In article <3DC943CF.84A68F32 at san.rr.com>, Darren New writes >Robin Becker wrote: >> Funnily enough they kept telling me that as soon as I switched to >> F99/C++ etc etc that everything would be portable. > >Your confusion is in thinking that "portable" is a binary value. Fortran >was certainly more portable than assembler, as was C. Tcl is certainly >more portable than Fortran or C. > >The other problem, of course, is that people keep improving their >capabilities, so what was portable is no longer adequate. Fortran is >quite portable, as long as you don't want to do 3D graphics driven by a >data glove. > >As long as you don't want to do development in multiple languages or >dynamically load code safely over the net into some other OS process, >Tcl and Python are pretty good choices. Otherwise, you might want to >consider C# or Java. > >See how it works? :-) yes you claim to have a better mousetrap :) and suddenly ther are 1.5.2/2.0/2.1/2.2/2.3a1 versions of Python and 6.4/7.1....8.4 of Tcl and I must buy the right C compiler or OS or things don't really quite port oh well there you go. English was portable until everyone started using it ;) -- Robin Becker From fperez528 at yahoo.com Wed Nov 13 13:51:27 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 13 Nov 2002 11:51:27 -0700 Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> Message-ID: Ken Starks wrote: > So we need: > 1. LaTeX for authors > 2. XML for the machine > 3. Variety for the readers > > To me this boils down to a two-way conversion system, with > a 'there-and-back' circular function that preserves all > content, and turns rapidly into a constant loop. [snip] > If this works, then it doesn't matter a damn which of > Latex and xml is the 'official' one. Good luck. Writing such a tex<->xml converter is an insanely non-trivial task, and I know a few bright people who have tackled it. If you do succeed, _please_ let the Lyx team know about it. There's interest in using XML in Lyx, but one of the hurdles is that the Lyx format, while not exactly latex, is reasonably tied to it. Latex is very hard to parse correctly, from what I've seen. Considering it's basically a full-blown programming language, short of rewriting TeX itself, this won't be a simple task... A nice starter project (which a friend of mine is working on) is a tex->MathML parser. Please drop a line if you get such a gizmo going, I'd love to see it. Cheers, f. From jslm at earthlink.net Mon Nov 18 01:08:20 2002 From: jslm at earthlink.net (joshua solomon) Date: Mon, 18 Nov 2002 06:08:20 GMT Subject: wxPython question References: Message-ID: "Chris Liechti" wrote in message news:Xns92C9DA5E62FACcliechtigmxnet at 62.2.16.82... > "joshua solomon" wrote in > news:lNRB9.2743$fY3.294687 at newsread2.prod.itd.earthlink.net: > > > Basically I have a loop within the OnPaint handler which I am using > > for bouncing a ball around on a screen. > > don't do the loop for the animation in the event handler. do it in a > separate thread nad call Refresh() or us a wxClientDC to draw in that loop > directly. > > GUI rule 1: event handlers have to be short (in time) > > so no animations and workers. use Threading instead. > Thanks for the info Chris. It worked. From mwh at python.net Wed Nov 27 08:37:19 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 27 Nov 2002 13:37:19 GMT Subject: Implementation of the global statement References: <8ef9bea6.0211270526.5a1278c5@posting.google.com> Message-ID: <7h3adjvqgs4.fsf@pc150.maths.bris.ac.uk> hungjunglu at yahoo.com (Hung Jung Lu) writes: > The global statement as in > > def f(x): > global y > ... > > is a directive to the parser. Well, compiler, really. > Internally the parser must keep a list of the "locally-globalled" > names. Yup, at least on some level. > Yes, you guessed right, out of pure curiosity: is this list > accessible from Python? Don't think so, as the list only exists during compiling and you can't hook into it or only execute one phase of it. > If not, why not? :) See above. You can probably get the compiler package to do what you want. Cheers, M. -- 48. The best book on programming for the layman is "Alice in Wonderland"; but that's because it's the best book on anything for the layman. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From i.steinhardt at web.de Fri Nov 22 05:19:18 2002 From: i.steinhardt at web.de (x-herbert) Date: 22 Nov 2002 02:19:18 -0800 Subject: problem with regex Message-ID: Hi, I have a problem with the regex in python: I will e.g. only find the word eMail in a string. Her is a part of my code... ..................... key = "eMail" i = ".....bla bla XXXX ..." #see below for XXXX... regkey = "\\b"+key+"\\b" # for find key alone regex = re.compile(regkey) result = regex.search(i) if result: print "find" else: print "find not" ....................... Result: XXXX: print: eMail find # o.k. ;-) eMailNews find not eMail_News find not eMail-News find # upps why!!!!!!!!!!!!!!!! eMail*News find # upps why!!!!!!!!!!!!!!!! eMail?News find # upps why!!!!!!!!!!!!!!!! eMail#News find # upps why!!!!!!!!!!!!!!!! ...etc. I think, the regkey = "\beMail\b" find this word alone.... ????? Thanks! Ingolf From oracle_vs_ms at yahoo.dk Thu Nov 7 03:30:18 2002 From: oracle_vs_ms at yahoo.dk (Peter Lorenzen) Date: 7 Nov 2002 00:30:18 -0800 Subject: Subclassing the min() build-in function? References: <18eef4ae.0211060911.2c0a7731@posting.google.com> Message-ID: <18eef4ae.0211070030.15604f21@posting.google.com> Thank you very much, all of you. I works great. Regards, Peter From john.abel at pa.press.net Fri Nov 15 08:47:20 2002 From: john.abel at pa.press.net (John Abel) Date: Fri, 15 Nov 2002 13:47:20 +0000 Subject: Calling A Deconstructor Message-ID: <3DD4FAE8.5080905@pa.press.net> Hi, I have a class, with an __init__, and a main function, basically a wrapper around smtplib. I wish to add a __del__ to the class. Two questions: Do I need to do it this way? If so, how do I can close the instance, so the __del__ is called? The script will be permanently resident, so I wanted to make sure that I didn't have various connections open to the smtp server. Thanks John From dave at pythonapocrypha.com Fri Nov 15 13:34:37 2002 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 15 Nov 2002 10:34:37 -0800 (PST) Subject: A really bad idea. In-Reply-To: Message-ID: On Fri, 15 Nov 2002, Daniel Dittmar wrote: > holger krekel wrote: > > But in fact i'd like to see some examples of what is readable and > > what is not readable in your oppinion. > [snip] > list comprehension: not readable, because you don't know what to search for. It's funny what people do and don't find readable, huh? I use list comps all the time because to me they are almost always more readable than the equivalent code and more vertically compact as well. I wouldn't mind having a dictionary comp but don't need it nearly as much, even less so a generator comp. Just my $0.02, Dave From mstenner at phy.duke.edu Wed Nov 13 21:14:03 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Wed, 13 Nov 2002 21:14:03 -0500 Subject: calendar modules In-Reply-To: ; from CousinStanley@HotMail.com on Wed, Nov 13, 2002 at 05:03:50PM -0700 References: <7396d2b2.0211131136.160ee567@posting.google.com> Message-ID: <20021113211403.A12442@phy.duke.edu> On Wed, Nov 13, 2002 at 05:03:50PM -0700, Cousin Stanley wrote: > || I tried. But checking the day of the week I was born > || didn't work. This calendar seems limited to >= 1970-01-01 > > It seems there is also a future limit ... > > ( 1970 , 01 ) <= ( iYear , iMonth ) <= ( 2038 , 01 ) Yes, both of these come from the fact that "unix time" is counted as the number of seconds since the "epoch", which is the first seconds of 1970. If you represent it as a 32 bit unsigned int, that gives you about 68 years. -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From brian_l at yahoo.com Thu Nov 7 23:15:59 2002 From: brian_l at yahoo.com (Brian Lenihan) Date: 7 Nov 2002 20:15:59 -0800 Subject: PySol Windows binaries, anyone? References: Message-ID: Christian Tismer wrote in message news:... > Does somebody have a working PySol for me? > Or maybe one of the last working installers is still > around? I'd also put this on my website for people > to download. Markus seems to be no longer reachable > by email. I have some stuff here which should help: http://homepage.mac.com/brian_l From yduppen at xs4all.nl Sun Nov 3 06:18:23 2002 From: yduppen at xs4all.nl (Yigal Duppen) Date: Sun, 03 Nov 2002 12:18:23 +0100 Subject: Macros in Python, and using reg exps to build a scheme interpreter References: Message-ID: <3dc50600$0$39814$e4fe514c@dreader5.news.xs4all.nl> > Currently in one of my classes I'm building a scheme interpreter > in Java. This has brought two questions to mind. First does python use > language macros to define higher level functionality. And two does anyone > know a good place to look for how to implement a scheme parser using > regular expressions? As others already mentioned, regexes are not very suitable for the entire parsing. It's usually better to use a parser generator. For an example of a (partial) scheme interpreter in Python, have a look at http://www.xs4all.nl/~yduppen/site/psyche.html YDD -- http://www.xs4all.nl/~yduppen From bokr at oz.net Wed Nov 13 04:47:16 2002 From: bokr at oz.net (Bengt Richter) Date: 13 Nov 2002 09:47:16 GMT Subject: python gui rant References: <3dd217e2$0$231$4d4ebb8e@news.nl.uu.net> Message-ID: On Wed, 13 Nov 2002 10:21:33 +0100, "Gumuz" wrote: >sorry guys/girls, but i had to vent this :) > > >i am using wxPython at the moment as my python gui. Coming from a nice IDE >like Delphi it's really frustrating to get a nice layout together. I tried >some tools. The one i liked most, because of it's simplicity was wxGlade, >but still... it's not there yet. I might have missed something here and I >don't want to complain, but I think that a good, robust gui-designer will >open up a lot of posibilities for python. i might give it a shot! > Your mention of Delphi made me recall that you can right click on a gui form and select 'view as text' from the popup menu, and you get to see all the parameters that define your layout. E.g. a default form with one button dropped on it near the top left: object Form1: TForm1 Left = 200 Top = 108 Width = 544 Height = 375 Caption = 'Form1' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] PixelsPerInch = 96 TextHeight = 13 object Button1: TButton Left = 40 Top = 24 Width = 75 Height = 25 Caption = 'Button1' TabOrder = 0 end end I wonder if anyone has written a translator for this information to port a GUI design into wxWindows or tkinter. The Delphi IDE is quite nice for fiddling with your visual design (other aspects of Delphi are nice too, but that's another topic). Regards, Bengt Richter From dig.list at nm.ru Wed Nov 13 04:47:56 2002 From: dig.list at nm.ru (DIG) Date: Wed, 13 Nov 2002 03:47:56 -0600 Subject: newbie Q: shortcuts for long module names? In-Reply-To: ; from "Robert Oschler" on Tue, Nov 12, 2002 at 03:21:25AM References: Message-ID: <20021113034756.A32761@lifebook> Hi, Robert Oschler ! On Tue, Nov 12, 2002 at 03:21:25AM +0000, Robert Oschler wrote: > Let's say I import a module with a long name: > > import com.long.module.name > > Now every time I access a function in com.long.module.name I have to prepend > "com.long.module.name" to the member function. Is there generally accepted > and safe way to "alias" the module name or bring it into the local namespace > so I can either omit or alias the module name with something much shorter? I have seen this a few times: import Tkinter tk=Tkinter root = tk.Tk() button = tk.Button( ) button['text'] = "test" root.pack() root.mainloop( ) Line "tk=Tkinter" allows you to have whatever you want as a module's name. In your case this could be: import com.long.module.name short_one = com.long.module.name or even import com.long.module.name m = com.long.module.name Best regards, -- DIG (Dmitri I GOULIAEV) From dave at pythonapocrypha.com Fri Nov 15 12:08:08 2002 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 15 Nov 2002 09:08:08 -0800 (PST) Subject: Python urllib.urlretrieve vs. Perl getstore In-Reply-To: <20021115152947.D30315@prim.han.de> Message-ID: Adam S wrote: > > I have a Perl and a Python version of a program designed to fetch > large files (40MB) from a remote HTTP server. > > Initial tests indicate that the Perl version, using getstore() > is 3-4 times faster than the Python version. Is there a reason > for this and is there another Python library HTTP file fetch > function I can use? I don't want to use FTP as there > is no anonymous logon for this server. 40 MB files? Hmm... maybe is urllib pulling the entire file into memory? If so, the slowdown might have nothing to do with the network and everything to do with the OS swapping memory to disk. -Dave From maney at pobox.com Mon Nov 25 13:20:39 2002 From: maney at pobox.com (maney at pobox.com) Date: Mon, 25 Nov 2002 18:20:39 +0000 (UTC) Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <093kra.3n3.ln@beastie.ix.netcom.com> <1038199757.350382@yasure> Message-ID: Jacek Generowicz wrote: > When you call a subroutine, you are calling a specific piece of > code. The caller decides what will be executed. When you pass a > message, the decision as to which exact code should be executed is > made elsewhere (some form of dispatch). > > But it looks as if my understanding of message passing is different > from Pascal's. Maybe, but probably less so than you imagine. You're desribing it from the relatively concrete, implementation side; Pascal has preferred the fuzzy, metaphorical language that was introduced, IMO, in an effort either to make a useful but trivial formalism sound like it was something wonderful, or to hilight the important new ways of thinking about and structuring programs that the formalism (ie., language support) made much more convenient. This is Monday, so today I'll say it was the former, handwaving; on Tuesdays I prefer the metaphor as pedagogical device. And so it goes through the week... From gmuller at worldonline.nl Sat Nov 2 12:27:55 2002 From: gmuller at worldonline.nl (GerritM) Date: Sat, 2 Nov 2002 18:27:55 +0100 Subject: Foot in mouth disease References: <3dc3dc4e$0$12762$afc38c87@news.optusnet.com.au> Message-ID: "Derek Thomson" schreef in bericht news:3dc3dc4e$0$12762$afc38c87 at news.optusnet.com.au... <...snip...> > > Then there's the fact that it takes between 5-10 lines of Java to do the > same thing in Python, depending on what you're doing. Having a very high > level language, as opposed to a high level one, definitely helps > refactoring in that there's much less code to refactor. Look at the size > of Fnorb (*), compared to Java ORBs. Or just look at the size of the > Fnorb IDL compiler ... and it's even readable. I know which I'd like to > be refactoring. > > (*) http://fnorb.org > <...snip...> Do you by any means have the data at hand (kloc's for Java, kloc's for comparable Python; ORB and/or IDL compiler)? I am highly interested in any substantiated evidence with respect to language efficiency/expressiveness. > > -- > D. regards Gerrit Muller -- www.extra.research.philips.com/natlab/sysarch/ From cnetzer at mail.arc.nasa.gov Fri Nov 8 19:17:00 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Fri, 8 Nov 2002 16:17:00 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? In-Reply-To: <7b8f89d6.0211081548.f91b468@posting.google.com> References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7b8f89d6.0211081548.f91b468@posting.google.com> Message-ID: <200211090017.QAA18787@mail.arc.nasa.gov> On Friday 08 November 2002 15:48, larry wrote: > > Why do SOME people think Lisp is a fantastic programming langugae? > Are we missing something? Because for all it's silly, irritating parenthesis, it got some things very right. Whenever I see a new language, I tend to ask myself: "What subset of LISP is it trying to do, and what does it give up to do so." -- Chad Netzer cnetzer at mail.arc.nasa.gov From mwh at python.net Thu Nov 7 06:24:57 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 7 Nov 2002 11:24:57 GMT Subject: segmentation fault when unpickling an object in another Python instance References: <3DC96AAD.9090503@web.de> <3DC99AF6.2030906@web.de> Message-ID: <7h3lm45zktm.fsf@pc150.maths.bris.ac.uk> Raik Gruenberg writes: > It's not cPickle specific - I got the same segmentation fault when > using normal pickle. > > Getting a minimum example will take some time and it can get quite > long. I can switch off the error by deleting a line in the constructor > of the pickled object... > > Summary so far, I can not unpickle my object if: > - The constructor of this object called (before pickling) a certain > method of an internally referenced object > - this internal object encapsulates an Numeric array > - the certain method deletes parts of this array (via Numeric.compress ) > > Rings a bell for someone?? I'd like to apply my SEP[1] field and say this is likely to be a bug in Numeric. Not sure though. Can you try just pickling & unpickling a Numeric.array that has had bits chopped out of it with .compress()? Cheers, M. [1] Someone Else's Problem: I'm a developer on the Python project, but not NumPy :) -- A difference which makes no difference is no difference at all. -- William James (I think. Reference anyone?) From sismex01 at hebmex.com Mon Nov 18 10:15:51 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 18 Nov 2002 09:15:51 -0600 Subject: Pythoncal, anyone? (My (late) beef with Simple Generator syn tax (PEP 255)) Message-ID: > From: Greg Ewing [mailto:see_reply_address at something.invalid] > Sent: Sunday, November 17, 2002 8:27 PM > > I have an idea: Suppose there were a "don't" > statement that could be put in front of another > statement to, effectively, comment it out, > e.g. > > def foo(): > # This function does nothing > don't print "Hello" > > Then an empty generator could be written > > def g(): > don't yield None > > Now, since this isn't going to do anything, > it should be permissible to omit any expressions > that would otherwise be required in a statement > covered by a "don't", leaving just > > def g(): > don't yield > Yeah, and let's create a "mesh" operator, and a "worm", and "rabbit-ears", and "wax-wane", and ... :-) Been reading too much intercal, eh? ;-) -gustavo From nhodgson at bigpond.net.au Thu Nov 7 06:49:46 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Thu, 07 Nov 2002 11:49:46 GMT Subject: "Universal Gateway" References: <1y63gc02.fsf@morpheus.demon.co.uk> Message-ID: Thomas Heller: > With this module available, and an additional com foundation > which is included in it's test directory, Neil's sample > can be written in this way: That's much nicer than my code. > I didn't advertise my ctypes module, because the documentation is not > yet complete, and I probably don't have the time to support it. It can take a lot of time to support open source code but this deserves wider distribution. If I was working on Windows (I'm currently stuck on Linux) I'd certainly want to use this module as it moves beyond calldll allowing much clearer and maintainable code. A good improvement would be to read type libraries to build the message lists and argument descriptions. Neil From gumuz at looze.net Wed Nov 13 05:01:22 2002 From: gumuz at looze.net (Gumuz) Date: Wed, 13 Nov 2002 11:01:22 +0100 Subject: python gui rant References: <3dd217e2$0$231$4d4ebb8e@news.nl.uu.net> Message-ID: <3dd22136$0$229$4d4ebb8e@news.nl.uu.net> that's not such a bad idea! imho, delphi has the best IDE of all rad's i've seen. thanks for the suggestion "Bengt Richter" wrote in message news:aqt734$r6j$0 at 216.39.172.122... > I wonder if anyone has written a translator for this information to port a GUI design > into wxWindows or tkinter. The Delphi IDE is quite nice for fiddling with your visual > design (other aspects of Delphi are nice too, but that's another topic). > > Regards, > Bengt Richter From mhammond at skippinet.com.au Tue Nov 19 06:54:38 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 19 Nov 2002 11:54:38 GMT Subject: Will python binaries compiled on vs.net? In-Reply-To: References: Message-ID: <2EpC9.16894$nK4.44372@news-server.bigpond.net.au> Thomas Heller wrote: > Thomas Heller writes: >>Mark Hammond writes: >> >> >>>I simply like the VC6 UI better. I have a full VC7 installed here, >>>but never use it. >>> >> >>Same for me, but one thing annoys me: if an access violation is raised >>or a breakpoint encountered, now VC7 pops up (after asking several >>questions) if I press the cancel button in the message box to debug >>the application. >> >>So my question is: How can I restore the debugger from VC6 to be the >>default again? > > > Found it myself :-) > > The path to the debugger is stored in HKLM\Software\Microsoft\Windows > NT\CurrentVersion\AeDebug, in a value named Debugger. Fortunately > MSVC7 saved the value from VC6 as PreVisualStudio7Debugger, so it was > easy to restore. Exactly what I did ;) Much happier now :) Mark. From hjwidmaier at web.de Tue Nov 5 00:49:22 2002 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: 4 Nov 2002 21:49:22 -0800 Subject: Tkinter disregards font encoding References: <6e990e29.0211040009.33127f7@posting.google.com> Message-ID: <6e990e29.0211042149.2768fb11@posting.google.com> loewis at informatik.hu-berlin.de (Martin v. L?wis wrote in message news:... > What is the value of self.priceVar? It's a (normal) string. > Here is my theory: you are using a Latin-1 locale, and use a byte > string for the priceVar, where you use '\xe4' to denote the EURO SIGN. > However, in Latin-1, '\xe4' denotes the CURRENCY SIGN. Tk tries to > convert the local encoding (latin-1) into the font encoding (latin-9); > since latin-9 does not support the CURRENCY SIGN, this conversion > fails. My locale is set to 'de_DE at euro', which ought to result in using Latin-9. (At least that's what I thought.) I just tried my program on my box at work, and, without any changes, I got a euro sign. Sigh. > Instead, you should use a Unicode string to denote the EURO SIGN, > which would be u'\u20ac'. I'll try that. Thanks. Hans-Joachim From fredrik at pythonware.com Sat Nov 9 11:25:59 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 09 Nov 2002 16:25:59 GMT Subject: re.sub() bug? References: <3dcb7ea6$1_4@omega.dimensional.com> Message-ID: Mike Brown wrote: > Python 2.2.1 on FreeBSD. > These work as expected: > > >>> re.sub(u'f', u'b', u'foo') # keep string as Unicode > u'boo' > >>> re.sub(u'f', u'b', 'foo') # coerce string to Unicode > u'boo' > > But this doesn't work the way I'd think it would: > > >>> re.sub(u'f', u'b', u'') # coerce string to non-Unicode?! > '' > > So, is this a bug? It's a buglet, sure. But if you write code that depends on this difference, your code is a lot more fragile (and less future-proof) that it should be. Python's Unicode system allows you to mix Unicode strings with standard strings, as long as the latter contain only ASCII characters. Good practice is to make sure your code is as tolerant as Python. (or to put it another way, write code that does the right thing if an operation returns a Unicode string instead of the corresponding ASCII string, and likewise, if a function that usually returns a Uni- code string returns an ordinary string instead). Standard strings containing non-ASCII data is a different thing; they're encoded, and should be seen as binary buffers. From schond at eecs.ku.edu Wed Nov 27 20:08:42 2002 From: schond at eecs.ku.edu (David Schonberger) Date: Wed, 27 Nov 2002 19:08:42 -0600 (CST) Subject: a simple question about class composition Message-ID: <20021127190730.L17081-100000@tesla.eecs.ku.edu> I have the following two class definitions in a file called myclass.py: ###begin### class MyClass: def __init__(self, txt): self.text = txt def printText(self): print "Text for MyClass " + str(self.text) + "\n" class MyOtherClass: def __init__(self,txt): self.text = txt def printText2(self): print "Twice the text for MyOtherClass " + str(2*self.text) + "\n" ###end### I then have the following code in a file called mycontainerclass.py: ###begin### from myclass import * class MyContainerClass: def __init__(self, txt): self.text = txt self.one = MyClass(" I like Vanilla Coke") self.two = MyOtherClass("I like Classic Coke") def printContainerText(self): print "Container class text " + str(self.text) + "\n" def invokePrint(self): self.one.printText() self.two.printText2() if __name__ == "__main__": myobj = MyContainerClass("I like both Vanilla Coke and Classic Coke") myobj.invokePrint() myobj.printContainerText() ###end### When I try to run this code for MyContainerClass I get the following error: ###begin### Traceback (most recent call last): File "C:/Python22/mycontainerclass.py", line 18, in ? myobj = MyContainerClass("I like both Vanilla Coke and Classic Coke") File "C:/Python22/mycontainerclass.py", line 7, in __init__ self.two = MyOtherClass("I like Classic Coke") NameError: global name 'MyOtherClass' is not defined ###end### Any idea what is happening? I came across similar code in Lutz's "Learning Python" (a good three years old; perhaps this is part of the problem). I am running Python 2.2.1 on Win2K but have run into the same problem on Linux. Note that if I comment out the stuff about MyOtherClass in MyContainerClass--i.e. the stuff having to do with self.two--everything works fine, with MyClass successfully embeded in MyContainerClass. Any help would be appreciated. Thanks. Regards, David *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* * David Schonberger * * Department of Electrical Engineering and Computer Science * * University of Kansas * * email: schond at eecs.ukans.edu * *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* From mgarcia at cole-switches.com Thu Nov 14 16:58:02 2002 From: mgarcia at cole-switches.com (Manuel M. Garcia) Date: Thu, 14 Nov 2002 21:58:02 GMT Subject: Open and reading a file... References: Message-ID: <3468tuokdjcbr1qv9r96m7sflvana7too4@4ax.com> On Thu, 14 Nov 2002 16:12:41 -0500, "Marlon Rea" wrote: > Can someone help me with opening and reading a file???? THANK YOU ALL Wow. A perfect example of its kind. I found this as well: >From: "Marlon Rea" >Newsgroups: alt.os.windows2000 >Subject: Re: Title Bar Has Gone Missing??? >Date: Tue, 5 Nov 2002 15:39:28 -0500 > > >When is dought re-boot. > > >"Mona Suitter" wrote in message >> My title bar has gone missing???? How do I get it back? Do I have to >> reinstall Windows?? >> Any info would be greatly appreciated!!! >> Thanks! >> Mona :) Incredible... The blind leading the blind. Anyway... ***NOT TESTED, TRY AT YOUR OWN RISK!!!*** for x in open('read.txt').readlines(): print x From claird at lairds.com Fri Nov 8 11:39:21 2002 From: claird at lairds.com (Cameron Laird) Date: Fri, 08 Nov 2002 16:39:21 -0000 Subject: slow on HPUX, SunOS, fast on MS Win2K and Linux? References: Message-ID: In article , Ian Parker wrote: . . . >In a previous incarnation as a datacentre manager, I was increasingly >embarrassed that of all the "serious" machines in our datacentre (Sun, >IBM and HP, Compaq Alpha) only the some of Compaq Alphaservers were >faster, CPU for CPU, than the recent Intel boxes. We bought the >"serious" machines for more for their multiprocessing, large memory, i/o >bandwidth or even OS (e.g. for VMS or Tru64 UNIX clustering). . . . This is somehow even more so for mainframes, whose CPU performance for decades has been mediocre, but which remain champs at moving data around. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From support at internetdiscovery.com Fri Nov 15 16:17:04 2002 From: support at internetdiscovery.com (Mike Clarkson) Date: Fri, 15 Nov 2002 21:17:04 GMT Subject: lisp scheme lush python etc. References: <9a6d7d9d.0211120754.5245cc65@posting.google.com> Message-ID: <3dd56449.9609081@nntp.ix.netcom.com> On 12 Nov 2002 07:54:01 -0800, aaron at reportlab.com (Aaron Watters) wrote: >I abandoned Lisps and scheme for Python about a decade ago >(with misgivings) primarily because > 0) portability and stability > 1) libraries and portable extension framework > 2) it's friendly to other software > (from above and below and anywhere else) > 3) the syntax doesn't stink > (but if it was done over I'd add brackets) > 4) it's easy enough for noneggheads > 5) Everything I liked to do that was easy > in Lisps was also easy (and clearer too) in > Python. (ymmv) >It seems to me that most similar languages still >fail on at least one of the above. (1,3,5) are very >much judgement calls, of course. > >The major thing that is missing, of course is some sort of >(optional, inferred) type checking. I'm also getting >nervous about bloat... What would be really interesting would be a Lython -a Python written in Common Lisp, like Jython is written in Java. I think Lisp would be as good a language as Java for writing an intepreter, and there might be good performance from Lython given the very good native code compilers that are available for Lisp. It would give Lisp another lease on life, would prove the portability of Python again, and would expose the Python community to some of the first class type inferencing and optimizations made by Lisp compilers (for example the compiler called 'Python' in CMU Lisp). Mike. From bondpaper at earthlink.net Wed Nov 6 21:02:18 2002 From: bondpaper at earthlink.net (Tom) Date: Thu, 07 Nov 2002 02:02:18 GMT Subject: Long overflow problem References: Message-ID: In article , Fernando Perez wrote: > Tom wrote: > > > > def myFunc (i, j): > > for a in range(i, j): > > print a > > > > I get the same error. Are there any implicit conversions going on here? > > Yes, the problem is that range() doesn't accept longs. You can consider it a > bug, but it's a feature :) > > The quick fix is to do 'for a in range(j-i)' instead, and operate with 'i+a' > instead. > > Cheers, > > f Ok...it's a range issue. And in addition to your suggestion, I just realized....a simple "while i < j..." would have sufficed. Amazing how the simplest answers take the longest to figure out sometimes. : ) Regards, Tom From loewis at informatik.hu-berlin.de Tue Nov 5 05:45:33 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 05 Nov 2002 11:45:33 +0100 Subject: UDP broadcasts => 'Permission denied' References: Message-ID: Alexandre Fayolle writes: > However, it could be interesting to provide more information for people > using non-unix systems where these manpages are not easily available. Most definitely. The current state is the direct result of contributors not having the energy to elaborate more, and thus refer to existing documentation whereever possible. Referring to existing documentation is a good thing, especially as the behaviour might change across systems. However, contributions to improve the documentation would be most welcome. Contributors should phrase the documentation carefully to point out potentially differences in behaviour across systems. E.g. the set of errno values you can get from a specific system call can vary, as does the set of available socket options, fcntl functions, etc. Regards, Martin From kkto at csis.hku.hk Wed Nov 27 22:51:51 2002 From: kkto at csis.hku.hk (Isaac To) Date: 28 Nov 2002 11:51:51 +0800 Subject: if : References: <3DE4102D.7D4291F4@alcyone.com> <3DE58723.5040306@something.invalid> <3o3buus1f8kv1psdps2nsq3ed8ltq5ece8@4ax.com> Message-ID: <7iof8a1hd4.fsf@enark.csis.hku.hk> >>>>> "Courageous" == Courageous writes: >> This is a special case of the general principle that it's usually >> clearer if expressions don't have side effects. Courageous> Oh, quite true! As a general rule of thumb, I consider Courageous> expressions with side effects to be bad coding practice. I Courageous> don't mind at all that Python doesn't allow them. How about if Python disallow functions to do anything "with a side effect"? After all, function calls are expressions. Regards, Isaac. From aahz at pythoncraft.com Mon Nov 18 09:32:41 2002 From: aahz at pythoncraft.com (Aahz) Date: 18 Nov 2002 09:32:41 -0500 Subject: Pythoncal, anyone? (My (late) beef with Simple Generator syntax (PEP 255)) References: <3DD84FDA.3010708@something.invalid> Message-ID: In article , Skip Montanaro wrote: > Greg> I have an idea: Suppose there were a "don't" statement that could > Greg> be put in front of another statement to, effectively, comment it > Greg> out, > >Dunno if your suggestion is serious, but if so, you could extend the pass >statement, yes? Re-read the Subject: line. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From bokr at oz.net Thu Nov 14 04:29:21 2002 From: bokr at oz.net (Bengt Richter) Date: 14 Nov 2002 09:29:21 GMT Subject: pythonic way to optimize access to imported value? References: <3DD1AB92.3030409@something.invalid> <3DD2E9A0.8050500@something.invalid> Message-ID: On Thu, 14 Nov 2002 13:09:04 +1300, Greg Ewing wrote: >Bengt Richter wrote: > >> Plus that version retains a reference to math, where I'd like to think that >> I would wind up with just a reference to a double with the 3.14.. value. I.e., >> def foo(pi = math.pi): >> return pi > > >Yes, that's probably what I should have written. > >> Also I think I would like a keyword that governs >> a block scope instead of just the scope of an assignment. E.g., >> >> def foo(): >> predef: >> import math >> pi = math.pi >> del math >> seven = 7 >> return pi, seven > > >Too complicated. You could get the same effect by putting the >code outside the def: > > from math import math_pi did you mean from math import pi as math_pi ? > > def foo(): > const pi = math_pi > const seven = 7 > ... > > del math_pi Not quite the same effect: you are introducing temporary global bindings. And ISTM your version really only looks less complicated because you moved two statements out of the local scope. To avoid the global temp, I suppose you could write def foo(): const pi = [__import__('math')][0].pi const seven = 7 but down that road lies much abuse, trying to cram block scope intentions into expression scope. I don't think it's possible to anticipate what people will want to do, except that people will tend to work around limitations in ugly ways if there's no clean way to express their intent. So I'd rather provide a freer "scope" ;-) BTW, I'd suggest "preset" as closer to the semantic mark than "const" if your proposal gets adopted. Maybe my block introducer should similarly be "presets:". Then for minimal one-liner usage, it would look concise and similar def foo(): presets: seven = 7 ... vs. def foo(): const seven = 7 ... or def foo(): preset seven = 7 ... I like the option of simple multiple values on a single line too. def foo(): presets: seven = 7; eight = 2**3 ... Regards, Bengt Richter From BPettersen at NAREX.com Wed Nov 20 15:43:55 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Wed, 20 Nov 2002 13:43:55 -0700 Subject: Permuting data Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019201BFD7DC@admin56.narex.com> > From: user at domain.invalid [mailto:user at domain.invalid] > > Hi, > I have encountered a following problem: I need to permute > randomly 200 > lines of data 100 times... Meaning that each iteration, data > lines are > in the random order. What would be the proper way to do it? Module: random, Function: shuffle. -- bjorn From fgeiger at datec.at Fri Nov 22 02:48:39 2002 From: fgeiger at datec.at (F. GEIGER) Date: Fri, 22 Nov 2002 08:48:39 +0100 Subject: [wxPython] I'd like to catch mouse click events within a textcontrol References: <3ddd24d9@news.swissonline.ch> Message-ID: <3ddde146@news.swissonline.ch> Thanks for the info, Cliff, and for the sample code. Perfect. Stupid me: After all a textCtrl is a window... Kind regards Franz "Cliff Wells" schrieb im Newsbeitrag news:mailman.1037919514.18620.python-list at python.org... On Thu, 2002-11-21 at 10:24, F. GEIGER wrote: > I'd like to catch mouse click events within a text control and then read the > mouse pointer position. Alas, the only events I found in the dox are, > EVT_TEXT, EVT_TEXT_ENTER, EVT_TEXT_URL, EVT_TEXT_MAXLEN. Those events are specific to the wxTextCtrl, but you can also use the events that are common to *all* controls: from wxPython.wx import * class ClickableText(wxTextCtrl): def __init__(self, parent, id): wxTextCtrl.__init__(self, parent, id) EVT_LEFT_DOWN(self, self.OnClick) def OnClick(self, event): print event.GetX(), event.GetY() raise SystemExit app = wxPySimpleApp() frame = wxDialog(None, -1, "Test") text = ClickableText(frame, -1) frame.ShowModal() -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From max at alcyone.com Mon Nov 18 05:22:38 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 18 Nov 2002 02:22:38 -0800 Subject: 'for' loop in python, error: unsubscriptable object References: <7913deb3.0211180155.4a243cdf@posting.google.com> Message-ID: <3DD8BF6E.6D53930B@alcyone.com> george wrote: > for max in range[CLA, RBW, BAG, MRB, NOG]: This is not what you meant. You're treating range (which is a builtin function) as a mappable object, and subscripting it with a tuple. I'm not quite sure what you meant to do, but that sure wasn't it. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ The great artist is the simplifier. \__/ Henri Amiel CSBuddy / http://www.alcyone.com/pyos/csbuddy/ A Counter-Strike server log file monitor in Python. From grante at visi.com Wed Nov 27 10:57:51 2002 From: grante at visi.com (Grant Edwards) Date: 27 Nov 2002 15:57:51 GMT Subject: do you guys help newbies?? References: Message-ID: <3de4eb7f$0$22216$a1866201@newsreader.visi.com> In article , malik m wrote: > #initialize variables > totalMilesDriven = 0 #total miles driven > > totalGallonsPerTank = 0 #total gallons per tank > > counter = 0 #bogus counter Here's a style hint: Get rid of the comments above. 0) It's obvious you're initializing variables. No comment required. 1) You picked good names for the variables, so the comments describing the variables are just distractions. -- Grant Edwards grante Yow! Were these parsnips at CORRECTLY MARINATED in visi.com TACO SAUCE? From peter at engcorp.com Sat Nov 16 12:51:50 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 16 Nov 2002 12:51:50 -0500 Subject: quick question References: <20021116120631.08993.00000062@mb-fo.aol.com> Message-ID: <3DD685B6.DF1C65FF@engcorp.com> Bwfc10 wrote: > > Thank you for your help, it isn't > homework but whats wrong with > me asking on here when i do get homework? "Give a man a fish and you feed him for a day. Teach a man to fish and you feed him for a lifetime..." Nothing "wrong" from our point of view, except the feeling we might be participating in activity that is actually detrimental to your own development. Isn't one supposed to do one's homework by oneself, generally, to benefit from the learning involved? >From your point of view, the "wrong" would obviously be if you got a detailed answer which showed you *exactly* how to do it, or even included actual code, rather than merely pointing you in the right direction. For example, your request was quite acceptable, but the best response would be just "have you looked at the sort() method for lists?". If you were then to experiment with sort, and you were reasonably bright, you would quickly figure out a way to use it to find the most popular flavour of ice cream. If that answer were not enough for you, the next good answer would probably be something like "have you worked through the online tutorial yet?". A better way of asking these questions is to try to come up with your own solution, and then post your best attempt with the question. That way people can (a) help you along the path you've already chosen (if it could work), and (b) get a feeling that you've taken more than two seconds to think about this and that you've actually *tried*. Of course, this group being what it is, someone will almost always post a fully functional solution with annotated source without even questioning whether that will hurt you more than it will help. ;-) I actually find that a little sad, personally... -Peter From paska at kios.sk Fri Nov 8 03:42:59 2002 From: paska at kios.sk (Stano Paska) Date: Fri, 08 Nov 2002 09:42:59 +0100 Subject: string.strip Message-ID: <3DCB7913.8000801@kios.sk> Hi, in documentation: string.strip(s[, chars]) but in real life strip takes only 1 parameter I have python 2.2.2 Stano. From tjreedy at udel.edu Mon Nov 4 00:45:43 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 4 Nov 2002 00:45:43 -0500 Subject: can't assign value to array element References: Message-ID: "Joe Heafner" wrote in message news:HoCdnRcDleGnR1igXTWcqg at ctc.net... > y = zeros(m, Float) y is now array of m 0.0 > y[0] = b reset first value to b > > for j in range(0,m,1): ... > y = y[j] y is now a float. This cannot be what you meant to do > y[j+1] = y+(k1+2.*k2+2.k3+k4)/6. cannot index a float, hence message > When run, this code give the error "TypeError: object does not support > item assignment" for hte next to last line. I presume the last line would > give the same error. Yes, but only because you did same thing of rebinding name 't' to a float. > What am I doint wrong? I'd appreciate any help. Figure out what really want to do with t and y. I suspect you want tj = t[j] yj= y[j] and use tj and jy in code that follows in loop. Terry J. Reedy From lac at strakt.com Sat Nov 30 05:05:12 2002 From: lac at strakt.com (Laura Creighton) Date: Sat, 30 Nov 2002 11:05:12 +0100 Subject: Newbie Question: Aborting a Python script In-Reply-To: Message from Tom Nunamaker of "Sat, 30 Nov 2002 03:44:51 CST." References: Message-ID: <200211301005.gAUA5Cen015458@ratthing-b246.strakt.com> > How do you stop a script during execution? Do I have to throw an error > like a divide by zero? I didn't see any abort, stop, halt, etc type of > function. > > Thanks > > Tom > -- > http://mail.python.org/mailman/listinfo/python-list You want sys.exit. See http://www.python.org/doc/current/lib/module-sys.html Laura Creighton From drewp at bigasterisk.com Sat Nov 2 20:45:41 2002 From: drewp at bigasterisk.com (Drew Perttula) Date: 2 Nov 2002 17:45:41 -0800 Subject: tkinter bug? tk bug? References: Message-ID: <18f7875.0211021745.636774fe@posting.google.com> "Michael Bakkemo" wrote in message news:... > I am not sure where things are going wrong, but binding to the "" and > "" TK events seems to work fine except for the right side > control and alt keys: the event hands me the correct values, but the > event hands me the left side values. To wit: # I made the code a lot shorter. I assume this still exhibits the error: import Tkinter def KeyDown(ke): print "keydown:", ke.keysym_num, ke.keycode, ke.keysym def KeyUp(ke): print "keyup:", ke.keysym_num, ke.keycode, ke.keysym root = Tkinter.Tk() root.bind("", KeyDown) root.bind("", KeyUp) root.mainloop() > gives me the following when the right side Alt and Control keys are pressed > and released. > > >>> > keydown: 65514 18 Alt_R > keyup: 65513 18 Alt_L > keydown: 65508 17 Control_R > keyup: 65507 17 Control_L > > > My question is, where (what level) are things going wrong? I doubt it is my > code (but hey, what do I know) tkinter? the tk level? my keyboard driver? > With the code above, I get good behavior on left and right control, alt, and shift. Have you tried the 'xev' utility? That would help you separate a symbol list typo in tk, etc, from a funny keyboard mapping in your windowing system. -Drew From schaffer.SPAM at optonline.net Fri Nov 1 12:52:28 2002 From: schaffer.SPAM at optonline.net (Les Schaffer) Date: Fri, 01 Nov 2002 12:52:28 -0500 Subject: Wrapping a .dll under windows with SWIG References: <8beb91f5.0210312226.7eb08c08@posting.google.com> Message-ID: Ben C wrote: > Hi there, > > I want to wrap a .dll under windows and have access to it's functions > etc. The problem is that all I have is the .dll and header file ... no > source ... i've successfully wrapped DLL files sans .lib files, by using function pointer table and LoadLibrary() / GetProcAddress(). see the swig stuff for the PyGoldMine library at: http://sourceforge.net/projects/pygoldmine/ http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/pygoldmine/PyGoldMine/SWIG/ http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/pygoldmine/PyGoldMine/SWIG/gm5s32.i?rev=1.1&content-type=text/vnd.viewcvs-markup Les Schaffer From Oschler at earthlink.net Sat Nov 9 20:33:22 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sun, 10 Nov 2002 01:33:22 GMT Subject: [Jython] out of memory during jythonc compilation Message-ID: I tried to compile a python file using the following options: jythonc --deep --jar new.jar new.py After cranking away for several minutes, it terminated with an "out of memory" message, and suggested increasing the heap size with the "-mx" option. I then tried: jythonc -J-mx1000000 --deep --jar new.jar new.py And got the same error. I then tried 50M instead of 1M for the heap size and still go an "out of memory" error. new.py pulls in the Jython XML package structure, and the memory error always occurs right after "processing codecs". Anybody know what I might be able to do about this? thx From jdhunter at ace.bsd.uchicago.edu Tue Nov 19 05:09:43 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 19 Nov 2002 04:09:43 -0600 Subject: Simple Encryption In-Reply-To: ("Bronek Carr"'s message of "Tue, 19 Nov 2002 09:26:18 -0000") References: Message-ID: >>>>> "Bronek" == Bronek Carr writes: Bronek> Hi all, I am trying to write a simple ROT-13 encryption Bronek> script in python. A good starting point would be a Bronek> function which gets the ascii value of a character in a Bronek> string. I would assume this function already exists in Bronek> one of the packages, as it does in every other language I Bronek> use. I cannot find it if it does, can anyone help me. ord is what you want: >>> ord('a') 97 It's inverse is chr: >>> chr(ord('a')) 'a' Not to stop you from having fun, but just wanted to let you know that rot13 is a built-in string encoding in recent versions of python >>> 'abc'.encode('rot13') 'nop' John Hunter From CousinStanley at HotMail.com Wed Nov 20 10:54:54 2002 From: CousinStanley at HotMail.com (Cousin Stanley) Date: Wed, 20 Nov 2002 08:54:54 -0700 Subject: quick question References: <20021116051220.01520.00000047@mb-bk.aol.com> Message-ID: John ... Your counter class seems to work the best on my machine of all the versions we've been through thus far running about almost 30% faster than the original normal loop version ... Using the ~260,000 record [ 2.6 MB ] IceCream.txt file as input ... 8.84 Seconds ... Original Normal Loop 5.39 Seconds ... Original Normal Loop Psyco 8.29 Seconds ... JH Map Psyco 6.31 Seconds ... class counter 4.01 Seconds ... class counter Psyco 32.46 Seconds ... class counter letter freq 11.20 Seconds ... class counter letter freq Psyco These results are under Win98 First Edition using a 250 MHz processor ... The counter class code is nice and simple and I think that applying the read() method to the file to automagically end up with input byte value frequencies is pretty slick ... I haven't checked the Python CookBook yet to see if anything similar to your counter class is available there or not, but if it isn't, it should be ... I think it's also worthwhile to emphasize the Psyco binding improvements in all cases here, especially as shown in the last 2 tests in the list above where the Psyco version improvement is dramatic and that is achieved with a single line of code ... Thanks again for your help and feedback ... Cousin Stanley From max at alcyone.com Tue Nov 12 20:03:01 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 12 Nov 2002 17:03:01 -0800 Subject: total and utter newbie References: <3DD1A2F3.1040802@cyberspace.org> Message-ID: <3DD1A4C5.F5AE0857@alcyone.com> trewornan wrote: > Is there anything like a cast in Python? Just out of interest. Casting can mean different things; certainly Python has conversion functions, such as int, str, float, long, etc. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ God said: "Let Newton be"; and all was light. \__/ Alexander Pope Blackgirl International / http://www.blackgirl.org/ The Internet resource for black women. From bokr at oz.net Mon Nov 25 21:00:53 2002 From: bokr at oz.net (Bengt Richter) Date: 26 Nov 2002 02:00:53 GMT Subject: Issue with new-style classes and operators References: <3DE215D1.D9A3FEF9@jandecaluwe.com> Message-ID: On Mon, 25 Nov 2002 18:36:45 -0500, "Terry Reedy" wrote: > >"Jan Decaluwe" wrote in message >news:3DE215D1.D9A3FEF9 at jandecaluwe.com... >> Hi: >> >> I'm confused by the following behavior of new-style classes >> and operators: > >I think you have a right to be. > >> >> class MyInt(object): >> def __init__(self, val): >> self.val = val >> def __getattr__(self, attr): >> return getattr(self.val, attr) > >> >>> a = MyInt(3) >> >>> a.__add__(4) >> 7 > >This works because '__add__' is seen as just an attribute name, >nothing special, which is resolved because of __gettattr__ booting >attribute lookup to self.val. As far as the interpreter is concerned, >this might as well have been a.whatever(4). > >> >>> a + 4 >> Traceback (most recent call last): >> File "", line 1, in ? >> TypeError: unsupported operand types for +: 'MyInt' and 'int' > >Lookup of special methods invoked by syntax other than explicit >instance.attr appears to have been changed for new classes by stopping >the lookup process before calling __getattr__. > >This appears to contradict the current new-class doc at >http://python.org/2.2/descrintro.html > >"Note that while in general operator overloading works just as for >classic classes, there are some differences. " > >Which are...? > >"(The biggest one is the lack of support for __coerce__; new-style >classes should always use the new-style numeric API, which passes the >other operand uncoerced to the __add__ and __radd__ methods, etc.) " > >what else? but then > >"There's a new way of overriding attribute access. The __getattr__ >hook, if defined, works the same way as it does for classic classes: >it is only called if the regular way of searching for the attribute >doesn't find it. But you can now also override __getattribute__, a >new operation that is called for *all* attribute references." > >But you found a difference in __getattr__. Contrary to inplication of >doc, __getattribute__ is also not called for a+4. (Not a big loss >since attempt to access any attribute, including .__dict__, causes >infinite loop.) I opened sf bug report 643841. > >>I don't think is can be the intention. Or can it? > >Beats me. We'll see. > Adding some print statements: Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class MyClassicInt: ... def __init__(self, val): ... self.val = val ... def __getattr__(self, attr): ... attv = getattr(self.val, attr) ... print '--(old)--\n%s => %s\n%s\n--' % ( ... attr, attv, attv.__doc__ ) ... return getattr(self.val, attr) ... >>> class MyInt(object): ... def __init__(self, val): ... self.val = val ... def __getattr__(self, attr): ... attv = getattr(self.val, attr) ... print '--(new)--\n%s => %s\n%s\n--' % ( ... attr, attv, attv.__doc__ ) ... return getattr(self.val, attr) ... >>> ci = MyClassicInt(3) >>> ci.__add__(4) --(old)-- __add__ => x.__add__(y) <==> x+y -- 7 >>> ci + 4 --(old)-- __coerce__ => x.__coerce__(y) <==> coerce(x, y) -- 7 >>> ni = MyInt(3) >>> ni.__add__(4) --(new)-- __add__ => x.__add__(y) <==> x+y -- 7 >>> ni + 4 Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand types for +: 'MyInt' and 'int' >>> Either way, the code looks different for the two cases: >>> from ut.miscutil import disev >>> disev('ci.__add__(4)') 0 SET_LINENO 0 3 LOAD_NAME 0 (ci) 6 LOAD_ATTR 1 (__add__) 9 LOAD_CONST 0 (4) 12 CALL_FUNCTION 1 15 RETURN_VALUE >>> disev('ci + 4') 0 SET_LINENO 0 3 LOAD_NAME 0 (ci) 6 LOAD_CONST 0 (4) 9 BINARY_ADD 10 RETURN_VALUE But apparently BINARY_ADD reacts differently to being supplied with classic vs new style object as an argument together with int. Apparently, with a classic object it tries to get a __coerce__ method. Note that what comes back from getting the __add__ attribute from an object *instance* is a bound method that acts like a callable object, and since the attribute is gotten from self.val, which is an integer, the associated object is an integer, even though the __getattr__ was supposedly a method of MyInt. Hence passing the bound method an integer to add naturally works. An this works the same for both types, when the attribute access is explicit. When the __coerce__ method is returned, it is similarly bound to the self.val value which is an int instance. So the coerce works. If there is an actual __add__ method in the class, it is found before __getattr__ is tried for the new-style class: >>> def add(x,y): ... print 'adding %s + %s' % (`x`,`y`) ... return x.val + y ... >>> MyInt.__add__ = add >>> ni + 4 adding <__main__.MyInt object at 0x007D7BB0> + 4 7 (Note that __repr__ is found without resort to __getattr__ above). But binary add works differently for the old: >>> MyClassicInt.__add__ = add >>> ci + 5 --(old)-- __coerce__ => x.__coerce__(y) <==> coerce(x, y) -- 8 The coerce succeeded and MyInt.__add__ never got involved. Of course, explicitly you get there: >>> ci.__add__(6) --(old)-- __repr__ => x.__repr__() <==> repr(x) -- adding 3 + 6 9 And of course, we mustn't be fooled by the names: >>> b = MyInt('bbb') >>> b.__add__('x') adding <__main__.MyInt object at 0x00839730> + 'x' 'bbbx' >>> b + 'x' adding <__main__.MyInt object at 0x00839730> + 'x' 'bbbx' >>> del MyInt.__add__ >>> b + 'x' Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand types for +: 'MyInt' and 'str' >>> b.__add__('x') --(new)-- __add__ => x.__add__(y) <==> x+y -- 'bbbx' Regards, Bengt Richter From aleax at aleax.it Tue Nov 19 11:19:18 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 19 Nov 2002 16:19:18 GMT Subject: Python embedding question: how to expose a new "builtin"? References: Message-ID: Rodrigo B. de Oliveira wrote: > I've built an ISAPI module that allows .py files to be executed by IIS, > everything is working fine and the performance is great. Now I want to > expose an object in such a way that every imported module could see it, I > tried the following code but it didn't quite work: > > > > PyObject* __builtin__ = PyImport_ImportModule("__builtin__"); > PyObject_SetAttrString(__builtin__, "application", > (PyObject*)_pyapplication); Py_DECREF(__builtin__); > > This looks to me like the correct way to do what you ask. > Notes: > * _pyapplication is an instance of a C new style class What IS "a C new style class"...? > The problem is: the modules can see the name "application" but > dir(application) returns [] and if I try to access any of application's > attributes I get an AttributeError. > > Thoughts? Looks to me like the problem is with the _pyapplication object rather than with the exposing of it in the built-ins module. What happens if you architect another way to let Python code get at that same object? Does "is" show the two ways give the same object, and what are the symptoms on e.g. dir for each? I think you should get the same results, confirming the problem is with the object and not with the way you're choosing to expose it. Alex From claird at lairds.com Mon Nov 4 21:10:22 2002 From: claird at lairds.com (Cameron Laird) Date: Tue, 05 Nov 2002 02:10:22 -0000 Subject: loggin out automatically References: <1036253358.19897.0@doris.uk.clara.net> <3DC718BE.7060706@cyberspace.org> Message-ID: In article <3DC718BE.7060706 at cyberspace.org>, trewornan wrote: >Cameron Laird wrote: >> >> So: did that make it clear? No, you cannot use >> system("logout") >> or a close variation to achieve what you want, but, >> yes, there are several Python-based ways to write it. > >Yes I think I understand that although it seems a convoluted way to go >about things. > >I couldn't find anything any in the linux documentation which could do >it - PAM etc just doesn't seem to be into it. > >Thanks for your help > >M > Say again what you want: is it automatically to limit one particular user to a fixed session length? Do you have a collection of users you want to limit? Do you want to intervene before each action, or have them hap- pen automatically? Are the users logging in through telnetd, sshd, ...? Are they X consumers? Precise understanding might reveal that this is less convoluted than it currently appears. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From mis6 at pitt.edu Tue Nov 5 13:10:34 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 5 Nov 2002 10:10:34 -0800 Subject: parenthesis References: <2259b0e2.0211041224.7c24635b@posting.google.com> Message-ID: <2259b0e2.0211051010.66af1168@posting.google.com> > Wondering why I didn't just write: > > >>> import re > >>> rx = re.compile(r'([()]|[^()]+)') > >>> class Addelim: > ... def __init__(self, delim): > ... self.parens=0; self.delim=delim > ... def __call__(self, m): > ... s = m.group(1) > ... if s=='(': self.parens+=1 > ... if self.parens==1 and s==')': > ... self.parens=0 > ... return s+self.delim > ... if s==')': self.parens -=1 > ... return s > ... > >>> exp = '(a*(b+c*(2-x))+d)+f(s1)' > > It was natural to be able to specify the delimiter. And the + is probably > better than the * on the non-paren "[^()]+" part of the pattern. Not really. My benchmark gives essentially the same for "[^()]+*" and "[^()]*", no sensible difference. > Then using \n as delimiter to break into lines one can just print it. > > >>> print rx.sub(Addelim('\n'),exp) > (a*(b+c*(2-x))+d) > +f(s1) > > Which you could also use like: > > >>> print rx.sub(Addelim('\n'),exp).splitlines() > ['(a*(b+c*(2-x))+d)', '+f(s1)'] > > Or to get back to your original requirement, > > >>> print rx.sub(Addelim('\n'),exp).splitlines()[0] > (a*(b+c*(2-x))+d) > > But I suspect it would run faster to let a regex split the string and then use > a loop like yours on the pieces, which would be '(' or ')' or some other string > that you don't need to look at character by character. E.g., > > >>> rx = re.compile(r'([()])') > >>> ss = rx.split(exp) > >>> ss > ['', '(', 'a*', '(', 'b+c*', '(', '2-x', ')', '', ')', '+d', ')', '+f', '(', 's1', ')', ''] > > Notice that the splitter matches wind up at the odd indices. I think that's generally true > when you put parens around the splitting expression, to return the matches as part of the list, > but I'm not 100% certain. Anyway, you could make use of that, something like: > > >>> > >>> parens = 0 > >>> endix = [] > >>> for i in range(1,len(ss),2): > ... if parens==1 and ss[i]==')': > ... parens=0; endix.append(i+1) > ... elif ss[i]=='(': parens += 1 > ... else: parens -= 1 > ... > >>> endix > [12, 16] > > You could break the loop like you did if you just want the first expression, > or you could grab it by > > >>> print ''.join(ss[:endix[0]]) > (a*(b+c*(2-x))+d) > > or list the bunch, > > >>> lo=0 > >>> for hi in endix: > ... print ''.join(ss[lo:hi]) > ... lo = hi > ... > (a*(b+c*(2-x))+d) > +f(s1) > > or whatever. Which is not as slick, but probably faster if you had to do a bi-ig bunch of them. > > I think when the fenceposts are simple, but you are mainly interested in the data between, splitting > on a fencepost regex and processing the resulting list can be simpler and faster than trying to > do it all with a complex regex. > > Regards, > Bengt Richter I strongly suspect that in this simple problem the simple approach is by far the fastest. Bye, Michele From jason at omeninternet.com.au Mon Nov 18 23:58:23 2002 From: jason at omeninternet.com.au (Jason Friedland) Date: Tue, 19 Nov 2002 15:58:23 +1100 Subject: AttributeError with 'time' module References: <3dd9c16f$0$16997$afc38c87@news.optusnet.com.au> Message-ID: <3dd9c3eb$0$13151$afc38c87@news.optusnet.com.au> Jason Friedland wrote: > Hi there > > I'm just starting out on Python so forgive me if this is a silly question. > > I am attempting to make use of the time module (RH 7.3, Python 2.2.2) > and keep receiving the following error: > > ---------------------- > AttributeError: 'module' object has no attribute 'strftime' > ---------------------- > > Upon running the script below: > > ---------------------- > import time > > def writeLogFile(message, file_name): > file_date = time.strftime('%a, %d %b %Y %H:%M:%S', \ > time.localtime(time.time())) > file_text = " - " + message > > try: > file = open(file_name, "a") > except: > print "Couldn't append to file!" > sys.exit() > > file.write(file_date) > file.write(file_text) > file.write("\n") > file.close() > ---------------------- > > I have checked out the time module info at > http://www.python.org/doc/2.2.2/lib/module-time.html but this appears to > be the correct usage. > > Is there something I'm missing here? > > TIA > > Jason Friedland > OK got it - there was a file named time.py in the same directory as the script I was trying to run. Tsk tsk... schoolboy error. Jason Friedland From martin at v.loewis.de Sun Nov 17 03:02:17 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 17 Nov 2002 09:02:17 +0100 Subject: Calling local functions from the C API References: Message-ID: Jon Parise writes: > def SomeFunction(): > pass > > ... gets evaluated by PyRun_RunString(). Later on, I'd like to call > SomeFunction from C (embedded Python interpreter). > > Is that still not possible without playing with stack frames and such? Ah, so you have a char* that has Python source code, and you want to run a specific function in it. For such questions, always ask yourself how you would achieve this effect in pure Python, and then you'll see how to do it in C. In Python, you could write d = {} exec sourcecode in d func = d['SomeFunction'] func() Now just do the same in C. Which of the four steps is unclear to you? Regards, Martin From markus.vonehr at ipm.fhg.de Fri Nov 29 07:35:28 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Fri, 29 Nov 2002 13:35:28 +0100 Subject: py2exe and PIL prob References: <3DE74619.497CB50C@ipm.fhg.de> Message-ID: <3DE75F10.A02DECB0@ipm.fhg.de> Now I've tried it with McMillans installer 5b4. No problems at all. Markus Markus von Ehr schrieb: > > Hi, > > I am opening an image using PIL with: > > from Image import * > > self.mi = open(filename) > > Everything is alright opening the images in two different programs. > After using py2exe I have two cases/errors: > 1. > > File "Tkinter.pyc", line 1285, in __call__ > File "corr.pyc", line 178, in openImage > File "Image.pyc", line 949, in open > File "Image.pyc", line 204, in init > File "ntpath.pyc", line 408, in abspath > File "imputil.pyc", line 98 in _import_hook > File "", line 52, in _import_top_module > File "imputil.pyc", line 207, in _import_top > File "imputil.pyc", line 258, in _import_one > File "", line 161, in get_code > File "Image.pyc", line 927, in open > ValueError: bad mode > > 2. > Another program: > Exception in TKinter callback > Traceback (most recent call last): > File "Tkinter.pyc", line 1285, in __call__ > File "BioChip.pyc", line 260, in Load > File "Image.pyc", line 960, in open > IOError: cannot identify image file > > So everything is OK with the unpacked program, but after using py2exe > it doesn't work any more. > What can I do then? I want to create a shipping version. > > Any hints? > > Markus From KZEMBOWER at jhuccp.org Wed Nov 13 13:10:22 2002 From: KZEMBOWER at jhuccp.org (KEVIN ZEMBOWER) Date: Wed, 13 Nov 2002 13:10:22 -0500 Subject: Raw Newbie: What's the " Thank you, Alan, holger and Simon, for all your help. The '%%' worked like a champ. It never occurred to me that the author of ezmlm-browse would have written his own template system. Thank you for removing this source of frustration. Some of the files in the system are copyright Bruce Guenter, so I'll write to him with any further questions. Thanks, again, for all your help. -Kevin Zembower >>> Alan Kennedy 11/13/02 12:37PM >>> KEVIN ZEMBOWER: >> I've found templates which look like this: >> >>
["%(type)s" not shown] >> >>
>> >>
%(markup_urls(html(body)))s
>> >> >> Obviously, this is python code embedded in HTML, very similar to php in >> HTML, with which I am more familiar. However, I can't find any >> references to the "> The specific problem I'm working on involves the line '
> width="640">'. I'd like to change the width to "100%", but the percent >> sign must be interpreted as a special character. It causes strange >> errors. I've tried escaping it with 'width="100\%"', but this doesn't >> seem to work, either. Any help on this small problem? I don't know for certain, but the "100%" may be being interpreted as a python "format string". See these urls for information on format strings. http://www.python.org/doc/current/tut/node9.html http://sandbox.mc.edu/~bennet/python/code/io.html IFF it is a format string, then the solution is to double up the % sign: i.e. express it like so "
". However, if that isn't the problem, I don't have any further suggestions to make. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan -- http://mail.python.org/mailman/listinfo/python-list From joost_vanrooij.net Mon Nov 18 11:05:59 2002 From: joost_vanrooij.net (Joost van Rooij) Date: Mon, 18 Nov 2002 17:05:59 +0100 Subject: file upload via http Message-ID: <3dd90ff4$0$46609$e4fe514c@news.xs4all.nl> Hello, I would like to upload a picture (generated by a webcam) to be uploaded to my website. I don't want to use the ftp protocol because of a firewall which only allows me to connect via http. I tried to do this using the code below but that didn't seem to work, can somebody help me out? Joost import httplib body = open("./image.jpg","r") headers = {"Content-type": "multipart/form-data", "Accept": "image/jpeg"} conn = httplib.HTTPConnection("www.server.net:80") conn.request("POST", "/showme/picture/upload.php",body , headers) response = conn.getresponse() print response.status, response.reason conn.close() From max at alcyone.com Mon Nov 4 07:59:43 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 04 Nov 2002 12:59:43 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Nov 4) Message-ID: QOTW: "This newsgroup is friendlier than most. We only require 5 hours of Googleing before you can ask a question! ;-)." Manuel M. Garcia "Python resists making major library decisions preferring to leave it to the individual, while Perl's 'first-through-the-gate-naming' wins the standard." Emile van Sebille "PyChecker is at revision 0.8.11, but don't let that fool you, it is very usable and finds an amazing array of Python coding errors." Manuel M. Garcia Articles and threads Barry A. Warsaw talks about the Python mailing list/newsgroup gateway problems which explain the erratic traffic for the past week or so: http://groups.google.com/groups?selm=mailman.1035997172.19952.python-list%40python.org Michael Hudson suggests an approach (and then an improvement) for doing interactive and iterative development, a sort of module reload on steroids which uses metaclasses: http://groups.google.com/groups?threadm=m2pttq8yaa.fsf%40python.net A question about the future of Jython results in informative and reassuring responses: http://groups.google.com/groups?threadm=3dc18ae0%240%2484941%24e4fe514c%40dreader4.news.xs4all.nl A question about "protecting" Python source from prying eyes leads to a discussion of the pros and cons of deliberate obfuscation vs. licensing: http://groups.google.com/groups?threadm=aq3dsg%24l0s%241%40news.netpower.no Software SpamBayes, a Python-based spam filtering solution which uses a Bayesian approach to analyzing incoming messages, has reached an early stage where it can be used, via the command line, a POP3 intermediary, or Outlook 2000: http://spambayes.sourceforge.net/ http://spambayes.sourceforge.net/applications.html PyNassi, a program structure chart editor and debugger written with and for Python, reaches version 1.2: http://www.ingo-linkweiler.de/diplom/ Albatross is a small, flexible Python system for developing stateful Web applications: http://www.object-craft.com.au/projects/albatross/ PiP attempts to wed python with PHP, in the form of a Python extension in PHP: http://www.csh.rit.edu/~jon/projects/pip/ Jeremy Hylton announces the final releases of ZODB 3.1, an object database for Zope that provides transactional persistence, and ZEO 2.0, a client-server system which uses it: http://www.zope.org/Products/StandaloneZODB http://www.zope.org/Products/ZEO http://sourceforge.net/projects/zodb Python-DSV is a module for importing and exporting delimiter separated values, a generalization of comma separated value (CSV) formats: http://python-dsv.sourceforge.net/ Psyche is an attempt to combine the best qualities of Python with those of Scheme (a Lisp-like language): http://www.xs4all.nl/~yduppen/site/psyche.html Resources Ironically, at PHPCon, it emerges that Rackspace, which heavily relied on PHP in getting off the ground, is converting a large portion of their code to Python (as reported in Jeremy Zawodny's Web log): http://jeremy.zawodny.com/blog/archives/000282.html The Python 2.3a0 development version of the documentation has been updated: http://www.python.org/dev/doc/devel/ ======================================================================== Everything 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 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 newly-revitalized newsgroup at least 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 summarizing action on the python-dev mailing list once every other week. http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect 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 Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ 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 Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org 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 rmunn at pobox.com Wed Nov 27 18:06:28 2002 From: rmunn at pobox.com (Robin Munn) Date: Wed, 27 Nov 2002 23:06:28 GMT Subject: do you guys help newbies?? References: <5ddauu0k5mffu8kfmrto430d0inhonn8bu@4ax.com> Message-ID: malik m wrote: > On Wed, 27 Nov 2002 21:16:19 GMT, malik m > wrote: > >>On Wed, 27 Nov 2002 14:38:34 -0600, John Hunter >> wrote: >> >>>>>>>> "malik" == malik m writes: >>> >>> malik> i didnt to import that yet but i will try even tho i think >>> malik> the program did what i want it to:) >>> >>>What do you think your mpg is if you drive 3 miles on a tank that >>>holds 2 gallons? What does your program tell you it is ..... >>> >>>John Hunter >> >> >>hmm yea i see what you're saying... ok i'll put it in. > > > yea i see now. this is one of the new features of 2.2.2 that my deitel > book told me about isnt it? is the deitel boook that bad? > i know that the end of chapter tests are getting rediculously hard and > they are testing me on things they havent even taught me. i dont think > this is for a newbie, this book... I would recommend the book _How to Think Like a Computer Scientist_: http://www.ibiblio.org/obp/thinkCSpy/ which you can read entirely on-line, for free! The reason I would recommend this book is because programming is more than just learning the basics of if/else statements and while loops. One of the most important programming skills to learn is problem analysis: looking at a problem ("Hmm, I want to write a program that will calculate miles per gallon") and figuring out not just one way to do it, but several ways to do it, and deciding which way is best. ("I could ask the user to type in the mileage and the gallons. But what if he already has that information in a file? Or what if he wants not just the average miles per gallon, but also a graph of the different miles/gallon rates he got at different times? And...") Programming is more of an art or a craft than a science. (That's why one of the most famous books in computer science is called "The Art of Computer Programming"!) There are skills, ways of thinking about problems, that can be taught, although they are best refined by experience. This book -- _How to Think Like a Computer Scientist_ -- attempts to teach those skills. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From tweedgeezer at hotmail.com Wed Nov 27 04:43:17 2002 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 27 Nov 2002 01:43:17 -0800 Subject: Python Tutorial Was: Guido's regrets: filter and map References: <698f09f8.0211261046.582254a5@posting.google.com> <3DE40E21.A547F49E@alcyone.com> Message-ID: <698f09f8.0211270143.5a3b9f0f@posting.google.com> Erik Max Francis wrote in message news:<3DE40E21.A547F49E at alcyone.com>... > Jeremy Fincher wrote: > > > The biggest problem with filter, map, and reduce is that they're > > functions, not methods. > > But since they can operate on _any_ sequence, this makes the most sense. Since they operate on any sequence, they should be methods of any sequence. As functions, yes, they operate on all sequences, but they only return lists. As methods, map/filter would return sequences of the same type they operated on, which is (IMO) far more appropriate. In short, why should a map on a string return a list instead of a string? Why should a filter on a binary tree return a list instead of another binary tree? > But there are several other things that can act as sequence objects, > such as strings, tuples, or user-defined types that don't derive from > list but define a __getitem__ method. filter, map, and reduce really do > belong in the realm of standalone functions, not methods, because they > can apply to any type that _acts_ as a list, whether or not it is a > list, a builtin sequence, or even something which at first sight doesn't > appear to be a sequence type at all (but acts the part). But I think it would be more appropriate for map/filter to return sequences of the same type as their argument sequences, not just return lists blindly. And that requires that map/filter be methods, not functions over sequences. Jeremy From mwh at python.net Tue Nov 26 05:36:00 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 26 Nov 2002 10:36:00 GMT Subject: Python Tutorial Was: Guido's regrets: filter and map References: Message-ID: <7h365uksju6.fsf@pc150.maths.bris.ac.uk> Grant Edwards writes: > In article , David Brown wrote: > > >> I never liked filter, map and reduce. > > So don't use them. ;) It's not quite that simple of course. If you're unlucky enough, every now and then you read code SOMEONE ELSE wrote! They're all fine in simple cases, but some of the most tortous Python code I've seen invloved artificially -- and probably fruitlessly -- stuffing code into calls to map in a quest for performance. Shudder. Cheers, M. -- If Unicode is a horde of zombies with flaming dung sticks, the hideous intricacies of JIS, Chinese Big-5, Chinese Traditional, KOI-8, et cetera are at least an army of ogres with salt and flensing knives. -- Eric S. Raymond, python-dev From hansgeunsmeyer at earthlink.net Tue Nov 19 10:39:45 2002 From: hansgeunsmeyer at earthlink.net (hg) Date: 19 Nov 2002 07:39:45 -0800 Subject: Fast construction of Python list from large C array of int's - Extension Module References: Message-ID: <95959723.0211190739.27aaed7e@posting.google.com> quadric at primenet.com wrote in message news:... > Is this the fastest way to do this? It will probably be a bit faster if you use PyList_SETITEM instead of PyList_SetItem. Since you're creating a brand new list, it's safe to use the macro. (The macro just plugs in the new values, without checking that the list is really a PyList, without checking for buffer over/underflow, and without trying to decrease the ref count of an old list item.) > Any inherent dangers here? As Alex already pointed out, you definitely have to check that neither your list nor any of the PyLongs is NULL. Hans From costanza at web.de Sun Nov 10 17:09:05 2002 From: costanza at web.de (Pascal Costanza) Date: Sun, 10 Nov 2002 23:09:05 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: David Garamond wrote: > Jacek Generowicz wrote: [...] > yes, that's good and all. the only problem is, most people _don't > like_it. they are _allergic_ to ((())). so what gives? the things that > will make them like: > > (+ 1 1) > > over (or the same as): > > 1+1 > > are probably only brain surgery and heavy brainwashing. ...or some nice examples. ;) > (+ 1 1) 2 > (+ 1 1 1) 3 > (+ 1 1 1 2) 5 > (+ 2) 2 > (+) 0 > (*) 1 The last two examples are a bit strange - why would you want to apply "+" to no arguments? Well, this can be very handy when you want to generate code in one part of your program (for example, in macros), but you don't want to care about special cases that may occur wrt number of arguments. Now, let's go on - "funcall" takes a function and applies it to the remaining arguments. > (funcall '+ 1 1 1) 3 > (funcall '* 2 3) 6 ...and so on. Now here is another nice macro. (defmacro apply-operators (op-list arg-list) `(loop for op in ',op-list do (format t " ~A: ~A~%" op (funcall op , at arg-list)))) * Remember that macros get code as input and generate code as output. (See another recent post of mine.) * ` means: create a list but evaluate everything that's marked with a , or ,@ * ',op-list means: evaluate op-list when processing this macro, but quote the result (regard it as data, not code) in the code that is generated. (See below.) * ,@ evaluates what follows, unwraps one pair of parentheses and inserts the result in the surrounding list * (format t ...) produces formatted output on standard output. ~A means: take one argument and print it. ~% means: start a new line. So here is an application. > (apply-operators (+ * min max) (5 4 6 3 7)) +: 25 *: 2520 min: 3 max: 7 You can always take a look at the code a specific macro produces. > (macroexpand-1 '(apply-operators (+ * min max) (5 4 6 3 7))) (loop for op in '(+ * min max) do (format t " ~A: ~A~%" op (funcall op 5 4 6 3 7))) Pascal -- Given any rule, however ?fundamental? or ?necessary? for science, there are always circumstances when it is advisable not only to ignore the rule, but to adopt its opposite. - Paul Feyerabend From chris.lyon at spritenote.co.uk Wed Nov 27 04:35:59 2002 From: chris.lyon at spritenote.co.uk (Chris Lyon) Date: 27 Nov 2002 01:35:59 -0800 Subject: Browser differences Mozilla v IE Message-ID: I've been developing CGI python scripts for generating web pages which are served from IIS. I've been viewing them from IE successfully for sometime now. I've just downloaded and installed Mozilla and when I try to run the same pages from Mozilla it trys to download them and run them in a DOS window. I'm rateh confused can anyone shed any light on where I should be tweaking to sort this out? From heafnerj at spam.vnet.net Tue Nov 19 20:53:34 2002 From: heafnerj at spam.vnet.net (Joe Heafner) Date: Tue, 19 Nov 2002 19:53:34 -0600 Subject: static variables? References: <3DDAE658.49A129DE@alcyone.com> Message-ID: Erik Max Francis wrote: > Check the other thread going on right now with exactly the same subject. > Got it. Thanks. JH From bokr at oz.net Mon Nov 18 15:18:04 2002 From: bokr at oz.net (Bengt Richter) Date: 18 Nov 2002 20:18:04 GMT Subject: How to write Inline Functions in Python? References: Message-ID: On Mon, 18 Nov 2002 00:57:52 -0800, Brian Quinlan wrote: >Michael Stenner wrote: >> I feel like we're going around in circles here. I'm talking about >> python. It looks like 'inline' would produce serious speedups in some >> cases. Therefore, it looks like an inline command would not be >> useless. > >Doing this would be almost impossible because Python name binding is >done at runtime. For example, how would you compile this? > True, binding is done at runtime, but ISTM an alternate binding mechanism is conceivable. I.e., the purpose of inlining is typically to generate a code sequence "in line" where the source is apparently calling the inline function, binding what would otherwise be the parameter names in function body directly to the arguments and avoiding the whole call rigamarole -- which is significant overhead in Python. The question is, what kind of object would a *compiled* inline function have to be to be used in Python analogy to that? I.e., what if you had a mutable code body type, where there would be mutable slots corresponding to places where function parameters were referenced? Let's how that could be used in your examples... >if random.choice([0, 1]): > from foo import baz # baz is an inline function >else: > from bar import baz # baz is an inline function > Either way, baz would be a mutable code body with no parameter slots. > >def my_func(): > baz() my_func would just get the baz code body at def time. Note that inline means global references if any go to the global name space of the my_func def environment. > >Or this? > >inline def foo(): > .... > >inline def bar(): > .... > >def my_func() > foo() > globals['foo'] = bar > foo() at def-time, globals()['foo'] is not dynamically touched, so you get def my_func() globals()['foo'] = bar # I assume you meant the () the result of a my_func() call would do whatever implies, plus rebind the global foo at run time to the inline bar mutable code object (which a subsequent def could "call" and get inlined into itself). > > >Or this? > >from bar import baz # baz is an inline function > baz would be bound to a mutable code body >def my_func() > .... > return baz # the fact that baz is inline isn't known at compile time > my_func would just return the reference. What's more interesting is def(inline) times_ten(x): return x*10 then def my_func(y): return times_ten(y) should get the body of times_ten with the reference to x changed to y E.g., looking at current code: >>> def times_ten(x): ... return x*10 ... >>> dis.dis(times_ten) 0 SET_LINENO 1 3 SET_LINENO 2 _______________________________________________ <<-- mutable code body / \ 6 LOAD_FAST 0 (x) | <<--mutable code parameter slot x gets replaced 9 LOAD_CONST 1 (10) | 12 BINARY_MULTIPLY | \_______________________________________________/ 13 RETURN_VALUE 14 LOAD_CONST 0 (None) 17 RETURN_VALUE >>> def my_func(y): ... return times_ten(y) ... >>> dis.dis(my_func) 0 SET_LINENO 1 3 SET_LINENO 2 ____________________________________________________ / \ <<-- replaced at def time if times_ten 6 LOAD_GLOBAL 0 (times_ten) | <<-- is mutable code body at def time 9 LOAD_FAST 0 (y) | <<-- actual parameter y ref replaces (x) 12 CALL_FUNCTION 1 | < in mutable code slot when body is substituted \____________________________________________________/ 15 RETURN_VALUE 16 LOAD_CONST 0 (None) 19 RETURN_VALUE This is just HOTTOMH, but I think there is something there. Note that this is not a source macro operation. Regards, Bengt Richter From pyth at devel.trillke.net Mon Nov 11 09:45:08 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 11 Nov 2002 15:45:08 +0100 Subject: something like "if" that returns a value? In-Reply-To: ; from Paul_Rudin@scientia.com on Mon, Nov 11, 2002 at 02:11:56PM +0000 References: Message-ID: <20021111154508.U30315@prim.han.de> Paul Rudin wrote: > >>>>> "hk" == holger krekel writes: > hk> Paul Rudin wrote: > >> I'm having a little play with python, just to try it out; and one > >> thing that I find I miss from other languages is something like > >> lisp's if: > >> > >> (if x y z) > >> > >> which returns y if x is true and z otherwise. > >> > >> I realise that I can define a function that does this for me; but > >> is there a succinct way of expressing this in the base language? > > hk> for me > > hk> x and y or z > > hk> basically does what you want. But you *need* to be sure that 'y' > hk> is true. some people don't like this 'abuse' but many use it on > hk> a regular basis (without big problems i'd say). > > Thanks for the reply. > > Yes, there are circumstances where this looks ok; but I'm a bit uneasy > with this idiom. The main problems being: > > - (as you say) you need to depend on the value of y; yes. > - potentially both y and z are evaluated; and no. more precisely, only if x is true and y is false is z also considered. which referes back to the previous point. > - there's a degree of obfuscation here, the code is less > comprehensible than something like: if x then y else z. IMO it's not overly hard to get used to it. It certainly isn't as evident (as has the aforementioned pitfall) as in some other languages. Funny enough, i don't need this ternary operation often. And if one the expressions is more complex i use a proper if-clause. regards, holger From martin at v.loewis.de Mon Nov 18 18:32:09 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 19 Nov 2002 00:32:09 +0100 Subject: return values for exceptions References: Message-ID: "N. Thomas" writes: > I suppose that I could trap the exception, and then return a value based on > that, but I'm not too sure if that is the right way to go about doing it. That is the right way. You can either use sys.exit, or raise SystemExit, with the status you want to get out of Python. Returning 1 for an uncaught is hard-coded in Python. Regards, Martin From tim.one at comcast.net Sun Nov 17 12:07:57 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 17 Nov 2002 12:07:57 -0500 Subject: Uninstalling Python 2.1.3 hosed Outlook Express In-Reply-To: Message-ID: [Edward K. Ream] > I just did a vanilla uninstall of Python 2.1.3, which was > installed normally from Python-2.1.3.exe a few days ago without > "rollback", IIRC. Afterwards the file msoe.dll could not be > initialized, so Outlook Express could not be run. No big deal; It would be to me, *if* there were a plausible connection. But there are no other reports of this (or anything like it), and the PLabs installer doesn't muck with any system DLLs apart from msvcrt.dll. The latter is refcounted by MS's software, so would not be deleted unless nothing was using it anymore; even then, the uninstaller would pop up a dialog box asking whether you wanted to delete it. > downloading and installing the OE service pack appears to have fixed > everything. Thought someone would like to know. I'm using XP, > the latest service packs. I've noted it, but you should assume the problem was due to something lse -- I do . From steve at ferg.org Sat Nov 30 09:16:03 2002 From: steve at ferg.org (Stephen Ferg) Date: 30 Nov 2002 06:16:03 -0800 Subject: ANN: EasyGui version 0.5 Message-ID: I've just released easygui version 0.5 It is available at http://www.ferg.org/easygui This version fixes some minor infelicities, and adds a new feature called "integerbox" to support getting an integer value from a user. For those not familiar with EasyGui, here is an excerpt from the documentation: ****************************** Experienced Pythonistas need support for quick and dirty GUI features. New Python programmers need GUI capabilities that don't require any knowledge of tkinter, frames, widgets, callbacks or lambda. This is what EasyGui provides. Using EasyGui, all GUI interactions are invoked by simple function calls. EasyGui is different from other GUIs in that it is NOT event-driven. It allows you to program in a traditional linear fashion, and to put up dialogs for simple input and output when you need to. If you are new to the event-driven paradigm for GUIs, EasyGui will allow you to be productive with very basic tasks immediately. Later, if you wish to make the transition to an event-driven GUI paradigm, you can move to an event-driven style with a more powerful GUI package such as anygui, PythonCard, Tkinter, wxPython, etc. EasyGui is there just to do very basic stuff. More elaborate stuff should be done with more powerful tools. Here is a code snippet using EasyGui. msg ="What is your favorite flavor?" title = "Ice Cream Survey" choices = ["Vanilla", "Chocolate", "Strawberry", "Rocky Road"] choice = choicebox(msg, title, choices) # note that we convert choice to string, in case # the user cancelled the choice, and we got None. msgbox("You chose: " + str(choice), "Survey Result") From cnetzer at mail.arc.nasa.gov Thu Nov 14 18:08:36 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Thu, 14 Nov 2002 15:08:36 -0800 Subject: update tkinter window In-Reply-To: <20021114215941.GA8100@4j.lane.edu> References: <20021114215941.GA8100@4j.lane.edu> Message-ID: <200211142308.PAA08002@mail.arc.nasa.gov> On Thursday 14 November 2002 13:59, Roger wrote: > I've been messing with tkinter a little. > I was trying to just come up with a window that would show the current > time. > stealing some code from examples, I came up with: [snipped] Here is my quick rewrite which probably does what you want: from time import localtime, strftime from Tkinter import * class myclock(Frame): def update_stats(self): self.contents.set(strftime("%H:%M:%S",localtime())) self.after(self.msecs, self.update_stats) return def __init__(self, msecs=1000): Frame.__init__(self) self.msecs=msecs self.contents=StringVar() self.entry=Entry(textvariable=self.contents) self.entry.pack() self.update_stats() return m = myclock( msecs=1000 ) m.pack() m.mainloop() > ------------------------------------------------------------ > the problem is the window keeps adding a new time making the window ever > increasing in size. Because you were calling pack() in the update_stats() method, which caused it to pack again. You could have forgot() the widget first, and then packed it, but that was unnecessary. As you see, I packed the Entry in the __init__, so that it only occurs *once* when 'myclock' is created, and so doesn't pack repeatedly in the Frame. Some notes: I also create the Entry to refer to the StringVar immediately. Then, whenever you update the StringVar, using set, the Entry widget automatically updates. It is almost *NEVER* a good idea for a widget to pack() itself in its own __init__ method. It is error prone, and makes it hard to reuse your widget. When you subclass Frame, you are saying that your new class *IS* a Frame, and will behave like a Frame (and could be used everywhere a Frame is used). Frames do not pack() themselves, and neither should you. The code that creates myclock() should pack it (or grid it, etc.), like it would any other frame. (when I started with Tkinter, I did the same thing as you, and had to painfully unlearn that technique) -- Bay Area Python Interest Group - http://www.baypiggies.net/ Chad Netzer cnetzer at mail.arc.nasa.gov From wlfraed at ix.netcom.com Wed Nov 27 20:57:18 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Wed, 27 Nov 2002 17:57:18 -0800 Subject: do you guys help newbies?? References: <200211280809.01424.bhards@bigpond.net.au> Message-ID: John Hunter fed this fish to the penguins on Wednesday 27 November 2002 01:35 pm: >>>>>> "Brad" == Brad Hards writes: > > Brad> How far is a mile? How much is a gallon? > > A mile is approx 1.7048275260088487e-13 light years. > According to my HP 48SX, it is 1.70111428361E-13 light years. (though it also seems to have MiUS -- 1.70111768584E-13). One mile is also 1.609344E18 Fermi > A gallon is a half a peck. > Isn't a peck a "dry" measure? > The units aren't terribly important for this problem. Other than the strange aspect that metric users tend to reverse the nature of the units... Rather than distance/volume I often saw volume/distance (litres/km for instance) -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From shannon at centre.edu Thu Nov 7 13:38:44 2002 From: shannon at centre.edu (CShannon) Date: 7 Nov 2002 10:38:44 -0800 Subject: Making a better textbook (was Re: The Deitel book) References: <87b0ada6.0211011453.1df4d216@posting.google.com> Message-ID: <815e8a38.0211071038.208c7577@posting.google.com> I am a college professor and use Python as the language in our first course -- designed for both majors and non-majors alike. There are a number of good python reference books around. Most of them are not appropriate as text books however because they have few examples and often no exercises. I like a book that is moderate in size. Books often have more material than can be covered in a single semester but it shouldn't be so large (or expensive) as to intimidate all but the bravest of souls. In my course, students are also expected to buy a text dealing with social/ethical issues. I realize the problem of course. In my class we do cover all the introductory material, and object oriented programming, but we also use VPython for graphics and write some cgi scripts to process html forms. Selecting exactly the topics to satisfy very diverse topics without writing an enormous text is not easy. benalan at cs.bu.edu (Ben Wiedermann) wrote in message news:... > "Chris Gonnerman" wrote in message news:... > > > Textbooks aren't designed to be entertaining, true; but frankly > > I found it painful to read in the final form. The content isn't > > the first thing one notices about a book; rather it's the > > presentation (cover, art, paper, etc.) > > I was one of the authors of the Deitel book; but just to be clear: I > am speaking as a Python evangelist. I am not speaking for any of my > coauthors or for my employer. That being said... > > One of the major goals for the book was to try to push Python down > into CS1 courses, where I believe it deserves far more consideration > than it currently receives. Our hope was that the book would > demonstrate to professors how well suited Python is as a first > programming language *and* how easy it is for novice programmers to > create more complex applications (e.g., GUI, multimedia, etc.). > > However, I've noticed that most of the post-publication criticism of > the book has focused on issues like presentation, art, etc. It's not > my job to dispute these claims. I personally believe that an author > should stay out of subjective discussions of his book, once that book > has been published. But I still very much believe in the promise of > Python in the university. And because the Deitel book is the only > college textbook of which I am aware, I wanted to get some feedback on > what would make a more successful Python textbook. How high does > presentation rank when considering a book? Are there examples of other > college textbooks that people think do an excellent job in the > presentation department? What kinds of materials can we (as a > community) produce to get schools to consider and adopt Python as a > first programming language? Any other thoughts on Python in the > university? From ccashman at attbi.com Mon Nov 25 21:39:01 2002 From: ccashman at attbi.com (Colin Cashman) Date: Tue, 26 Nov 2002 02:39:01 GMT Subject: Determining if a string is base64 or uu encoded? Message-ID: <99BE9.139964$nB.11463@sccrnsc03> Is there a function that given a string or file (or Message, etc.) will determine whether the string or file is encoded, and if so, what type of encoding that is (base64 vs. uuencoding)? Thanks in advance! Colin -- I am Jack's obfuscated source code. From tracy at reinventnow.com Tue Nov 26 09:12:07 2002 From: tracy at reinventnow.com (Tracy Ruggles) Date: 26 Nov 2002 06:12:07 -0800 Subject: Guido's regrets: filter and map References: <9PvekLArvL49Ewa2@jessikat.fsnet.co.uk> <8cmrra.qvc.ln@beastie.ix.netcom.com> Message-ID: MacOS X 10.2.2 -- 867Mhz G4 -- Python 2.2.1 [~/Desktop] tsr% python2.2 aa.py for loop took 5.00 list comprehension took 6.41 map took 4.02 [~/Desktop] tsr% python2.2 aa.py for loop took 4.97 list comprehension took 6.42 map took 4.08 [~/Desktop] tsr% python2.2 -O aa.py for loop took 4.91 list comprehension took 6.35 map took 4.03 [~/Desktop] tsr% python2.2 -O aa.py for loop took 4.91 list comprehension took 6.33 map took 3.99 Alex Martelli wrote in message news:... > Dennis Lee Bieber wrote: > ... > > Well, to add some more embers... Two runs under Mandrake 8.2, on a > > 733MHz P-III with RDRAM (Dell XPS B733r), Python 2.2, using the program > > listed above. > > [ ... ] > > [wulfraed at beastie wulfraed]$ python t.py > > for loop took 7.61 to make a list of 500000 items > > list comprehension took 7.31 to make a list of 500000 items > > map took 6.85 to make a list of 500000 items > > And Mandrake 9.0, 1.33 GHz AMD Athlon, and 266-MHz DDR : > > [alex at lancelot alex]$ python2.2 -O aa.py > for loop took 2.87 to make a list of 500000 items > list comprehension took 2.75 to make a list of 500000 items [ ... ] > map took 2.47 to make a list of 500000 items > [alex at lancelot alex]$ python2.3 -O aa.py > for loop took 2.33 to make a list of 500000 items > list comprehension took 2.32 to make a list of 500000 items > map took 1.61 to make a list of 500000 items From martin at v.loewis.de Sat Nov 16 17:24:46 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Nov 2002 23:24:46 +0100 Subject: Calling local functions from the C API References: Message-ID: Jon Parise writes: > I'm familiar with calling functions using PyObject_CallObject(). > I generally use PyImport_ImportModule() to import a callable object > from some module before executing it. > > However, I'm unclear as to how to go about getting a callable object > from the current local scope (i.e. not from a named module). > > Help, please. =) By "local scope", do you mean as in "local variable"? I.e. you do def foo(): def bar() pass myext.somefunc() and then you want the somefunc, which is implemented in C, to access bar??? That isn't supported. It is possible, but you will have to read the source yourself to find out how to do it. Instead, I recommend that you do myext.somefunc(bar) instead, i.e. passing the callable as an argument to the extension. Regards, Martin From mis6 at pitt.edu Fri Nov 8 16:59:12 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 8 Nov 2002 13:59:12 -0800 Subject: Ethics in abstract disciplines (was: Making a better textbook (was Re: The Deitel book)) References: <87b0ada6.0211011453.1df4d216@posting.google.com> <815e8a38.0211071038.208c7577@posting.google.com> <3DCBD7DE.E132BD77@hotmail.com> <7h3smycxeau.fsf@pc150.maths.bris.ac.uk> Message-ID: <2259b0e2.0211081359.876e379@posting.google.com> Michael Hudson wrote in message news:<7h3smycxeau.fsf at pc150.maths.bris.ac.uk>... > Alan Kennedy writes: > > > These days, is there such a thing as a mathematics course that doesn't > > involve extensive exposure to Computer Science? > > Yes, the one I did at Cambridge (UK) had very little CS content (there > were computer projects in the second and third years but you could > ignore them if you chose to -- I didn't, but I know people who did). > I think I could have attended three hours of lectures on how to > program in Pascal (I *did* ignore those -- my projects were a bizarre > melange of Python, Haskell and Common Lisp tied together by bash > scripts). > > I graduated in 2000; I don't think much has changed since ('cept it > might be C and not Pascal now). > > Cheers, > M. When I was studying Physics at the University of Padua (in the nineties) we had an official booklet of the faculty with advices about the choice of non-mandatory courses. I still remember the sentence about computer science courses. Translating quite literally from Italian it reads something like "In no case plans of studies involving CS courses from other faculties will be accepted by this Physics commission". I would not be surprised if this politics was still enforced. In more ten years of Physics (including the Ph.D.) I never had a single course about programming (excluding maybe two or three seminars in one of the laboratory course I had, but they were unofficial, not part of the course; we also had computer hours in the afternoon, but unofficial and not mandatory). It could seems strange to somebody, but personally I second that politics. Programming is a nice thing you can do for fun by yourself, but the University has to teach you the real thing, not to spend your time on other topics. Whereas it is true that lots of physicist (and mathematicians) spend a lot of time on computers for their research, it is also true that there still many researchers which can completely avoid the computer (I am one of them). I think that, at least in Europe, most of Physics and Mathematics course still do not involve extensive exposure to Computer Science. And this is a good thing. -- Michele Simionato - Dept. of Physics and Astronomy 210 Allen Hall Pittsburgh PA 15260 U.S.A. Phone: 001-412-624-9041 Fax: 001-412-624-9163 Home-page: http://www.phyast.pitt.edu/~micheles/ From op73418 at mail.telepac.pt Mon Nov 18 17:56:43 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Mon, 18 Nov 2002 22:56:43 +0000 Subject: Hmm... An idea: if a,b==c,d: References: Message-ID: <7vritu48rhphl04peeapus5vf425877idm@4ax.com> On Mon, 18 Nov 2002 21:49:15 GMT, "Richard Dillingham" wrote: >Kind of like we have multiple assignments in a line (oldx,oldy=x,y), what do >you think of the ability to have multiple tests in an if statement with only >one == or >=. > >This would mean that lines like the following: >if posx>=coords[0] and posy>=coords[1] and posx<=coords[2] and >posy<=coords[3]: > >Could be rewritten like so: >if posx,posy>=coords[0],coords[1] and posx,posy<=coords[2],coords[3] > > Hmm, can't you do that already with tuples? It is just an extra pair of parenthesis... All the best, Gon?alo Rodrigues From herrn at gmx.net Thu Nov 7 18:19:17 2002 From: herrn at gmx.net (Marco Herrn) Date: 7 Nov 2002 23:19:17 GMT Subject: default argument depending on another argumen? References: Message-ID: Gerhard H?ring schrieb im Artikel : > Marco Herrn wrote in comp.lang.python: >> I want to define a function like this: >> >> def foo(self, bar, x= bar.x): >> .... >> pass >> >> Now I have the problem that 'bar' isn't really known when defining this >> function. >> So how can I achieve this behaviour? > > There's a FAQ entry o this, too IIRC :-) > > The workaround looks like this: > > def foo(self, bar, x=None): > if x is None: > x = bar.x > ... Thanks again. I see, I have to look more often on the website ;) Bye Marco -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From max at alcyone.com Mon Nov 11 17:58:43 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 11 Nov 2002 14:58:43 -0800 Subject: something like "if" that returns a value? References: Message-ID: <3DD03623.808F9D6E@alcyone.com> John Roth wrote: > The 'and' 'or' hack is the cannonical way of doing this. It short > circuits properly, and it returns the value of the expression that was > evaluated. ... but does not work as expected when the "then" expression evaluates to false. It's important to not forget that when using it, which is one of the reasons it is unappealing. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Exercise is wonderful. I could sit and watch it all day. \__/ Louis Wu Fauxident / http://www.alcyone.com/pyos/fauxident/ A "faux" ident daemon in Python From TrentM at ActiveState.com Fri Nov 29 14:50:24 2002 From: TrentM at ActiveState.com (Trent Mick) Date: Fri, 29 Nov 2002 11:50:24 -0800 Subject: ANN: ActivePython 2.2.2 released! Message-ID: <20021129115024.B15277@ActiveState.com> We are pleased to announce that version 2.2.2 of ActivePython is now available for download from http://www.ActiveState.com/ActivePython This is a bugfix release and supersedes previous ActivePython releases. ActivePython is ActiveState's quality-assured binary build of Python. Builds are currently available for Windows, Linux and Solaris. In addition to the core, ActivePython features: * expat for XML processing; * zlib for data compression; * Tkinter for Tk development; * a large set of useful Python documentation; and, * on Windows, Mark Hammond's PyWin32 extensions, including the Pythonwin IDE, support for Python ASP, the PythonCOM system. Please submit email feedback to ActivePython-feedback at ActiveState.com, and file bugs against ActivePython at http://bugs.ActiveState.com/ActivePython. Thanks, and enjoy! Trent -- Trent Mick TrentM at ActiveState.com From bokr at oz.net Mon Nov 18 17:09:11 2002 From: bokr at oz.net (Bengt Richter) Date: 18 Nov 2002 22:09:11 GMT Subject: changing the Python grammar ? References: <2259b0e2.0211181221.2eab9db7@posting.google.com> Message-ID: On 18 Nov 2002 12:21:52 -0800, mis6 at pitt.edu (Michele Simionato) wrote: >Browsing on the on-line refencence manual you can find the formal >definition of the Python grammar: http://python.org/doc/current/ref/grammar.txt > >It is pretty clear, for instance you see what is a valid identifier: > >identifier ::= > (letter|"_") (letter | digit | "_")* > >letter ::= > lowercase | uppercase > >lowercase ::= > "a"..."z" > >uppercase ::= > "A"..."Z" > >digit ::= > "0"..."9" > >But now a question arise to me: can I modify the grammar ?? > >Suppose for instance I want to make able Python to recognize identifiers >starting with some funny symbol, say "@". All I must do is to modify >the first line of the grammar as > >identifier ::= > ["@"] (letter|"_") (letter | digit | "_")* > >In the best of the worlds, I would look for some file in the Python >source distribution containing the grammar, I would change that line, >and recompiling I would have a new Python able to understand identifiers >starting with "@". Is this possible in practice ? > >Notice that I do NOT want to introduce ugly perlish-like identifiers in >Python, I simply want to know how much it is possible to customize the >Python grammar: is this a simple hack or a nightmare ? > >I find this possibility (if real) very intriguing, even if I see that >this can be very dangerous. > >Reactions ? Comments ? Am I asking a too naive question ? I have no idea >of how the grammar is implemented in the C code in reality. > The tools are all there, but depending on what kind of change you make, it may imply the need for a host of other changes. Very tricky stuff. There are several things you need to rebuild in the right order, to get core functionality going with revisions. If you have MSVC++6.x on windows, for starters read (your paths may vary): D:\Python-2.2.2\PC\readme.txt D:\Python-2.2.2\PC\example_nt\readme.txt D:\Python-2.2.2\PCbuild\readme.txt Regards, Bengt Richter From fclift at verio.net Fri Nov 8 17:41:27 2002 From: fclift at verio.net (Fred Clift) Date: Fri, 8 Nov 2002 15:41:27 -0700 (MST) Subject: complicated class question In-Reply-To: Message-ID: <20021108154048.M58763-100000@vespa.dmz.orem.verio.net> On Fri, 8 Nov 2002 sismex01 at hebmex.com wrote: > > # Save the original 'a' in '_a', > # install 'new_a' in it's place. > A._a = A.a > A.a = new_a incidentally, is there any reason I really want to save the 'old' a? just in case I want to swap it back? Fred -- Fred Clift - fclift at verio.net -- Remember: If brute force doesn't work, you're just not using enough. From skip at pobox.com Tue Nov 12 06:39:48 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 12 Nov 2002 05:39:48 -0600 Subject: Optimisation problem In-Reply-To: <10F0E58C0018054484E329DC494C4D7F01ADCE@mexper1.maptek.net.au> References: <10F0E58C0018054484E329DC494C4D7F01ADCE@mexper1.maptek.net.au> Message-ID: <15824.59524.825868.530999@montanaro.dyndns.org> Simon> I have created a quaternion class which I am using for rotations Simon> in OpenGL. .... Simon> Does anyone have any idea how I can optimise this code? It is Simon> going to be used in a very tight rendering loop. I would prefer Simon> to keep all the code in Python, and avoid writing any external Simon> modules. That depends on a number of things. Starting with the code itself and sticking strictly to Python and using only eyeballs and a text editor (that is, nearly no brain power ;-), you can eliminate some duplicate computations and avoid a bunch of attribute references and a needless function call: from math import sin, cos class Quaternion: def __init__(self, degree, x, y, z): matrix = self.matrix = range(16) angle2 = degree * 0.0087266462599716477 result = sin(angle2) self.w = cos(angle2) self.x = x * result self.y = y * result self.z = z * result # where __createMatrix() used to start... w,x,y,z = self.w, self.x, self.y, self.z zz = z*z yz = y*z yy = y*y xx = x*x xy = x*y xz = x*z wy = w*y wx = w*x wz = w*z matrix[0] = 1.0 - 2.0 * ( yy + zz ) matrix[1] = 2.0 * ( xy - wz ) matrix[2] = 2.0 * ( xz + wy ) matrix[3] = 0.0 matrix[4] = 2.0 * ( xy + wz ) matrix[5] = 1.0 - 2.0 * ( xx + zz ) matrix[6] = 2.0 * ( yz - wx ) matrix[7] = 0.0 matrix[8] = 2.0 * ( xz - wy ) matrix[9] = 2.0 * ( yz + wx ) matrix[10] = 1.0 - 2.0 * ( xx + yy ) matrix[11] = 0.0 matrix[12] = 0.0 matrix[13] = 0.0 matrix[14] = 0.0 matrix[15] = 1.0 I believe that leaves the external interface of your Quaternion class intact (its matrix, w, x, y, and z attributes should be the same as before) and doesn't screw up the computation, but I didn't test the code. To understand why these changes have any effect you need to understand a little bit about the Python virtual machine. It's worth running import dis dis.dis(Quaternion) before and after you make the above changes to see how the generated byte code changes. You might want to also check out any or all of Psyco: http://psyco.sourceforge.net/ PyInline: http://pyinline.sourceforge.net/ Weave: http://www.scipy.org/ Pyrex: http://www.cosc.cantebury.ac.nz/~greg/python/Pyrex/ They all bend or break your "avoid writing any external modules" to a greater or lesser degree, but are all worth investigating. Psyco requires next to no changes to your source code but is Pentium-specific. PyInline and Weave allow you to embed C/C++ code into your Python code and have them compiled and linked on-the-fly. Pyrex allows you to write extension modules in a language that is almost exactly Python. -- Skip Montanaro - skip at pobox.com http://www.mojam.com/ http://www.musi-cal.com/ From simonb at webone.com.au Sat Nov 23 20:35:23 2002 From: simonb at webone.com.au (Simon Burton) Date: Sun, 24 Nov 2002 12:35:23 +1100 Subject: Guido's regrets: filter and map Message-ID: Hello, I just read Guido's "python regret's" slide's from OSCON, http://www.google.com/search?hl=en&ie=ISO-8859-1&q=OSCON+%22python+regrets%22 and one thing i can't work out is, he is saying we can do map() and filter() with list comprehensions (it's faster too) eg. amapedlist = [ somefunc(x) for x in alist ] But how would we do a filter with list comprehensions? Simon Burton From ianb at colorstudy.com Fri Nov 1 14:42:53 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 01 Nov 2002 13:42:53 -0600 Subject: Macros in Python, and using reg exps to build a scheme interpreter In-Reply-To: References: Message-ID: <1036179773.527.1937.camel@dsl-65-184-205-5.telocity.com> On Thu, 2002-10-31 at 14:46, Peter L. Markowsky wrote: > Currently in one of my classes I'm building a scheme interpreter > in Java. This has brought two questions to mind. First does python use > language macros to define higher level functionality. And two does anyone > know a good place to look for how to implement a scheme parser using > regular expressions? You can create a tokenizer with regular expressions, though Scheme's tokenization rules are simple enough you could pretty much do it with string.find. You can't turn the tokens into a parse tree using regular expressions, but the relation between tokens and parse trees in Scheme is clear enough that it should be obvious how you'll do that portion. I.e., you'll want to tokenize the expression (cons "a" 'a) into something like: [('symbol', '('), ('identifier', 'cons'), ('string', 'a'), ('symbol', "'"), ('identifier', 'a'), ('symbol', ')')], and then turn that into something more sensible. Ian From smulloni at bracknell.smullyan.org Fri Nov 1 11:57:28 2002 From: smulloni at bracknell.smullyan.org (Jacob Smullyan) Date: 1 Nov 2002 11:57:28 -0500 Subject: python bulletin board software Message-ID: Does anyone know of any bulletin board software written in Python other than Zope's various contributions? I've come across only relatively trivial scripts so far, nothing at the level of sophistication of the various PHP forums (phpBB, for instance). js From gminick at hacker.pl Wed Nov 27 15:16:09 2002 From: gminick at hacker.pl (Wojtek Walczak) Date: Wed, 27 Nov 2002 20:16:09 +0000 (UTC) Subject: do you guys help newbies?? References: Message-ID: Dnia Wed, 27 Nov 2002 19:47:47 GMT, malik m napisa?(a): > p.s. does anyone know what the big 2.2.2 updates are? Take a look at: HTH. -- [ ] gminick (at) underground.org.pl http://gminick.linuxsecurity.pl/ [ ] [ "Po prostu lubie poranna samotnosc, bo wtedy kawa smakuje najlepiej." ] From aahz at pythoncraft.com Sun Nov 24 02:44:25 2002 From: aahz at pythoncraft.com (Aahz) Date: 24 Nov 2002 02:44:25 -0500 Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: In article , wrote: >Aahz wrote: >> >> ObJennie: Joel Rosenberg, _D'Shai_ > >Oh, let's see some new hands for a change... Try some different chum, then. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From rmunn at pobox.com Sun Nov 10 01:33:10 2002 From: rmunn at pobox.com (Robin Munn) Date: Sun, 10 Nov 2002 06:33:10 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h31y5uyj81.fsf@pc150.maths.bris.ac.uk> <3DCD6038.7E6EC76B@kolumbus.fi> Message-ID: Martti Halminen wrote: > Richard Dillingham wrote: > >> > The only thing that could make me at all comfortable with using Lisp >> > would be if I had an editor that would color-highlight not keywords or >> > strings, as color-highlighting usually goes, but levels of parenthesis >> > indentation. So that this: >> > >> > (a (b (c (d e)))) > >> >> I wonder why you aren't writing >> (a >> (b >> (c >> (d e) >> ) >> ) >> ) > > > A lisp programmer would write it like this: > > (a > (b > (c > (d e)))) > > or the original: (a (b (c (d e)))) if using so short names and no > control structures causing special indentation. Both of you are right with regard to indentation; you can tell that I don't use Lisp, as I am completely unfamiliar with proper indentation techniques. The second form (with the closing parentheses lined up) would confuse me if I tried to read someone else's code, whereas the first (sort of C-like) form of indentation allows me to see at a glance which parenthesis is being closed where. > >> The issue with 'Python being easier to read than Lisp,' IMHO, is mainly that >> Python FORCES you to use indentation, whereas Lisp does not. And that has become one of the major reasons why I like Python: I can read code written by anyone, even language newbies, and understand it without having to puzzle out their indentation style. The other reason why I like Python is the power of introspection. (I have this peculiar mental "image" of a TV commercial like the "Behold the power of cheese!" commercials found on US television, except the slogan is "Behold the power of introspection!") >> >> Since Lisp does not force you to write readable code, you have to force >> yourself to use indentation. > > For a beginner it might be forcing, for the professionals it is a major > tool. Not using the canonical indentation style is a sure sign of a > newbie in comp.lang.lisp. > >> But I don't see a bunch of C programmers typing >> if (a) { if (b) { if (c) { asdf; } else { zzzz; }} else { foo; }} else >> {bar;} >> like a Lisp coder might type >> (if (a) (if (b) (if (c) (asdf) (zzzz)) (foo)) (bar)) > >> (if (a) >> (if (b) >> (if (c) >> (asdf) >> (zzzz) >> ) >> (foo) >> ) >> (bar) >> ) >> > > (if (a) > (if (b) > (if (c) > (asdf) > (zzzz)) > (foo)) > (bar)) > > Would be the normal way to write this. Well, I can understand the structure behind the canonical Lisp indentation style. And it might be horizon-broadening to attempt a serious program in Lisp sometime. But despite the fact that I *know* there's logical structure to it, seeing Lisp code still makes me think of "You are in a maze of twisty little parentheses, all similar." :-) Incidentally, I am not trying to bash Lisp; it's just that my own initial reactions were negative, and I haven't found the positive in it that I know to be there. But having found a language (Python) that thinks the way I do, and being able to have my thoughts flow into real code without the language getting in the way, I find myself disinclined to invest time and mental energy learning a language that *doesn't* flow for me. My general take on why Python is popular, while Lisp and Scheme aren't? For most people, learning Lisp seems to be an uphill struggle, whereas Python simply *flows*. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From bhards at bigpond.net.au Tue Nov 5 16:02:31 2002 From: bhards at bigpond.net.au (Brad Hards) Date: Wed, 6 Nov 2002 08:02:31 +1100 Subject: More about simple question In-Reply-To: <20021105180901.76557.qmail@web21208.mail.yahoo.com> References: <20021105180901.76557.qmail@web21208.mail.yahoo.com> Message-ID: <200211060802.31379.bhards@bigpond.net.au> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Wed, 6 Nov 2002 05:09, xinghua shi wrote: > Hey,thanks you all. Actually, I messed up the > indentation and I first thought it's not a big problem > as I used to write in C. I'm just changing over from C myself. Python is definately not the same language, and you should _not_ think of it as "C with a different syntax" > I still have another question. If I have a file named: > foo.py. then how can I get an excetable, say foo? > In C, I could use > % gcc foo.c -o foo > > So how can I do similar in Python? > %python foo.py -o foo > doesn't work of course. Python isn't compiled, and you probably shouldn't be looking for an answer that involved a compiler. Typically, you'd make a script: http://www.python.org/doc/current/tut/node4.html#SECTION004220000000000000000 I'm not sure how well this will work in Windows though. There are other alternatives (py2exe is one that I've seen, but not played with) http://starship.python.net/crew/theller/py2exe/ - -- http://linux.conf.au. 22-25Jan2003. Perth, Aust. I'm registered. Are you? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE9yDHnW6pHgIdAuOMRAtVQAJ9WU2IbqjAv748eCSwWWBVCcDFIrQCfWxqg HePyjZMJzgE2jNXDAarrJ6I= =+g1q -----END PGP SIGNATURE----- From martin at v.loewis.de Tue Nov 5 17:49:19 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 05 Nov 2002 23:49:19 +0100 Subject: using the PSF license for one's code References: <918bc22f.0211051301.2010d077@posting.google.com> Message-ID: donnal at donnal.net (Donnal Walter) writes: > If one wishes use an OSI-approved license for one's own code, there > are many to choose from, two of which are GPL and the PSF license. If > one chooses GPL, there are explicit instructions at the Gnu Web site > on how to use the license. On the other hand, I have not seen any such > instructions for using the PSF license. Can one simply refer to the > PSF license without making changes? No: that is "between the Python Software Foundation (PSF), and the Individual or Organization (Licensee) accessing and otherwise using Python 2.2 software". Unless you are the PSF, and unless you ship Python 2.2, you cannot meaningfully establish such a contract. > Or is it advisable to make a revised copy, changing the name of the > name of the owner/copyright holder from PSF to oneself, for example? > What else is required? If you systematically update all legal entities in this document, you certainly arrive at what I would consider a meaningful license, and you could use it right away. I don't think anybody but you and your licensee could "require" anything about your license: If you want to put the text "you can use this software only on Sundays" into the license, nobody could stop you from doing so. Of course, with any changes to the license text, the license probably loses their OSI-approvedness (ask OSI for details). In short, we (the PSF) don't care about other uses of this text, beyond it being a license for Python. Regards, Martin From zopestoller at thomas-guettler.de Mon Nov 4 11:40:36 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Mon, 04 Nov 2002 17:40:36 +0100 Subject: Encoding of String Message-ID: Hi! Is there a way to get the encoding of a string? Suppose I do: mystring="blu" ustring=unicode(mystring, "utf-8") later I want to know which encoding ustring has: ustring.getEcoding() --> "utf-8" Is there something like "getEcoding()"? thomas From clpy at a-nugget.de Mon Nov 4 18:34:36 2002 From: clpy at a-nugget.de (Guido Goldstein) Date: 05 Nov 2002 00:34:36 +0100 Subject: UDP broadcasts => 'Permission denied' References: Message-ID: Hi! On Mon, 4 Nov 2002 23:47:51 +0100 Christian Kaenzig wrote: [...] > But then I wanted the client not to send its data explicitely to the server, > but send a broadcast packet instead, so I told the client to send it to > ''. This didn't work :-(. It printed the folowing message : > > s.sendto('Hello world',(HOST, PORT)) > socket.error: (13, 'Permission denied') [...] Try the following: --- cut --- if hasattr(socket,'SO_BROADCAST'): s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.sendto('Hello world',(HOST, PORT)) --- cut --- This allows broadcast messages going out from the given socket. HIH Guido From dansilva at lynx.dac.neu.edu Sun Nov 24 16:15:18 2002 From: dansilva at lynx.dac.neu.edu (Daniel Silva) Date: Sun, 24 Nov 2002 16:15:18 -0500 Subject: Why is Python popular, while Lisp and Scheme aren't? In-Reply-To: <3DE07539.2040905@nyc.rr.com> Message-ID: Who cares about converting Python coders to Lisp/Scheme or Scheme coders to Python? Just write a couple of compilers (Python->Scheme and Scheme->Python) and use any language you like ;) BTW, on ease of learning: scheme is horrible to the eye at first glance because kids learn C-like syntax first and math looks weird in prefix. You need a good book like How to Design Programs or The Little Schemers, and a good week or two, to break that ice. Watch out for DrPython! ;) ----------------------------------- Daniel Silva dsilva at ccs.neu.edu From hansgeunsmeyer at earthlink.net Wed Nov 20 21:44:56 2002 From: hansgeunsmeyer at earthlink.net (hg) Date: 20 Nov 2002 18:44:56 -0800 Subject: Understanding PyEval_InitThreads References: <7kf83526.fsf@python.net> Message-ID: <95959723.0211201844.7ce3458@posting.google.com> Thomas Heller wrote in message news:<7kf83526.fsf at python.net>... > Unfortunately it won't work this way. > > Think of call_some_c_code() being the C standard library's qsort > function, and call_back_into_python() is the function pointer I gave > qsort to do the comparison. There's no way to pass the thread state to > the callback function! I'm not sure if I understand you, but what you're saying doesn't make sense to me. The call_back_into_python is called by call_some_c_code, so if you pass a pointer to the current thread state as arg, you could also pass it on to call_back_into_python, couldn't you? It doesn't matter whether or not call_back_into_python itself is passed as an argument to call_some_c_code. Another moment to pass on a pointer to the current thread state would be when you register the Python object that will actually be called by your callback. I assume here that your call_back_into_python is intended to wrap a call to PyObject_CallObject. If so, you have to pass it a pointer to some callable Python object, so I assume you have some function to register which object will actually be called by your call_back_into_python. So, at the moment when you register this Python function, you could also save and/or pass on a pointer to the current thread state. No? > > Storing the thread state in a global variable would be possible, but > in this case it wouldn't be thread safe, I assume, and *only* work if > the callout into C is done by my extension module. I see no reason why this wouldn't be thread-safe. You could store the current thread state when you initialize your module. As far as I understand it, it doesn't really matter _what_ the thread state is that you swap into the current state before you do the callback, as long as it is _some_ valid thread state (not NULL). So, before you do the callback, at any moment when you're in the main Python thread, you could store a pointer to the then current threadstate. Hans From andys at collegenet.com Tue Nov 19 16:10:05 2002 From: andys at collegenet.com (higgeldy Piggeldy) Date: 19 Nov 2002 13:10:05 -0800 Subject: Telnetlib help. I need a case function. Message-ID: <1d4aad28.0211191310.6300984a@posting.google.com> Hi, I wrote this script a while ago to renew my library books for me. Our library here has a telnet interface where you can renew your books. So I tried to automate that for myself, now I need to upgrade it because there are cases where it hangs on the read_until because the server is sending something unexpected, and I am wondering if anyone could help me get it to react to different input. here is the script: #!/usr/bin/python import telnetlib import sys import string import re import regsub import regex import smtplib succeed = re.compile("( *Successful renewal for title '.*'\.)") maynot = re.compile("( *You may not renew '.*\.)") noneleft = re.compile(" *No items were renewed .*") due = re.compile ("( *Due Date = \d\d \w\w\w \d\d\d\d)") tn = telnetlib.Telnet("dyna.multnomah.lib.or.us") tn.read_until("login: ") print "logging in!\n" tn.write("fastcat\n") tn.read_until(">>") tn.write("\n") #tn.read_until("<> ") tn.write("\n") tn.read_until("N") tn.write("\n") tn.read_until("DYNA -") tn.write("\n") tn.read_until(" :") def renew(thiscard,thispin,thisemail): fileout = open ('temp.txt','w') tn.write("17\n") tn.read_until("barcode") tn.write(thiscard+"\n") print "\n\nrenewing ", print "for ",thisemail tn.read_until("PHONE") tn.write(thispin+"\n") tn.read_until("below") tn.write("1\n") i=1 for i in range(24): tmp = open('dyna.tmp','w') i=i+1 tn.read_until("below") tn.write("r\n") (tn.read_until('renew')) tn.write(`i` + "\n") tmp.write (tn.read_until("Enter")) tn.write("\n") tmp.close() file = open('dyna.tmp','r') while 1: line = file.readline() if not line: break successobj = succeed.search(line) maynotobj = maynot.search(line) dueobj = due.search(line) if successobj: fileout.write (repr(successobj.groups())+"\n") if maynotobj: fileout.write ("ATTENTION"+"\n"+repr(maynotobj.groups())+"\nATTENTION\n") if dueobj: fileout.write (repr(dueobj.groups())+"\n") file.close() # tn.read_until("below") tn.write("so\n") fileout.close() filein = open ("temp.txt","r") fileout = open ("temp2.txt","w") msg = "Subject:Automatic Library Renewal Notice For:"+thisuser+".\r\n\r\nThank You for using my service.\nPlease feel free to send any donations or suggestions to me at sweetfamily at qwest.net\n\n" while 1: line = filein.readline() if not line: break matchobj = string.replace (line,"(","") matchobj = string.replace (matchobj,")","") matchobj = string.replace (matchobj,'"','') matchobj = string.replace (matchobj,"'","") matchobj = string.replace (matchobj,",","") matchobj = string.replace (matchobj,"/","") print matchobj, msg = msg+matchobj fileout.write(matchobj) filein.close() fileout.close() fromaddr = "From:andys at collegenet.com" toaddr = "To: " toaddr = toaddr + thisemail print toaddr sending = smtplib.SMTP('mail.collegenet.com') sending.set_debuglevel(0) sending.sendmail(fromaddr,toaddr,msg) sending.quit() cardpatt = regex.compile ('^card:\(\w*\)') pinpatt = regex.compile ('^pin:\(\w*\)') emailpatt = regex.compile ("email:\(.*\)") userpatt = regex.compile ("user:\(.*\)") config = open("telnetter.cfg") status =0 while 1: line = config.readline() if not line:break card = cardpatt.match(line) pin = pinpatt.match(line) email = emailpatt.match(line) user = userpatt.match(line) if card>=0: thiscard = str(cardpatt.group(1)) status = status +1 if pin>=0: thispin = str(pinpatt.group(1)) status = status +1 if email>=0: thisemail = str(emailpatt.group(1)) status = status +1 if user>=0: thisuser = str(userpatt.group(1)) status = status+1 if status == 4: status =0 renew(thiscard,thispin,thisemail) #renew("21168013143409","6422") #renew("21168018228841","6422") tn.read_until("Enter>") tn.write("19\n") tn.close() print "DONE!!" It trips up on the tn.read_until("below") because the server is sending something else since there are no books to renew. Thanks --Andrew From costanza at web.de Fri Nov 22 18:12:29 2002 From: costanza at web.de (Pascal Costanza) Date: Sat, 23 Nov 2002 00:12:29 +0100 Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <2259b0e2.0211210838.7647301a@posting.google.com> <2259b0e2.0211220946.5f61f641@posting.google.com> <3DDE711E.3010005@web.de> <6qyD9.60432$Yw.2729711@news2.tin.it> Message-ID: Alex Martelli wrote: > Pascal Costanza wrote: > ... > >>(All the scripting languages I have seen so far rely on C for the hairy >>stuff - and I definitely don't like that. There should be some >>alternative.) > > > There is. Jython, www.jython.org, is an implementation of the Python > language in and for Java -- complete, working, and quite solid. Ah, yes, of course. But you don't want to suggest that Java is a language that is useful for doing hairy and complex stuff. (Sure, most things become hairy and complex in Java, but that's a totally different story. ;) I mean, Python is already more advanced than Java. > Vyper, > vyper.sf.net, was a similar project to implement a new dialect of Python in > O'Caml (now the project is marked as "no longer active"). Interesting... > Python.NET was a > similar (research) project to implement Python in C#, also now finished. Oh my goodness. ;) > Of these, I would only suggest Jython as feasible for production work today. > But surely if a third production-level implementation could be added to > Classic Python and Jython, this *would* be quite a significant and > meaningful accomplishment. > > It's probably important to identify the motivations that would convince > somebody to use the hypothetical "LisPython" rather than Common Lisp, > Classic Python, or Jython; having a clear target in mind can ease many > design choices later on. What are your ideas in the matter? I must admit that I don't have very clear ideas and detailed plans in this regard, only a strange mixture of visions and gut feelings. ;) As I said before, Python could be a good surface language for Common Lisp. Something like Dylan was. The original idea in Lisp was to provide the so-called M-expressions one day, but that never turned out to be accepted by Lispers. I think the problem with M-expressions or Dylan is that these were completely new languages. Choosing an already existing language (for example Python) could be the better choice because it is already accepted (and proven to work in practice). Of course, that language should already be close to Common Lisp, but I don't see any major problems in that regard with Python. Another motivation is as follows: I think the basic idea of .NET (or better the CLR) is quite interesting, i.e. to have a common portable runtime that can be used by many different languages. However, the design of the CLR is still very limited (it is slightly more open than the JVM, and that's what Microsoft wants .NET to be compared against, although they don't admit it publicly). For example, the CLR has only a limited object model that is hard to target from languages that want to include interesting features like multiple inheritance or multi-methods. So in the long run, given that Microsoft really wants to live up to its stated goals, the limitations of the CLR need to (and I guess, will) be relaxed step by step. If you think this out, you will realize that this must end in something that has a similar expressive power as that of Lisp. (Here, I am referring to the code=data feature again that would ultimately allow you to translate any kind of language.) So my main vision is to turn Common Lisp into such a kind of common runtime for various languages. That's one reason why I started the JVM implementation in Common Lisp. Does this make some sense? Pascal P.S.: I know that this sounds like a major undertaking. ;) -- Given any rule, however ?fundamental? or ?necessary? for science, there are always circumstances when it is advisable not only to ignore the rule, but to adopt its opposite. - Paul Feyerabend From neal at metaslash.com Thu Nov 7 22:04:23 2002 From: neal at metaslash.com (Neal Norwitz) Date: Thu, 07 Nov 2002 22:04:23 -0500 Subject: Dynamic loading of modules in AIX Message-ID: I'm trying to get python to load dynamic modules. But after loading the module, when code inside the module calls back into the main program, it seg faults. More details below. Anybody have any ideas what could cause this? At one point, I believe this worked. It's possible the machines aren't configured properly or don't have the necessary patches. Currently, the interpreter builds and seems to work fine. However, it can't load modules. Well, actually it can load modules, but as soon as the module calls a python utility (an API in libpython), it seg faults. Specifically (I cleaned the lines up and took out some stuff): neal at dupont [~/python/dist/src]$ make # snip line running build running build_ext building 'struct' extension gcc -g -c Modules/structmodule.c ./Modules/ld_so_aix gcc -bI:Modules/python.exp structmodule.o \ -L/usr/local/lib -o build/lib.aix-4.3-2.3/struct.so gcc -Wl,-einitstruct -Wl,-bE:struct.exp -Wl,-bI:Modules/python.exp \ -Wl,-bhalt:4 -Wl,-bM:SRE -Wl,-T512 -Wl,-H512 -lm \ -o build/lib.aix-4.3-2.3/struct.so \ build/temp.aix-4.3-2.3/structmodule.o -L/usr/local/lib ./python -c 'import struct' make: *** [sharedmods] Segmentation fault gcc version is 3.2. I tried xlc, but got the same results. I think xlc's version is 5.7.6.5 (5765-C6400). My LIBPATH was empty. I also set LIBPATH to the directory where libpython2.3.a lives, but it doesn't help. This is on AIX 4.3.1.0, but I've had the problem on 4.3.3.x and 4.2.1.0. Here's some more details: #0 0xd009be70 in Py_InitModule4TraceRefs () from build/lib.aix-4.3-2.3/struct.so #1 0xd009ac3c in initstruct () at /home/neal/python/dist/src/Modules/structmodule.c:1535 #2 0x101182e0 in _PyImport_LoadDynamicModule (name=0x2026d70c "struct", pathname=0x20161594 "build/lib.aix-4.3-2.3/struct.so", fp=0x0) at Python/importdl.c:53 This indicates that the dynamic load of struct.so was successful. (#2) The call to initstruct() in struct.so was successful. (#1) But inside the module, when we try to call Py_InitModule4TraceRefs() (or Py_InitModule in the code), it crashes. I don't know why. Suggestions? Thanks, Neal From sismex01 at hebmex.com Mon Nov 18 10:27:35 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 18 Nov 2002 09:27:35 -0600 Subject: Tkinter wart: bug or feature? Message-ID: > From: support @ internetdiscovery.com [mailto:support @ > internetdiscovery.com] > > On Sat, 16 Nov 2002 14:57:28 GMT, "Fredrik Lundh" > wrote: > > >David Eppstein wrote: > > > >> ...or do all the ugly bookkeeping necessary to make sure > that image1 > >> gets deleted when and only when it is no longer needed > > > >where all the "ugly bookkeeping necessary" is one extra line: > > > > lbl = Tkinter.Label(win.window, image=image1) > > lbl.photo = image1 > > This is still a bug workaround, just like using global. You're still > expecting the end user to do ugly bookkeeping, but only for images: > I don't have to hold a reference to text1 global for it to work. > No other commonly used entity in the Tkinter API has this > counter-intuitive behavior. It's also very counter-intuitive to what > Tkinter is wrapping, namelyTk itself. I've been reading this thread, and it doesn't seem to be a bug really, but a compromise between the two distinct ways that Python and Tcl manage their objects; in Python, if you lose all references to an object, it automagically disappears (including images); in Tcl, if you lose all references to an image, it doesn't disappear, you can reclaim it v?a "calling it by it's name". So, what would you propose? If you don't delete the image (in Tk) when the object is reclaimed, then the image is still lost to Python, because although Tk remembers it, Python doesn't. Maybe using a class dictionary in the Image class could help; when an image is instantiated *with* a name, upon creation, it's name is added to this dictionary. Upon destruction of the Python object, if it doesn't have a name, Tk's image object is also deleted. > I've seen a number of different bug workarounds for this, but > my question remains: is this a bug or feature? It has been > Benevolently declared to be Not a Bug, but clearly others have had > trouble with this too. If it's reopened as a bug we can do something > about it as there are obvious fixes as I pointed out, but if it's a > feature there's nothing we can do. Nothing to *cancel* the current behaviour, but that doesn't mean you can't make it better. -gustavo From psayuj at rediffmail.com Sun Nov 24 01:19:59 2002 From: psayuj at rediffmail.com (paul sayuj kanjirathingal) Date: 24 Nov 2002 06:19:59 -0000 Subject: embedding python inC Message-ID: <20021124061959.31099.qmail@webmail28.rediffmail.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From harsh at computer.org Sat Nov 23 14:17:15 2002 From: harsh at computer.org (Stacy White) Date: Sat, 23 Nov 2002 19:17:15 GMT Subject: DCOracle2 performance tuning Message-ID: <%uQD9.122449$1O2.8846@sccrnsc04> I work with a large body of Perl code, and am toying around with the possibility of converting to Python. One thing standing in my way is my inability to make DCOracle2 perform comparably to Perl's DBD::Oracle. DCOracle2 performance is good relative to DBD::Oracle until it's faced with large result sets. For instance, time for: c = db.cursor() c.execute("select one_field from table_with_10000_rows") r = c.fetchone() while r: r = c.fetchone() is 0.620u 0.030s 0:00.75 86.6% 0+0k 0+0io 1193pf+0w vs. my $sth = $dbh->prepare("SELECT one_field from table_with_10000_rows"); $sth->execute(); while (my $data = $sth->fetchrow_arrayref) { } at 0.480u 0.040s 0:00.62 83.8% 0+0k 0+0io 1211pf+0w So not quite as fast, but still acceptable (about 0.12s in either case is due to login time, so the Python code takes about 25% longer, but that's not too big a deal). But changing the execute line to select all 50 fields from the table: c.execute("select * from table_with_10000_rows") changes the Python time to: 10.780u 0.120s 0:10.74 101.4% 0+0k 0+0io 5549pf+0w vs. a Perl time of: 1.960u 0.060s 0:02.18 92.6% 0+0k 0+0io 1218pf+0w I've fiddled around with fetchmany, and fetchall with no luck. For example, changing the inner loop to: rows = c.fetchmany(20) while len(rows): for r in rows: pass rows = c.fetchmany(20) leaves me with the same performance. Any suggestions? From bokr at oz.net Mon Nov 4 21:25:57 2002 From: bokr at oz.net (Bengt Richter) Date: 5 Nov 2002 02:25:57 GMT Subject: parenthesis References: <2259b0e2.0211041224.7c24635b@posting.google.com> Message-ID: On 4 Nov 2002 22:05:11 GMT, bokr at oz.net (Bengt Richter) wrote: >On 4 Nov 2002 12:24:31 -0800, mis6 at pitt.edu (Michele Simionato) wrote: > >>Suppose I want to parse the following expression: >> >>>>> exp='(a*(b+c*(2-x))+d)+f(s1)' >> >>I want to extract the first part, i.e. '(a*(b+c*(2-x))+d)'. >> [... previous version ...] Wondering why I didn't just write: >>> import re >>> rx = re.compile(r'([()]|[^()]+)') >>> class Addelim: ... def __init__(self, delim): ... self.parens=0; self.delim=delim ... def __call__(self, m): ... s = m.group(1) ... if s=='(': self.parens+=1 ... if self.parens==1 and s==')': ... self.parens=0 ... return s+self.delim ... if s==')': self.parens -=1 ... return s ... >>> exp = '(a*(b+c*(2-x))+d)+f(s1)' It was natural to be able to specify the delimiter. And the + is probably better than the * on the non-paren "[^()]+" part of the pattern. Then using \n as delimiter to break into lines one can just print it. >>> print rx.sub(Addelim('\n'),exp) (a*(b+c*(2-x))+d) +f(s1) Which you could also use like: >>> print rx.sub(Addelim('\n'),exp).splitlines() ['(a*(b+c*(2-x))+d)', '+f(s1)'] Or to get back to your original requirement, >>> print rx.sub(Addelim('\n'),exp).splitlines()[0] (a*(b+c*(2-x))+d) But I suspect it would run faster to let a regex split the string and then use a loop like yours on the pieces, which would be '(' or ')' or some other string that you don't need to look at character by character. E.g., >>> rx = re.compile(r'([()])') >>> ss = rx.split(exp) >>> ss ['', '(', 'a*', '(', 'b+c*', '(', '2-x', ')', '', ')', '+d', ')', '+f', '(', 's1', ')', ''] Notice that the splitter matches wind up at the odd indices. I think that's generally true when you put parens around the splitting expression, to return the matches as part of the list, but I'm not 100% certain. Anyway, you could make use of that, something like: >>> >>> parens = 0 >>> endix = [] >>> for i in range(1,len(ss),2): ... if parens==1 and ss[i]==')': ... parens=0; endix.append(i+1) ... elif ss[i]=='(': parens += 1 ... else: parens -= 1 ... >>> endix [12, 16] You could break the loop like you did if you just want the first expression, or you could grab it by >>> print ''.join(ss[:endix[0]]) (a*(b+c*(2-x))+d) or list the bunch, >>> lo=0 >>> for hi in endix: ... print ''.join(ss[lo:hi]) ... lo = hi ... (a*(b+c*(2-x))+d) +f(s1) or whatever. Which is not as slick, but probably faster if you had to do a bi-ig bunch of them. I think when the fenceposts are simple, but you are mainly interested in the data between, splitting on a fencepost regex and processing the resulting list can be simpler and faster than trying to do it all with a complex regex. Regards, Bengt Richter From tjreedy at udel.edu Sun Nov 24 18:48:21 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 24 Nov 2002 18:48:21 -0500 Subject: if : References: <3DE14A0C.E0CDBC16@alcyone.com> Message-ID: "Bengt Richter" wrote in message news:arrjjs$2ro$0 at 216.39.172.122... > except in perverse ways (and this is not the only one): > >>> b=123 > >>> if [a for a in [b]][0] == 123: print 'aha' > ... > aha > >>> a > 123 Interesting ... > > BTW, are list comprehensions going to get their own local namespace sometime > or is this the way it's going to be forever? Probably same as for for loops. tjr From ngterry2000 at yahoo.com.hk Mon Nov 11 23:01:16 2002 From: ngterry2000 at yahoo.com.hk (=?big5?q?Terence=20Ng?=) Date: Tue, 12 Nov 2002 12:01:16 +0800 (CST) Subject: HTML email marketing tool Message-ID: <20021112040116.5154.qmail@web41107.mail.yahoo.com> I guess it cannot consider as spaming if I provide the option to remove from the mailing list. Thanks! Terence _________________________________________________________ ??(???)????(???)??????(???)... Over 800 latest ringtones, only on Yahoo! http://ringtone.yahoo.com.hk From doug.fort at verizon.net Tue Nov 26 20:15:26 2002 From: doug.fort at verizon.net (Doug Fort) Date: Wed, 27 Nov 2002 01:15:26 GMT Subject: accessing front of a list References: Message-ID: On Wed, 27 Nov 2002 00:50:35 +0000, Simon Bunker wrote: > This is probably a fairly newbie question - and also because I am > coming from a Perl background. I was wondering if there is a Python > equivilant to Perls shift operator? > > There seem to be many ways of getting access to the end of an array - > pop() append() etc but I couldn't find anyting to shift off the front like > when > reading in argv. > You can pop() from either end of a list. pop(0) gives you the head, pop() or pop(-1) give you the end. But when accessing a list from front to rear, I find my self using constructs like 'for x in l:...' or the functional programming tools map(), filter(), reduce(), etc. -- Doug Fort, Programmer http://www.dougfort.net From tjreedy at udel.edu Sat Nov 16 16:39:57 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 16 Nov 2002 16:39:57 -0500 Subject: Formatted Output - Floating Point Numbers References: Message-ID: "David Marshall" wrote in message news:d8d62a73.0211161321.12603c31 at posting.google.com... > Im new to python and I was wondering if anybody could tell me how to > modify the output to only obtaiu 2 decimal places. Look up % formating operator. tjr From hanzac at cmmail.com Tue Nov 26 07:41:35 2002 From: hanzac at cmmail.com (hanzac) Date: 26 Nov 2002 04:41:35 -0800 Subject: Does anyone use Jython to implement a robot of Robocode? I hava a problem. Message-ID: I have succeeded in creating & running a robot which was coded in Jython, But the problem is when I first run the robot, it is disabled but after a round it runs well. The code is here (SampleBlaze.py): // The Robot from robocode import * class SampleBlaze(Robot): dist = 50 def run(self): while 1: self.turnGunRight(5) def onScannedRobot(self, e): if e.getDistance() < 50 and self.getEnergy() > 50: self.fire(3) else: self.fire(1) self.scan() def onHitByBullet(self, e): self.turnRight(self.normalRelativeAngle(90-(self.getHeading()-e.getHeading()))) self.ahead(self.dist) self.dist *= -1 self.scan() def onHitRobot(self, e): turnGunAmt = self.normalRelativeAngle(e.getBearing()+self.getHeading()-self.getGunHeading()) self.turnGunRight(turnGunAmt) self.fire(3) def normalRelativeAngle(self, angle): if angle > -180 and angle <= 180: return angle fixedAngle = angle while fixedAngle <= -180: fixedAngle += 360 while fixedAngle > 180: fixedAngle -= 360 return fixedAngle From mwh at python.net Fri Nov 8 05:56:43 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 8 Nov 2002 10:56:43 GMT Subject: power TypeErrors References: <20021107192126.26346.92569.Mailman@mail.python.org> Message-ID: <7h3wunoxrgu.fsf@pc150.maths.bris.ac.uk> Terry Hancock writes: > [interesting stuff] Thanks. > FP > I'm not sure what your background is, > > MH> Algebraic geometry, mainly, plus a little theoretical physics & number > MH> theory. > > Yep. It's ironic that mathematicians hardly ever "do math" (by which I mean > calculations)! Hey, I "do calculations"... > It's scientists that do that -- mostly applied physics folks: > astronomers, chemists, geologists, engineers, and some biologists. > > Mathematical and theoretical physics applications tend to stay very > conceptual. They manipulate equations, but they hardly ever have to > actually plug in numbers and solve them (especially in droves). ... just not usually with numbers :) Cheers, M. -- For their next act, they'll no doubt be buying a firewall running under NT, which makes about as much sense as building a prison out of meringue. -- -:Tanuki:- -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From mwh at python.net Tue Nov 19 08:09:09 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 19 Nov 2002 13:09:09 GMT Subject: Hmm... An idea: if a,b==c,d: References: <7h3r8dhvkbc.fsf@pc150.maths.bris.ac.uk> <3DDA32B7.5060508@zuken.de> Message-ID: <7h3el9hvheu.fsf@pc150.maths.bris.ac.uk> "Jan D. Wegner" writes: > Hi, > > using py 2.2.2 on winNT > > l = (1, 2, 3, 4) > ans = l in [l] # is tuple l in list l ? > ans > 1 # allways true > ans < 2 > 1 # its a boolean, though ... > > am I right? > > ( or is ther a chance to execute 'if l in ( [l] < 2 ):' ) Nope, it's much more surprising than that... Cheers, M. -- For their next act, they'll no doubt be buying a firewall running under NT, which makes about as much sense as building a prison out of meringue. -- -:Tanuki:- -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From patrickw106 at yahoo.com.au Thu Nov 21 18:42:57 2002 From: patrickw106 at yahoo.com.au (Patrick W) Date: 22 Nov 2002 10:42:57 +1100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <87u1ib6bte.fsf@key.localdomain> <3u3D9.49382$Yw.2293340@news2.tin.it> <874rabdo3t.fsf@key.localdomain> <5r6D9.50977$Yw.2347638@news2.tin.it> Message-ID: <87wun6ij5q.fsf@key.localdomain> Alex Martelli writes: > > I don't WANT to use a language that lets me redesign it -- worse, I > most definitely don't want to use a language that lets _others_ > redesign it, and find myself stuck using and supporting half a dozen > different (and mostly badly designed) languages in as many disparate > projects. If my purpose in life was to experiment with programming > languages, I would surely feel differently; but it's not. Fair enough too! For personal hacks, I *love* to use a language that lets me redesign it without inflicting pain on anyone else. In a group setting I'd prefer to use Python or 'vanilla' CL for most purposes. Macros are excellent for tinkerers (like me) and for experts like language designers. If the two uses are kept distinct (experimenting with ideas vs writing macros for other people's consumption in order to evolve a language), there is no problem. But I agree the *potential* for hubris is great, and potentially deadly. ;-) > So, I do miss multiple dispatching, which would let me avoid this > infrastructure building just like I can avoid it in the more common > single dispatch case. > > But I don't miss it ENOUGH to wish that Python had macros (shudder)...:-). > Not by a long shot, in fact... Same here. It's Lisp AND Python for me. Not OR. From mertz at gnosis.cx Wed Nov 27 02:29:58 2002 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Wed, 27 Nov 2002 02:29:58 -0500 Subject: Python Tutorial Was: Guido's regrets: filter and map References: <3de39ce9$0$22220$a1866201@newsreader.visi.com> <3DE44D27.3030904@something.invalid> <6GH59kKkXIpD092yn@gnosis.cx> Message-ID: <2RH59kKkXYeD092yn@gnosis.cx> ||And it doesn't replace reduce at all -- we've yet to see a construct ||proposed to do that (aside from writing it out as an explicit loop). Actually... here's an... ummm... "improved" version: reduce = lambda func, seq, init=None:\ [(l.append(func(l[i],seq[i])),l[-1]) for l in [[init or seq[0]]] for i in range(len(seq))][-1][1] Yours, Lulu... -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! ------------------------------------------------------------------------- From bhards at bigpond.net.au Tue Nov 26 01:12:59 2002 From: bhards at bigpond.net.au (Brad Hards) Date: Tue, 26 Nov 2002 17:12:59 +1100 Subject: if : In-Reply-To: References: Message-ID: <200211261713.00298.bhards@bigpond.net.au> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Tue, 26 Nov 2002 10:33, Delaney, Timothy wrote: > The most common of these are = vs ==, and just about anything to do with > pointer dereferencing. There are some useful defensive techniques. I often test for equality to a constant. If you put the constant on the left side, the compiler will help you: eg. if ( 0 == pointer) { } > The next most common class of errors involve memory issues - dereferencing > invalid pointers, double-freeing, failing to free memory, etc. Memory checking tools seem to be grossly underused. > ObRant: What the hell is the difference between an "implementation defined" > feature, and an "undefined" feature? In both cases, a particular > implementation is free to do whatever it wants. The only possible > difference I can think of is that "implementation defined" implies that the > implementation should at least try to do something useful ... and actually > document what it does. - From the Sep 2002 issue of "Linux Magazine" (the European one):, in relation to a C tutorial: "The three phrases that should strike fear into the hear of any programmer are 'implementation defined', 'unspecified' and 'undefined' .... Implementation defined means it is up the compiler vendor to pick a method, document it, and stick by it - at least within this particular version ... Unspecified means that the compiler writers know what will happen, but they haven't document it.... Undefined mena that anything can happen. And it means anything. The results need not adhere to logic, the expression in question, or even the day of the week... Suffice to say, you should never write code that relies on, expects, or follows any of these criteria". - -- http://linux.conf.au. 22-25Jan2003. Perth, Aust. I'm registered. Are you? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE94xDrW6pHgIdAuOMRAsY3AJ9ojZO0v7jl+x34moCsPaHNy/38NACgnPG+ TkIsz3sFsU7InA8Ejdj69qk= =Q+rJ -----END PGP SIGNATURE----- From martin at v.loewis.de Sat Nov 9 02:27:38 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 09 Nov 2002 08:27:38 +0100 Subject: Determining Presence Of GUI Support References: <42aiqa.jp82.ln@boundary.tundraware.com> Message-ID: Tim Daneliuk writes: > Is there a portable method of determining whether the current runtime > environment supports a GUI or text-based interface? I would like to > write a single program which autosenses the presentation environment > and works accordingly. I'm not quite sure what you mean by "environment" and "supports GUI". The environment may support a GUI, but you may not have the libraries, or you may have a GUI, have the libraries, but your program may not be prepared to use these libraries, and so on. To verify whether you have Tk libraries, import Tkinter. If that gives an ImportError, you don't have Tk libraries. Then, create an Tkinter.Tk instance. If that gives a Tkinter.TclError, you cannot use Tk as a GUI. For other libraries, similar procedures apply. HTH, Martin From bebert at tiscali.dk Sat Nov 23 09:11:17 2002 From: bebert at tiscali.dk (Bjarke Dahl Ebert) Date: Sat, 23 Nov 2002 15:11:17 +0100 Subject: Iteration of strings References: Message-ID: "Terry Reedy" wrote in message news:faWdnQY6h6rRT0OgXTWcqw at comcast.com... > > Some function expects a list of strings, > Here is the root of your problem. In a real sense, Python functions > have no expectation as to type. Yes they do - the expectation is just not explicitly stated, and it is often more "vague" than any simple formal type system could express. > > This is unfortunate, because in a sense, a string is also a list of > strings! > Not just 'in a sense'. Substituting 'sequence' for 'list', this is a > defined feature of the anguage. If one wants the polymorphism, this > is fortunate, not unfortunate. I consider being able to iterate > through strings a great feature. But even though we have dynamic types, there is nothing wrong with having *strong* dynamic types, i.e. not anything applies to anything. I don't want everything to automatically convert into something that any given operation can work on. Then we end up as in Perl, where strings and numbers are somewhat magically converted into each other. > Polymorphism is part of the heart of the language. An > extra line of code here and there to limit it when not wanted is part > of the price of the benefits. Yes, it's probably good to explicitly limit the types of arguments (or other objects gotten from "somewhere" during function execution). E.g., assert isinstance(...). That catches many error early in the call stack, instead of giving strange, incomprehensible errors deeper down. > And the trend is to increase it. For > instance, 'for key in somedict:' just became legal in 2.2. It > previously would have raised an exception. So now you can also worry > about what happens if 'somestringlist' is somehow passed in as a dict > ;<). Yes, that can lead to suprizes too. IMHO, it would be better to require the more explicit "for key in somedict.iterkeys():". But of course, the new syntax (or actually, semantics of dict.__iter__) leads to more brevity, when we know what we are doing :-). Bjarke From wilk-spamout at flibuste.net Tue Nov 19 17:45:03 2002 From: wilk-spamout at flibuste.net (William) Date: 19 Nov 2002 23:45:03 +0100 Subject: wxPython crashing windows References: Message-ID: <87bs4lqivk.fsf@flibuste.net> Dave Brueck writes: > On Tue, 19 Nov 2002, trewornan wrote: > > > Well the subject says it all - has anyone else found wxPython crashing > > windows (all the way to a blue screen). > > No. not more... i had this problem with an old version of windows95. I had to install the "MS Control Update" http://wxpython.org/download.php#prerequisites -- William Dode - http://flibuste.net From ulbi at ivs.tu-berlin.de Mon Nov 4 10:55:19 2002 From: ulbi at ivs.tu-berlin.de (Andreas Ulbrich) Date: Mon, 04 Nov 2002 16:55:19 +0100 Subject: problem's with strings References: Message-ID: Richard Mertens wrote: > first problem: > > I'd like to convert a text-file von unix to windows and vice versa > > Do you know a solution for this > > > When the python script is reading the text-file i have always the Nextline - > Character on the end. How do you I remove it? from windows to unix: somestring.replace('\r', '') vice versa: somestring.replace('\n', '\r\n') From johs+n at ifi.uio.no Sat Nov 9 09:29:36 2002 From: johs+n at ifi.uio.no (Johannes =?iso-8859-1?q?Gr=F8dem?=) Date: Sat, 09 Nov 2002 15:29:36 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: * Ian Bicking : > But that's not going to be mainstream. In a heterogeneous environment > both Lisp and Smalltalk have serious issues. This is really implementation-specific, not strictly language- specific. There are Common Lisps that integrate well with C. There are even Lisps that let you use inline-assembler and inline-C in your Lisp-code. -- Johannes Gr?dem From boud at valdyas.org Sun Nov 3 08:30:56 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Sun, 03 Nov 2002 14:30:56 +0100 Subject: Foot in mouth disease References: <3dc3a6fd$0$84999$e4fe514c@dreader7.news.xs4all.nl> Message-ID: <3dc52687$0$84997$e4fe514c@dreader7.news.xs4all.nl> Skip Montanaro wrote: > > Boudewijn> With Python, I'm using grep as my main refactoring tool -- > Boudewijn> but I'm trying really hard to get into the habit of using > Boudewijn> bicyclerepairman (from emacs), which seems superior the > Java Boudewijn> tools I have used. > > I thought I saw a refactoring editor project on SF some time ago which was > written in and for Python. SF's search tool isn't working for me at the > moment. Does anyone know if this project is still active? > It that isn't bicyclerepairman, I wouldn't know. I try really hard to remember to use bicyclerepairman (also Eric, a really great debugger written in PyQt), but I'm so set in my ways that I very seldom use them... -- Boudewijn Rempt | http://www.valdyas.org From zhitenev at cs.vsu.ru Tue Nov 26 12:13:12 2002 From: zhitenev at cs.vsu.ru (Lexy Zhitenev) Date: Tue, 26 Nov 2002 20:13:12 +0300 Subject: wxPython Prob References: <3DE3A017.AEE4CE2B@ipm.fhg.de> Message-ID: "Markus von Ehr" wrote: news:3DE3A017.AEE4CE2B at ipm.fhg.de... > There occurs the error that the bitmaps used in: > images.getNewBitmap() > images.getOpenBitmap() > etc. are not found. > > (I imported images in the beginning.) > > Anyone knows the answer? > > Markus The only reason I can thinlk of is that images are not from %PYTHONPATH%\Lib\site-packages\wxPython\demo subdir. I've tried the sample from wxPython demo. Everything is OK. Look at it. Maybe, it will help From gerhard.haering at opus-gmbh.net Fri Nov 15 06:03:13 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 15 Nov 2002 11:03:13 GMT Subject: My (late) beef with Simple Generator syntax (PEP 255) References: Message-ID: In article , Alex Martelli wrote: > Neil Schemenauer wrote: >> Just wrote: >>> IMO the best idiom for this currently is >>> >>> def foo(): >>> while 0: >>> yield "whatever" >> >> This whole discussion is silly, IMHO. The best idiom is: >> >> def foo(): >> return [] > > Actually, I suspect returning () instead -- empty tuple, not > empty list -- is even better. To wit: > > [snip proof] > > admittedly the difference is going to be even less in 2.3, > but still, it's about 100 milliseconds per million empties one > returns -- a few billions, and we'd be talking about REAL > performance issues. Surely any implementation of something > as frequent as "returning an empty iterable" cannot aspire > to the title of "the best" with that sort of performance hit. Yeah, it's quite likely that this will be the bottleneck of your app. That's why you should squeeze the last percent or so of optimization out and return an empty string: [Python 2.2.2/win32] D:\tmp>python ba.py emptylist 1.71 emptytuple 1.16 emptystring 1.15 emptylist 1.72 emptytuple 1.16 emptystring 1.15 emptylist 1.72 emptytuple 1.16 emptystring 1.15 No /dev/emoticon on Windows, either. -- Gerhard H?ring OPUS GmbH M?nchen Tel.: +49 89 - 889 49 7 - 32 http://www.opus-gmbh.net/ From max at alcyone.com Sat Nov 9 16:54:41 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 09 Nov 2002 13:54:41 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h3adkiyjjr.fsf@pc150.maths.bris.ac.uk> Message-ID: <3DCD8421.283D193F@alcyone.com> Ng Pheng Siong wrote: > According to Michael Hudson : > > > { Java, Python, ocaml, Common Lisp, C++, perl } > > What language is this funny looking list in? ;-) It's standard set notation from mathematics :-). -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ I'm paranoid. But am I paranoid enough? \__/ Louis Wu Official Omega page / http://www.alcyone.com/max/projects/omega/ The official distribution page for the popular Roguelike, Omega. From claird at lairds.com Wed Nov 20 13:02:49 2002 From: claird at lairds.com (Cameron Laird) Date: Wed, 20 Nov 2002 18:02:49 -0000 Subject: Updating A Tkinter Window every 100 ms? References: Message-ID: In article , Martin v. Loewis wrote: >josiah7 at hotmail.com (Josiah) writes: > >> Is there a better way? Why does the "lift()" function not work with >> "self.master.lift()"? > >Because self has no attribute master. I suggest doing > >self.master = master > >inside __init__. . . . Also, I suspect there's a better way to achieve what Josiah *really* wants; I just don't know what the latter is. Is it to make modal dialogues, or prevent user resizing, or ...? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From sandysj at juno.com Mon Nov 11 11:16:43 2002 From: sandysj at juno.com (Jeff Sandys) Date: Mon, 11 Nov 2002 16:16:43 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCBDAAD.AD27DFEE@juno.com> <80a8af7d.0211081147.15cfd915@posting.google.com> Message-ID: <3DCFD7EB.D1A74FC1@juno.com> Klaus Momberger wrote: > Jeff Sandys wrote in message news:<3DCBDAAD.AD27DFEE at juno.com>... > > One reason is that Python has a lower threshold for learning. > > We can get a non-programmer productive in Python in 8-16 hours > > > Pardon me, but I totally disagree on that. > A *non-programmer* *productive* in Python within 8 hours ??? Gimme a break. The *non-programmers* are computer and unix literate engineers and scientist. And *productive* means able to write a simple file manipulation script on their own. Our *trainer* is a computer scientist/programmer with good communication skills. 7th and 8th graders can start writing functions after about 4-6 hours and classes after 8-12 hours of computer lab training. What I am talking about is the threshold of productivity, when people can write a useful program on their own, not when someone can write a full feature 1000+ lines of code application. These times are from my personal experience, what is your experience? My point is that the sooner someone can do something productive on their own the more likely they are to continue using the tool, and Python has a lower threshold that Lisp or Scheme. (It's just my opinion, I could be wrong) Thanks, Jeff Sandys From donn at u.washington.edu Fri Nov 22 16:38:44 2002 From: donn at u.washington.edu (Donn Cave) Date: 22 Nov 2002 21:38:44 GMT Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <2259b0e2.0211210838.7647301a@posting.google.com> <093kra.3n3.ln@beastie.ix.netcom.com> Message-ID: Quoth Pascal Costanza : | Donn Cave wrote: | |> The procedural aspect of Python is also natural but not necessarily |> benign. This is basically the linear descendent of assembly language, |> with variables for registers and other superficial differences; the |> alternative (or one of them, anyway) is the equational reasoning you |> find in functional and logic programming languages. It's arguably |> true that the normal programmer can more easily conceive a procedural |> solution to a problem, but it is not true that this solution will |> naturally be robust and maintainable. | [...] | | That's even true for code that superficially looks like OOP. An | extremely well-presented example and discussion of this can be found at | http://csis.pace.edu/~bergin/patterns/ppoop.html That's an interesting read, all right, but ``procedural'' is used there in a different sense, I believe, than I intended it - in fact, almost the opposite. In the sense I'm using it, OOP _is_ procedural, or nearly always. By some accounts, that may not have been the original idea, but the alternative (OO that is not procedural) seems to be difficult to find or describe. Probably the best counter example, of a language that emphasizes what I'm calling ``equational'' rather than procedural, is Haskell. It's the most prominent example of a ``non-strict, purely functional'' programming language (``non-strict'' is a queer term that probably doesn't mean what you think.) Haskell has a type class system that supports polymorphism, but it's no OOPL. There's an O'Haskell offshoot that I find really interesting (though evidently I'm alone on that, because it seems to be a dead project), and it really illustrates the point by adding OO to Haskell and not making it a bit like any ordinary OOPL. Any real program will fall somewhere in between - nothing stops me from writing C code that is purely functional in places, and no Haskell program can do anything without resorting to some fundamentally procedural code to put it in motion. But you can expect to see a strongly procedural approach in OOPLs, because the object is all about encapsulating program state - and that program state is the stuff of procedural programming. Donn Cave, donn at u.washington.edu From usenet at coastergames.net Sat Nov 16 17:37:45 2002 From: usenet at coastergames.net (Tyler Eaves) Date: Sat, 16 Nov 2002 22:37:45 GMT Subject: Formatted Output - Floating Point Numbers References: Message-ID: David Marshall wrote: > Im new to python and I was wondering if anybody could tell me how to > modify the output to only obtaiu 2 decimal places. > > the section of my program that needs modification > > display.divide(57,7) # I only want 2 decimal places returned > > I have a module called display and my function divide() returns the > result of the two numbers divided. However, I only want this number to > two decimal places. > > I have tried: round(display.divide(57,7) [,2]) > But this results in an error message saying invalid syntax > > > Any help would be much appreciated Use the % operator. IE: print "%.2f" % yourFloat -- Tyler Eaves From duncan at NOSPAMrcp.co.uk Thu Nov 14 04:34:21 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 14 Nov 2002 09:34:21 +0000 (UTC) Subject: Newbie question References: Message-ID: "Firdaus Janoos" wrote in news:aqvlp2$rtb$1 at tilde.itg.ti.com: > I know this is kind of dumb, but i cant figure out how to execute > a .py > file (not a module - a pgm ) from IDLE. I am unable to "load" the > file. The IDLE menu has options for > File/Open > and File/Open Module > and neither of these open and load the file I want to execute. They > just exhibit some pretty strange behavior. > Can anyone give me a clue ? File/Open lets you open a script or a module for editing by specifying its filename. File/Open Module lets you open a module for editing by specifying the name of the module. For this to work the module source has to be in a directory in sys.path. Once you have a module or script open for editing, 'Edit/Run script' lets you run the currently open file as a script (even if you opened the file using Open Module). If you just want to run a script then it is often easiest to start it from outside Idle, even if you are using Idle to edit it at the time. Just save and then start the script from your usual command line or gui shell. One word of warning, Idle doesn't run the script in a separate process, so after you have run a script once, any variables it created will be left lying around. This can have implications when you run the script again. This is especially true if the script is a unit test which imports the module that it tests as the module to be tested will not be reloaded unless you or your script do it explicitly. Also, should the script lock up or crash the Idle environment will go with it. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From ktilton at nyc.rr.com Tue Nov 19 15:23:51 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Tue, 19 Nov 2002 20:23:51 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <44d4f61c.0211181708.465f5838@posting.google.com> <3DDA7385.2020609@nyc.rr.com> Message-ID: <3DDA9EB4.8020802@nyc.rr.com> David Eppstein wrote: > In article , > Steven Rumbalski wrote: > > >>David Eppstein wrote: >> >> >>>>The numbers I hear are that CL runs on average 20% slower than C. >>> >>>This is after how many decades of Lisp compiler development? >>> >> >>Sheesh. How long have C compilers been around? > > > Not as long as Lisp by a long shot,.. Lisp has been around a long time, but how long have Lisp compilers been around? > and C was designed to be easy to > compile. Hunh? That was my point. Compiled CL being 20% slower than C has nothing to do with the ability of CL compiler writers, it has to do with late binding and dynamism in general. I mean, this whole digression is silly. CL compiler writers have access to the research on compiler design. And like I said, apparently they know what they are doing based on CL being almost as fast as (portable) assembler. The digression is silly for another reason: it started with someone saying Lispers should not call other languages slow. Whether you like respect CL compiler writers or not, compiled CL is almost as fast as C. so.... slow! slow! slow! :) Mind you, slow is fine given the performance of today's systems. I mean, it's relative, and a relatively slow language with other virtues is great if it is fast enough. My apps tend to use as much speed as they can get, but a whole lot get more than enough horsepower from today's boxes, so why not use that surplus to power an only relatively slow language. -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From stuart at bmsi.com Thu Nov 7 22:31:18 2002 From: stuart at bmsi.com (Stuart D. Gathman) Date: Fri, 08 Nov 2002 03:31:18 GMT Subject: Getting SSL certificate Message-ID: The httplib modules supports SSL, but does not check certificates. Fine, but I couldn't find a way to get the server certificate to check it myself. How do I get the server certificate from an HTTPSConnection object? I dug down to where it calls the _socket C module, and still didn't find anything that would fetch this info for me. For this application, I just need to check for a specific name and specific signer. I suppose checking that the signature is valid could get involved, but I can't try until I can get the certificate. And attempting to check with false positives is no worse than not checking at all. Furthermore, when playing with urllib, proxies don't seem to work with the https protocol. It passes the "https://host.com" url to the proxy server, instead of using the proxy CONNECT request needed for SSL. Am I doing something wrong? I set the proxy like this: export https_proxy="http://myproxyhost:8081" (And http_proxy works as expected.) -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From jon at csh.rit.edu Sat Nov 16 16:57:36 2002 From: jon at csh.rit.edu (Jon Parise) Date: Sat, 16 Nov 2002 16:57:36 -0500 Subject: Calling local functions from the C API Message-ID: <20021116215735.GA17174@csh.rit.edu> This seems like it should be a common, easy task, so perhaps I'm complicating the problem. I'm familiar with calling functions using PyObject_CallObject(). I generally use PyImport_ImportModule() to import a callable object from some module before executing it. However, I'm unclear as to how to go about getting a callable object from the current local scope (i.e. not from a named module). Help, please. =) -- Jon Parise (jon at csh.rit.edu) :: http://www.csh.rit.edu/~jon/ From bokr at oz.net Sun Nov 17 23:03:30 2002 From: bokr at oz.net (Bengt Richter) Date: 18 Nov 2002 04:03:30 GMT Subject: pythonic way to optimize access to imported value? References: <3DD85526.6020606@something.invalid> Message-ID: On Mon, 18 Nov 2002 15:49:10 +1300, Greg Ewing wrote: >Bengt Richter wrote: > >> I assumed that it is possible to release all references to an imported module, so that >> the garbage collector can eliminate it from memory > > >That won't happen -- the module remains in the global >list of modules maintained by the interpreter, even if >all other references to it go away. > You clipped my footnote section and reference, which I thought indicated that I saw that that is the way it ordinarily works: """ >>> >>> import sys >>> sys.modules.get('math') >>> pi = __import__('math').pi import math # builtin >>> sys.modules.get('math') >>> del sys.modules['math'] >>> sys.modules.get('math') >>> import math import math # previously loaded (math) ^^^^^^^^^^^^^^^^^^^^^^^^ Is there no way to do a private throwaway import? """ So, on to the final question, which I'd still be interested in an answer to. BTW, to me, irreversibly tangled loading operations smack of problems that you "solve" by rebooting windows. IOW, IMO there ought to be a way to do a temporary global-side-effect-free import and delete all traces of its having been done -- without restarting the interpreter or invoking a second interpreter instance. After all, it's basically just instantiating an instance of a special class, isn't it? I would think if I dig in the import code there should be a place where an isolated instance is created, before it's irreversibly (?) hooked into the system. Regards, Bengt Richter From Hobbes2176 at yahoo.com Fri Nov 1 11:49:28 2002 From: Hobbes2176 at yahoo.com (Mark) Date: Fri, 01 Nov 2002 11:49:28 -0500 Subject: PyQwt References: <3znw9.43274$iV1.36511@nwrddc02.gnilink.net> <3DC2102F.8080706@SPAMnwinternet.com> Message-ID: Jim wrote: > I don't know how gentoo packages PyQt, but it isn't possible > any longer to build PyQt without the sip files (unless someone Ah, this might be the problem. If the PyQT distribution has the .sip files but they aren't necessary after PyQT is built, they may not get installed anywhere. Might that be the case? > If you have a working 'locate' or 'find' you should be able to > determine where qtmod.sip is located if you have them, and the Yup. I rebuilt the locate database (updatedb) and then locate'd and nada. > 'import qt' in the Python interpreter if PyQt is installed > correctly. 'import qt' works. > files to build. You can usually get a message to Gerard on > the PyKDE mailing list (which also serves for PyQt, sip and > some related stuff) at: > > http://mats.gmd.de/mailman/listinfo/pykde > > and there should be other PyQwt users on the list as well. > > > Jim Thanks a ton. I'll get in touch with that list if it isn't the problem I mentioned above. Regards, Mark From wlfraed at ix.netcom.com Tue Nov 12 15:32:14 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 12 Nov 2002 12:32:14 -0800 Subject: How do I reply to an item in the list ? References: <44ee1dc2.0211120501.2c9e3215@posting.google.com> Message-ID: Patrick.Carabin at MyRealBox.COM fed this fish to the penguins on Tuesday 12 November 2002 05:01 am: > with Re : in Subject line, with groups.google, it DIDN'T place in the > thread, but as a separate message( new thread, NOT answer In a thread > ). Now trying with NO Re : in the subject Oh, main thing I notice is that there are no /references/ in your header, which means that it is considered the start of a thread... -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From marklists at mceahern.com Fri Nov 15 11:17:11 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 15 Nov 2002 10:17:11 -0600 Subject: wrapping all class methods In-Reply-To: Message-ID: [Robin Becker] > What's the 'proper' pythonic way to do this kind of global wrapping? Hi Robin, I don't know the answer, but I think aspect-oriented programming provides some ideas. Pedro Rodriguez has posted working code for doing AOP to the list: http://groups.google.com/groups?selm=pan.2002.01.22.15.52.49.832551.1637%40c lub-internet.fr Perhaps, if nothing else, Pedro's code may give you some ideas? I'd be very interested to hear what you come up with. What you're trying to do can be done with metaclasses fairly easily--but that requires (afaik) modifying the modules you want to wrap. Which makes it not a very good strategy for AOP (as Pedro has pointed out). See this thread: http://groups.google.com/groups?selm=mailman.1025278420.26105.python-list%40 python.org Cheers, // mark - From fperez528 at yahoo.com Fri Nov 8 14:12:55 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Fri, 08 Nov 2002 12:12:55 -0700 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: Eddie Corns wrote: >>I don't know much about Python, but I looked at this comparison >>between Python and Common Lisp ( >>http://www.norvig.com/python-lisp.html ), and I couldn't help but >>wonder why Python is popular, while Common Lisp and Scheme aren't? > > My opinion (the short version anyway) is that because Python is a lot easier > to learn and use. It's a bit like the difference between a point and click > camera and a 'real' one - to use a 'real' camera for even a simple photo you > need to understand the whole biz. However, unlike some languages I won't > mention, Python does its best to give the max. power (of Scheme,Haskell > etc.) for the max. ease of use. Flawed analogy, I think. I'd rather say: python is like a modern SLR with full auto modes: you can use it like a point'n'shoot, but still get very good results and the benefit of good lenses and a sophisticated exposure system. But once you move the dial to the 'manual' zone (P,Tv,Av,M for the photo-buffs) you are on your own, with as much control as you want (from simple adjustments in P to full manual in M). So in python the beginner feels comfortable, but he can grow into sophisticated things without the tool _ever_ getting in his way. That's why the point'n'shoot analogy is bad: in that case, the tool gets in your way and limits what you can do. If you want, Pascal is the point'n'shoot of programming languages: easy for beginners, utterly useless for serious work (yes, I wrote tons of pascal back in the day, so I know what I'm talking about). Lisp feels more like a viewcamera. You can't get _anything_ done unless you understand the fundamentals very well. But if you do, there are some very fancy things you can do. Cheers, f. From martti.halminen at kolumbus.fi Wed Nov 27 21:22:13 2002 From: martti.halminen at kolumbus.fi (Martti Halminen) Date: Thu, 28 Nov 2002 04:22:13 +0200 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3de1f902$0$695$edfadb0f@dread12.news.tele.dk> Message-ID: <3DE57DD5.B24BC297@kolumbus.fi> Robin Munn wrote: > What I'm going off of here is my memory of having to count and re-count > parentheses as I was writing to make sure that I was putting in the > right number of closing parens to finish a structure. With > color-highlighting, I could at least be certain *at a glance* of which > paren was lining up with which. Yes, I know I could use % in vi, and > that there is some equivalent function in emacs, but that would be much > slower than just seeing it. Whenever I put the cursor next to a closing paren in my emacs, it also highlights the corresponding opening paren. Have you managed to turn show-paren-mode off somehow? A more visible version of this happens if you do (setq show-paren-style 'expression) in your .emacs or the *scratch* buffer. > And no, I haven't needed indentation-based highlighting in Python. But > what I'm talking about isn't really indentation-based, it's > nesting-level based. And the reason for it is because I still don't > understand how to indent *properly* in Lisp, and can't find a good > reference on how to indent properly. Color highlighting would at least > give me the visual cues I need until I learn to indent. While there is a relatively standard style in Lisp indentation, it is so common that most places don't bother to document it :-\ http://www.lisp.org/table/style.htm has a paragraph about it, not very thorough. In practice, CL programmers mostly use whatever indentation Emacs does: the programmer doesn't make indentation decisions, just hits ctrl-j, TAB or M-x indent-sexp as needed and looks what happens. If the result looks unexpected (to a practiced eye), then it's time to start checking what went wrong. [By the time you start defining your own macros you'll probably want to modify their indentation, but at that time you're likely familiar with the style already.] -- From slawus at imf.au.dk Fri Nov 1 03:14:03 2002 From: slawus at imf.au.dk (Slawus) Date: Fri, 01 Nov 2002 09:14:03 +0100 Subject: MS Windows + Python + VTK -- how to install? Message-ID: Hello! How to make VTK (www.vtk.org) working with Python on Windows? What should I do to make this commands working: >>> from libVTKCommonPython import * >>> from libVTKGraphicsPython import * ? I have installed Python 2.2.2, NumPy and SciPy and they are working well. -- Slawomir Razniewski. From rmunn at pobox.com Sat Nov 30 13:34:10 2002 From: rmunn at pobox.com (Robin Munn) Date: Sat, 30 Nov 2002 18:34:10 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3de1f902$0$695$edfadb0f@dread12.news.tele.dk> <96u4sa.llp.ln@cvs> Message-ID: Max Ischenko wrote: > > Robin Munn wrote: > > > [...] > > >> where each indentation level would be a different color (foreground? >> background?). I wonder how hard it would be to modify lisp.vim to allow >> this? Well, that's not a project I really have time for at the moment; >> maybe later on. > > This's been done already: > >=== from Vim/after/syntax/lisp.vim [snip the code that's exactly what I was looking for] Fantastic! I looked in the Vim syntax files but didn't think about the after directory. Time to take another look at Lisp, methinks... By the way, for the several people up-thread who mentioned paren-highlighting after typing: you're right, that would make for a good solution to figuring out how many right-parens to type in any given situation. I still think that color-highlighting of parens will be useful as well, though, in one specific case: scanning the code you've just typed (without moving the cursor) to see the structure. If you're a veteran Lisper, you'll have used proper indentation, of course; but if you're a newbie, or if you're reading code written by a newbie, you can't necessarily trust that indentation matches actual code structure. In that case, color-highlighting could be *very* useful for speeding up the time it takes to verify the code. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From wganz at texoma.net Tue Nov 12 10:19:27 2002 From: wganz at texoma.net (Will Ganz) Date: Tue, 12 Nov 2002 09:19:27 -0600 Subject: Can python find fibonacci series in a single line of code? In-Reply-To: Message-ID: :> My Perl-addicted friend shows me that he can find fibanicci series in :> a single line of code. Perl is like some of the doctor's writing that I try to decipher at the hospital. Great for writing prescriptions but invoke divine intervention to read more than a couple of sentences. In fact, doctors will ask nurses to interpret other doctor's writings to read the progress notes.* The same with Perl. One liners and anything less than 100 lines you can do in Perl, but get Python for anything that you are going to have to maintain later. After having dealt with 15000 line Perl 'programs' with all global variables and documented solely by "self documenting variable names" (?quick, what is the difference in $filedate, $FileDate, and $Filedate?) Python is quite the relief to use. * estimated 45,00~>98,000 Americans die annually from medication errors v.s. 15,980 Americans murdered in the year 2001 From skip at pobox.com Fri Nov 8 07:44:14 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 8 Nov 2002 06:44:14 -0600 Subject: Upload file with multipart/formdata In-Reply-To: References: Message-ID: <15819.45470.706423.583305@montanaro.dyndns.org> Thomas> I want to upload a binary file with the script from: Thomas> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 Thomas> ASCII files get uploaded without problem, but binary data gets Thomas> cut before all 0xA1 bytes. Just taking an educated guess since I can't get to ActiveState's website to browse that recipe, but... Open the file in binary mode, e.g. f = file("somefile", "rb") -- Skip Montanaro - skip at pobox.com http://www.mojam.com/ http://www.musi-cal.com/ From robin at jessikat.fsnet.co.uk Thu Nov 28 09:49:30 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 28 Nov 2002 14:49:30 +0000 Subject: Is it possible to write web-based GUI using Python? References: <3DE4448E.5080201@attglobal.net> <3b091a1c.0211280411.7ee5443a@posting.google.com> Message-ID: A bit off topic, but using the newer features of browsers and dynapi.sf.net it's possible to get statefull behaviour on the browser using CGI without flushing the current page using javascript. I've been using a python cgi backend to interrogate a db to produce slices of very long dropdowns. Under the hood dynapi is using layers or ilayers and reading documents, one of the leading developers, Raymond Irving, claims >Robin, > >The IOElement has some new features that you're going >to really love! You don't have to call >"dynapi.onLoad(myOnLoad);" any more, infact you'll be >able to make synchronous calls! Even better is to >ability to create a "web service" and call it's >functions using dynapi! > >example: > >var result=myService.getUsers(); >// getUsers is a remote method on a server -- Robin Becker From sismex01 at hebmex.com Mon Nov 25 17:40:00 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 25 Nov 2002 16:40:00 -0600 Subject: Issue with new-style classes and operators Message-ID: > From: Jan Decaluwe [mailto:jan at jandecaluwe.com] > Sent: Monday, November 25, 2002 4:39 PM > > Alex Martelli wrote: > > > > So, to wrap an arbitrary object X in such a way that X's special > > methods will be used by any operator, you need to ensure you do > > the wrapping with a _class_ that exposes said special methods. > > That's generally easiest to do with a factory function with a > > nested class that uses inheritance, but you have many other choices > > depending on what exactly you're trying to accomplish. > > Mm, I think I see, thanks for that. (I'll try again to > understand this from the documentation.) However, if I use > inheritance from an immutable type, the subtype is automatically > immutable also, right? Maybe not... Mind you, I don't know why someone would want to do this. >>> class MuTint(int): def __init__(self): self._items = {} def __getitem__(self, item): return self._items[item] def __setitem__(self, item, value): self._items[item] = value def __delitem__(self, item): del self._items[item] >>> m = MuTint() >>> m 0 >>> m["hello"] = 2 >>> m["goodbye"] = 3 >>> m 0 >>> print m 0 >>> m["hello"] 2 > So I wanted mutability, I'm back to delegation ... and apparently > stuck with new-style classes ??? > > Jan But what's to great about old-style classes? -gustavo From acalcium at aol.com Thu Nov 7 05:38:37 2002 From: acalcium at aol.com (ACalcium) Date: 07 Nov 2002 10:38:37 GMT Subject: Making a better textbook (was Re: The Deitel book) References: Message-ID: <20021107053837.29445.00002985@mb-mg.aol.com> >fall. The only thing that >bothers me about Python for teaching is the lack of enforced private >members for classes. As an Why can u teach this in CS2 when they learn their 2nd programming language? I think Python as a first language is a good idea. They can always build on this knowledge. From maney at pobox.com Wed Nov 13 00:42:31 2002 From: maney at pobox.com (Martin Maney) Date: Wed, 13 Nov 2002 05:42:31 +0000 (UTC) Subject: Why is Python popular, while Lisp and Scheme aren't? References: Message-ID: Brian Quinlan wrote: > People make frequent mistakes with inline assignment in other languages > (e.g. C), so it shouldn't be allowed. You'll be wanting to throw out all manner of things on that basis, since there's nothing of much use that hasn't been the source of problems for some. I know, you have to draw the line somewhere, but to me this seems like a good deal of value to lose for what IME is little gain in idiot-proofing. I can agree that the value seems to be lower in Python in that the need for this arises less often than in, say, C. I haven't yet decided if I think that's due more to the language itself or to the way the lack of operator= has led to the construction of facilities to make it unnecessary for common uses. :-/ Mind, if the real answer is "Because Guido doesn't like it", I can reconcile myself to that. I'm just wondering if there's some other, more articulable, reasoning at work. (I guess I am saying that I don't consider "people make mistakes" a reason, at least not much of one. Possibly I have, for whatever reason, had a great deal less trouble with this than average. (hmmm, average *what*, exactly?)) > I don't think that indentation has anything to do with this. Think about the straightforward implementation of this in legal Python with less undersized indentation than I used before: for l in lines: m = re1.match(l) if m: ... process type 1 else: m = re2.match(l) if m: ... process type 2 else: m = re3.match(l) if m: ... process type 3 It interacts in that the non-operator assignment makes it imposible to use elif, so that each case has to buy another indentation level. And, yes, that could be avoided by repeating the match for the case that succeeded, but that seems about equally ugly to me: if re1.match(l): m = re1.match(l) ... elif re2.match(l): m = re2.match(l) ... > I'd write that as: > > def process_type_1(first, second, ...): > process type 1 record ... > > def process_type_2(first, second, ...): > process type 2 record ... > > processing_rules = [(r'....', process_type_1), > (r'....', process_type_2), > ...] > > > compiled_rules = [(exp.compile(), func) for (exp, func) in > processing_rules] > > for l in file.readlines(): > for exp, func in compiled_rules: > match = exp.match(l) > if match is not None: > apply(func, m.groups()) > break Yes, that approach occurred to me. It seemed, and still seems, like a great deal of overhead and effort for little if any gain in clarity, although it certainly does solve the marching right off the screen problem. > Notice that: > - it is very easy to add new record types You have two things that have to be added for each new case: a regexp and a code block. This doesn't allow much if any better propinquity of corresponding regexes and code; neither does the savings in explicit logic boilerplate appear to outweigh the function-form bolierplate it requires. Now, if Python had something like lambda that could be used to define a real function, not just an expression's worth of code, I might like this better, since then the regex and code could actually be brought together. But it doesn't. More generally, making it easier to add cases is not itself an advantage here. And adding generality is not always a win, since there's usually some cost... as I know too well, because I am prone to err in that direction myself. :-) > - record processing is more modular In general, yes. Not significant: the processing is usually very simple, along the lines of reordering the fields, dropping a few, maybe pasting two together. > - the code is pretty simple But not IMO as simple as the straightforward way of writing it, at least not at the scale involved here. The average number of patterns and rules for each file's data is probably under two; there are a great many whose processing is really trivial, and the combined recognition of a valid datat line and parsing by the regex is the real meat of it. I've long since refactored this to make those cases quite small - a list of parameters and the stylized parsing function that is on the order of one screen of code. But there are quite a lot of files, and some of them are a good deal messier, and it is these latter that I have mostly described - because they were where the problem became noticeable. I think the worst have about six pattern/action pairs (although there may be worse ones yet to come to my attention). Anyway, each file is handled separately, so adding a new file type doesn't touch any existing code at all for any of these approaches. BTW, I'd appreciate not being emailed a reply unless you're not posting publicly; that's just the way I am. Thanks. (hmmm, gotta migrate the random quote hack over to this machine...) From csshi99 at yahoo.com Mon Nov 4 23:23:52 2002 From: csshi99 at yahoo.com (xinghua shi) Date: Mon, 4 Nov 2002 20:23:52 -0800 (PST) Subject: More about simple question In-Reply-To: <001e01c2847f$96e07280$ba01010a@local> Message-ID: <20021105042352.48464.qmail@web21203.mail.yahoo.com> > > import sys,os,string > > pid = os.getpid() > > filename = ".ld.mon." + str(pid) > > print filename > > ^^^^^^^^^^Name error: name "filename" is not defined. > Actually, I have a file named "ld.stat.py" which is: def main(): import sys,os,string pid = os.getpid() filename = ".ld.mon." + str(pid) print filename And then I typed: python ld.stat.py And I use python2.2. Besides, if I want to run the file "ld.stat.py" by typing "ld.stat" directly, how to do with this? Thanks so much for your help. :) --------------------------------- Do you Yahoo!? HotJobs - Search new jobs daily now -------------- next part -------------- An HTML attachment was scrubbed... URL: From news at titanic.co.uk Sun Nov 10 08:14:00 2002 From: news at titanic.co.uk (Simon Faulkner) Date: Sun, 10 Nov 2002 13:14:00 +0000 Subject: CGI download CSV References: <3DCE4FD6.1050808@gazeta.pl> Message-ID: <0rmssug4b9o9uld7kn9mqg8bule76i2qdv@4ax.com> If I can get this to work it will be great. In Mozilla the file open in a browser rather than offering to save to disk In IE the file does nopt open. I will read a little more... Simon On Sun, 10 Nov 2002 13:23:50 +0100, bromden wrote: > From voodoo1man at hotmail.com Wed Nov 13 18:44:19 2002 From: voodoo1man at hotmail.com (Vlad S.) Date: 13 Nov 2002 15:44:19 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <7h3k7jlwock.fsf@pc150.maths.bris.ac.uk> <76c4da8e.0211101357.6a804d20@posting.google.com> Message-ID: <76c4da8e.0211131544.4b90e1fe@posting.google.com> anton at vredegoor.doge.nl (Anton Vredegoor) wrote in message news:... > On 10 Nov 2002 13:57:37 -0800, voodoo1man at hotmail.com (Vlad S.) wrote: > > Lisp> > > >the language, and get a YAPFL (yet another pseudo functional > >language). Last time I checked, Python fit into that category, so you > >already have what you say you want. > > Without confirming that I want that, I would like to mention that > functional languages can't have side effects. So in order to generate > any output at all some concessions have to be made. Strictly speaking > Lisp is not a functional language. My definition of a pseudo-functional language is one that implements the idea of first-class and anonymous functions (although the former is implied by the latter) and supports recursion (which, well, implies that it has functions =]). Continuations also seem to be becoming popular in these languages. I think Python pretty much satisfies the idea of a pseudo-functional language (admittedly from the little textbook-exercise experience I have with it, and the one look I took at stackless python), so Pythoners already have some of the major language construct benefits that Lispers enjoy, without the parentheses. Enjoy your syntax while you can, because judging where the "industry" is going (Java, XML and friends), in 10 years everything will look like Intercal. > To get at a strictly functionanl > language - now switching into science fiction mode - a possible > strategy could use an idea found in one of A.E. van Vogt's novel's. > Here a description of a part of the universe is made inside a human > brain which is indistinguishable from the real thing up until the > twentieth's decimal. This enables the main character to effect changes > in the universe because at that level of equality the description of > the universe and the universe itself cannot occupy separate locations. No need for all that =]. You can just use Church numerals ( http://www.wikipedia.org/wiki/Church_integer ), and that satisfies my definition, although I'm not very demanding. By that virtue Unlambda ( http://www.eleves.ens.fr:8080/home/madore/programs/unlambda/ ) claims to be Turing complete. From anthony_barker at hotmail.com Wed Nov 27 15:26:12 2002 From: anthony_barker at hotmail.com (Anthony_Barker) Date: 27 Nov 2002 12:26:12 -0800 Subject: Database Programming References: <3875fcac.0211260752.60e2e457@posting.google.com> Message-ID: <899f842.0211271226.703db9c@posting.google.com> > Unfortunately, you'll definitely need a third-party library for just being > able to make use of DB. Then you can write some classes to wrap around this > library, tune them for your needs and use it just like any other Python > program. What about dbi, ZODB & ZEO, And Gadfly (a small python rdbms)? From bromden at gazeta.pl Sun Nov 10 12:11:16 2002 From: bromden at gazeta.pl (bromden) Date: Sun, 10 Nov 2002 18:11:16 +0100 Subject: CGI download CSV References: <3DCE4FD6.1050808@gazeta.pl> <0rmssug4b9o9uld7kn9mqg8bule76i2qdv@4ax.com> Message-ID: <3DCE9334.2000308@gazeta.pl> > In Mozilla the file open in a browser rather than offering to save to > disk > In IE the file does nopt open. it depends on a browser's settings, nothing to do with server side -- bromden GCS d- s+: a- C++$ UL(++++) 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 blalor+dated+1037892895.0fc75e at ithacabands.org Sat Nov 16 10:34:51 2002 From: blalor+dated+1037892895.0fc75e at ithacabands.org (Brian Lalor) Date: Sat, 16 Nov 2002 08:34:51 -0700 (MST) Subject: Python instead of php In-Reply-To: <20021116153007.GA2139@lilith.ghaering.test> Message-ID: On Sat, 16 Nov 2002, Gerhard H?ring wrote: > > With the recent release of a standalone ZPT/TAL interpreter, I think replacing > > PHP with Python is easier than ever. Out of the box you can interpret TAL > > templates with relative ease simply by passing in an execution context (which > > in my case was just a dict). Its well worth a look. > > Do you have an URL for the standalone ZPT/TAL? http://www.zope.org/Members/4am/ZPT -- Brian Lalor | http://introducingthelalors.org/ blalor at ithacabands.org (email) | blalor at jabber.ithacabands.org (jabber) N33?27.369' W111?56.304' (Earth) From eric.brunel at pragmadev.com Fri Nov 15 04:20:12 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Fri, 15 Nov 2002 10:20:12 +0100 Subject: tkinter - tk window remains References: Message-ID: Dubois, Jeff wrote: > I am using Tkinter to bring up a ScrolledText window. > However, when the user closes the window by clicking on the X button in > the upper right of the ScrolledText window the "tk" window remains. Based > on documentation I have read I have tried using the .withdraw() method in > hopes the tk window would disappear. However the tk window still remains. > The code I am using is: > > rootWin = Tk() > rootWin.withdraw() > st = ScrolledText(master=rootWin) > st.pack(side=TOP, expand=1, fill=BOTH) > st.insert(END, "\n\n\n\n THIS IS MAIN WINDOW!\n") > rootWin.mainloop() > > I am using python2.1 on an Windows NT operating system. Where did you get your ScrolledText class? Even the one delivered with Tkinter (which is utterly broken and that you definetely shouldn't use) doesn't show this behaviour. Apparently, the one you're using is quite broken if it opens a new window. The st.pack stuff should create the ScrolledText widget in the "tk" window, so you shouldn't have to do a rootWin.withdraw(). My advice(s) would be: 1/ Create the ScrolledText with ScrolledText(rootWin) instead of ScrolledText(master=rootWin). The "master=" stuff is not needed and can lead to problems like yours 2/ Use a better ScrolledText class, like the one in Pmw (see http://pmw.sourceforge.net). And I'm quite sure you'll want all the other classes in Pmw too...! HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From jorgencederberg at hotmail.com Tue Nov 5 08:21:31 2002 From: jorgencederberg at hotmail.com (=?iso-8859-1?Q?J=F8rgen_Cederberg?=) Date: Tue, 5 Nov 2002 14:21:31 +0100 Subject: bug report w\o registering References: Message-ID: "Anton Vredegoor" wrote in message news:aq8cmh$gcq$1 at news.hccnet.nl... > On Tue, 5 Nov 2002 15:49:20 +1100, "Delaney, Timothy" > wrote: > > >> From: anton at vredegoor.doge.nl [mailto:anton at vredegoor.doge.nl] > >> > >> Here's a bug report. I don't want to register at SourceForge now > >> (browser settings etc.). Sorry for the inconvenience. > > > >If you do not submit to sourceforge, the bug report *will* be lost. > > If you do not read the traceback you will not detect the bug. If read the traceback, and there is no bug. Extract from the Library reference: > > Anton. > > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on > win32 > Type "copyright", "credits" or "license" for more information. > IDLE 0.8 -- press F1 for help > >>> import os,popen2 > >>> infile,outfile = os.popen2("dir","b",-1) > >>> outfile,infile = popen2.popen2("dir","b",-1) > Traceback (most recent call last): > File "", line 1, in ? > outfile,infile = popen2.popen2("dir","b",-1) > File "D:\PYTHON22\lib\popen2.py", line 123, in popen2 > w, r = os.popen2(cmd, mode, bufsize) > TypeError: popen2() argument 2 must be string, not int > >>> From bokr at oz.net Mon Nov 4 00:45:13 2002 From: bokr at oz.net (Bengt Richter) Date: 4 Nov 2002 05:45:13 GMT Subject: import Image vs from PIL import Image vs import PIL.Image References: Message-ID: On 4 Nov 2002 04:57:37 GMT, bokr at oz.net (Bengt Richter) wrote: >I seem to have succeeded in building PIL from source with jpeg and zlib 1.1.4 >on windows NT. PIL and its pdf documentation manual are very nice (note that >if you're still using an old Acrobat 3 reader you will need to upgrade to >read the pdf manual). > >I backtracked and took alternate routes and hacked here and there on the way >to the goal, so there were probably numerous places where something could have >gone wrong, but it seems to work if -- and here's where my question comes in -- >I put 'from PIL ' in front of the import statements in documentation examples. > >Googling reveals some discussions of similar symptoms in the past, but I didn't >find a solid diagnosis or suggestion in what I skimmed. > >Hm... Not that I think I really want the available-for-import-using-a-plain-name >namespace to include a lot of stuff from various packages all the time. I may want >to use it just as an ordinary package anyway. > >I think I'd rather work up some kind of mechansim to expose only what I'm interested >in at a given time, something like use_package('xxx') and then having site-packages/xxx >put temporarily in the search path. I haven't explored package use that much, so perhaps >there already is such a feature amongst the batteries? > >I am running 2.2.2, and getting the following (separate invocations of Python to be sure): > > [20:43] C:\pywk\pilt>python > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import Image > >>> Image.core > > >>> ^Z > >The above obviously stops anything further from working, though it's easy to work around: > > [20:43] C:\pywk\pilt>python > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> from PIL import Image > >>> Image.core > > >>> ^Z > > > [20:43] C:\pywk\pilt>python > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import PIL.Image > >>> PIL.Image.core > > >>> ^Z > >I had to copy zlib.dll into the PIL directory so that _imaging.pyd would load >the latter ways, but I'm wondering why the import _imaging in Image.py is apparently >seeing things differently. > >What did I glitch or omit? Or what is the explanation? > Never mind. I glitched it by having put a bad _imaging.pyd under \python22 along the way. Removing it fixed the problem. Regards, Bengt Richter From brian_ at yahoo.com Mon Nov 4 02:55:41 2002 From: brian_ at yahoo.com (Brian Lenihan) Date: Sun, 3 Nov 2002 23:55:41 -0800 Subject: import Image vs from PIL import Image vs import PIL.Image References: Message-ID: In article , bokr at oz.net says... > > Thanks, but that wasn't the problem. I had caused it with hacking detritus. > > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import Image > >>> Image.core > > >>> ^Z > > [22:20] C:\pywk\pilt>cat D:\python22\lib\site-packages\PIL.pth > PIL > > But I notice an interesting difference in the name and place of the dll. Yours > is right under site-packages\ as PIL_imaging.pyd and mine is under > site-packages\PIL\ as _imaging.pyd. Did you install via the binary installer? > I built it myself. Well, now I'm confused. I removed PIL.pth and got the same path you do. I put PIL.pth back and still get the same path you do. From frans at haarman.com Sun Nov 3 14:58:52 2002 From: frans at haarman.com (Frans) Date: Sun, 03 Nov 2002 19:58:52 GMT Subject: Parsing & question about usages off classes! References: Message-ID: <0efx9.175905$Mf5.8592441@Flipper> Alex Martelli wrote: > If by any chance your request for creating new classes > has nothing to do with creating new classes but is rather > about binding dynamically computed names to new instances > of an existing class, my earnest advice is not to do that. > Use dictionaries and lists, NOT variables with dynamically > determined names -- the latter is never a good approach. Ok. I am trying a different approach. But I am still having problems. I want to create several new list. The name off the new lists will come from another list. That way I can create several lists, depending on the data received from logfiles. Is that possible ? Or isnt that a good idea either ? :) So basicly: my_list['some','data'] variable = my_list[0] variable = list Now this doesnt work, but the result I want is a new list with the name 'some'. Thanks, Frans From cnetzer at mail.arc.nasa.gov Fri Nov 15 19:42:53 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Fri, 15 Nov 2002 16:42:53 -0800 Subject: Tkinter wart: bug or feature? In-Reply-To: References: <3dd563db.9499247@nntp.ix.netcom.com> Message-ID: <200211160042.QAA24657@mail.arc.nasa.gov> On Friday 15 November 2002 13:36, David Eppstein wrote: > > So, just so I'm clear about this, the workaround is to add image = None > to your procedure, before it returns? That's not how I took it. Assuming you actually meant "image1 = None", then that would explicitly lose the reference to the Tkinter.Image object, which happens anyway once the function returns and the 'image1' variable goes out of scope. What Mike was saying is that: lbl = Tkinter.Label(win.window, image=image1) Hands off image1 to the Label object, which eventually becomes a Tcl/Tk construct. However, this does NOT increase the reference count for the Tkinter.Image object itself, and so when image1 goes out of scope, it gets a reference count of zero, and causes the actual image memory to be deleted, which causes Tk to not display the image (because the Tcl/Tk delete command was called on it) In a class, you could just keep a reference to the image to keep it alive as long as Tkinter.Label is alive. But in a function, Tkinter.Label as well as Tkinter.Image both go away (the difference is that Tkinter.Label being garbage collected does NOT cause the forget and/or destroy method to be called on the Tcl/Tk widget itself.) I agree that it is an inconsistency. I think I agree with Mike that collection of Tkinter.Image should NOT call "image delete" at this point; however, that causes other problems (when DOES the Image ever get deleted?) Since the python object is destroyed, the name is lost (to Python, not to Tk), and so the simplest alternative is to leak. Not really nice, but hey, the Tcl/Tk widget is leaked to (leaked meaning Tk knows about it, but to Python, it is gone) -- Bay Area Python Interest Group - http://www.baypiggies.net/ Chad Netzer cnetzer at mail.arc.nasa.gov From fperez528 at yahoo.com Wed Nov 13 12:22:13 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 13 Nov 2002 10:22:13 -0700 Subject: Installing dislin (scientific data plotting software) References: <3DD12A29.8B34ED2C@cs.nott.ac.uk> <3DD26D66.C96D0C5F@cs.nott.ac.uk> Message-ID: Turhan Ozen wrote: > Is there any other recommendations either for using dislin or any advise > on a powerful plotting tool to use with python apart from dislin? You could try IPython (http://www-hep.colorado.edu/~fperez/ipython/) as a working environment. It's not GUI based and under Windows has some limitations, but it's better than the default python shell. Under Linux/Unix/OSX, which have proper terminals and readline support, it's quite nice IMHO (granted, I may be a bit biased :) Other plottinng options: - Gnuplot. That's what I use. IPyhton comes with addons to make it much nicer for regular use. - Grace. I also use it occasionally, though I'm less familiar with it. It only does 2d though. - Chaco (http://scipy.org). This is not production code yet, but watch out for it in the future. Cheers, f. From martin at v.loewis.de Fri Nov 29 15:46:05 2002 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 29 Nov 2002 21:46:05 +0100 Subject: catch output of threads References: <87of88723i.fsf@flibuste.net> Message-ID: William writes: > Is it possible to catch the output from print of differents threads ? > In a single thread, i can change the value of sys.stdout... but with > differents thread i don't know ? You can still change the value of sys.stdout, even for multiple threads. The print statement internally uses sys.stdout itself. If multiple threads interleave print statements, you will get mixed output on your replaced sys.stdout, just as you would with the standard sys.stdout. HTH, Martin From imbosol at vt.edu Tue Nov 12 18:17:00 2002 From: imbosol at vt.edu (Carl Banks) Date: Tue, 12 Nov 2002 18:17:00 -0500 Subject: simple metaclass question References: <3DD08DC1.A4CFE557@irl.cri.nz> Message-ID: Blair Hall wrote: > Please don't ask me why, but in trying to use metaclasses > I simplified my code to the following: > > class M(object): > def __init__(cls,name, bases,dict): > cls.val=0 > > def set(cls,n): > cls.val = n > > class A(object): > __metaclass__ = M > val = 3 I'm trying to get the hang of this metaclass thing myself. Let me see if I can interpret. The definition of class A essentially (and maybe really) becomes the following assignment: A = M("A", (object,), {'val': 3, '__metaclass__': M}) What does this do? Well, M, being a class, when called, returns an instance of class M. So that is what A is bound to. There are two problems then: 1. You initialized cls.val in M's __init__ to zero, but you probably should have initilized cls.val to dict['val']. 2. Because M is not a subclass of type, instances of M are not types. Therefore, A is not a type. (I'm not sure of this one, though. I think in Python an object can be a type only if it is a subclass of type; I'm not sure if this is true in other languages with metaobjects.) > I was then surprised to see that >>>> A.val > 0 This is because A is bound to a instance of the class M. Because you initialized the val attribute of the instance to zero, and A is bound to the instance, A.val is zero. Here is something that probably does what you expected: class M(type): def __init__(self,name,bases,dict): self.val = dict['val'] def set(self,n): self.val = n -- CARL BANKS From cliechti at gmx.net Wed Nov 20 15:39:28 2002 From: cliechti at gmx.net (Chris Liechti) Date: 20 Nov 2002 22:39:28 +0200 Subject: sockets and encryption References: <6pintugofjalm0sbg1u2g4q91bdonmbupk@4ax.com> Message-ID: Paul Nilsson wrote in news:6pintugofjalm0sbg1u2g4q91bdonmbupk at 4ax.com: > I'm wondering if anybody knows of an encryption module which allows a > client/server to set up a SSH type connection. Eg. the server pushes > over a static publick key and an hourly generated key, the client > generates a session key and fires this back at the server, then the > session is encrypted with this key and blowfish (or something > similar). well you could of course use pyssh and have something that works. > Ideally I'd like to be able to drop these sockets in where I'm using > the standard socke library now. you could use ssh and port forwarding > It's not really to difficult to code this up, however I really don't > want to re-invent the wheel here. sure and with pycrypto it's realy easy. however getting something _secure_ is an other task (making it attack proof). http://pyssh.sourceforge.net/ http://www.amk.ca/python/code/crypto.html chris -- Chris From max at alcyone.com Sun Nov 24 16:55:19 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 24 Nov 2002 13:55:19 -0800 Subject: print to file References: <3DE1081F.ABBF3863@sympatico.ca> Message-ID: <3DE14AC7.7020D25B@alcyone.com> "Colin J. Williams" wrote: > >>> f=file('ugh.py', 'w') > >>> print 'abc' >> f > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand type(s) for >>: 'str' and 'file' > >>> > Am I misinterpreting Section 6.6 of the language doc? > > I get a similar result with Python or PythonWin. The synax is print >> f, 'abc' -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Money talks / But love is for real / And you know that \__/ Neneh Cherry Erik Max Francis' bookmarks / http://www.alcyone.com/max/links/ A highly categorized list of Web links. From whisper at oz.net Fri Nov 15 16:48:28 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 15 Nov 2002 13:48:28 -0800 Subject: Possible Win32 Tkinter bug? In-Reply-To: Message-ID: It sounds to me as though you don't have the right modality set for the message box or something is messed up about your tkinter installation. Windows has 3 dialog modalities: application modal - the dialog gets the focus, the main app is disabled and control returns to the app when the dialog is dismissed. IIRC, this is what a tkMessageBox is by default and there's no option to change the modality. system modal - the dialog gets the focus, all apps are disabled and control returns to the app when the dialog is dismissed. non modal - the dialog is essentially an independent window. all other apps are responsive, including the app that launched the dialog. The app next in the z-order would get the focus when the dialog is dismissed. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Tim Daneliuk > Sent: Friday, November 15, 2002 2:10 > To: python-list at python.org > Subject: Re: Possible Win32 Tkinter bug? > > > Eric Brunel wrote: > > > > > Windows has a quite different idea on which window should get the focus > > than any other window manager on other platforms. We often > encountered such > > strange behaviours. > > > > Did you try to explicitely do a tkraise and/or focus_set on the > main window > > after your message box has been shown? It may help. I also once > saw that > > calling successively withdraw(), then deiconify() on the main > window can > > solve such problems. > > > > In other words: you're on Windows, so the standard way to do > things is to > > hack until you get the behaviour you want... ;-) > > > > HTH > > > Thanks - I'll look into it... > -- > ------------------------------------------------------------------ > ------------ > Tim Daneliuk > tundra at tundraware.com > > -- > http://mail.python.org/mailman/listinfo/python-list From kemu at sdf-eu.org Thu Nov 28 09:35:47 2002 From: kemu at sdf-eu.org (Jonas Geiregat) Date: Thu, 28 Nov 2002 15:35:47 +0100 Subject: importing question ? Message-ID: <3de62963$0$214$ba620e4c@news.skynet.be> >>> import classes >>> a = veryBigSnake() Traceback (most recent call last): File "", line 1, in ? NameError: name 'veryBigSnake' is not defined >>> from classes import * >>> a = veryBigSnake() why doesn't the first import work ? and the second does and what is the difference between those two ? From bokr at oz.net Sat Nov 23 13:08:38 2002 From: bokr at oz.net (Bengt Richter) Date: 23 Nov 2002 18:08:38 GMT Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <093kra.3n3.ln@beastie.ix.netcom.com> Message-ID: On Fri, 22 Nov 2002 17:56:37 -0800, Dennis Lee Bieber wrote: >Donn Cave fed this fish to the penguins on Friday 22 November 2002 >10:01 am: [...] > >> So the first challenge may be to learn to think in Python, but then >> you need to learn to think beyond it. >> > Whereas I prefer to "think in" the abstract, and /then/ apply >transforms to map the abstract constructs to the target language. > I like this way of putting it, but I took thinking "beyond it" [Python] to mean thinking in the abstract, so perhaps you are pointing to the same place? IMO the interesting question is what "beyond-Python" elements are involved in thinking "in the abstract." ISTM the imagination uses patterns in some representational medium too, though coupled so closely with our experience of thinking that we are scarcely aware of the process. I.e., we can infer that there are normally subconcious processeses underlying our experience of thinking, just as there are underlying our experience of having control of our bodies. How does learning Python produce "beyond-Python" elements to think with in the abstract, that are different from "beyond-Fortran" elements, or "beyond-Lisp" elements, or even "beyond-assembler" elements? I think after a time of using a language's representational forms in programming, one's mind creates mental representations of the essential abstractions involved, apart from the details of their physical representation syntax. Fortran has abstractions too, but, e.g., no idea of dictionary per se binding a particular set of names to a particular set of objects. Learning python gives you the abstract notion of name->thing relationships to think with. You can get this notion from in Lisp as well, but in Fortran name->thing relationships are narrowly contrained (for useful purposes) and don't give you the general abstract notion. OTOH, arrays also have abstract counterparts, and Fortran and associated libraries gives you some useful things there. So I would say "thinking in" a language is thinking in the abstract, but restricting oneself to the abstractions that map easily to representatons in the syntax of the language. The more powerful the language, the less the restriction. The best languages are those that will give you the cleanest and most powerful abstractions to think with, while also providing a clutter-free and natural representation syntax that lets you map both ways easily. ISTM Python is really excellent in this within its bounds (which are pretty wide if you include "greater Python" with the neighborhood). Regards, Bengt Richter From gerhard.haering at opus-gmbh.net Fri Nov 8 05:12:05 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 8 Nov 2002 10:12:05 GMT Subject: string.strip References: Message-ID: In article , Stano Paska wrote: > Hi, > > in documentation: string.strip(s[, chars]) > but in real life strip takes only 1 parameter > > I have python 2.2.2 But you've read the documentation for 2.3. (.../doc/current on python.org). -- Gerhard H?ring OPUS GmbH M?nchen Tel.: +49 89 - 889 49 7 - 32 http://www.opus-gmbh.net/ From martin at v.loewis.de Thu Nov 7 10:20:04 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 07 Nov 2002 16:20:04 +0100 Subject: slow on HPUX, SunOS, fast on MS Win2K and Linux? References: Message-ID: Alex Martelli writes: > > Is there some reason python code which builds objects should be > > notably slow on HPUX or SunOS? Some known code optimization problem? > > Not known to me, but the symptom sounds very much like malloc > is very slow on those platforms compared with malloc on the Intel > hardware platforms you've confronting them with. The HP-UX malloc is reportedly *very* slow if multi-threading is enabled. So unless you need threads, recompiling Python without thread support might give significant improvements. If, by "SunOS", you really mean "SunOS 4" (i.e. not Solaris), the same strategy might help, as might upgrading to Solaris. > You could try building 2.3a0 off CVS -- it has VERY substantial > optimizations in terms of memory allocation and handling in > particular -- or, even with 2.2.2, try to force it to be built to > use pymalloc (I have not needed to do it so I'm not sure about the > details, but I'd guess it would probably be some --with-what=ever at > config), which is an optimized-for-Python memory allocation package. While that option exists, I would advise against using it: pymalloc was significantly improved before enabling it in 2.3. Regards, Martin From hungjunglu at yahoo.com Wed Nov 27 18:30:40 2002 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 27 Nov 2002 15:30:40 -0800 Subject: Implementation of the global statement References: <8ef9bea6.0211270526.5a1278c5@posting.google.com> Message-ID: <8ef9bea6.0211271530.23ee1e3a@posting.google.com> Mikael Olofsson wrote in message news:... > Is there an obvous way to have f (still defined in A) manipulate > objects in B when executed in B? (Related to my other reply.) Before anyone asks the question on how to execute a function code that takes arguments, two personal comments: (a) You've gone far too deep into Python internals, (b) Read http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=000101be5e3f%248e8e65c0%244e9e2299%40tim&rnum=6 regards, Hung Jung From maney at pobox.com Fri Nov 22 18:26:27 2002 From: maney at pobox.com (maney at pobox.com) Date: Fri, 22 Nov 2002 23:26:27 +0000 (UTC) Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <2259b0e2.0211210838.7647301a@posting.google.com> <093kra.3n3.ln@beastie.ix.netcom.com> Message-ID: Donn Cave wrote: > engineer now, but the reality is that for any substantial problem there > are way more possible bad OO solutions than good ones, and finding a > good one is not any kind of easy. s/bad OO solutions/bad solutions/ If design space weren't so vast, and the good solutions so small a portion of it, programming would be a lot easier. From jkraska at san.rr.com Mon Nov 25 23:09:32 2002 From: jkraska at san.rr.com (Courageous) Date: Tue, 26 Nov 2002 04:09:32 GMT Subject: if : References: Message-ID: On Mon, 25 Nov 2002 20:05:56 +0000 (UTC), maney at pobox.com wrote: >David Brown wrote: >> correctness. This particular "feature" is a huge source of bugs and >> frustration in C programming - mixing up "=" and "==" in conditions is >> probably the biggest single cause of C program bugs. Python, on the other > >Are you speaking from experience,... In my own personal experience, the most common typo I make in C like languages is the =/== error. I'm lucky enough to generally see this error before I send it to the compiler and fool myself into thinking the code is good. C// From cliechti at gmx.net Tue Nov 5 17:24:35 2002 From: cliechti at gmx.net (Chris Liechti) Date: 6 Nov 2002 00:24:35 +0200 Subject: calldll question References: <3DC847D5.60908@ihug.co.nz> Message-ID: Matthew wrote in news:3DC847D5.60908 at ihug.co.nz: > import calldll OK > > dll = calldll.load_library() OK > func = calldll.get_proc_address(dll, ) OK > > Now how-to execute this func? don't use calldll directly, use windll instead. there you can just call the method as if "dll" was an object. chris -- Chris From Oschler at earthlink.net Mon Nov 11 12:20:28 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Mon, 11 Nov 2002 17:20:28 GMT Subject: [Jython] out of memory during jythonc compilation References: Message-ID: "Andreas Ulbrich" wrote in message news:aqo0j2$nj0$1 at mamenchi.zrz.TU-Berlin.DE... > > thx > I've had similar problems quite a while ago when Jython was called > JPython and had version numbers less than two. Increasing the heap size > helped, but you may want to try something more substantial than 50 MB. > Give it everything your machine has. I managed to compile everything > when the heapsize was at least 256 MB. A fast machine comes handy, too :-) > Andreas, Yikes! Ok, will do. Unfortunately all I have is 256MB and unfortunately Dell saw fit to only put two DIMM slots in the system. Guess I'll have to replace the 2 128's with 256's. thx From pinard at iro.umontreal.ca Fri Nov 29 10:47:09 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 29 Nov 2002 10:47:09 -0500 Subject: Parser building in Python In-Reply-To: <20021129141633.GB29515@k6.in-berlin.de> References: <20021129141633.GB29515@k6.in-berlin.de> Message-ID: [ml] > I like to write a parser in Python. The language itself is not LALR(1), > but I could do some tricks to make it LALR(1). What are the best tools > to write lexers and parsers in Python? Maybe sth. similar to ANTLR? SPARK is a good bet, it accepts grammars which may deviate a bit from those we are used to. However, for big inputs, it might be slow. For one of the projects I work for, SPARK seems very acceptable to the team, and it will likely go in real production in a few months from now. Everybody seems to agree that we saved weeks (or maybe months) of development by using SPARK. But in the whole adventure, the real saver was switching to Python instead of C, for a rather complex system formerly written in PL/I. It was tinily difficult convincing the management to do so, our prediction that we were saving years of development and maintenance was a strong selling point. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From usenet at soegaard.net Tue Nov 12 19:25:04 2002 From: usenet at soegaard.net (Jens Axel Søgaard) Date: Wed, 13 Nov 2002 01:25:04 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCF83B2.2030008@web.de> <3DD0D765.3030907@web.de> <3DD16CAF.41214BBA@alcyone.com> Message-ID: <3dd1ffd7$0$63936$edfadb0f@dread15.news.tele.dk> Pascal Costanza wrote: > ...but that results in other problems, like the need for hygienic > macros, and so on. I rather prefer Common Lisp, because it's much more > pragmatic IMHO, and I think it's easy to learn as well if you have a > good tutorial. (And there are several on the web...) Beating http://www.htdp.org and http://www-mitpress.mit.edu/sicp/ are hard though. -- Jens Axel S?gaard From brian at sweetapp.com Thu Nov 7 14:22:41 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 07 Nov 2002 11:22:41 -0800 Subject: Syntax Error, help a newbie In-Reply-To: <20021107103055.2566.qmail@web40503.mail.yahoo.com> Message-ID: <002b01c28693$0ac71950$21795418@dell1700> > Do you mean, my syntax is not correct? :) Yeah; get rid of the colon. Also, are you expecting some kind of variable expansion with '$removed$'? > My problem is that the code is not written by myself. > Is part of a big platform which I am supossed to > support. I am used to shell scripts but not to Python > at all. There are a few Python tutorials. The official one is: http://www.python.org/doc/current/tut/tut.html > I have reviewed previous support messages and now I > see that Python 2.2 is required. The package > python2-2.2-16 is installed in my system. Does this > mean I should deinstall python-1.5.2-38? Don't install Python 1.5.2. The operating system needs it to be there. Cheers, Brian From see_reply_address at something.invalid Tue Nov 26 23:49:59 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 27 Nov 2002 17:49:59 +1300 Subject: Why not a, b += i, j? (augmented assignment via tuple unpacking) References: <3de3e129$0$4437$a1866201@newsreader.visi.com> Message-ID: <3DE44EF7.3060402@something.invalid> Jeff Epler wrote: > but in that case, what is > a, b += t > equivalent to? Obviously it's a, b = iadd(a, t[0]), iadd(a, t[1]) > What about > t += a, b This is already meaningful: t = iadd(t, (a, b)) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From costanza at web.de Mon Nov 18 14:18:01 2002 From: costanza at web.de (Pascal Costanza) Date: Mon, 18 Nov 2002 20:18:01 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> Message-ID: Alexander Schmolck wrote: >>I think the blurred boundaries between the core language and the library in >>Common Lisp are a big advantage. > > [...] > Another related problem is that Common Lisp doesn't scale well. It is a big > and complex language and that's it. While this might be a big productivity win > for an experienced developer who can leverage a large collection of well > thought out standard functions, it makes it a bad choice for many other > scenarios (if you knew neight CL nor python, would you rather have your > application scripted in python or CL?). If you had previously worked mainly with languages like Smalltalk, Prolog or some other Lisp dialects, Common Lisp would probably be the better bet. ;-) I am only half-joking - of course, it is more likely that people's previous backgrounds make it more natural to do things in Python than in Common Lisp. But it always depends on the concrete setting. >>To summarize some claims, some people say that Common Lisp is too big while >>some say that it is lacking in APIs. However, you can't say both things at the >>same time, this would be contradictory. If you want to try a Lispy language > > > I see no contradiction. Common lisp, compared to python, for example, is > lacking in libraries to achieve specific tasks needed for many real world > applications (such as GUIs, net protocols, text-processing, etc.), but comes, > unlike to python, with plenty of looping constructs including a Turing > complete format function, amongst other things. Now python programmers doing > Numerics don't have to worry about the SOAP module and vice versa for web > developers, whereas *all* CL programmers have to master loop, dolist, format > and whatever else lurks in cl:. Since specialized libraries for the task at > hand win out over more powerful language concepts, with CL you often have to > know much more in order to be able to do much less than with python. I understand your point. However, some minor points: For all of the areas you mention (GUI, net, text) there exist libraries in Common Lisp. And you don't need to know about the details of loop and format, etc., in the beginning. You're right in that you have to know more when you use Common Lisp. This is partly the case because the culture is very different when compared to Python. Languages like Python, Ruby, Perl, and so on, are primarily "single-vendor" languages. (I don't know if this is a good wording - I am not a native speaker.) Of course, there are other implementations of Python, like Jython, Stackless Python, and so on, but the standards are primarily set by one implementation. The ANSI Common Lisp standard is defined as an abstract definition, and there are many vendors that (more or less successfully) implement this standard. Many of the complications you mention can be traced back to this fact. (For example, Vendor A may provide an excellent GUI API, whereas Vendor B may have the best net library - but you may not be able to have both. I am making this up, it's not as bad as that - this is just to illustrate what I mean.) > That doesn't mean that python is generally better than CL, it just means that > people are not as irrational as lispers generally belief for often prefering > python over CL. Of course not. I think I have mentioned this before - I don't like language advocacy. My take on this is as follows: It pays off to take a look at many different languages and learn what they have in common and in what respects they differ. It's more important to know the general concepts that are common to many languages than to understand the accidental details of a particular language (of course, you should also know a certain number of languages on a very detailed level). In the long run, this allows you to be productive in almost any language in a short amount of time. The more often your head has been turned around by new languages/concepts the better. ;) There are studies that show that knowing several languages well is one of the most noticeable common characteristic of good programmers. So, for example, a set of languages I would propose to learn includes Common Lisp, Scheme, Haskell, OCaml, Prolog, Python, Ruby, gbeta. (Not that I know them all... ;) Pascal -- Given any rule, however ?fundamental? or ?necessary? for science, there are always circumstances when it is advisable not only to ignore the rule, but to adopt its opposite. - Paul Feyerabend From mauro at mr-potatohead.com Mon Nov 4 10:03:09 2002 From: mauro at mr-potatohead.com (Mauro) Date: 4 Nov 2002 07:03:09 -0800 Subject: =?ISO-8859-1?Q?Grupo_de_debate_sobre_Python_em_portugu=EAs.?= Message-ID: <3b55ea60.0211040703.5768503@posting.google.com> Ol? pessoal, J? ha algum tempo existe um grupo de debate sobre Python em portugu?s chamado Jiboa - Python. Mesmo existindo j? a algum tempo, o movimento dele, obviamente ? bem menor que o comp.lang.python. Ent?o sem tirar os m?ritos do comp.lang.python gostariamos de divulgar o J-P para aproximarmos mais os usu?rio do Python. No entanto a lingua prim?ria utilizada no grupo ? o portgu?s, (N?o sendo restrito mensagens e ingl?s, mas prefeririamos em portugu?s). O endere?o ?: http://members.tripod.com.br/jiboia/ O endere?o para mensagens ?: jiboia-python at grupos.com.br Obs. Solicitamos a quem desejar enviar mensagens, se cadastrar no grupo antes. Agradecemos a todos pela aten??o. []'s Jiboia - Grupo de Discuss?o sobre Python From psimmo60 at hotmail.com Thu Nov 21 10:11:32 2002 From: psimmo60 at hotmail.com (Paul Simmonds) Date: Thu, 21 Nov 2002 15:11:32 +0000 Subject: Gnuplot on Windows Message-ID: Hi folks, I've got a graphical application that uses Michael Haggerty's Gnuplot-py extension. On Unix, this works great (thanks Michael) by basing IO on a popen command. The Windows version of gnuplot is a GUI app, so a stdin stream is created by wrapping it in a console app using the PostMessage Windows API command (done through the public domain pgnuplot program). I'm having trouble writing to this stream, though. This illustrates the problem: Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>import Gnuplot >>>a=Gnuplot.Gnuplot() >>>a.plot('1.dta') # A simple data file Traceback (most recent call last): File "", line 1, in ? File "F:\SIMMONDS\python22\Lib\site-packages\Gnuplot\_Gnuplot.py", line 281, in plot self.refresh() File "F:\SIMMONDS\python22\Lib\site-packages\Gnuplot\_Gnuplot.py", line 222, in refresh self(self.plotcmd + ' ' + string.join(plotcmds, ', ')) File "F:\SIMMONDS\python22\Lib\site-packages\Gnuplot\_Gnuplot.py", line 206, in __call__ self.gnuplot(s) File "F:\SIMMONDS\python22\Lib\site-packages\Gnuplot\gp_win32.py", line 122, in __call__ self.write(s + '\n') IOError: [Errno 22] Invalid argument >>># Working through the hierarchy gives me >>>a.gnuplot.gnuplot >>>a.gnuplot.gnuplot.write("hello") Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 22] Invalid argument I had a check through the Gnuplot-py project page, and there was another support request describing the same thing, but no answer was given. I'd be grateful for any comments. Thanks in advance, Paul ********************************************** I used to have a handle on life, but it broke. ********************************************** _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From norbulus at hotmail.com Sat Nov 9 23:46:20 2002 From: norbulus at hotmail.com (Norbert) Date: 9 Nov 2002 20:46:20 -0800 Subject: Member variable in object spontaneously turns to None Message-ID: <15a857d.0211092046.549df8c2@posting.google.com> I am encountering a strange problem where some member variables, initialized upon instantiation of the object they are contained in, suddenly appear as having the value 'None' when I try to access them. Other member variables in the affected object are unchanged. class Foo: def __init__(self): self.bar = 0 self.x = 0 self.y = 'a' matrix = [] for i in range(10): row = [] for j in range(10): row.append(Foo()) matrix.append(row) print "%d" % matrix[0][0].bar 0 print "%d" % matrix[0][0].x 0 .... print "%d" % matrix[1][1].bar 0 print "%d" % matrix[1][1].x None I am perplexed. Any help would be appreciated. Thanks. From david at no.westcontrol.spam.com Thu Nov 7 09:50:41 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Thu, 7 Nov 2002 15:50:41 +0100 Subject: just a little program References: <1036679049.891080@news.liwest.at> Message-ID: "news.liwest.at" wrote in message news:1036679049.891080 at news.liwest.at... > Hello List! > > I'm a student and i got a homework i just cannot solve: (I study economics, > so i'm absolutley out of programing) > > We have to write code that will do the following: > > You just put in any number and the program will multiply and divide this > number from 2 to 9 > > This is how it should look like: > > 13 * 2 > 26 * 3 > 78 * 4 > 312 * 5 > 1560 * 6 > 9360 * 7 > 65520 * 8 > 524160 * 9 > 4717440 : 2 > 2358720 : 3 > 786240 : 4 > 196560 : 5 > 39312 : 6 > 6552 : 7 > 936 : 8 > 117 : 9 > 13 > > We have to define an own function like def something(input) and it should be > solved with a for-loop > > Any help would be appreciated > > Cheers and greetings from Austria > You mean, like: def foo(x) : p = x for i in range(2, 10) : print "%d * %d = %d" % (p, i, p*i) p = p * i for i in range(2, 10) : print "%d / %d = %d" % (p, i, p/i) p = p / i But why would you want to do this? What does this have to do with economics? And why do you specifically want a for loop? From zhitenev at cs.vsu.ru Fri Nov 15 05:30:16 2002 From: zhitenev at cs.vsu.ru (Lexy Zhitenev) Date: Fri, 15 Nov 2002 13:30:16 +0300 Subject: getcwd 2.2.1 vs. 2.2.2 and PythonWin References: <4cce07d5.0211141728.7364f526@posting.google.com> Message-ID: > A few days ago, I asked about how to find the directory where my > script was running. Someone posted that I should use getcwd. Not exactly so. os.getcwd returns current dir, and it is not always the dir where script lies. > At home, it worked fine with Wing IDE and command line, but getcwd in > PythonWin would return the directory where PythonWin.Exe was sitting. By default, the shortcut to PythonWin sets its working dir to \site-packages\PythonWin, so, before you save anything or open, cwd is there, and not in your script dir. For an arbitrary module you can get its path by examining module.__file__, but a script being executed doesn't have it. From nhodgson at bigpond.net.au Thu Nov 7 04:10:07 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Thu, 07 Nov 2002 09:10:07 GMT Subject: Python Browser Applets References: Message-ID: Terry Hancock: > It seems like this would have to mean that the > "Netscape Methods" would include drawing primitives > or a canvas object that can be drawn to, That would be a good way for it to work! But it doesn't :-( > but I haven't found it yet (Or maybe I'm misunderstanding > how it works, and the plugin has to talk to the underlying window > library -- but that seems bizarre and awkward). The plugin creates a native window and uses platform specific drawing functions. > In any case, I figure it means writing a "Netscape Plugin Renderer" > for PyUI. This would give me option > > 3) Run Applet on Python Plugin (Requires embedded python > plugin -- big project?, Netscape Plugin Renderer for PyUI -- small, > contribs to AnyGUI and PyUI if needed). > > The plugin route is kind of the "high road" though -- very nice result, > but it clearly requires the most work. Yes, writing a cross platform plugin is lots of work, especially if you want it to integrate well into the browser, such as cooperating in sizing and in event routing including command keys. It is simpler if your plugin area is a fixed size area that is isolated from the browser. Neil From martin at v.loewis.de Fri Nov 15 07:53:01 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 15 Nov 2002 13:53:01 +0100 Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> Message-ID: DaveP writes: > > That might be the case. However, as a question, I meant it seriously: > > What do I gain from converting the Python documentation to XML? > > In an earlier mail you mentioned the toolset for XML. > Saves a lot of work. What specific work does what specific toolset save in the specific case of Python documentation? All the work that can be saved has already been done. > Docbook has a significant multi-lingual element for boiler plate, > the techniques are re-usable though. Norm Walsh did a talk on it > at a conference I hosted in 2001 if you are interested. I don't think that the multi-lingual feature helps, in practice. It allows you to edit multi-lingual documents - which likely won't happen. Instead, you want different documents for different languages, and synchronize the translations from time to time - where the English document is always the master document. So while I do see some advantages from using XML for that, I don't see any additional advantages from using Docbook, for translation. Regards, Martin From missive at frontiernet.net Tue Nov 19 00:48:04 2002 From: missive at frontiernet.net (Lee Harr) Date: Tue, 19 Nov 2002 05:48:04 -0000 Subject: Interfaces Message-ID: Are interfaces still a happening proposition? Most of the documents I find on the web are 3-4 years old. I notice that __future__ has 'division', 'generators', and 'nested_scopes', but no 'interfaces'. Did we decide that we are not interested? Or are we waiting to see how this goes in Zope before making any commitment? From jb at cascade-sys.com Thu Nov 14 18:04:47 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Thu, 14 Nov 2002 15:04:47 -0800 Subject: A really bad idea. References: <4STA9.9987$744.345722@news1.tin.it> Message-ID: <3DD42C0F.8090706@cascade-sys.com> Manuel M. Garcia wrote: > A good point. Python is pretty darn small. I disagree. > O'Reilly's Python Pocket > Reference for Python 2 is 124 pages, and only because the major > modules are referenced starting at page 65. I collect pocket reference guides, and FWIW, Python's is the largest! Perl 5 (including libraries) is only 48 pages. I have C/C++ pocket refs that work out to 8 pages for the language and 8 pages for the libraries. Python includes virtually all of the features commonly available to most languages plus a bunch of extra features that appear only in non mainstream languages or that are entirely unique to Python. Tuples, Longs, Imaginary numbers, list comprehensions, while/else, for/else, generators, are examples of Python features that are not commonly available in other languages. The list grows considerably if we include features common to Perl (e.g., lists, dictionaries, slices, strings) but which are otherwise missing from most mainstream languages. I suppose the one thing Python (Perl and others) leave out are variable and type declarations, which goes to making the language seem smaller than others. I don't raise this point to complain or suggest Python is bad. I actually think it's a tribute to Python's superior design that so MUCH functionality is contained in a manageable tool. Python is so well designed that it SEEMS small even though it's comparable to the most elaborate programming systems ever made. Disagreeing with the OP, I rather think Python tends to go overboard the other way in deference to newbies and naive programmers. This is why Python consciously rejects assignment within an expression, ++ and --, ?:, var parameters and goto, even though most experienced programmers already know how these constructs work. It's ostensibly the reason why integer division was redefined to produce a real result -- because naive users might be "confused" by a truncated integer result. I think the designers are overly pedantic on this point overall and thus sometimes make the wrong call. In any case, it's certainly not fair to suggest that Python errs in adding "hard to understand" features. Some learning curve is inevitable even in the most readable language. Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From brian at sweetapp.com Tue Nov 26 14:34:19 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 26 Nov 2002 11:34:19 -0800 Subject: readability statistics In-Reply-To: Message-ID: <010601c29582$d0637020$21795418@dell1700> > Does anybody know where I can find a module > which calculates some python code readability statistics. > Like for example: > % comment lines. > average line length > average module number of lines > etc... I don't know if such a utility already exists or not, but you could probably write one in less than an hour. Look at the tokenize module. Cheers, Brian From zhitenev at cs.vsu.ru Tue Nov 26 11:54:26 2002 From: zhitenev at cs.vsu.ru (Lexy Zhitenev) Date: Tue, 26 Nov 2002 19:54:26 +0300 Subject: How to convert ASCII-number => HEX -number => string of numbers in HEX ? References: <3de39ca8$1@news.vip.fi> <3DE3A33E.3050505@Linux.ie> Message-ID: "Padraig Brady" wrote: news:3DE3A33E.3050505 at Linux.ie... > Hmm ''.zfill() isn't present on python 2.2 at least? > (string.zfill() is?) > > P?draig. > Maybe, you have a broken version? ActivePython 2.2.1 does have .zfill() and string.zfill(). Lexy. From jaykay2199113223 at aol.com Sun Nov 17 14:31:59 2002 From: jaykay2199113223 at aol.com (Jaykay2199113223) Date: 17 Nov 2002 19:31:59 GMT Subject: learning python and what i need ?help please Message-ID: <20021117143159.08975.00000149@mb-fo.aol.com> hi there i need advice on what i need to begin to learn python,do i need to download a compiler,if so any preferences you could tell to use and anyother advise thanx stevie my e-mail address is STEPHEN414 at AOL.CO.UK From Gareth.McCaughan at pobox.com Thu Nov 28 18:08:02 2002 From: Gareth.McCaughan at pobox.com (Gareth McCaughan) Date: Thu, 28 Nov 2002 23:08:02 +0000 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3de1f902$0$695$edfadb0f@dread12.news.tele.dk> <3DE666F0.32F64BA6@alcyone.com> Message-ID: "Courageous" wrote: > On Thu, 28 Nov 2002 10:56:48 -0800, Erik Max Francis wrote: > > >deed, I think it's highly ironic that people are complaining about > >parenthesis-counting when it comes to Python, because "I don't want to > >be keeping track of whitespace indentation" is one of the key > >anti-Python sentiments (from people who have never used it). The fact > >that we're not complaining about this in Python now, of course, is > >because it's a non-issue -- you _don't_ have to do such things, your > >editor does it for you. For Lisp programming, it's exactly the same > >thing. > > But requires a specific class of editor, whereas all other editors > around can handle basic programming languages. I frequently edit Lisp code using vim. It works just fine. There are lots of very cool things you can do with emacs, but I can't quite see how the existence of an editor with exceptionally good language support is supposed to be a disadvantage. -- Gareth McCaughan Gareth.McCaughan at pobox.com .sig under construc From dsavitsk at e-coli.net Tue Nov 19 16:08:02 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Tue, 19 Nov 2002 21:08:02 GMT Subject: stopping SimpleHTTPServer References: Message-ID: "Alex Martelli" wrote in message news:AptC9.28393$744.1027998 at news1.tin.it... > dsavitsk wrote: * * * > In your subclass, you need to override method handle_error, which by > default processes all exceptions (including the SystemExit exception > raised by sys.exit) by printing a traceback and continuing. Check if > the exception is SystemExit and then re-raise it, otherwise delegate > to your base-class's handle_error for normal error processing... > right. I am not getting something very fundamental, so this is a good learning opportunity ... I added a method as below (found from a Steve Holden post) def handle_error(self, request, client_address): import exceptions etype, evalue = sys.exc_info()[:2] if etype is exceptions.SystemExit: raise print '-'*40 print 'Exception happened during processing of request from', print client_address import traceback traceback.print_exc(1000, sys.stdout) print '-'*40 sys.stdout.flush() but it doesn't seem to be used upon an error. Instead the original handle_error method is called. So how do I convince my program that this one is the one to use? Python 2.1.3, b/t/w. thanks From see_reply_address at something.invalid Tue Nov 12 20:03:04 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 13 Nov 2002 14:03:04 +1300 Subject: Optimisation problem References: <7h3heem23ju.fsf@pc150.maths.bris.ac.uk> Message-ID: <3DD1A4C8.7080803@something.invalid> 'm suregabor wrote: > you're saying that for example > > x,y = 2,4 > > creates a tuple? > > i thought thatr x,y=2,4 is the same as x=2;y=4 The result is the same, but the experiment below demonstrates that the former is implemented by building a tuple and then immediately unpacking it again. This surprised me, because I thought someone claimed a while ago that this case was optimised. But apparently it's not! (I tried it with python -O too, and the result was the same.) Python 2.2 (#1, Jul 11 2002, 14:19:37) [GCC 3.0.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import dis >>> def f(): ... x,y = 2,4 ... >>> dis.dis(f) 0 SET_LINENO 1 3 SET_LINENO 2 6 LOAD_CONST 1 (2) 9 LOAD_CONST 2 (4) 12 BUILD_TUPLE 2 15 UNPACK_SEQUENCE 2 18 STORE_FAST 1 (x) 21 STORE_FAST 0 (y) 24 LOAD_CONST 0 (None) 27 RETURN_VALUE >>> -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From pyth at devel.trillke.net Fri Nov 8 04:25:53 2002 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 8 Nov 2002 10:25:53 +0100 Subject: re.sub() bug? In-Reply-To: <3dcb7ea6$1_4@omega.dimensional.com>; from mike@skew.org on Fri, Nov 08, 2002 at 02:06:45AM -0700 References: <3dcb7ea6$1_4@omega.dimensional.com> Message-ID: <20021108102553.J30315@prim.han.de> Mike Brown wrote: > Python 2.2.1 on FreeBSD. > These work as expected: > > >>> re.sub(u'f', u'b', u'foo') # keep string as Unicode > u'boo' > >>> re.sub(u'f', u'b', 'foo') # coerce string to Unicode > u'boo' > > But this doesn't work the way I'd think it would: > > >>> re.sub(u'f', u'b', u'') # coerce string to non-Unicode?! > '' > > So, is this a bug? I think so. File a bug report at sourceforge. holger From ktilton at nyc.rr.com Thu Nov 21 18:32:45 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Thu, 21 Nov 2002 23:32:45 GMT Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <2259b0e2.0211210838.7647301a@posting.google.com> Message-ID: <3DDD6D7A.3010308@nyc.rr.com> Bengt Richter wrote: > On Thu, 21 Nov 2002 18:03:48 +0100, Pascal Costanza wrote: >>Could you try to describe what it means to you to think in Python? What >>makes it different from thinking in other languages? (This is not a >>rhetorical question!) >> > > (Please pardon my jumping in with my view. I realize you didn't ask me ;-) Nor did you answer him! :) What is it about Pythonthink that is different from Otherlangthink? I actually was wondering the same thing, because I do not see a lot different in Python from C other than very practical advantages, such as the indentation thang and GC. But I just am digging into Python, so whadoiknow? My biggest mindfuck was learning Prolog. Declarative vs procedural. The prior champ was Logo, specifically learning to think recursion when I wanted to iterate. That sort of thing. -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From shalehperry at attbi.com Mon Nov 4 11:00:24 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Mon, 4 Nov 2002 08:00:24 -0800 Subject: Foot in mouth disease In-Reply-To: <31575A892FF6D1118F5800600846864DCBDA9B@intrepid> References: <31575A892FF6D1118F5800600846864DCBDA9B@intrepid> Message-ID: <200211040800.24696.shalehperry@attbi.com> On Monday 04 November 2002 07:52, Simon Brunning wrote: > > Changing an object's type, ah, now that's a different matter. It's usually > not just the declaration which needs to change, you have arguments to > change all over the place, casts to add, it just seems to go on forever. > Eclipse doesn't help here. (Does EMACS?) With Python, of course, you change > your object instantiation, and re-run your unit tests. If the signatures of > the old and new types match, you are good to go. > emacs only has intelligent search and replace capabilities unless programmed otherwise. It could be done but to my knowledge it does not exist today. You can get pretty far with search and replace though. I understand bicyclerepairman to be a good emacs package for Python refactoring. From eddie at holyrood.ed.ac.uk Fri Nov 8 12:41:00 2002 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 8 Nov 2002 17:41:00 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? In-Reply-To: <31575A892FF6D1118F5800600846864DCBDAD0@intrepid> (message from Simon Brunning on Fri, 8 Nov 2002 17:26:39 -0000) References: <31575A892FF6D1118F5800600846864DCBDAD0@intrepid> Message-ID: <200211081741.RAA25389@holyrood.ed.ac.uk> Too easy - try Seen that :) and most of the others. And as for those extensions - a language that needs integers just isn't trying. There's probably not much to choose between them really but I prefer functional style. Eddie From blackprogramming at yahoo.com Tue Nov 5 23:33:50 2002 From: blackprogramming at yahoo.com (black) Date: Tue, 5 Nov 2002 20:33:50 -0800 (PST) Subject: Tkinter's button In-Reply-To: <1036511890.1389.1.camel@m-franklin> Message-ID: <20021106043350.37309.qmail@web14506.mail.yahoo.com> thanx but why we could check items by format like this: myButton["state"] as I remembered that is with dictionary, while myButton is instance here how could we invoke a dictionary with an instance name ? thanx in advance~ Martin Franklin wrote: On Tue, 2002-11-05 at 03:46, black wrote: > > Howdy~ > > I have a button create with this line: > import Tkintertk=Tkinter.Tk()button=Tkinter.Button(tk) > and I found we could add some "property" with this format: > button["text"]="Howdy" > is that a hint that all buttons have a predifined dictionary ? and how to check all members ? I searched tutorial about Tkinter but found nothing. print button.config() will list all the configuration options and values..... you can also update widgets like:- button.config(text="hello") -- http://mail.python.org/mailman/listinfo/python-list --------------------------------- Do you Yahoo!? HotJobs - Search new jobs daily now -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at no.westcontrol.spam.com Tue Nov 26 05:11:15 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Tue, 26 Nov 2002 11:11:15 +0100 Subject: Python Tutorial Was: Guido's regrets: filter and map References: <20021126043142.4323.25612.Mailman@mail.python.org> Message-ID: > map(), filter(), and reduce() do not represent all of the uses for filter, > and thus, they can't all be replaced by list comps (BTW, I never used > reduce, never understood what it was good for, and don't immediately > see how it can be done using list-comps -- would be genuinely interested > in seeing a couple of example if anyone's willing). > I've used reduce() a couple of times, such as for calculating checksums of strings to/from a serial port. But I wouldn't miss it much if I didn't have it - a for loop would do just as well. > So I think lambda still has a place, though I wouldn't want to increase > its capabilities (such as making non-expression functions possible). Agreed - if you make your lambdas too complicated, they won't fit on a line or two, so you would be better off with a seperate function anyway. > > > I find lambda quite useful for creating simple anonymous functions to pass > > to GUIs as button commands and the like. I suppose the same effect could be > > obtained by adding a couple more lines to define a temporarily-named > > function, but then I'd have to think up a name. I've been known to waste > > hours trying to come up with names for new computers. I'm not quite so > > indecisive about functions, but it does seem to be one of my weak points. > > Agreed -- the general pattern of passing functions as first-class objects > is supported by providing the simplicity of lambda for the degenerate > case, just like numerical or aggregate data literals support passing > variables (do I recall correctly that you couldn't pass literals to functions > in Pascal? I remember being very annoyed by that, coming from > Fortran). > > As for the pain of thinking up a name -- I think it's actually a good > sign. It shows you care. Good names are a real benefit to your own > future self and to anyone else who must read your code. Though they > weren't primarily interested in programming but in websites, I found the > book "Information Architecture" (O'Reilly), to be very influential in > my thinking about variable names and other "labels" -- which is the > term they use. Not saying I always live up to the ideal, but it gave me > an ideal to try for. ;-D > Good names are the key to readable and maintanable programming. But there are plenty of cases where no name is better than some dummy name. If you have to refer to something, it should have a good, sensible name. If you don't have to refer to it, then it is an advantage to have no name - it saves cluttering namespaces, and it makes dir() more useful. > Cheers, > Terry > > -- > Terry Hancock ( hancock at anansispaceworks.com ) > Anansi Spaceworks http://www.anansispaceworks.com > From johs+n at ifi.uio.no Mon Nov 11 05:11:43 2002 From: johs+n at ifi.uio.no (Johannes =?iso-8859-1?q?Gr=F8dem?=) Date: Mon, 11 Nov 2002 11:11:43 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: * Carl Banks : >> (All sane editors support paren-matching.) > I know that. But that's just humans using the editor to count for > them. The point was you can't eyeball the nesting of parentheses. I fail to see the problem. Okay, it is slightly inconvenient to write it on paper, but who does that, anyway? This is 2002, not 1960. > Notes about when a particular form is evaluated are all over the spec. > There are a lot of macros and special forms for which it isn't clear > whether you should quote an argument or not. For which it isn't clear to you, you mean. (Even if it may sound like it, the previous sentence is not meant as an insult.) > In Lisp, sometimes it isn't even *defined* when code gets > evaluated. No, that's Scheme. -- Johannes Gr?dem From bokr at oz.net Fri Nov 8 00:29:07 2002 From: bokr at oz.net (Bengt Richter) Date: 8 Nov 2002 05:29:07 GMT Subject: Newbie: needs help with ... References: <20021108032601.4438.75566.Mailman@mail.python.org> Message-ID: On Thu, 7 Nov 2002 19:46:44 -0800, Terry Hancock wrote: >On Thursday 07 November 2002 07:26 pm, python-list-request at python.org wrote: >> I'm trying to print the contents of a list. >> >> Python displays "..." until I press enter. Why is it waiting for me to >press enter ? >> >> >>>?for x in l2[:5] : print x >> ... > >I'm not exactly sure whether: > >for x in l2[:5]: print x > print x, x > >would be legal (it's certainly bad style), so maybe the Apparently not: >>> l2 = range(10) >>> for x in l2[:5]: print x ... print x, x File "", line 2 print x, x ^ SyntaxError: invalid syntax >interpreter ought to figure out that there won't be anything >more in the loop. But what the "..." is about is the way the >interactive interpreter decides when a loop is actually Not just loops, but any first-level indented block >complete: > >>>> if x in l2[:5]: >... print x >... print "x = %d" % x >... > >That last "..." with no content tells the interpreter you're done >so it can actually run the loop. (So you can't have any >blank lines when you're pasting code into the interpreter Ah, I misread that. But you can have blank lines. Pasting three: (first using """ to have something I can block copy for pasting) >>> """ ... print 'first' ... ... print 'third' ... ... """ "\nprint 'first'\n\nprint 'third'\n\n" Ok, here I paste the three lines including EOL on the third: >>> print 'first' first >>> >>> print 'third' third You can paste them. It's just that they take effect when the blank lines are encountered. The serious requirement is just the opposite: you _must_ have a blank line to signal a dedent to level zero if you are going to paste a block with additional lines following after the dedent, which I guess you mean by "to test it". >to test it, and each loop must have a blank line as well as >a dedent). > A workaround is to put an "if 1:" in front of the bunch of code with multiple indent/dedent from/to level zero, to make them into a single block. E.g., (at least in console window of NT using python 2.2.2) BTW, I definitely think this could be smarter, but it must be hard to make it so or I'm sure it would be. Below I pasted the line groups all at once (I think ;-): >>> def foo(): # line 1 ... print 'Hi from foo' # line 2 ... foo() # line 3 File "", line 3 foo() # line 3 ^ SyntaxError: invalid syntax I don't see why it couldn't recognize the dedent and process the def and then the last line. Workaround: >>> if 1: # line 0 ... def foo(): # line 1 ... print 'Hi again' # line 2 ... foo() # line 3 ... Hi again >>> def foo(): # line 1 ... print 'Hi from foo' # line 2 ... # this is not blank ... foo() File "", line 4 foo() ^ SyntaxError: invalid syntax >>> def foo(): # line 1 ... print 'Hi from foo' # line 2 -- next line blank ... >>> foo() # previous line blank Hi from foo >>> # Also, why can't it consume a comment like this and prompt with >>> ? ... >>> >This is a difference between the interactive and script >modes of operation of python. You see the same thing with >tcsh and bash, BTW (though the prompt symbols are >different). > I'm not going to check on it ;-) Regards, Bengt Richter From hancock at anansispaceworks.com Tue Nov 26 03:04:54 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 26 Nov 2002 00:04:54 -0800 Subject: Borgengi (Re: Perl to python convertor) In-Reply-To: <20021126073601.1411.22111.Mailman@mail.python.org> References: <20021126073601.1411.22111.Mailman@mail.python.org> Message-ID: On Monday 25 November 2002 11:36 pm, Greg Ewing wrote: > ?????? ?. wrote: > >>? ?Actually, Microsoft is sort of a mixture between the Borg and the Ferengi. > > First rule of assimilation: You will be acquired! Someone really needs to write an intro to Zope called "The Rules of Acquisition". ;-) Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From zopestoller at thomas-guettler.de Fri Nov 8 07:26:13 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Fri, 08 Nov 2002 13:26:13 +0100 Subject: Upload file with multipart/formdata Message-ID: I want to upload a binary file with the script from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 ASCII files get uploaded without problem, but binary data gets cut before all 0xA1 bytes. Any hints? The server is zope 2.5.1, but this shouldn't be the problem, since the upload works with a browser. thomas From ianb at colorstudy.com Wed Nov 13 16:32:19 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 13 Nov 2002 15:32:19 -0600 Subject: RE function In-Reply-To: <20021113211520.46197.qmail@web10202.mail.yahoo.com> References: <20021113211520.46197.qmail@web10202.mail.yahoo.com> Message-ID: <1037223139.499.42.camel@dsl-65-184-205-5.telocity.com> On Wed, 2002-11-13 at 15:15, lily wrote: > > Hello, > > I need help. I am trying to parse some strings where I want to use the RE function. How can I find all the lines that start with '(object Operation' and should contain the word 'Trace' followed by ': {' ? > > (object Operation... > > |Trace: {...} > > > > ... )) > > I tried using the following code to capture all the instances of these patterns: > > tracepattern = re.compile("\(object\s+Operation<.*?>+\sTrace<.*?>\)") You don't want those <>'s in there, just: tracepattern = re.compile("\(object\s+Operation.*?\sTrace.*?\)") (I also got rid of a + in <.*?>+) Of course, this doesn't search for what you describe, it searched for things like (object Operation some junk Trace some other junk) -- you described {} in there somewhere, but that doesn't show up in your RE. Ian From i.linkweiler at web.de Fri Nov 1 07:26:28 2002 From: i.linkweiler at web.de (Ingo Linkweiler) Date: Fri, 01 Nov 2002 13:26:28 +0100 Subject: MySQL + Python. References: <3DC1783F.5000003@web.de> Message-ID: <3DC272F4.4010905@web.de> This is a simple working example of mySQL. Now I want to use a "DictCursor". How do I use it, or where do I find it? c=db.cursor(???DictCursor???) ???? Ingo # ....................8-<....................... # A simple mysql-test # requires a database test, table benutzer, rows (userid, name) import MySQLdb db=MySQLdb.connect("localhost","username","password","test") c=db.cursor() # insert new item # c.execute("""INSERT INTO benutzer (userid, name) VALUES (7,"Thomas")""") # start... print c.execute("""SELECT * FROM benutzer""") # get one item print c.fetchone() # get all items print c.fetchall() print "finished" From jepler at unpythonic.net Mon Nov 18 07:47:54 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 18 Nov 2002 06:47:54 -0600 Subject: pythonic way to optimize access to imported value? In-Reply-To: References: <3DD85526.6020606@something.invalid> Message-ID: <20021118064744.A4002@unpythonic.net> On Mon, Nov 18, 2002 at 04:03:30AM +0000, Bengt Richter wrote: > IOW, IMO there ought to be a way to do a temporary global-side-effect-free > import and delete all traces of its having been done -- without restarting > the interpreter or invoking a second interpreter instance. Let us know when you've implemented it. Some of the problems: Modules need not be side-effect-free. For instance, the following is a (very harmful) legal Python module: from os import system system("rm -rf /") Modules may refer to other modules, so you'll need to make any other "import"s that happen during that time special. Unloading C modules may not work on all platforms, and may never be possible when there are references to objects in the module. If any nontrivial object from the module is kept, the module will be around anyway, even if it's not listed in sys.modules. Functions hold a reference to the module's globals, for instance. Any non-trivial class has methods, and any interesting object is an instance. I think that the presence of modules in sys.modules is used by the system to break cycles like that of functions. At cleanup, a module's dictionary is cleared which breaks the module->function->module cycles and allows collection. It's still not exactly clear to me what all these complications would gain me anyway... Jeff From Jeff.Dubois at westgroup.com Fri Nov 15 14:56:56 2002 From: Jeff.Dubois at westgroup.com (Dubois, Jeff) Date: Fri, 15 Nov 2002 13:56:56 -0600 Subject: tkinter - tk window remains Message-ID: Hi Chad, The code you suggested did solve the persistent tk window problem. Thanks! Jeff -----Original Message----- From: Chad Netzer [mailto:cnetzer at mail.arc.nasa.gov] Sent: Thursday, November 14, 2002 4:51 PM To: Dubois, Jeff; python-list at python.org Subject: Re: tkinter - tk window remains On Thursday 14 November 2002 13:29, Dubois, Jeff wrote: > I am using Tkinter to bring up a ScrolledText window. > However, when the user closes the window by clicking on the X button in > the upper right of the ScrolledText window the "tk" window remains. On my linux machine, your code never pops open a window (since you withdraw it), before mainloop(). If I comment that out, it works like you expect (closing the window exits the program). And judging from the code, that is to be expected (since you use the rootWindow as the parent of your widget) I expect that on Windows, the rootWindow is not really the Tk() root window (Do you get an extra, blank window if you don't withdraw it? I assume that's what you mean by the tk window). Obviously there are platform differences in the behavior of Tk. I suggest you solve it like this: from Tkinter import * from ScrolledText import ScrolledText import sys bogusrootWin = Tk() bogusrootWin.withdraw() rootWin = Toplevel( master=bogusrootWin ) st = ScrolledText(master=rootWin) st.pack(side=TOP, expand=1, fill=BOTH) st.insert(END, "\n\n\n\n THIS IS MAIN WINDOW!\n") rootWin.protocol( "WM_DELETE_WINDOW", sys.exit ) rootWin.mainloop() ie. You explicitly create a Toplevel window to use for your application, and then using the wm_protocol() method on a Toplevel, you can ask the window manager to run sys.exit (or whatever you prefer) when the window is killed. -- Bay Area Python Interest Group - http://www.baypiggies.net/ Chad Netzer cnetzer at mail.arc.nasa.gov From jonah13579 at hotmail.com Sat Nov 23 21:57:11 2002 From: jonah13579 at hotmail.com (Jonah) Date: 23 Nov 2002 18:57:11 -0800 Subject: Regular expression question Message-ID: <9a5f3d1c.0211231857.78125e43@posting.google.com> What would be the python equivalent of the following perl script? I use the idiom often for quick templating tasks. It finds every occurrence of %%WHATEVER%% in $source and replaces it with the results of a subroutine call to sub whatever (lowercased) and is passed $variable. $source=~ s/%%(.*?)%%/lc($1)->($variable)/eg ; Thanks in advance. From tjreedy at udel.edu Mon Nov 25 22:09:24 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 25 Nov 2002 22:09:24 -0500 Subject: Determining if a string is base64 or uu encoded? References: <99BE9.139964$nB.11463@sccrnsc03> Message-ID: <-FqdnXYLFZnAe3-gXTWcog@comcast.com> "Colin Cashman" wrote in message news:99BE9.139964$nB.11463 at sccrnsc03... > Is there a function that given a string or file (or Message, etc.) will > determine whether the string or file is encoded, and if so, what type of > encoding that is (base64 vs. uuencoding)? Brute force method would be to run string thru both decoders (both are somewhere in library) and see which, if either, completes without protest. TJR From pieroul at attglobal.net Sat Nov 30 12:29:22 2002 From: pieroul at attglobal.net (Pierre Rouleau) Date: Sat, 30 Nov 2002 12:29:22 -0500 Subject: Python classes: how to find the name of (potential) parent class? Message-ID: <3DE8F572.6080106@attglobal.net> Is it possible to find, at run time, what are the parent class of a given Python class? -- Pierre Rouleau From fredrik at pythonware.com Wed Nov 6 14:26:59 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 06 Nov 2002 19:26:59 GMT Subject: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up References: Message-ID: <72ey9.2839$h%5.100976@newsb.telia.net> Jon Ribbens wrote: > My jonpy modules are producing the following warning when compiled > under Python 2.3 (current cvs): > > FutureWarning: hex/oct constants > sys.maxint will return positive > values in Python 2.4 and up > > The offending line of code is as follows: > > data = struct.pack("!I", len(nameval[0]) | 0x80000000) > > As far as I can tell, this change, when it comes in, will make no > difference at all to the way this code works. Am I right? What am > I supposed to do to make the warning go away? Rewrite 0x80000000 as > 0x40000000 * 2 ? ;-) add the sign? or disable the warning? (see docs for the warning module) the answer might be hidden somewhere in here, but I'm not sure (we're at transition phase B0, I think): http://www.python.org/peps/pep-0237.html From harsh at computer.org Sun Nov 24 17:03:54 2002 From: harsh at computer.org (Stacy White) Date: Sun, 24 Nov 2002 22:03:54 GMT Subject: DCOracle2 performance tuning References: <%uQD9.122449$1O2.8846@sccrnsc04> <3DE06FE1.3010602@epost.de> Message-ID: <3DE14CCC.2010700@computer.org> Gerald Hein wrote: > I never tried cx_Oracle, but it might be worth a try for you .. Very interesting. cx_Oracle is much faster in some cases, but the same speed in others. Hmmm. Thanks for the tip. From adrian at twistedliving.com Sun Nov 24 01:28:46 2002 From: adrian at twistedliving.com (adrian at twistedliving.com) Date: Sun, 24 Nov 2002 01:28:46 -0500 Subject: Exec`ing external programs Message-ID: I`m doing something like import os,sys a = open('host_list', 'r') for host in a.readlines(): os.system('xterm -e atl.py %h &',%(host)) What I`m trying to do is read a list of hostnames and for each one open an xterm and exec atl.py with host as an argument. I am unable to background the job, so It hangs until I close the first window. However if I set a to a list of hostnames inside the script, it functions correctly, but fails when reading from a file. I tried copy.deepcopy after reading from the file with the same results. Any ideas ? Adrian From ngterry2000 at yahoo.com.hk Tue Nov 12 20:38:03 2002 From: ngterry2000 at yahoo.com.hk (=?big5?q?Terence=20Ng?=) Date: Wed, 13 Nov 2002 09:38:03 +0800 (CST) Subject: HTML email marketing tool In-Reply-To: Message-ID: <20021113013803.23827.qmail@web41115.mail.yahoo.com> I know what a spammer do. My situation is that: My company has just finished an electronics fair, and received a lot of business cards asking for quotation, etc. I am not asking for a heavy weight mailing list server. There is already a lot on the internet. This is a very common business practice. I just want to be smart sending the emails to this list instead of sending the emails one by one. Terence P.S. Grant, you are so XXX. --- Fernando P?ez ??????> Grant Edwards wrote: > > > Do the letters FOAD mean anything to you? > > In case our email-marketer-spammer friend is too > dense for google (which I'm > sure would have provided him tons of tools for his > noble enterprise), here's > google's first hit so he can look it up directly: > > http://www.valinor.sorcery.net/glossary/FOAD.html > > cheers, > > f. > -- > http://mail.python.org/mailman/listinfo/python-list _________________________________________________________ ??(???)????(???)??????(???)... Over 800 latest ringtones, only on Yahoo! http://ringtone.yahoo.com.hk From BPettersen at NAREX.com Tue Nov 19 18:17:18 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Tue, 19 Nov 2002 16:17:18 -0700 Subject: wxPython crashing windows Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019201BFD76B@admin56.narex.com> > From: Cliff Wells [mailto:LogiplexSoftware at earthlink.net] > > On Tue, 2002-11-19 at 13:12, trewornan wrote: > > Well the subject says it all - has anyone else found > wxPython crashing > > windows (all the way to a blue screen). Even the most basic program > > seems to do this. > > Check line 10 in your program. ROFL!! -- bjorn From adrian at twistedliving.com Sun Nov 24 03:28:08 2002 From: adrian at twistedliving.com (adrian at twistedliving.com) Date: Sun, 24 Nov 2002 03:28:08 -0500 Subject: Exec`ing external programs References: Message-ID: Grant Edwards wrote: > In article , adrian at twistedliving.com wrote: > > >>import os,sys >> >>a = open('host_list', 'r') >>for host in a.readlines(): >> os.system('xterm -e atl.py %h &',%(host)) >> >>What I`m trying to do is read a list of hostnames and for each one >>open an xterm and exec atl.py with host as an argument. I am unable >>to background the job, so It hangs until I close the first window. > > > My guess: Each of the strings returned by readlines contains a newline at > the end. The shell sees that newline (which is before the ampersand) and > runs the command in the foreground. > > >>However if I set a to a list of hostnames inside the script, it >>functions correctly, but fails when reading from a file. > > > Here's a hint: Since you know it works when 'a' is a hand-coded list of > strings, and fails when a.readline() is used, take a careful look at the > difference between the 'host' values in the two cases. > You`re right, I did a copy.deepcopy to try and seperate the list from the file ( I was reaching) , and I did notice it contained newlines, It just didn`t click, thanks for your help Adrian From mistericeberg at hotmail.com Tue Nov 12 03:31:33 2002 From: mistericeberg at hotmail.com (Georges Bernier) Date: 12 Nov 2002 00:31:33 -0800 Subject: Create DLL in Python ? References: <1b318b70.0211111607.74ace07@posting.google.com> <4bZz9.5692$mN6.2514493@newssrv26.news.prodigy.com> Message-ID: <1b318b70.0211120031.436438c0@posting.google.com> "dsavitsk" wrote in message news:<4bZz9.5692 > The easiest thing to do is to create a COM server which is what a dll is, or > rather can be. The simplest way to do this is as follows ... > > class MY_COM_SERVER: > > # change this next line. a new id can be generated with > # >>> import pythoncom > # >>> print pythoncom.CreateGuid() > _reg_clsid_ = '{F69D8FCD-97BF-4D60-B5E5-199FC3C63172}' > > # list the public methods > _public_methods_ = ['COM_SERVER_METHOD'] > > # the server's name in the registry > _reg_progid_ = 'PythonCOMServer.FirstServer' > > def COM_SERVER_METHOD(self): > return 'Hello, World!' > > if __name__ == '__main__': > import win32com.server.register > win32com.server.register.UseCommandLine(MY_COM_SERVER) > > Register it by running it in an ide, or by double clicking the file. It > would be accessed from VBScript as > Set x = CreateObject('PythonCOMServer.FirstServer') > x.COM_SERVER_METHOD > > This creates a late bound COM server accessed like any other dll. There are > many more details, and you should look in the book Python Programming on > Win32 for more. > > if, however, the original dll is not a COM object, then I can't help. > > -d dsavitsk, Thanks a lot for your clear answer. Actually the current DLL I have to replace is not a COM server but that sounds like a good idea. I've seen the Win32 book on Safari that's definitely one that should be on my shopping list. Cheers, Philippe. From aleax at aleax.it Thu Nov 7 10:11:11 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 07 Nov 2002 15:11:11 GMT Subject: slow on HPUX, SunOS, fast on MS Win2K and Linux? References: Message-ID: Harry George wrote: > Is there some reason python code which builds objects should be > notably slow on HPUX or SunOS? Some known code optimization problem? Not known to me, but the symptom sounds very much like malloc is very slow on those platforms compared with malloc on the Intel hardware platforms you've confronting them with. You could try building 2.3a0 off CVS -- it has VERY substantial optimizations in terms of memory allocation and handling in particular -- or, even with 2.2.2, try to force it to be built to use pymalloc (I have not needed to do it so I'm not sure about the details, but I'd guess it would probably be some --with-what=ever at config), which is an optimized-for-Python memory allocation package. Alex From aleax at aleax.it Fri Nov 22 10:18:11 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 22 Nov 2002 15:18:11 GMT Subject: Proposal: min(None, x) and max(None, x) return x References: Message-ID: Andrew Koenig wrote: > Eric> So I told myself: wouldn't it be great if max(None, x) or > Eric> min(None, x) always simply returned x? > > My first thought was that this was an excellent idea. > > Then I thought again. > > Here's the problem: The notion that max(None, x) and min(None, x) > should both return x is one of three desirable properties that cannot > all be true at once. Here are the other two: > > 1) Whenever x < y, min(x, y) is x and max(x, y) is y. > > 2) < is an order relation over all types. Unfortunately point (2) doesn't hold in Python today. > The desirability of (1) should be obvious. (2) is more subtle, but > it is necessary for it to be possible to sort a vector of heterogenously > typed objects. Indeed, you can sort a list containing, say, a None, a string, an integer and a float -- but if you add to the list a fifth element that is a complex, POOF, you can't sort it any more. That didn't use to be so, if I recall correctly, in Python 1.5.2, but has been that way for quite a while now. Why comparing string 'plak' with the number 23 is OK, but comparing it with 23j isn't, kind of escapes me -- but apparently property (2) was deemed less desirable than the ability to forbid e.g. comparing 23j with 42j. To the point of changing Python's previous behavior, no less:-(. > Now, if max(None, x) and min(None, x) both yield x, and (1) is true, > then x > None and x < None must both be true. But then (2) cannot > be true. > > So the cost of your proposal would be either to break the consistency > between max/min and >/<, or to render unsortable vectors of values > that include None. > > I don't think it's worth it. I don't think it's worth it either -- even the weaker guarantee of being able to state (just to play with chaining...;-): b >= min(a,b) <= a and b <= max(a,b) >= a *unless an exception is raised while evaluating the expression* is still pretty good. However, _some_ kind of language-mandated guarantees about the behavior of certain cross-type comparisons _might_ be nice. Right now, I don't think the language makes ANY such guarantees (except for comparisons between ints, longs and floats, and between plain and Unicode strings, where sensible conversions are indeed guaranteed). Alex From grisha at apache.org Thu Nov 28 16:14:24 2002 From: grisha at apache.org (Gregory (Grisha) Trubetskoy) Date: Thu, 28 Nov 2002 16:14:24 -0500 Subject: ANNOUNCE: Mod_python 3.0.1 In-Reply-To: <3de52d75$1@news.mt.net.mk> References: <3de52d75$1@news.mt.net.mk> Message-ID: <20021128160937.X52698-100000@eden.ispol.com> On Wed, 27 Nov 2002, [iso-8859-5] ?????? ?. wrote: > > > The Apache Software Foundation and The Apache HTTP Server Project are > > pleased to announce the release of mod_python 3.0.1. > > skipping through the online documentation, I noticed the PythonOutputFilter > directive. If I understand corectly this and the AddOutputFilter Apache > deirective will enable me to register different Python handlers for > different file-extensions in the SAME directory, no. Not quite true because a filter is something different from a handler. But you _can_ assign different handlers to different file extensions by specifying them after a "|". This wasn't possible in 2.x.: http://www.modpython.org/live/mod_python-3.0.1/doc-html/dir-handlers-syn.html Grisha From david at no.westcontrol.spam.com Wed Nov 6 11:04:26 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Wed, 6 Nov 2002 17:04:26 +0100 Subject: using the PSF license for one's code References: <918bc22f.0211051301.2010d077@posting.google.com> <3dc867de$0$24754$7b0f0fd3@reader.news.newnet.co.uk> <918bc22f.0211060732.47b2198d@posting.google.com> Message-ID: "Donnal Walter" wrote in message news:918bc22f.0211060732.47b2198d at posting.google.com... > David Brown: > > There are basically two categories of open source licences, as far as I can > > see - gpl-type licences (you can use our source, but you have to apply the > > same licence to the modified code) and bsd-type licences (you can use our > > source for anything you want, but you have to acknowledge the copyright). I > > am a great believer in the spirit of a licence rather than the letter of the > > licence, and as far as I can see, the Python licence is in the same spirit > > as the BSD licence. I don't know how that would stand up in court, however, > > but hopefully it will never have to. > > Well, I'm not likely to take anyone to court, and neither is my > University for that matter. > > For entities like PSF that distribute a lot of copies of their > software, it probably makes sense to write their own specific > licenses, but for everyone else (like me) it seems to boil down to > choosing GPL or BSD. Who would have guessed that it could be this > simple? (And I am not being sarcastic; this thread has helped me > considerably.) Thanks. > > Donnal Walter > Arkansas Children's Hospital > University of Arkansas for Medical Sciences That's certainly how I look at it (perhaps with a bit of variation - if I want to release a Python module, I'd probably say "python licence" rather than "bsd" licence, simply to be consistant with other python modules). But if you are doing something big or important, you might want to get some legal guys to look at it - my (perhaps unfounded) impression is that American lawyers are much better at "letter of the law" than "spirit of the law". From emrich at bigfoot.extrastuff.com Mon Nov 18 15:53:50 2002 From: emrich at bigfoot.extrastuff.com (D a v i d E m r i c h) Date: Mon, 18 Nov 2002 20:53:50 GMT Subject: changing the Python grammar ? References: <2259b0e2.0211181221.2eab9db7@posting.google.com> Message-ID: "Michele Simionato" wrote in message news:2259b0e2.0211181221.2eab9db7 at posting.google.com... ... > But now a question arise to me: can I modify the grammar ?? > > Suppose for instance I want to make able Python to recognize identifiers > starting with some funny symbol, say "@". All I must do is to modify > the first line of the grammar as > > identifier ::= > ["@"] (letter|"_") (letter | digit | "_")* > > In the best of the worlds, I would look for some file in the Python > source distribution containing the grammar, I would change that line, > and recompiling I would have a new Python able to understand identifiers > starting with "@". Is this possible in practice ? > > Notice that I do NOT want to introduce ugly perlish-like identifiers in > Python, I simply want to know how much it is possible to customize the > Python grammar: is this a simple hack or a nightmare ? All the parser source code is provided in the distribution. I would start with Parser/tokenizer.c (except I wouldn't go there). It could be a very simple change. Have fun. David From ktilton at nyc.rr.com Wed Nov 20 17:03:19 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Wed, 20 Nov 2002 22:03:19 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: Message-ID: <3DDC0702.2030808@nyc.rr.com> Brian Quinlan wrote: > Kenny Tilton wrote: > >>documentation available at a keystroke, and apropos to search for >>stuff you suspect is in the language > > > Python has several nice help tools. Try typing "help()" at an > interactive shell. great. btw, i did not mean my list to be /in contrast/ with any other language, just why i find it approachable. > > >> true garbage collection (I am /not/ looking forward to reference >>counting or the hoops one has to jump thru to handle cyclic refs) > > > Python does not require any such hoops. Python uses a generational > garbage collector to deal with circular references. oops. i committed the sin so often committed against Lisp, viz, Living in the past. my bad. -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From hancock at anansispaceworks.com Wed Nov 6 16:33:05 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 6 Nov 2002 13:33:05 -0800 Subject: Python Browser Applets Message-ID: Hi all, Well, I've researched this further, and for those who are interested, I think I found a much better (read "easier") solution: First, AnyGUI is probably a better standard GUI to provide for the Applet/Plugin. As an attempt at a common standard, it's a much smaller API than Tkinter or PyGTK (though it provides backends for them). It is still somewhat incomplete, though. http://anygui.sourceforge.net One of the backends "planned" for AnyGUI is "PyUI" which I looked up: http://pyui.sourceforge.net and it is a GUI implemented against a "renderer" which is a very small class that has to be implemented for each class which simply handles the basic drawing actions. The PyGame 2D renderer bundled with it has less than 250 lines of Python code, which define methods like drawText() and drawRect(). So the simplest approach is simply to write an AWT renderer for PyUI which can then run in Jython. At that point, the Java-only restriction is lifted, because PyUI can also run on PyOpenGL or PyGame/SDL renderers (as well as several other choices), so the applet would run in C Python as well. At this point, I have 2 choices: 1) Run on Java-1.0-enabled browsers (which is pretty much all the commercial browsers, but not the free ones until you install a plugin). (Requires developing AWT renderer, possibly contributing to AnyGUI & PyUI projects to fill out any missing features). 2) Run as an independent Python application. For convenience, this can be configured as a "Helper App" in the browser so it will pop up when needed (Renderer already written -- actually a choice of them, may require AnyGUI/PyUI contribs). If I want to get more ambitious, it is possible to get the Netscape/ Mozilla Plugin SDK (and the Python Embedding manual) and write a Plugin to embed the Python interpreter to run Python Applets natively. I have found evidence that someone *once* did this, but all traces of the original implementation seem to have vanished from the web, and I'm not sure if it would've been easy to update a Python 1.5.2 plugin to Python 2.1+ (though it might). Possible starting places include: Mozilla Plugins Page: http://www.mozilla.org/projects/plugins/ Alice: http://www.alice.org WPY: http://www.python.org/ftp/python/wpy/ Reading the Plugin API docs, though, I have to admit to being somewhat lost -- I haven't figured out how a Plugin actually can draw itself into the browser window space allocated for it. It seems like this would have to mean that the "Netscape Methods" would include drawing primitives or a canvas object that can be drawn to, but I haven't found it yet (Or maybe I'm misunderstanding how it works, and the plugin has to talk to the underlying window library -- but that seems bizarre and awkward). In any case, I figure it means writing a "Netscape Plugin Renderer" for PyUI. This would give me option 3) Run Applet on Python Plugin (Requires embedded python plugin -- big project?, Netscape Plugin Renderer for PyUI -- small, contribs to AnyGUI and PyUI if needed). The plugin route is kind of the "high road" though -- very nice result, but it clearly requires the most work. Lastly, there are the Free Java implementations -- meaning the JVMs, the class libraries, and the "Open Java Interface" plugins. If one or more of these work, we have option 4) Run Applet on *Free* Java browser platform (need the AWT renderer, contribs to AnyGUI, PyUI, and Free Java OJI of your choice -- maybe KaffeOJI, which does exist). Kaffe OJI: http://www.kaffe.org/ftp/pub/packages/kaffe-mozilla-oji/ I have summarized these options in a diagram at: http://www.anansispaceworks.com/NaryaInfo/client_html As well as an idea for Zope-integration, but don't worry about that part -- it's just a way to make deploying the applets easier on the server side. The "Version 2" Zapplet is a pretty terrifying diagram, although I think it makes it look worse than it is -- it's just using a trick I got from a Java Applet/Plugin paper to make the process a lot more automatic for the user. The PreLoader and Loader, for example, can be fairly small programs, and I believe I have some sample code to start from. Version 2 is basically meaningless without the Python Applet Plugin (option #3). It's clear to me that I'm going to implement the AWT renderer and possibly contribute the the PyUI and AnyGUI projects to bring any missing widgets up to the level needed to implement my client applets. That's 100% python code, BTW, no extension modules in Java or C. I'm wondering if anyway has an interest in pursuing the plugin route. It does look do-able, but maybe a lot of work. Wouldn't be so bad if it were broken up among a few interested parties. It would probably be a snap for me to implement the "Plugin Renderer" for PyUI along with the AWT one (that is, if I can ever figure out how plugins draw themselves). Basically, I'm asking if anyone would be motivated to embed the Python browser into a plugin? Wanted to pass along my progress, and see if anyone's interested in the plugin part. If not, I'll probably just focus on writing * Jython backend for PyUI * Zapplet ("Version 1") for Zope * Docbook applet * Drawing applet which is the 20% of the effort that does 80% of the job ;-D. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From usenet at imperialviolet.org Mon Nov 25 07:39:01 2002 From: usenet at imperialviolet.org (Adam Langley) Date: Mon, 25 Nov 2002 12:39:01 +0000 Subject: Issue with new-style classes and operators References: <3DE215D1.D9A3FEF9@jandecaluwe.com> Message-ID: On Mon, 25 Nov 2002 13:21:37 +0100, Jan Decaluwe wrote: > class MyInt(object): > def __init__(self, val): > self.val = val > def __getattr__(self, attr): > return getattr(self.val, attr) > > >>>> a = MyInt(3) >>>> a.__add__(4) > 7 >>>> a + 4 > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand types for +: 'MyInt' and 'int' (Firstly, I should point out that it *does* work if one makes MyInt an old-style class) Well, the language reference states that: "The + (addition) operator yields the sum of its arguments. The arguments must either both be numbers or both sequences of the same type. In the former case, the numbers are converted to a common type and then added together. In the latter case, the sequences are concatenated." Since MyInt is neither a number (not derived from int) nor a sequence, the TypeError is technically correct. But, since __add__ is valid, it does somewhat violate the principle of least surprise from my point of view. From bokr at oz.net Wed Nov 20 14:03:32 2002 From: bokr at oz.net (Bengt Richter) Date: 20 Nov 2002 19:03:32 GMT Subject: Bug in Win32file WaitCommEvent ??? References: <3ddaa58d$0$4459$a1866201@newsreader.visi.com> <3ddba9d6$0$4464$a1866201@newsreader.visi.com> Message-ID: On 20 Nov 2002 15:27:18 GMT, grante at visi.com (Grant Edwards) wrote: [...] > >I've seen plenty of apps that assume it doesn't wait all the >time. If I had a C compiler and knew how to write a simple >console app for Win32, it would be easy enough to figure out >how it really does work. The Win32 guys I work with directly >all write device drivers and none of them know how the >user-land API works. > I found this, which seems to indicate someone else worried about it, and did a patch, but apparently wasn't 100% sure it was needed ;-/ http://www.cygwin.com/ml/cygwin-patches/2001-q4/msg00297.html Regards, Bengt Richter From sismex01 at hebmex.com Tue Nov 26 09:54:38 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 26 Nov 2002 08:54:38 -0600 Subject: Python Tutorial Was: Guido's regrets: filter and map Message-ID: > From: Grant Edwards [mailto:grante at visi.com] > Sent: Monday, November 25, 2002 10:27 PM > > I find lambda quite useful for creating simple anonymous > functions to pass to GUIs as button commands and the like. > I suppose the same effect could be obtained by adding a couple > more lines to define a temporarily-named function, but then I'd > have to think up a name. I've been known to waste hours trying > to come up with names for new computers. I'm not quite so > indecisive about functions, but it does seem to be one of my > weak points. > Ahh!! But the ideal throw-away name for anonymous functions is "_", or "__". I always use it for one-line definitions because it's clear, and ... "forgetable". :-) >>> def _(): print >> sys.stderr, "Button clicked!" >>> btn = Tkinter.Button(main, command=_) Since "_"'s usage is exactly on the next line from it's definition, you know where it went, and you can forget about it without remorse, or reuse it. Sure, it has the "problem" of being two lines instead of one, and a lambda in that position is more concise: >>> btn = Tkinter.Button(main, command=lambda:sys.stderr("Button clicked!\n")) but, with a lambda, you are limited to only an expression, not any statements. So using a throwaway function does have it's advantages. Anyway, to each it's own. But I do concurr with those who say that with the acquisition of list comprehensions, map(), reduce(), filter(), lambda() et-al, should be on the road to deprecation and eventual elimination, being the black un-pythonic sheep of the family. Good Tuesday! -gustavo From jdhunter at ace.bsd.uchicago.edu Tue Nov 19 19:16:02 2002 From: jdhunter at ace.bsd.uchicago.edu (jdhunter at ace.bsd.uchicago.edu) Date: Tue, 19 Nov 2002 18:16:02 -0600 Subject: matching multiple regexs to a single line... In-Reply-To: ("Alexander Sendzimir"'s message of "Tue, 19 Nov 2002 14:45:38 GMT") References: Message-ID: Wouldn't it be a simpler and more readily maintainable design drop the regex_ids and use a list of tuples where the first element is a rgx and the second element is an action? In your version you have to maintain a dictionary and a list, as well as (somewhat superfluous) regex ids. import re # you do want the re wrapper, not sre lines = map(str,range(3)) # some dummy lines for testing handler1 = handler2 = handler3 = lambda x: None # some very dumb handlers regexs = ( ( re.compile( r'regex1' ), handler1 ), ( re.compile( r'regex2' ), handler2 ), ( re.compile( r'regex3' ), handler3 ), ) for line in lines : for (rgx, action) in regexs: m = rgx.match( line ) if m: action(m) John Hunter From daniel.dittmar at sap.com Fri Nov 15 11:43:21 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Fri, 15 Nov 2002 17:43:21 +0100 Subject: A really bad idea. References: Message-ID: holger krekel wrote: > But in fact i'd like to see some examples of what is readable and > what is not readable in your oppinion. zip, enumerate: readable, because you can search the docs for the words. It is also easy to implement variations: returning other datatypes, returning an iterator to preserve memory. Thus the whole program becomes easier to understand because similar task are called in a similar way. list comprehension: not readable, because you don't know what to search for. You can't create dictionary comprehension or generator comprehension (both have been proposed on c.l.p), thus making the resulting program less regular. Daniel From jbublitzNO at SPAMnwinternet.com Wed Nov 13 15:23:48 2002 From: jbublitzNO at SPAMnwinternet.com (Jim) Date: Wed, 13 Nov 2002 20:23:48 GMT Subject: python, Qt and HOOPS 3D References: <3DD2A05D.5050007@elemtech.com> Message-ID: <3DD2B4C2.3060507@SPAMnwinternet.com> Karl G. Merkley wrote: > I am looking for the python bindings for the HOOPS-Qt widget. > Has anybody done this? Is anyone willing to share? If not > does someone have any pointers on how to go about doing this? > I've been playing around with swig but haven't had any luck making > it work yet. I'm not familiar with HOOPS-Qt at all, so this is somewhat speculative. There is a complete set of Python bindings for PyQt (http://www.riverbankcomputing.co.uk) using sip. If HOOPS-Qt depends on other Qt widgets, this would probably be your best starting point, as you can import the bindings for the rest of Qt and wouldn't have to redo them. There isn't any complete documentation for doing bindings with sip. I'm working on some stuff to make sip bindings easier to do (along with docs hopefully), but it'll be a while before I have anything to release (if ever). If HOOPS-Qt isn't an extremely large set of files, you can use PyQt or PyKDE as examples of how to do bindings with sip manually. You can get help with sip and PyQt on the PyKDE mailing list at: http://mats.gmd.de/mailman/listinfo/pykde If you're interested, email me directly and I'll try to give you some more info. Jim From op73418 at mail.telepac.pt Sun Nov 17 17:45:56 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Sun, 17 Nov 2002 22:45:56 +0000 Subject: Possibly a stupid question regarding Python Classes References: <3dd7c140$1_6@nopics.sjc> Message-ID: On Sun, 17 Nov 2002 11:18:29 -0500, "Adonis" wrote: >Is this even possible: > >class Foo: > def Bar(self): > print 'Foo' > >class Fib(Foo): > def Bar(self): > # do the original Foo.Bar() > # NOTE: w/o needing to instantiate Foo > # then do: > print 'Bar' > >So in essence I want to override the Bar function, but as well do what it >would if it were instantiated. I know I could instantiate Foo prior to >printing Bar, but was wondering if there was a way to keep it within the >same process. > >Any help is greatly appreciated. > >Adonis > In the 2.2 new-style class world you can use super(Fib, self).Bar() To call your super class's implementation of the Bar method. HTH, Gon?alo Rodrigues From grante at visi.com Mon Nov 18 10:55:46 2002 From: grante at visi.com (Grant Edwards) Date: 18 Nov 2002 15:55:46 GMT Subject: Serial Port References: <3dd47570$1@news.nz.asiaonline.net> <3dd514e8$0$4448$a1866201@newsreader.visi.com> Message-ID: <3dd90d82$0$22206$a1866201@newsreader.visi.com> In article , David Brown wrote: > "Grant Edwards" wrote in message > >> On a slight tangent, anybody know where there's documentation >> or examples of doing stuff like overlapped serial I/O under >> Win32 with events and callbacks and suchlike in Python? I >> haven't found a copy of the Python on Win32 book yet... > > I find it easier to run serial communication in a seperate > thread if I need asynchronous communication. Yes, it's far easier to use a thread per port. But my task is to try to troubleshoot serial driver bugs triggered by certain sequences of Win32 system calls. My customers are dyed-in-the-wool Win32 hacks who do things the most obtuse, complex way possible. They love callbacks and I/O completion ports and all that cruft. When they do stuff like that and report problems, my requirement isn't to write a program that performs serial I/O, it's to do it in a certain way in order to reproduce problems reported by customers. > You don't normally have so many serial ports open at a time > that the threading overhead is significant, I don't? I usually limit my test cases to 32 ports if possible, but on occasion have to use 100+ ports. > it is much easier than messing with the overlapped I/O stuff, > and it is platform-independant. Oh, I know it's easier doing sych I/O, and I don't care about platform independance. I've never been asked to troubleshoot a Win32 driver under Linux. :) > To be entirely honest, though, the couple of Python programs I > have written so far that use the serial port have not bothered > with threading either - they just send out something, and wait > for a reply or timeout (using the inWaiting() function from > pyserial, along with time.sleep). But if I needed something > more advanced, then I *would* use threads - I've done it in > Delphi, and it works fine. I use threads a lot for serial communications too. Sometimes one-thread-per-port isn't what is required. -- Grant Edwards grante Yow! I was giving HAIR at CUTS to th' SAUCER PEOPLE visi.com ... I'm CLEAN!! From peter at engcorp.com Wed Nov 13 22:54:16 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 13 Nov 2002 22:54:16 -0500 Subject: Reminder: PyGTA meeting is Thursday November 14, 8-10 pm Message-ID: <3DD31E68.FA27082C@engcorp.com> Remember that Thursday night is the next meeting of PyGTA, the Toronto-area Python and Zope user group. It will be held at the 519 Church St. Community Centre, near Wellesley, from 8 to 10 p.m. Please visit http://web.engcorp.com/pygta/wiki/NextMeeting for other details of the meeting. There will be a draw for prizes from ActiveState, including some Python T-shirts and a free license for their Python IDE. We also have a bunch of cool Python balloons! :-) -Ian Garmaise and Peter Hansen, PyGTA organizers From jkraska at san.rr.com Sat Nov 23 12:54:59 2002 From: jkraska at san.rr.com (Courageous) Date: Sat, 23 Nov 2002 17:54:59 GMT Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <2259b0e2.0211210838.7647301a@posting.google.com> <093kra.3n3.ln@beastie.ix.netcom.com> Message-ID: >> If there's one thing that makes Python a bad choice for me, that's it. >> During development, static type systems save me a lot of trouble. Python is more for the type of person that finds that static type systems _give_ them a lot of trouble. C// From max at alcyone.com Sun Nov 24 16:52:12 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 24 Nov 2002 13:52:12 -0800 Subject: if : References: Message-ID: <3DE14A0C.E0CDBC16@alcyone.com> Andr? N?ss wrote: > if myvar = someFunction(): > > My question is, what is the rationale for this? Is it a technical > issue? Or > purely a matter of language design? I'm curious because I'm interested > in > the design og programming languages, not because I want this behavior > changed in Pyton :) It's a language design feature, intended to avoid the confusion between when people write (say, in C): if (a = b) ... but mean if (a == b) ... Instead in Python assignments are treated as statements, not expressions, so they cannot appear in an if clause. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Money talks / But love is for real / And you know that \__/ Neneh Cherry Erik Max Francis' bookmarks / http://www.alcyone.com/max/links/ A highly categorized list of Web links. From usenet at mike-warren.com Thu Nov 14 17:08:12 2002 From: usenet at mike-warren.com (Mike Warren) Date: Thu, 14 Nov 2002 22:08:12 GMT Subject: proxy object Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Greetings, I have a simplified example of what I want to do (which isn't working), which basically boils down to this: I want to return a ``proxy'' object which delays the instantiation of expensive-to-instantiated objects, but I want the object to -- after the instantiation -- behave just like it would without the proxy. This mostly works, but isinstance() fails, kind of: if the ``hack'' code below is enabled, then isinstance works but other things fail. So: 1. is there some way to override isinstance behaviour? or: 2. is there some way to ``replace'' the proxy instance with the ``other'' instance? 3. what exactly is going on below? Why is there an AttributeError about ``_something''? Okay, here's the example (I'm obviously not doing the delayed-instantiation business). Any hints? ,---- | class Proxy: | def __init__(self,obj,hack=0): | self._obj = obj | if hack: | self.__class__ = self._obj.__class__ | | def __getattr__(self,name): | return getattr(self._obj,name) | | class Foo: | def __init__(self): | self._something = "something" | | def something(self): | return self._something | | | a = Foo() | b = Proxy(a) | c = Proxy(a,hack=1) | | print a,b,c | | print "b is Foo?", isinstance(b,Foo) | print "c is Foo?", isinstance(c,Foo) | | print b.something() | print c.something() `---- - -- mike [at] mike [dash] warren.com GPG: 0x579911BD :: 87F2 4D98 BDB0 0E90 EE2A 0CF9 1087 0884 5799 11BD -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 and Gnu Privacy Guard iEYEARECAAYFAj3UHqgACgkQEIcIhFeZEb3thQCggqbj3yNK57tb5JGtnci3So0V PpwAnjnzJUaIc4+JWudSdGFENNzZ80H3 =Covo -----END PGP SIGNATURE----- From mwh at python.net Wed Nov 27 11:04:14 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 27 Nov 2002 16:04:14 GMT Subject: super() and __get__ References: Message-ID: <7h3znrvoveu.fsf@pc150.maths.bris.ac.uk> Mike Dean writes: > These are probably two separate questions, but... > > I was out on Guido's page on Unifying Types and Classes, trying to grok > super(), metaclasses, and th meaning of life. I think I get this > metaclass thing, but let me see if I get this right on super() - all > super() does, is create an object that responds to attribute access by > passing that access on to the first object (class, type, whatever) in > the MRO of the object with which super() was called, starting with the > type super() was called with (i.e., if class C has 10 base classes & > types, once all flattened out into the MRO, and class B is the 4th in > the MRO, then it only searches from B on). Am I correct? Probably :) All I think you have to know about super() is that you write def meth(args): ... super(, self).meth(args) For more info, the code is your friend. Be warned, brain-exploding dragons live in Objects/typeobject.c, but the implementation of super() probably isn't that bad. > Now, a couple more questions... > > Where did this __get__ thing used in describing super() (and another > thing or two on that page) come from? It's new in 2.2 if that's what you're asking. > I can't seem to find it in the docs anywhere. descrintro.html is the only documentation on this sort of thing, I think (there might be some stuff in some of the PEPs, but not much IIRC). > It was used in the Python Super() implementation, as well as another > time or two. > > Also, if object is the base class of type, why does object.__mro__ work > when object defines no __mro__? ? object.__mro__ is just (object,), no? Don't see the problem with that. > And finally, since __mro__ appears to be an attribute merely inherited > from type by all classes, if I have a fancy, can I override __mro__ to > suit some bizarre purpose? Um, I think the answer to that is "no". > Or is it ignored, simply a mechanism to access __mro__? It's a wrapper around the C level field tp_mro in the type struct. > Likewise, why does type also have an mro method, when there's > __mro__? You can make a class' metaclass have a .mro() method which will be called during class creation -- this is in descrintro.html isn't it? Or is it Lib/test/test_descr.py? Lots of stuff in that last that you might want to read, anyway. Cheers, M. -- Premature optimization is the root of all evil. -- Donald E. Knuth, Structured Programming with goto Statements From s997659 at ee.cuhk.edu.hk Wed Nov 13 10:58:03 2002 From: s997659 at ee.cuhk.edu.hk (Geiger Ho) Date: Wed, 13 Nov 2002 23:58:03 +0800 Subject: calendar modules In-Reply-To: References: Message-ID: thx On 13 Nov 2002, Gerhard [iso-8859-1] H?ring wrote: > In article , Geiger Ho wrote: > > Hi all, > > > > Wondering around the modules, I find that "calendar" does not function > > well in MS Windows. When I type "calendar.month(2002,11)", it outputs a > > string > > > > ' November 2002\nMo Tu We Th Fr Sa Su\n 1 2 3\n 4 5 6 > > 7 8 9 10\n11 12 13 14 15 16 17\n18 19 20 21 22 23 24\n25 26 27 28 29 > > 30\n' > > > > but rather in proper formating. > > Try "print calendar.month(2002, 11)" instead of the implicit repr that's called > in your case. > > > This seems calendar module is not platform > > It is. > -- > Gerhard H?ring > OPUS GmbH M?nchen > Tel.: +49 89 - 889 49 7 - 32 > http://www.opus-gmbh.net/ > > From grante at visi.com Tue Nov 19 20:05:24 2002 From: grante at visi.com (Grant Edwards) Date: 20 Nov 2002 01:05:24 GMT Subject: Bug in Win32file WaitCommEvent ??? References: <3ddaa58d$0$4459$a1866201@newsreader.visi.com> Message-ID: In article , Grant Edwards wrote: >> I don't think this last step is correct. > > Perhaps. If it isn't correct, where does the event mask get returned? Here's some example code I found at http://www.codeproject.com/system/serial_com.asp (among other sites). It uses GetCommMask() to read the mask value after the WaitCommEvent event has triggered. However, the MSDN page for GetCommMask says that it returns "a mask of events that are currently enabled". To me that means that GetCommMask() just reads back the value set by SetCommMask(). But, the bit definitions say that bits mean things like "A character was received and placed in the input buffer" not that this particular event is unmasked. while ( abContinue ) { BOOL abRet = ::WaitCommEvent(apThis->m_hCommPort,&dwEventMask, &ov); if ( !abRet ) ASSERT( GetLastError () == ERROR_IO_PENDING); arHandles[1] = ov.hEvent ; dwWait = WaitForMultipleObjects (2,arHandles,FALSE,INFINITE); switch ( dwWait ) { case WAIT_OBJECT_0: _endthreadex(1); break; case WAIT_OBJECT_0 + 1: DWORD dwMask; if (GetCommMask(apThis->m_hCommPort,&dwMask) ) { if ( dwMask & EV_TXEMPTY ) TRACE("Data sent"); ResetEvent ( ov.hEvent ); continue; } else { //read data here and reset ov.hEvent } } } And then other web pages claim that "An event mask, which controls which events set the state of the event object [...], can be set using the SetCommMask function. The current event mask can be retrieved by calling the GetCommMask function." Is it just me, or is a "mask" and the set of pending events two different things? Cripes, are all MS documents this bad? If this were Linux, we'd have just had a peek at the kernel code and settled this in 30 seconds. :) Here's another example I found at http://groups.google.com/groups?selm=%23Cq5e4pxAHA.2280%40tkmsftngp02 It apparently expects it to work the way I originally described it: if (WaitCommEvent(hCom, &dwEvtMask, &o)) dRes = dwEvtMask; else { fSuccess = GetLastError(); if(fSuccess == ERROR_IO_PENDING) { DWORD res; MSG msg; do { res = WaitForSingleObject(o.hEvent,nTimeOut); if(PeekMessage(&msg,NULL,WM_USER, FM_MSG_LAST,PM_REMOVE)) ProcessPostMsg(msg); }while(res == WAIT_TIMEOUT && !nTimeOut); switch(res) { case WAIT_OBJECT_0: dRes = dwEvtMask; case WAIT_TIMEOUT: break; default: break; } } } if(dRes == EV_RXCHAR) { // Lots of stuff } PurgeComm(hCom,PURGE_RXCLEAR); dwEvtMask = 0; dRes = 0x8000; How do you guys in Win32land answer questions like this? MSDN is useless, MS support is even worse according to the Win32 guys I've talkd to, and there doesn't seem to be any consensus on how this works among people actually using it! -- Grant Edwards grante Yow! I feel like I am at sharing a "CORN-DOG" with visi.com NIKITA KHRUSCHEV... From abidnego25 at yahoo.com Mon Nov 18 15:20:18 2002 From: abidnego25 at yahoo.com (les) Date: 18 Nov 2002 12:20:18 -0800 Subject: redirecting cgi error to browser Message-ID: <653cf871.0211181220.43beca9c@posting.google.com> hi, i would like to redirect the cgi error to my browser, for debugging purposes. i am looking for it on the net but am unable to find it. can someone please give me an example thanks From mclin at ctgi.com Fri Nov 22 10:11:03 2002 From: mclin at ctgi.com (Jon McLin) Date: 22 Nov 2002 07:11:03 -0800 Subject: Subclassing Numpy Arrays? Message-ID: <9b8c378b.0211220711.2ab041a6@posting.google.com> I have an application wherein I need to subclass Numpy arrays. This does not appear doable, at least directly. I can obviously create my own python wrapper class around arrays to enable subclassing, but this seems like a lot of work. especially given the on-going type/class unification. Can anyone provide insight into the likelihood and timeframe for subclassable array types in Numpy, or point me in a productive direction? Thanks, Jon From sismex01 at hebmex.com Wed Nov 6 17:10:34 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 6 Nov 2002 16:10:34 -0600 Subject: I "think" global is broken Message-ID: > From: Larry Bates [mailto:lbates at swamisoft.com] > > The following code works as expected. > > class test: > global _trace > def __init__(self): > if _trace: print "entering test.__init__" > return > > global _trace > _trace=1 > x=test() > > > Now if I move the class into a separate module called test.py > and change the main program it no longer works > > from test import * > global _trace, _debug > _trace=1 > x=test() > > I get undefined global error > > I just don't believe that this is the way it should work. > I understand that in this simple example I could > do an import test and (according to other posts > I've read it should work). But in a real world > example the external module has 8 classes in it > (and growing). It just doesn't seem right that I > would need to split it into 8 different modules. > > Am I missing something? > Thanks in advance for any assistance. > > Regards, > Larry Bates > lbates at swamisoft.com > As explained in another thread a bit ago, "globals" aren't truly "global", in the traditional sense of the word. Or, in the "customary" sense of the word. A global variable in Python is one that exists at the module level, and not as a local variable in a function or as an instance or class variable. Also, it only makes sense to do "global " inside a function, so that when you assign to it doesn't live as a local variable inside the function, but rather as a module-level variable. The only truly global _IDENTIFIERS_ are those inside __builtins__, but that is an implementation detail (as explained by f/bot) and, although you could create a truly global shared variable by assigning it to __builtins__., nothing stops the Python team from changing that behaviour eventually. So, retaking your example, in the second instance where it fails, when you execute "from test import *", you bring into __main__ (assuming your in the python shell) all identifiers in test which don't start with an underscore. BUT, wait a second; all functions which you import "remember" which module they come from, so when you execute "global" inside an imported function, it's accessing the module's namespace, and not the "importing" namespace. So, when you run "x=test()" the second time, the class tries to access a global variable (actually, a module variable) called "test._trace", and not "__main__._trace", which is your intent. HTH It's kinda tricky, ain't it. :-) -gustavo From cjw at sympatico.ca Mon Nov 4 16:02:36 2002 From: cjw at sympatico.ca (Colin J. Williams) Date: Mon, 04 Nov 2002 16:02:36 -0500 Subject: how to stop a running python command in pywin ide References: <7xEw9.9$%f4.153@news.oracle.com> Message-ID: <3DC6E06C.B640B932@sympatico.ca> An HTML attachment was scrubbed... URL: From pieroul at attglobal.net Sat Nov 30 12:32:25 2002 From: pieroul at attglobal.net (Pierre Rouleau) Date: Sat, 30 Nov 2002 12:32:25 -0500 Subject: Python exceptions: is there a way to find the exception attributes? Message-ID: <3DE8F629.4080108@attglobal.net> Is there a way to find out what arguments can be passed to a raised exception of specific class? Python has a set of built-in exceptions (as described in http://www.python.org/doc/current/lib/module-exceptions.html ) If someone needs to know what information can be passed (and retieved) from an IOError, one way is to go back to that document, read that exceptions.IOError is derived from exceptions.EnvironmentError and that EnvironmentError can be initiated with a 2-tuple or 3-tuple and that the attributes will be errno, strerror and filename. Is there a way to find out about the existence of these attributes without having to read the documentation, using the dir() function or something else? It would be nice to be able to do that from the interpreter. The only thing i have found using dir() is shown below and it does not give me the attributes. >>> import exceptions >>> exceptions.IOError.__doc__ 'I/O operation failed.' >>> dir(exceptions.IOError) ['__doc__', '__getitem__', '__init__', '__module__', '__str__'] >>> Of course, I could force an exception and print it like: >>> try: ... f=open("/invalid/invalid.oops") ... except IOError, e: ... print dir(e) ... ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args', 'errno', 'filename', 'strerror'] >>> Is this the only way ? -- Pierre Rouleau From arivu at qmaxtest.com Thu Nov 14 23:04:59 2002 From: arivu at qmaxtest.com (Arivazhagan) Date: 14 Nov 2002 20:04:59 -0800 Subject: How to write Inline Functions in Python? References: <3DD3C06D.61AAB36D@engcorp.com> Message-ID: Hi We are extending python to develop a Board Description language for ATE. say in our project there are 2 modules named a.py( provided by us ) and b.py.(the end user programs.) In a.py ------- import sys class Good : def __init__(self, name ) : self.__name = name def createGood( *names ) : for name in names : thisGood = Good( name ) #The following is done so that the objects created here can be accessed #from b.py without using the module name. #We just want to avoid this. sys.modules['__main__'].__dict__[name] = thisGood In b.py ------- from a import * createGood( 'A', 'B', 'C' ) #We want to access like this without that additional codes. print A print B print C regards b.arivazhagan Peter Hansen wrote in message news:<3DD3C06D.61AAB36D at engcorp.com>... > Arivazhagan wrote: > > > > Hi Tim > > > > I assume you're coming from C++. - Thats true. > > > > Hi > > > > My requirements here. > > > > we have three python files names a.py, b.py and c.py. > > In a.py we are calling a global function in c.py which creates objects > > of a class in c.py depending on the parameters passed. These objects > > are created in the scope of c.py. But i need to happen in a.py without > > using the module name. > > so I thought that if we inline the function call so that it expands we > > can access that object without referring to the module name. > > > > Is it possible? Is there some other methods to achieve this in python? > > Certainly there is, but you haven't explained clearly enough what you > really want. It sounds like you could simply be returning those objects > from a function defined in c.py and called from a.py. > > My guess is you are mucking around with global variables at module > scope level and getting yourself into a lot of trouble. > > Can you explain *why* you need to refer to objects defined in another > module without referring to that module's name? Or can you explain > why these objects are being created as globals instead of just > returning them from a function? > > -Peter From krissepu at vip.fi Tue Nov 26 11:09:23 2002 From: krissepu at vip.fi (Pekka Niiranen) Date: Tue, 26 Nov 2002 18:09:23 +0200 Subject: How to convert ASCII-number => HEX -number => string of numbers in HEX ? Message-ID: <3de39ca8$1@news.vip.fi> Hi, I looked thru modules binascii and struct but not found a way to convert hexadecimal value to a string of hex values according to ascii table. Example: number = 6673 (max is 0xFFF) hex -value = '0x1a11' string value = "\x31\x61\x31\x31" (31 is one, 61 is 'a') or: number = 333 (max is 0xFFF) hex -value = '0x14d' string value = "\x30\x31\x34\x64" (30 is zero, 31 is one, 34 is four, 64 is "d") I have got this far: x="" a = hex(333) for byte in a[2:].zfill(4): # Number is allways presented with 4 hex values (filling missing values with zeros) x = "%s%s" % ( WHAT HERE ) Anybody, is there a build in function or shortcut that does this ? -pekka- From bhards at bigpond.net.au Mon Nov 25 05:46:51 2002 From: bhards at bigpond.net.au (Brad Hards) Date: Mon, 25 Nov 2002 21:46:51 +1100 Subject: setting a socket to multicast Message-ID: <200211252146.51963.bhards@bigpond.net.au> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 G'day, I'm trying to write a simple UDP server that listens to a multicast group. This is roughly what I have so far: import socket port = 5353 addr = '224.0.0.251' s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(addr)) s.bind(("", port)) print "Waiting on port:", port while 1: data,addr = s.recvfrom(1024) print "Received", data, "from", addr However when I run it, it bombs out: Traceback (most recent call last): File "udpserver.py", line 8, in ? s.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(addr)) socket.error: (22, 'Invalid argument') I'm completely mystified by this. The man page for setsockopt(2) doesn't even mention EINVAL (at least on my system), and my usual network reference (Stevens, Unix Network Programming) failed me on this occasion. The documentation refers the man page, which is nice except that the system call has five arguments and the python call only has three I did fine one example that was pretty close: * http://www.pythonapocrypha.com/Chapter15/Chapter15.shtml, which does: s.setsockopt(SOL_IP,IP_ADD_MEMBERSHIP, inet_aton(addr)+inet_aton('')) and although the third argument looked a bit silly, it was all I had to work from. Can anyone enlighten me? Brad - -- http://linux.conf.au. 22-25Jan2003. Perth, Aust. I'm registered. Are you? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE94f+bW6pHgIdAuOMRAtWqAKCAAiAqs0nLkMiohyqrJ7sWC4l4qgCfZppm uE5k2r4JXerPXtsog2pUU1Y= =VMh7 -----END PGP SIGNATURE----- From op73418 at mail.telepac.pt Wed Nov 6 15:25:33 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 06 Nov 2002 20:25:33 +0000 Subject: Guilty secret: globals baffle me References: <3U9y9.19300$ko1.2872530@kent.svc.tds.net> <82ay9.98000$TD1.4405986@news2.tin.it> Message-ID: On 6 Nov 2002 17:21:46 GMT, bokr at oz.net (Bengt Richter) wrote: >I have an uncomfortable feeling there is unfinished >business in the way names in nested scopes and otherwise >related namespaces work. The global/local dichotomy doesn't >fully express the possibilities any more. IMO it would be nice >to have full access to accessible namespaces without magically >determined access mode restrictions based on full-function lookahead. > >I.e., we have a de facto hierarchy of name spaces defined by the >ability to nest functions. Why not have an access mechanism that >allows rebinding as desired? E.g., you could let locals take a depth argument, >so locals() is equivalent to locals(0), and locals(1) is the enclosing >name space, so locals(1)['x'] = 3 in bar above would rebind the x local to foo. > I totally agree with you. The uncomfortable feeling is underlined by the fact that you can rebind global names through the use of global (the only declaration in Python - ach!) but not names in the enclosing scope - if it is not global that is. Although I do not feel that there is a need for this feature in Python, it strikes as an ugly asymmetry - the ugliest in fact. I would just change a little bit your notation. Instead of reusing locals use something like enclosed() returning the enclosing scope. And you've guessed it - if you want to get at the next scope just use enclosed().enclosed(). The enclosed() at global scope should return None. Now if you wanted to rebind a variable in the enclosing scope you should be able to use the notation enclosed().x = and not dict notation. globals() should follow the same rules. With my best regards, Gon?alo Rodrigues From bswhb at 263.net Fri Nov 22 01:41:09 2002 From: bswhb at 263.net (Wang Hanbo) Date: Fri, 22 Nov 2002 14:41:09 +0800 Subject: With what module can Python handel *.tar.gz file? Message-ID: <000201c291f2$28ef74d0$d001a8c0@dctc.cs> Hi, Buddies, I have a file named ***.tar.gz, and I want to gunzip it with Python. With which modules can I accomplish this task? And how to? Hanbo 2002-11-22 -------------- next part -------------- An HTML attachment was scrubbed... URL: From benson123456 at yahoo.com Mon Nov 4 11:15:41 2002 From: benson123456 at yahoo.com (Benson Ngai) Date: 4 Nov 2002 08:15:41 -0800 Subject: Tkinter problem References: <369fc45d.0211031751.7ad1276@posting.google.com> Message-ID: <369fc45d.0211040815.65a967ba@posting.google.com> okButton=Button(msgWin,text="OK",command=msgWin.quit,justify=CENTER) #^^^^^^ Problem on this line^^^^^^^^^^^^^^^^^^^^^###### m.. This is really strange.... I am useing python 2.2.2 in windows 2000. when I run this program... the main windows would come up but then when I click on the "About" in the menu bar. a new windows would pop up with a small line of text and a "OK" button, but when I click on the "OK" butoon it close the whole program.... not just the sub-window. should I still use the .quit command?? if not..what other command should i use? I am new to python and Tkinter. please help Thanks a lot Benson From nhodgson at bigpond.net.au Tue Nov 5 06:32:08 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 05 Nov 2002 11:32:08 GMT Subject: "Universal Gateway" References: <1y63gc02.fsf@morpheus.demon.co.uk> Message-ID: Paul Moore: > If so, is there a way to *call* an arbitrary interface? > (Actually, I imagine that this should be possible using calldll plus a > reasonable amount of arcane pointer arithmetic, but it sounds like it > could be a bit messy and error prone...) Looks like my posts that include attachments are no longer propagating. Bruce Dodson: > I, too, salivated when I first heard about universal gateway. However, on > closer inspection, I found that it is outbound only: while it will allow you > to _implement_ just about any arbitrary interface in a Python server, it > will not allow your Python code to _access_ those custom interfaces as a > client. Way back in 1997, I published some very low level code for calling arbitrary COM vtable interfaces using calldll on the Pythonwin sig mailing list and it is visible at http://groups.yahoo.com/group/pythonwin-sig/message/490 Unfortunately the yahoo interface flattens the code and calldll has changed since then, and ni has gone away :-( , so the code, resurrected a bit, is at the end of this post and available from http://www.scintilla.org/COMVtable.py You can get copies of calldll and npstruct for Python 2.2 from http://www.activestate.com/PPMPackages/PyPPM/2.2+/packages/ It is a very ugly way to do COM. Neil import pythoncom import calldll import string import npstruct METH_QI = 0 METH_ADDREF = 1 METH_RELEASE = 2 METH_UPDATE = 13 METH_IS_UPTODATE = 14 class dwordbuf: def __init__(self): self.mb = calldll.membuf(4) def address(self): return self.mb.address() def value(self): return calldll.read_long(self.address()) class Unknown: def __init__(self, address, iid, fNeedAddRef = 1): self.address = address self.iid = iid # External use needs to addref, not needed if created by # internal QueryInterface if fNeedAddRef: self.AddRef() def __del__(self): self.Release() def Call(self, methnum, args = (), argdesc = "*", retdesc = "l"): if argdesc == "*": # intuit argument types argdesc = 'l'*len(args) #print 'Call ' + `methnum` + ' ' + `self.address` vtable = calldll.read_long(self.address) vtmeth = calldll.read_long(vtable+methnum * 4) # Prepend interface pointer to arg list argdesc = "l" + argdesc args = (self.address, ) + args #print args hres = calldll.call_foreign_function(vtmeth, argdesc, retdesc, args) return hres def QueryInterface(self, iid): # iid is a membuf holding a GUID bufPunk = dwordbuf() hres = self.Call(METH_QI, (iid.address(), bufPunk.address())) addrnewunk = bufPunk.value() return Unknown(addrnewunk, iid, 0) def AddRef(self): return self.Call(METH_ADDREF) def Release(self): return self.Call(METH_RELEASE) def GetCOMAddress(unk): # Ugly way to get address of COM object represented by a # PyIUnknown by asking for its string representation. cdesc = `unk` cpt = string.atoi(cdesc[36:-1],16) return cpt def GUIDBuf(guid): buf = calldll.membuf(16) gs = npstruct.pack('Llhhbbbbbbbb',( eval('0x' + guid[1:1+8]), string.atoi(guid[10:10+4],16), string.atoi(guid[15:15+4],16), string.atoi(guid[20:20+2],16), string.atoi(guid[22:22+2],16), string.atoi(guid[25:25+2],16), string.atoi(guid[27:27+2],16), string.atoi(guid[29:29+2],16), string.atoi(guid[31:31+2],16), string.atoi(guid[33:33+2],16), string.atoi(guid[35:35+2],16))) buf.write(gs,0,16) return buf StdPict = pythoncom.CoCreateInstance('{00000316-0000-0000-C000-000000000046}', None, 1, pythoncom.IID_IUnknown) StdPictOle = StdPict.QueryInterface('{00000112-0000-0000-C000-000000000046}', 1) iidOleObject = GUIDBuf('{00000112-0000-0000-C000-000000000046}') pictOle = Unknown(GetCOMAddress(StdPictOle), iidOleObject) hres = pictOle.Call(METH_IS_UPTODATE) print 'HRESULT = ' + hex(hres) # Destroy it now to avoid problems in automatic tear down pictOle = None From stuart at bmsi.com Wed Nov 20 21:02:40 2002 From: stuart at bmsi.com (Stuart D. Gathman) Date: Thu, 21 Nov 2002 02:02:40 GMT Subject: Need Function To Run As Long As Button Widget Pressed References: Message-ID: <49XC9.24338$0U1.2390152@news2.east.cox.net> On Wed, 20 Nov 2002 20:04:30 -0500, Josiah wrote: > def Go(self): > print "Working" > status = self.var.get() > if status == 1: > self.after(10, self.Go()) > > def IsPressed(self,event): ^^^^^ > self.var.set(1) > > def IsReleased(self,event): ^^^^^ > self.var.set(0) -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From duncan at rcp.co.uk Tue Nov 26 04:44:03 2002 From: duncan at rcp.co.uk (Duncan Booth) Date: Tue, 26 Nov 2002 09:44:03 +0000 (UTC) Subject: some questions.... References: Message-ID: eugene kim wrote in news:arumtk$pqa$1 @newsreader.mailgate.org: > wow.. i thought python is easy to learn.. > but there are lot's of corks.. > namespace, scoping rule, exec, eval.. > all confuses me.. > Simple rule: forget that exec and eval exist. You almost certainly don't need to use them. If you think you need either exec or eval then post here saying why you want to use them and 9 times out of 10 someone will tell you a simpler and cleaner way to do whatever it was. From jdhunter at ace.bsd.uchicago.edu Mon Nov 18 19:42:32 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 18 Nov 2002 18:42:32 -0600 Subject: file upload via http In-Reply-To: <3dd90ff4$0$46609$e4fe514c@news.xs4all.nl> ("Joost van Rooij"'s message of "Mon, 18 Nov 2002 17:05:59 +0100") References: <3dd90ff4$0$46609$e4fe514c@news.xs4all.nl> Message-ID: >>>>> "Joost" == Joost van Rooij writes: Joost> import httplib Joost> body = open("./image.jpg","r") Joost> headers = {"Content-type": "multipart/form-data", Joost> conn = httplib.HTTPConnection("www.server.net:80") Joost> conn.request("POST", "/showme/picture/upload.php",body , headers) Just a guess... Does conn.request want a string or a file object for body. You are passing it a file object. If it wants a string (and the help doesn't specify), you should call conn.request("POST", "/showme/picture/upload.php",body.read(), headers) Also, you may need to calculate the Content-Length field http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=3CBC9027.3010603%40nmt.edu&rnum=3&prev=/groups%3Fas_q%3D%2520HTTPConnection%2520request%2520post%26safe%3Dimages%26ie%3DUTF-8%26oe%3DUTF-8%26as_ugroup%3D*python*%26lr%3D%26hl%3Den http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=mailman.982178415.9822.python-list%40python.org&rnum=3&prev=/groups%3Fq%3D%2BHTTPConnection%2Brequest%2B%2Bgroup%253A*python*%26btnG%3DGoogle%2BSearch%26hl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8 John Hunter From detlev at die-offenbachs.de Sat Nov 30 12:12:49 2002 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 30 Nov 2002 18:12:49 +0100 Subject: ANN: Eric 3.00-beta1 released Message-ID: Hi, Eric 3.0.0-beta1 is available for download via http://www.die-offenbachs.de/detlev/eric3.html This release contains some bugfixes and some of the requested features like an alternative layout for the main screen, smaller icons, capability to add all python/designer files of a directory to a project. For details see the history file in the distribution. Please note that this is a feature freeze for 3.0.0. I will only fix bugs to get a stable release as soon as possible. New features will come with version 3.0.1. What is it? ----------- Eric 3.0.0 (or short eric3) is a Python IDE written using PyQt and QScintilla. It has integrated project management capabilities, it gives you an unlimited number of editors, an integrated Python shell, an integrated debugger and more. Please see for yourself by visiting the a.m. page (it contains a picture of Eric our mascot as well). Please report bugs, feature wishes or code contributions to eric-bugs at die-offenbachs.de Help wanted!! ------------- I would need some support in the area of more translations and user documentation. Any volunteers out there? Just let me know. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From gerhard.haering at opus-gmbh.net Thu Nov 28 14:33:35 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 28 Nov 2002 19:33:35 GMT Subject: Name of current method References: Message-ID: Thomas Guettler wrote: > Hi! Servus! > How can I get the name of the method which is executed? Why do you want to do this? Looks like something rather questionable to me. Anyway, you can raise an exception, catch it and analyse it using the methods in the 'traceback' module. I think your question has been discussed several times in the past here, so you should be able to find less vague answers via groups.google.com ;-) -- Gerhard H?ring OPUS GmbH M?nchen Tel.: +49 89 - 889 49 7 - 32 http://www.opus-gmbh.net/ From cnetzer at mail.arc.nasa.gov Mon Nov 18 16:39:50 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Mon, 18 Nov 2002 13:39:50 -0800 Subject: Tkinter wart: bug or feature? In-Reply-To: References: <3dd563db.9499247@nntp.ix.netcom.com> Message-ID: <200211182139.NAA20149@mail.arc.nasa.gov> On Saturday 16 November 2002 06:57, Fredrik Lundh wrote: > lbl = Tkinter.Label(win.window, image=image1) > lbl.photo = image1 > > which guarantees that the image won't be collected before > the widget itself. Well, maybe I need more schooling. Could someone look at this code and tell me where my reasoning goes wrong.: import Tkinter def make_photo_label( parent ): image2 = Tkinter.Image('photo', file="WatchmenLogo.gif") lbl2 = Tkinter.Label(parent, image=image2) lbl2.photo = image2 lbl2.pack(expand=1, fill=Tkinter.BOTH) return if __name__ == '__main__': root = Tkinter.Tk() make_photo_label( root ) root.mainloop() When make_photo_label() finishes execution, the 'lbl2' variable goes out of scope, and is deleted from the local namespace. So the Tkinter.Label object should be 'collected' (which DOESN'T mean that Tk forgets it; the widget is still packed, and still exists to Tk). When 'lbl2' is collected, the reference count of 'image2' drops. (?) Furthermore, when 'image2' it goes out of scope, it drops again. So it should (seemingly) be collected as well, and the image should become blank. I guess I don't understand how attaching image2 as an attribute to lbl2 should change anything. lbl2 still gets collected when the function is over, and in doing so, it's link to 'image2' should be broken, and then 'image2' should be collected. However, when running the program, I see that is NOT the case. The image only disappears if I comment out "bl2.photo = image2". Do I misunderstand reference counting? -- Bay Area Python Interest Group - http://www.baypiggies.net/ Chad Netzer cnetzer at mail.arc.nasa.gov From bokr at oz.net Mon Nov 4 17:05:11 2002 From: bokr at oz.net (Bengt Richter) Date: 4 Nov 2002 22:05:11 GMT Subject: parenthesis References: <2259b0e2.0211041224.7c24635b@posting.google.com> Message-ID: On 4 Nov 2002 12:24:31 -0800, mis6 at pitt.edu (Michele Simionato) wrote: >Suppose I want to parse the following expression: > >>>> exp='(a*(b+c*(2-x))+d)+f(s1)' > >I want to extract the first part, i.e. '(a*(b+c*(2-x))+d)'. > >Now if I use a greedy regular expression > >>>> import re; greedy=re.compile('\(.*\)') > >I obtain to much, the full expression: > >>>> match=greedy.search(exp); match.group() > >'(a*(b+c*(2-x))+d)+f(s1)' > >On the other hand, if I use a nongreedy regular expression > >>>> nongreedy=re.compile('\(.*?\)') > >I obtain too little: > >>>> match=nongreedy.search(exp); match.group() > >'(a*(b+c*(2-x)' > >Is there a way to specify a clever regular expression able to match >the first parenthesized group ? What I did, was to write a routine >to extract the first parenthesized group: > >def parenthesized_group(exp): > nesting_level,out=0,[] > for c in exp: > out.append(c) > if c=='(': nesting_level+=1 > elif c==')': nesting_level-=1 > if nesting_level==0: break > return ''.join(out) > >>>> print parenthesized_group(exp) > >(a*(b+c*(2-x))+d) > >Still, this seems to me not the best way to go and I would like to know >if this can be done with a regular expression. Notice that I don't need >to control all the nesting levels of the parenthesis, for me it is enough >to recognize the end of the first parenthesized group. > >Obiously, I would like a general recipe valid for more complicate >expressions: in particular I cannot assume that the first group ends >right before a mathematical operator (like '+' in this case) since >these expressions are not necessarely mathematical expressions (as the >example could wrongly suggest). In general I have expressions of the >form > >( ... contains nested expressions with parenthesis... )...other stuff > >where other stuff may contain nested parenthesis. I can assume that >there are no errors, i.e. that all the internal open parenthesis are >matched by closing parenthesis. > >Is this a problem which can be tackled with regular expressions ? > Well, they don't count, so if you want to count you have to throw in something extra. E.g., you could do this, to insert a delimiter after a closing right paren, and then split on the delimiter. Probably not wonderfully efficient, and I am just duplicating what you did, except the regex separates the chunks for me. >>> import re >>> rx = re.compile(r'([()]|[^()]*)') >>> class Addelim: ... def __init__(self): self.parens=0 ... def __call__(self, m): ... s = m.group(1) ... if s=='(': self.parens+=1 ... if self.parens==1 and s==')': ... self.parens=0 ... return s+'\x00' ... if s==')': self.parens -=1 ... return s ... >>> for e in rx.sub(Addelim(),exp).split('\x00'): print e ... (a*(b+c*(2-x))+d) +f(s1) Where exp was >>> exp '(a*(b+c*(2-x))+d)+f(s1)' Regards, Bengt Richter From gerhard.haering at gmx.de Thu Nov 14 14:51:25 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 14 Nov 2002 19:51:25 GMT Subject: Variable names on the fly? References: <3dd3f5fd$0$28311$fa0fcedb@lovejoy.zen.co.uk> Message-ID: Gon?alo Rodrigues wrote: > On Thu, 14 Nov 2002 19:13:22 -0000, "e-tones.co.uk" >>[...] Whats the proper format to concatenate (sp?) variable names. I >>used list+i, obviously this doesnt work, but what does :) > > As far as I know you cannot do this [...] There's little you cannot do in Python ;-) for i in range(3): locals()["list%i" % i] = [] ... it's actually a very bad idea. Use nested lists or a dictionary. OTOH being able to dynamically create class attributes by writing in the class object's __dict__ or by overriding __getattr__ sometimes really helps. -- Gerhard From jadestar at idiom.com Wed Nov 27 15:26:31 2002 From: jadestar at idiom.com (James T. Dennis) Date: Wed, 27 Nov 2002 20:26:31 -0000 Subject: Is it possible to write web-based GUI using Python? References: <3DE4448E.5080201@attglobal.net> Message-ID: <1038428791.467720@smirk> Ian Bicking wrote: > On Tue, 2002-11-26 at 22:05, Pierre Rouleau wrote: >> What I'd like to be able to do is implement a complete GUI-based control >> application (with buttons, slider, whatever widgets the app needs) >> accessible over the web. > If you confine yourself to HTML widgets (which does not includes > sliders, for instance), this is obviously possible -- that's what forms > are, after all. If you want widgets beyond what's available in HTML > (either more responsive/interactive, or simply widgets HTML doesn't > have, like decent file selection), then you will have to either code up > a Java applet (potentially in Jython), or write a client application. As a nitpick you might be able to implement many of these in JavaScript (Yuck!) and even in Mozilla's XUL (though that would limit you to Mozilla and newer Netscape clients *and* seems to mostly require JavaScript, anyway). From sav at ulj.menatepspb.com Tue Nov 26 15:43:20 2002 From: sav at ulj.menatepspb.com (Alexander Semenov) Date: Tue, 26 Nov 2002 23:43:20 +0300 Subject: Can't reconnect with asyncore. Message-ID: <3de3dcf4@post.ulj.menatepspb.com> Hi, Here is my code (WinXP, python22): import socket, asyncore, asynchat class strange_client(asynchat.async_chat): def __init__(self): asynchat.async_chat.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect(('192.168.32.30', 110)) self.push('USER sav\n') self.set_terminator('\r\n') self._buff = [] def collect_incoming_data(self, data): self._buff.append(data) def found_terminator(self): print self._buff self._buff = [] self.push('USER sav\n') def handle_close(self): self.close() print 'Reconnecting...' strange_client() strange_client() asyncore.loop() I'm trying to reach persistent client connection with asyncore, which can autorestore itself on errors. When I run this code I see C:\wrk\wrk>clitest.py warning: unhandled connect event ['+OK POP3 server ready ] ['+OK please send PASS command'] ... ['+OK please send PASS command'] It's ok. Now I break connection (dialup in my case) to server. ... ['+OK please send PASS command'] Reconnecting... ...and program is stuck. I have no success in waking it at all. Restoring dialup connection has no effect. Why so? How can I done this with asyncore? My program will be used on linux, maybe this problem disappered there? Alexander Semenov. From ktilton at nyc.rr.com Sat Nov 23 00:45:55 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Sat, 23 Nov 2002 05:45:55 GMT Subject: Newbie Q on searching lists Message-ID: <3DDF1673.4020203@nyc.rr.com> I see the index method on lists throws an error if the element sought is not found. I was hoping it would return None. The semantics I am coding happen to throw an error if a certain element is found in a list, so i want to code: if calculators.index[thisCalculator]: raise CircularDependency, thisCalculator Instead I (think) I have to: try: if calculators.index[thisCalculator]: raise CircularDependency, thisCalculator except ValueError: pass Not the end of the world, but more for the sake of getting to know Python: 1. Am I missing something? 2. Can I add a method to List that has the behavior I am after? 3. Should I just start a module of my favorite utilities and create there: def find( item, list): try: yada yada... 4. Other? -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From mis6 at pitt.edu Wed Nov 20 14:59:24 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 20 Nov 2002 11:59:24 -0800 Subject: how does import work ? References: <2259b0e2.0211200633.2ed7e075@posting.google.com> Message-ID: <2259b0e2.0211201159.24566af7@posting.google.com> Alex Martelli wrote in message news:... > Michele Simionato wrote: > ... > > Suppose now I import ONLY the function f2, but not f1: > > > >>>> from f1f2 import f2 > > That's basically equivalent to: > import f1f2 > f2 = f1f2.f2 > del f1f2 > except that if you already had an f1f2 identifier it's not disturbed. > > > therefore Python has imported f1 too, but is some hidden way, since > > f1 is not in the current namespace dictionary: > > Of course not, but it's in sys.modules['f1f2'] 's namespace, right > where it should be. > > > This behavior is quite confusing to me, somebody can explain what is > > happening ? > > HTH... > > > Alex Thanks, now it is clear. Michele From edream at tds.net Tue Nov 26 16:51:43 2002 From: edream at tds.net (Edward K. Ream) Date: Tue, 26 Nov 2002 21:51:43 GMT Subject: memory leaks in Tkinter References: Message-ID: Does this version of the Tk Text widget support unlimited undo? If so, text can not ever really be deleted and the widget will appear to leak. Not all "permanent" uses of memory can be considered bad. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From just at xs4all.nl Fri Nov 8 13:42:56 2002 From: just at xs4all.nl (Just) Date: Fri, 08 Nov 2002 19:42:56 +0100 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> Message-ID: In article , eddie at holyrood.ed.ac.uk (Eddie Corns) wrote: > My opinion (the short version anyway) is that because Python is a lot easier > to learn and use. It's a bit like the difference between a point and click > camera and a 'real' one - to use a 'real' camera for even a simple photo you > need to understand the whole biz. [ ... ] Nice analogy! Just From sismex01 at hebmex.com Wed Nov 13 17:45:08 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 13 Nov 2002 16:45:08 -0600 Subject: My (late) beef with Simple Generator syntax (PEP 255) Message-ID: > From: Cameron Horn [mailto:camhorn at mac.com] > Sent: Wednesday, November 13, 2002 4:38 PM > > On Wednesday, Nov 13, 2002, at 02:26PM, wrote: > > >> From: Cameron Horn [mailto:camhorn at mac.com] > >> Sent: Wednesday, November 13, 2002 4:26 PM > >> > >> On Wednesday, Nov 13, 2002, at 02:19PM, > wrote: > >> > >> >> From: Cameron Horn [mailto:camhorn at mac.com] > >> >> Sent: Wednesday, November 13, 2002 4:20 PM > >> >> > >> >> On Wednesday, Nov 13, 2002, at 02:16PM, David Eppstein > >> >> wrote: > >> >> > >> >> >On 11/13/02 2:11 PM -0800 Cameron Horn wrote: > >> >> >>> What I wonder is, why does it need to be a generator? > >> >> What's wrong with > >> >> >>> def foo(): return ( ) > >> >> >>> ? > >> >> >> > >> >> >> You're right if it's a one-time thing. However, if > I've got a > >> >> >> scaffolding like this, then it matters. > >> >> >> > >> >> >> def process_generator(function): > >> >> >> for x in function(): > >> >> >> print x > >> >> > > >> >> >How does the function foo() I defined above fail to > work in this > >> >> >scaffolding? > >> >> > >> >> In the "TypeError: iteration over non-sequence" sort of way. > >> >> > >> > > >> >An empty tuple is a sequence also; > >> > > >> >the "return ( )" thing is returning an empty tuple, > >> >not "None". You can make it clearer by using > >> >"return tuple()" rather than "return ()". > >> > >> Oops. Missed those parentheses. Then it is completely > >> useful, unless you end up using the "next" method. > >> > > > >In that case, if you reckon you're going to use .next() > >directly, then you should change 'foo' to something like > >the following: > > > >def foo(): return iter(tuple()) > > > >It's going to return a valid iterator which is going to > >try to iterate through an empty tuple, so it's going > >to raise StopIteration the first time you call .next(). > > > > > > Which is the obvious, clear and consistent way to create a > generator that doesn't do anything. Unless you're checking > types or doing any other low-level things that you probably > oughtn't. I return to my original point. And then, since > everything works and I'm just complaining about a tiny bit of > syntax, I shut up. > Interesting coincidence. I'm thinking of applying generators for a server application I'm creating, in which I'd use generators to simulate threading, like the cooperative multithreading available in Forth. It seems quite easy to just append all the generators that the application receives, kind of like tasks, into a list, and item by item, pop(0) it, do a .next(), and reappend it. The question is, what is more efficient: # Case one: enter a for loop and immediately break after # reappending to the tasks list; if the generator raises # StopIteration(), the append will never happen. gen = tasks_list.pop(0) for _ in gen: tasks_list.append(gen) break # Case two: use try-except. gen = tasks_list.pop(0) try: gen.next() tasks_list.append(gen) except StopIteration: pass Lets see what happens in a while. -gustavo From deltapigz at telocity.com Tue Nov 12 18:32:13 2002 From: deltapigz at telocity.com (Adonis) Date: Tue, 12 Nov 2002 18:32:13 -0500 Subject: Convert type() to string? References: Message-ID: <3dd18f77$1_6@nopics.sjc> Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> t = type('test') >>> t then just parse the text. not the best way but someone will respond with better code. hope this helps. Adonis "Robert Oschler" wrote in message news:s2gA9.47879$Lg2.13805658 at news2.news.adelphia.net... > I want to be able to print out the type() of a string for a "structure > walker" I'm writing. I need to be able to prepend a string of pad > characters to the type() so the following: > > print padstr + type(x) > > won't work because type() does not return a string. What's a good way to do > this? I'm using Python 2.1 + Python 2.2 (2.1 for Jython). > > thx > > > From roy at panix.com Thu Nov 14 08:08:13 2002 From: roy at panix.com (Roy Smith) Date: Thu, 14 Nov 2002 08:08:13 -0500 Subject: How to comment a block of codes in Python? References: <3dd375fd@dnews.tpgi.com.au> Message-ID: In article <3dd375fd at dnews.tpgi.com.au>, "Ben C" wrote: > try """ to start and """ to end commented section > This breaks if there are """'s inside the code block. For manually commenting something out for testing, I guess that's a pretty minor problem, but just something to be aware of. Personally, I like the idea of putting #'s in front of every line. It can be done automatically, it doesn't break no matter what's on the lines, and it makes it really obvious what's going on. From member at dbforums.com Wed Nov 13 08:35:13 2002 From: member at dbforums.com (bandekap) Date: Wed, 13 Nov 2002 13:35:13 +0000 Subject: Unicode in JSP References: <2041930.1037194073@dbforums.com> Message-ID: <2041931.1037194513@dbforums.com> Mistake in last query: My oracle database for three japanese characters it is storing data in "さ だ わ" instead of those japanese characters. Does this data in unicode format? What neccesary changes i need to do? -- Posted via http://dbforums.com From dave at pythonapocrypha.com Sun Nov 10 22:48:14 2002 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sun, 10 Nov 2002 19:48:14 -0800 (PST) Subject: PEP #99484663 In-Reply-To: Message-ID: On 10 Nov 2002, Russell Nelson wrote: > Suggested PEP: > > Treat { and } when encountered at the end of a statement like this: Ahhh.. the old "tailor the language to people who don't even like the language" approach. Doesn't it seem strange to risk alienating the people who like and support the language to appease those that don't? When I see a curly brace in Python my brain says "dictionary!" and I like it that way. Shouldn't my opinion as a happy user of Python weigh at least as much as that of someone who complains about it? :) > In this manner, people who are unable to wean themselves from silly > syntactic block structure tokens will be happy with Python, ...until they get to the next thing they don't want to wean themselves from. You don't hear of long-time Python users complaining about the indentation thing; it's a newbie/first impression issue. Not only do I like it as a feature, I see it as an open-mindedness filter: people who are willing to consider that something a little different than "normal" might be good stick around to give Python a try, others quickly move on to something more palatable without wasting too much of their own time (they would have probably been unhappy with Python anyway). -Dave From max at alcyone.com Fri Nov 29 18:50:55 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 29 Nov 2002 15:50:55 -0800 Subject: catch output of threads References: <87of88723i.fsf@flibuste.net> Message-ID: <3DE7FD5F.35EFC6DF@alcyone.com> William wrote: > Is it possible to catch the output from print of differents threads ? > In a single thread, i can change the value of sys.stdout... but with > differents thread i don't know ? > > My goal is to make a little server with multithread working on > windows without calling an external interpreter (like CGIHTTPServer > do). For my templating system EmPy -- which is not threaded -- I was forced to put together a system where a sys.stdout is replaced with a proxy object that can be "pushed and popped" by each evaluation/execution that might conceivably use sys.stdout or a print statement, so that the proxy object would direct the output to the output stream of the appropriate interpreter that was running. Unfortunately, though, this doesn't lend itself to a multithreaded environment (and is the primary reason why EmPy does not support threading), since you could easily encounter deadlocks (if, say, one thread stays in an execution loop for an indefinite period). I don't think there's any way to do what you want short of modifying the Python interpreter. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ In wildness is the preservation of the world. \__/ Henry David Thoreau Maths reference / http://www.alcyone.com/max/reference/maths/ A mathematics reference. From syver-en+usenet at online.no Sat Nov 9 11:18:48 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: 09 Nov 2002 17:18:48 +0100 Subject: Refactoring Browser (Bicycle Repairman) Message-ID: I am just so excited and impressed by the Bicycle Repairman, that I had to show an example here: Here's an instance method from a class (It's from a little Tkinter app that I made for my eldest son to sharpen up his multiplication skills) def ferdig(self): minutes, seconds = self._model.endMinutesSeconds() svarText = (u'Du har l?st %d oppgaver p? %0.0f ' 'minuter og %0.0f sekunder'% (self._model.correctAnswers(), minutes, seconds)) svarText2 = u'Det blir %0.1f riktige svar i minuttet'%((self._model.correctAnswers()/self._model.timeSpent())*60) endMsgText = u'%s\n%s'%(svarText, svarText2) self._endMsgLabel.configure(text=endMsgText) if askyesno("Ferdig!", u'Vil du spille engang til?'): self._model = GangeModel() self._endMsgLabel.configure(text = '') self.showGangestykke() else: self.quit() Now I just wanted to get a feel for how good the extractMethod refactoring in Bicycle Repairman worked, so I marked the following: svarText = (u'Du har l?st %d oppgaver p? %0.0f ' 'minuter og %0.0f sekunder'% (self._model.correctAnswers(), minutes, seconds)) svarText2 = u'Det blir %0.1f riktige svar i minuttet'%((self._model.correctAnswers()/self._model.timeSpent())*60) endMsgText = u'%s\n%s'%(svarText, svarText2) And chose ExtractMethod from my Bicycle Repairman menu in Emacs. Bicycle Repairman changes the code to: def ferdig(self): minutes, seconds = self._model.endMinutesSeconds() endMsgText = self.endMsgText(minutes, seconds) self._endMsgLabel.configure(text = endMsgText) if askyesno("Ferdig!", u'Vil du spille engang til?'): self._model = GangeModel() self._endMsgLabel.configure(text = '') self.showGangestykke() else: self.quit() and: def endMsgText(self, minutes, seconds): svarText = (u'Du har l?st %d oppgaver p? %0.0f ' 'minuter og %0.0f sekunder'% (self._model.correctAnswers(), minutes, seconds)) svarText2 = u'Det blir %0.1f riktige svar i minuttet'%((self._model.correctAnswers()/self._model.timeSpent())*60) endMsgText = u'%s\n%s'%(svarText, svarText2) return endMsgText Very neat, I know that this is the way a Refactoring Browser is supposed to work, but I can't help being impressed anyway :-) So, many thanks to the people who have worked hard to create a Python Refactoring Browser, and also making it possible to use it from different tools. -- Vennlig hilsen Syver Enstad From tundra at tundraware.com Thu Nov 14 19:00:07 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: 15 Nov 2002 00:00:07 GMT Subject: tkMessageBox: Changing Fonts, Colors, etc. Message-ID: <83d1ra.p19.ln@boundary.tundraware.com> I cannot seem to find a reference on how to change the font type, size, etc. and colors for one of the tkMessageBox critters like showinfo() or showwarning() Could some kind soul, direct me to same, please? TIA. -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From eppstein at ics.uci.edu Fri Nov 8 20:12:25 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 08 Nov 2002 17:12:25 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <9b8hqa.eo3.ln@beastie.ix.netcom.com> Message-ID: In article , Carl Banks wrote: > Python is more like Lisp than most other languages, though. It's > similar semantically. This makes little sense to me. Even the most basic data structures are different: Lisp is based around singly linked lists while Python uses vectors (with efficient random access unlike Lisp lists) and dictionaries. They are also not especially similar in programming style, although both are capable of being used with a wide variety of styles. The most important similarity I see is that in both languages, values have types but variables are untyped, but that was also true in radically different languages such as Snobol and APL; is that really enough to conclude that Python and Lisp are more like each other than anything else? -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From max at alcyone.com Mon Nov 25 16:18:29 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 25 Nov 2002 13:18:29 -0800 Subject: screen off? References: Message-ID: <3DE293A5.74B24485@alcyone.com> Adam Hupp wrote: > On Fri, 22 Nov 2002 21:49:06 +0000, Lance wrote: > > > Some of my programs generate considerable screen output. I would > > like to > > turn off the screen output to save time while developing. Is there a > > way to > > do this, and turn it back on again? > > You can do this by assigning a new file-like object to sys.stdout, > i.e. > > sys.stdout = open("/dev/null", "w") If the original poster is already running a UNIX-like system, then there's already an easier way to do this; redirect stdout to /dev/null from the shell: ./myScript.py > /dev/null As for non-UNIX systems which wouldn't have a /dev/null to open anyway, there's an easier work around; just create a file-like object that does nothing: class NullFile: def write(self, data): pass def writelines(self, lines): pass def flush(self): pass def close(self): pass and then sys.stdout = NullFile() -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Patriotism is the virtue of the vicious. \__/ Oscar Wilde WebVal / http://www.alcyone.com/pyos/webval/ URL scanner, maintainer, and validator in Python. From aleax at aleax.it Mon Nov 11 08:49:44 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 11 Nov 2002 13:49:44 GMT Subject: How to create and interactive, distributable program? References: <3dcfa0e3.921157@news.jaring.my> Message-ID: Kenneth Gomez wrote: > Hello all, > > In my course, I am asked to develop a basic finite element analysis [ snipped: some fundamental FEA specs ] > To do all of this, my questions are , can Python handle the > mathematics, e.g. does Python have a subroutine to inverse a matrix, > or find the modulus of a number,....? Or, is it like C, where I have > to write the subroutine myself? Python is a good language for numerically-intensive programming *IF* accompanied by the indispensable Numeric extension package (and possibly further add-ons to Numeric). So, basically just like in C, you won't have to code any of this fundmentals by yourself, but neither will you find them embedded in the language itself -- rather, you'll freely download and install suitable libraries. For Python and numeric maths, the choice is quite clear. Besides Numeric, I think you'll also want to get SciPy, from www.scipy.org, for many other useful tools. > Second, will I be able to create the GUI explained above within 3 > months? Yes, I think that 3 months for the GUI is a reasonable task -- if you mean for the GUI *plus* the functioning engine behind it, with just one person working on it and starting from zero knowledge of Python, I think that's quite aggressive but not entirely impossible (I'd deem it as utterly impossible with any other languages -- most powerful languages take three months just to LEARN properly). I think it might help to get the best cross-platform GUI engine around, i.e., Qt -- specifically, I'd suggest theKompany's "BlackAdder" Python IDE with PyQt, GUI-designer, etc. However, Qt and BlackAdder are commercial products, so if in addition to all other constraints you ALSO want to perform this feat with all-free tools, you'll have to use something else and save the money (e.g. about $50 for BlackAdder personal edition in its current beta state). > Third, can I make the GUI into an executable file so that I can run it > off the laptop/workstation that will be used for the presentation? It's no doubt easier to install the application in its native form (install Python, then Qt, Numeric, etc, then the app proper), but if you want it badly enough, you CAN also bundle everything up into an executable file (at least for Windows and Linux -- I don't think other platforms are currently supported). Two tools that can help are py2exe (Windows-only) and McMilla's installer (Windows and Linux). However, it IS one more task to cram into those hugely-dense three months -- I hope you don't mind working long hours...:-). > Thanking you in advance for your advise. If I were in your shoes, with an extremely aggressive schedule and a LOT of things to be done within that schedule, I'd choose the best tools (Python, Numeric, SciPy, Qt, BlackAdder), give up on ALL the non-absolutely-essential parts (the tidbit about bundling everything up into an executable file just for a presentation seems non-essential to me, for example), and try to stick to Extreme Programming principles as much as feasible (e.g., the 40-hours-per-week principle does NOT seem feasible under the given constraints and goals -- nor is pair programming going to be, if you'll be working alone). Working in short iterations and boiling deliverables down to specs (expressed as automated, executable, repeatable tests) and executable code gives you your best chance to have something usable (though not probably yet complete) within your deadline. Alex From gerhard.haering at opus-gmbh.net Tue Nov 5 05:50:48 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 5 Nov 2002 10:50:48 GMT Subject: How does Python handle probing to see if a file already exists? References: Message-ID: In article , Christopher R. Culver wrote: > Hello all, > > I've just begun learning Python after already getting pretty proficient in > C. However, I'm having a problem with a simple copying program. Ideally, > the program would check to see if the destination already exists and > prompt the user. In this this would be as easy as saying: > > probe_destination = fopen(/usr/bin/foo, 'r') > if (probe_destination) > { > some code here; > } > > However, translating that directly into Python doesn't work because if > Python can't find a file to open, it doesn't just return 0, it gives an > error and exits. Yes, Python does have exception handling, which is a very useful thing. You just have to decide what to do in the error case, for example: try: f = open("/usr/bin/foo") # some code here except IOError, reason: print "couldn't open file, because of", reason > How can I write this functionality in Python so that it > returns 0 and continues, or does Python have a totally different way of > handling this problem than C? In Python, you catch the exception and decide what to do with it (if anything). If, for example, you just want to ignore the IOError (but not other errors), you'd simply do: try: f = open("/usr/bin/foo") # some code here except IOError: pass It's also possible to check if a file exists before trying to open it: if os.path.exists("/usr/bin/foo"): # more code here But the existence of the file does not guarantee you have the necessary permissions to actually open it. It could also be deleted in the millisecond or so between your check and trying to open it. Or some other problem could occur. That's why using exceptions and catching the IOError is the only practical way if you want to produce robust code. -- Gerhard H?ring OPUS GmbH M?nchen Tel.: +49 89 - 889 49 7 - 32 http://www.opus-gmbh.net/ From ahmebah at hotmail.com Sat Nov 30 01:37:00 2002 From: ahmebah at hotmail.com (Sean McSomething) Date: Fri, 29 Nov 2002 22:37:00 -0800 Subject: if : References: Message-ID: "Andr? N?ss" wrote in message news:arqm0r$s6f$1 at maud.ifi.uio.no... > When I started learning Python one of the things that surprised me was that > you couldn't do assignments inside the if clause, e.g.: > > if myvar = someFunction(): > > My question is, what is the rationale for this? Is it a technical issue? Or > purely a matter of language design? I'm curious because I'm interested in > the design og programming languages, not because I want this behavior > changed in Pyton :) To start with, Java, PHP, Perl and the like do it because C did it. C did it because it was intended to be a 'portable assembly language', as such sometimes one must look back at how things work in assembly to understand it's behavior. My understanding of assembly is limited to a poor grasp of x86 and some brief looks at other systems, so bear with me. Every operation inside the CPU sets a status flag. A status flag is like a 1-bit register that reflects the result of the last operation; the x86 has flags (EFLAGS) for overflow, zero, negative, parity & cary-out. All operations set these flags, arithmetic, logical and assignment... With this in mind, lets look at how two different ways of doing the assignment would work. First off: myVar = someFunc(); if myVar doStuff() would call someFunc() and then pull the result off the stack, placing it into myVar. It would, in another step, get the result codes for myVar (most likely by comparing with 0; essentially it's a no-op who'se only purpose is to run myVar through the CPU to set status flags). Then there would be a jump (like a goto) that jumped based on the values of a status register. Using an assignment in the if statement, such as : if myVar = someFunc() doStuff would, again, call someFunc() and copy the result from the stack into myVar. At this point, the result code for that value (specifically the zero/non-zero flag) would be set and the next instruction could be a jump checking the results of those flags, and away we go. So, we have a minor optimization, that cuts out a single instruction. Back when C was designed, dropping a single instruction Really Mattered. Today, this behavior has no place in a high-level (taking high-level to mean "insulating the programmer from the fact that he is in fact working on a physical computing device) programming language, so it was not put into the Python language design; consequentially, the Python virtual machine wasn't designed to support this behavior meaning that the implemention of this behavior, originally used as an optimization, would be no more efficient than separate assignment & comparison statements and would likely be even less efficient. Of course, this could all be complete & utter bullshit, but it's a reasonable extrapolation from what facts I have & my understanding of things. From jdhunter at ace.bsd.uchicago.edu Tue Nov 19 03:31:31 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 19 Nov 2002 02:31:31 -0600 Subject: quick question In-Reply-To: ("Cousin Stanley"'s message of "Tue, 19 Nov 2002 00:03:14 -0700") References: <20021116051220.01520.00000047@mb-bk.aol.com> Message-ID: >>>>> "Cousin" == Cousin Stanley writes: Cousin> John ... I tried your suggestions of using the function Cousin> Did I implement your suggestions correctly ??? For Cousin> convenience in adding the mapped test to what I already Cousin> had, I used a global dictionary defintion ... Cousin> Would that have any significant affects on performace ??? Your implementation was fine. The answer (as your tests show) is that the overhead imposed by the function call is more than that of the loop. So my guess was wrong, which is why they say test test test rather than talk talk talk. I did one thing to try and improve the speed, but it didn't help much. global lookup of the global dictionary is slow in the counting function, so I derived a new class from dict called counting_dict class counting_dict(dict): def __call__(self, key): key = key.strip() self[ key ] = self.get( key , 0 ) + 1 def get_total(self): return reduce(int.__add__, self.values()) which you can use like votes = file('votes.dat').xreadlines() favorites = counting_dict() map(favorites, votes) total = favorites.get_total() It's nice, clean code, but it's also considerably slower than the original, un-psyco-d, loop version Elapsed Time : 0.87 Seconds ... loop (no psyco) Elapsed Time : 1.31 Seconds ... custom dict (no psyco) Cousin> I wasn't sure whether or not the Psyco binding was Cousin> necessary for the third pass through the script when the Cousin> mapped function is called ??? Well, in either case the map version loses to the normal version, both psyco'd or both not. But I would split the test cases into separate funcs, because once you psyco bind the function, you can't un-psyco it for further tests (AFAIK) Cousin> Since the printed output lines come out double-spaced Cousin> in the mapped function version, where's the most Cousin> convenient place to stick the strip() function without Cousin> interfering ??? See the __call__ func above. Note also in your code that else : if func_Type == 2 : can be written elif func_Type == 2 : Cheers, John Hunter From max at alcyone.com Mon Nov 18 20:03:55 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 18 Nov 2002 17:03:55 -0800 Subject: Hmm... An idea: if a,b==c,d: References: <3DD974C6.CD626D0A@alcyone.com> Message-ID: <3DD98DFB.FCEEF9D3@alcyone.com> Ben Wolfson wrote: > I was under the impression that a comparison of two tuples of equal > length > amounts to a pairwise comparison of the elements anyway. It does; I was only using == as an example, the more general case applies to any comparison operator. > or >= would have been a better choice. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ All the people in his neighborhood turn around and get mad and sing \__/ Public Enemy Erik Max Francis' bookmarks / http://www.alcyone.com/max/links/ A highly categorized list of Web links. From jdhunter at ace.bsd.uchicago.edu Mon Nov 18 19:58:35 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 18 Nov 2002 18:58:35 -0600 Subject: multi-quoted strings for HERE documents In-Reply-To: ("Michael P. Soulier"'s message of "19 Nov 2002 00:40:45 GMT") References: Message-ID: >>>>> "Michael" == Michael P Soulier writes: Michael> But then the block isn't really lined-up the same as Michael> the output will look like. It's a minor thing, I know, Michael> but it bugs me. Michael> Does anyone have a better way of doing this? How about s = """
cell contents
""" print s.lstrip() Or in python2.3 (untested) print s.lstrip('\n') http://www.python.org/dev/doc/devel/whatsnew/node12.html#SECTION0001210000000000000000 John Hunter From anton at vredegoor.doge.nl Tue Nov 5 09:23:07 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 05 Nov 2002 15:23:07 +0100 Subject: bug report w\o registering References: Message-ID: On Tue, 5 Nov 2002 15:49:20 +1100, "Delaney, Timothy" wrote: >> From: anton at vredegoor.doge.nl [mailto:anton at vredegoor.doge.nl] >> >> Here's a bug report. I don't want to register at SourceForge now >> (browser settings etc.). Sorry for the inconvenience. > >If you do not submit to sourceforge, the bug report *will* be lost. > >In any case, this is not a bug - it is documented behaviour. The order of >the parameters and return values of os.popen2 and popen2.popen2 are >different. Sorry about that! One small nit though: (Doc\lib\os-newstreams.html) This functionality is also available in the popen2 module using functions of the same names, but the return values of those functions have a different order. This tripped me because it says nothing here about parameters. Regards, Anton. From netizen.mail at attbi.com Fri Nov 8 17:39:34 2002 From: netizen.mail at attbi.com (netizen) Date: Fri, 08 Nov 2002 22:39:34 GMT Subject: java bindings Message-ID: Is there a binding for java in python? I dont mean using jython. I want to use some of the thinks the java has like jdbc, ldap. I know they exist in python but i would like to try this method instead. Thanks From Simon.Wittber at perth.maptek.com.au Tue Nov 12 02:44:28 2002 From: Simon.Wittber at perth.maptek.com.au (Simon Wittber (Maptek)) Date: Tue, 12 Nov 2002 15:44:28 +0800 Subject: Optimisation problem Message-ID: <10F0E58C0018054484E329DC494C4D7F01ADCE@mexper1.maptek.net.au> I have created a quaternion class which I am using for rotations in OpenGL. Usage goes something like this: q = Quaternion(zRot, 0.0, 0.0, 1.0) glMultMatrixf(q.matrix) Does anyone have any idea how I can optimise this code? It is going to be used in a very tight rendering loop. I would prefer to keep all the code in Python, and avoid writing any external modules. class Quaternion: def __init__(self, degree, x, y, z): self.matrix = range(16) angle = (degree / 180.0) * 3.1415926535897932384626433832795 result = math.sin(angle / 2.0) self.w = math.cos(angle / 2.0) self.x = x * result self.y = y * result self.z = z * result self.__createMatrix() def __createMatrix(self): self.matrix[0] = 1.0 - 2.0 * ( self.y * self.y + self.z * self.z ) self.matrix[1] = 2.0 * ( self.x * self.y - self.w * self.z ) self.matrix[2] = 2.0 * ( self.x * self.z + self.w * self.y ) self.matrix[3] = 0.0 self.matrix[4] = 2.0 * ( self.x * self.y + self.w * self.z ) self.matrix[5] = 1.0 - 2.0 * ( self.x * self.x + self.z * self.z ) self.matrix[6] = 2.0 * ( self.y * self.z - self.w * self.x ) self.matrix[7] = 0.0 self.matrix[8] = 2.0 * ( self.x * self.z - self.w * self.y ) self.matrix[9] = 2.0 * ( self.y * self.z + self.w * self.x ) self.matrix[10] = 1.0 - 2.0 * ( self.x * self.x + self.y * self.y ) self.matrix[11] = 0.0 self.matrix[12] = 0.0 self.matrix[13] = 0.0 self.matrix[14] = 0.0 self.matrix[15] = 1.0 -- simon . wittber @ perth . maptek . com .au -- From Simon.Wittber at perth.maptek.com.au Thu Nov 14 22:02:48 2002 From: Simon.Wittber at perth.maptek.com.au (Simon Wittber (Maptek)) Date: Fri, 15 Nov 2002 11:02:48 +0800 Subject: A really bad idea. Message-ID: <10F0E58C0018054484E329DC494C4D7F01BC97@mexper1.maptek.net.au> Simon> I doubt that the C / C++ reference includes examples on slicing Simon> lists and using dictionaries, whereas the Python reference would Simon> *have* to, as these constructs are integral to the language. >You might be surprised what you would find in the C++ standard library... Yeah there's plenty of nice things in the STL, but it's a library, not part of the language. From stuart.191 at ntlworld.com Sat Nov 2 19:10:05 2002 From: stuart.191 at ntlworld.com (Stuart MacGregor) Date: Sun, 03 Nov 2002 00:10:05 +0000 Subject: Tkinter in RH8.0 References: <3DC44642.3050501@grserv.med.jhmi.edu> Message-ID: RajGopal Srinivasan wrote: > I think you will also need tkinter-2.2.1-17.rpm > Yes, also tkinter itself had an rpm which was not loaded. All on disc 3 and not loaded by any option on the RH package thing. It all works now - thanks to all for your help. RH have not loaded gnorpm or kpackage this time - makes rpm browsing more work.... From mwh at python.net Tue Nov 5 10:14:46 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 5 Nov 2002 15:14:46 GMT Subject: Ruby and Python (was Re: Why is Python a good first scripting language?) References: Message-ID: "Patrick Ellis" writes: > Note that removing the primes = None line results in settling around 8.9 > instead of 8.6. My guess is this has to do with allocating and deallocating > millions of integer objects to put in the primes list. And that WinME's memory management appears to suck harder than vacuum. I haven't tried this, but I bet you wouldn't see that on almost any other operating system (except possible classic macos). > The 0.3 sec difference is how long it takes to deallocate the > returned list. Python 2.3 does memory more efficiently and is why it > runs faster. Also, it does let Win32's malloc get near enough to the action to get confused. > I came up with a new version that uses the Numeric package. It is > algorithmically identical, just with a few implementation changes. > > def sieve(n): > if n < 2: > return [] > limit = (int(math.sqrt(n)) / 2) + 1 > primes = Numeric.arrayrange(1, n+1, 2) > n = len(primes) > for p in primes[1:limit]: > if p: > # note that p*p is odd, so no need to subtract 1 > # before shifting right -- same thing in the end > primes[(p*p)>>1::p] = 0 > return list(Numeric.nonzero(primes)) > > The same test as above results in: > > Primes took 1.870 seconds > Primes took 1.810 seconds > Primes took 1.760 seconds > Primes took 1.810 seconds > Primes took 1.870 seconds > Primes took 1.750 seconds > Primes took 1.820 seconds > Primes took 1.810 seconds > Primes took 1.810 seconds > Primes took 1.810 seconds Impressive! > Because it uses arrays that store the integers directly, instead of many > tiny integer objects, it doesn't have the memory management overhead and > resulting increasing runtime. The biggest speed increase is replacing the > inner loop with an assignment statement to a slice (which doesn't work with > lists). It does in Python 2.3 though, and attempting to exploit that found a bug in the extended slice support (that I wrote, oops). Anyway, it was fairly easy to fix, so you've helped Python development with this post! Bet you didn't expect that. Helps the speed a bit, but not enormously (20% or so). Cheers, M. -- Just point your web browser at http://www.python.org/search/ and look for "program", "doesn't", "work", or "my". Whenever you find someone else whose program didn't work, don't do what they did. Repeat as needed. -- Tim Peters, on python-help, 16 Jun 1998 From gerhard.haering at gmx.de Fri Nov 1 03:32:12 2002 From: gerhard.haering at gmx.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Fri, 1 Nov 2002 09:32:12 +0100 Subject: how to use smtp starttls() encryption? In-Reply-To: <8f41cfd.0210312325.7ab7969f@posting.google.com> References: <8f41cfd.0210101719.ad47c7@posting.google.com> <8f41cfd.0210120805.6ced204a@posting.google.com> <8f41cfd.0210162236.3e5c970a@posting.google.com> <8f41cfd.0210211030.33365530@posting.google.com> <8f41cfd.0210312325.7ab7969f@posting.google.com> Message-ID: <20021101083211.GA364@gargamel.ghaering.test> * Xu, C.S. [2002-10-31 23:25 -0800]: > I did download the openssl-0.9.6g and compiled/installed, and I found > mandrake 9.0 already use openssl-0.9.6g; but the python 2.2.2 > I downloaded, after compiling still shows it used 0.9.5 ssl. > Exact same error when I tried to use python 2.2.2 to send out > emails. > > Now I've setup an temp. email account for you guys to help me > out, see whether you can use this account send emails first: [...] Seems to work: gerhard at gargamel:~$ python Python 2.2.2 (#1, Oct 18 2002, 03:24:30) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> import smtplib >>> s = smtplib.SMTP("mail.offleasecomputer.net") >>> s.starttls() (220, 'OpenSSL/0.9.5beta go ahead') >>> s.sendmail("gerhard.haering at gmx.de", ["testpythonsmtp at offleasecomputer.net" ], "hello, does it work?") {} >>> s.quit() -- Gerhard From jkraska at san.rr.com Tue Nov 19 20:44:55 2002 From: jkraska at san.rr.com (Courageous) Date: Wed, 20 Nov 2002 01:44:55 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DDA7126.6090308@nyc.rr.com> Message-ID: <04qltukm3dt8m5v2af4aist7tl2s9pihja@4ax.com> >BDFLs are great, but (somehow) Lispers got together and managed to carve >out Common Lisp and an ANSI spec for it. That's our BDFL. By the time a language reaches the standards committee, it is already dead. :) C// From mwh at python.net Thu Nov 28 05:40:30 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 28 Nov 2002 10:40:30 GMT Subject: status of Jython? References: <4cce07d5.0211271320.18d76ebc@posting.google.com> Message-ID: <7h3el96ouay.fsf@pc150.maths.bris.ac.uk> animeshk at yahoo.com (animeshk) writes: > I noticed on the Jython site that the last version of Jython is from > December 2001. I don't use it, but I believe that version works well. So the lack of updates shouldn't be taken as too bad a sign in itself. > What version of CPython is this "equivalent to" (if > that makes any sense)? 2.1? Yes. > Is there a new version available anywhere? Thanks! I think you can get development versions from CVS somewhere. Don't know what you'll find there, though. Cheers, M. -- Gullible editorial staff continues to post links to any and all articles that vaguely criticize Linux in any way. -- Reason #4 for quitting slashdot today, from http://www.cs.washington.edu/homes/klee/misc/slashdot.html From ktilton at nyc.rr.com Thu Nov 21 17:29:06 2002 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Thu, 21 Nov 2002 22:29:06 GMT Subject: To GC or not to GC? References: <3DDD4751.9050807@nyc.rr.com> Message-ID: <3DDD5E90.8070500@nyc.rr.com> Martin v. Loewis wrote: > Kenny Tilton writes: > > >>1. Is that doc up to date? I see Mar 2002, not too shabby. > > > Yes. > > >>2. Well, I should almost wait before asking further, but if you'll >>forgive a little lookahead, that "supplements reference counting" >>scares me. Is ref counting history or not? mind you, i understand >>there is a lot of code out there taht must be supported, but for new >>code...? > > > What do you mean, "for new code"? The reference counting is still > done, for all code. There is no reasonable way to disable it for some > code but leave it active for other code. Sorry, I looked at Python years ago and thought I saw /manual/ ref counting, but maybe that was just the stuff done by C code (which I understand is ineluctable). -- kenny tilton clinisys, inc --------------------------------------------------------------- ""Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it."" Elwood P. Dowd From anton at vredegoor.doge.nl Fri Nov 8 12:58:57 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 08 Nov 2002 18:58:57 +0100 Subject: Question about drawing simple graph in Python? References: Message-ID: On Thu, 7 Nov 2002 20:37:43 -0800 (PST), Mindy wrote: >I have two lists, say: >list1 = ['s1','s2','s1','s3'...] >list2 = ['t1','t2','t3','t3'...] > >I want to draw a simple graph, with 's1' points to >'t1', which means drawing one line between 's1' and >'s2' and an arrow pointed to 't1'. (for i in >range(len(list1), there's an edge between list1[i] and >list2[i]). So how to draw this graph in Python? I Have a look at: http://home.hccnet.nl/a.vredegoor/cartesian/cartesian.py It's a kind of virtual "millimeter" paper, it can be used to draw points, line pieces and edges between points. If the "withaxes" and "withgrid" arguments are not set to "yes" it produces the kind of output as described above. It's not a finished product yet, maybe it's going to end up as a function plotter, or maybe just as something to impress mathematicians with, I don't know yet. Since it's unfinished there are no docs, this will have to wait until I'll release it properly. However its possible to look at it already and it might give some idea's. Regards, Anton. From tjones at tolisgroup.com Mon Nov 4 12:28:13 2002 From: tjones at tolisgroup.com (Tim Jones) Date: Mon, 04 Nov 2002 10:28:13 -0700 Subject: Successfully Compiling 2.2.2 w/Tkinter under OS X References: Message-ID: <3DC6AE2D.5000703@tolisgroup.com> Brian Lenihan wrote: > Tim Jones wrote in message news:... > >>Actually, it's AquaTK with tcl/tk 8.4.1 in Aqua mode (tcl/tk apps from >>my Solaris and Linux systems work okay with the built version). >>macpython-sig answers were to use macpython. Unfortunately, this only >>provide Tkinter support under Classic, not OS X. >> >>Queries to other Mac and OS X oriented lists have resulted in silence. >>I'm sure that someone has gotten Python and Tkinter working under Aqua >>on OS X. > > > You have a couple choices: > > 1) Use 2.3a0 from CVS. It works with AquaTk as-is. > 2) Cut and paste the relevant portion of setup.py from 2.3.a0 into > the setup.py of 2.2.2. The part you need is in detect_tkinter_darwin() > > 8.4.1 seems to have fixed most of the obvious OS X problems. Thanks for this. I had just begun digging around in the setup.py script to get the libs path configured, but the 2.3 changes saved me from a gigantic headache. --------- Tim Jones tjones at tolisgroup.com From erno-news at erno.iki.fi Mon Nov 25 18:24:50 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 26 Nov 2002 01:24:50 +0200 Subject: sockets and encryption References: <6pintugofjalm0sbg1u2g4q91bdonmbupk@4ax.com> <8hi2uuguh0l0jlmrao1fjshle68op1kt4s@4ax.com> Message-ID: In article <8hi2uuguh0l0jlmrao1fjshle68op1kt4s at 4ax.com>, Paul Nilsson writes: | Doesn't ssl involve getting a certificate? in addition to the homebrew ca/selfsigned cert solution offered by another poster, ssl also has the option of not using any certificates at all (at least tls does, quick look makes me thing it was also in sslv3). this is called "anonymous" mode. it is simpler and safer if you would ignore the server certificate in any case. eg in openssl you can use these modes by using ciphersuites that have names beginning with "ADH-". (aside: this would be good for smtp opportunistic encryption w/starttls, although atleast sendmail out of the box seems to be configured to refuse anonymous connections for some reason). but as with the self-signed certificates, this can leave you open to man in the middle attacks. you can solve this by doing your own authentication inside the ssl connection. -- erno From news at agapow.net Mon Nov 4 14:44:07 2002 From: news at agapow.net (Paul-Michael Agapow) Date: Mon, 4 Nov 2002 19:44:07 +0000 Subject: [mac] Synopsis on OS X Message-ID: <1fl4r1l.yrjemn6armnyN%news@agapow.net> I've just have a few go at installing Synopsis on Mac OS X and neither the last release or the CVS version want to install, despite several permutations of autoconf, ./configure, make, at one point even complaining of the lack of a valid python installation! I've probably missed something obvious, but has anyone else had any success? (Relevant details: Python 2.2, MacOS 10.2) -- Paul-Michael Agapow (news at agapow.net) From clspence at one.net Mon Nov 4 19:05:19 2002 From: clspence at one.net (Chris Spencer) Date: 4 Nov 2002 18:05:19 -0600 Subject: help() function Message-ID: <0h2esukvqtolp17lt0hdg72ua9t038k18v@4ax.com> The documentation makes it clear that the help() function is only used in interactive mode. However, I see it as a really neato-way of generating standalone .txt files from docstrings in modules. However, as it currently stands, it looks like help() can ONLY be used in interactive mode, which means I can't capture the output to a file. Is there any way to get the same docstring formatting that help() uses, but be able to capture it to a variable or a file handle? Inquiring minds want to know. Chris. From mertz at gnosis.cx Wed Nov 27 18:07:42 2002 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Wed, 27 Nov 2002 18:07:42 -0500 Subject: Python Tutorial Was: Guido's regrets: filter and map References: <3de39ce9$0$22220$a1866201@newsreader.visi.com> <3DE44D27.3030904@something.invalid> <6GH59kKkXIpD092yn@gnosis.cx> <3de4953d$0$71699$edfadb0f@dread11.news.tele.dk> Message-ID: <+AV59kKkXEkQ092yn@gnosis.cx> "Anders J. Munch" wrote previously: |> reduce = lambda func, seq, init=None:\ |> [(l.append(func(l[i],seq[i])),l[-1]) |> for l in [[init or seq[0]]] |> for i in range(len(seq))][-1][1] | |Needs more "improvement" ;-) |>>> reduce(operator.add, [1,2,3]) |6 |>>> lulu_reduce(operator.add, [1,2,3]) |7 Yep. I got the stuff with optional 'init' wrong. Here's a version I am more confident about: reduce_ = lambda func, seq, init=None:\ [(l.append(func(l[-1],e)),l[-1]) for l in [init is None and seq[:1] or [init]] for e in seq[init is None:]][-1][1] Bengt Richter proposed a slightly longer version, but it required an external 'id' variable. I like mine better, especially now that I got rid of the 'i' numeric indexing, and just iterate directly over a slice of 'seq'. >>> from sick import reduce_ >>> from operator import add >>> reduce(add, range(5)), reduce_(add, range(5)) (10, 10) >>> reduce(add, range(1,5)), reduce_(add, range(1,5)) (10, 10) >>> reduce(add, range(5), 0), reduce_(add, range(5), 0) (10, 10) >>> reduce(add, range(1,5), 0), reduce_(add, range(1,5), 0) (10, 10) >>> reduce(add, range(5), 10), reduce_(add, range(5), 10) (20, 20) >>> reduce(add, range(1,5), 10), reduce_(add, range(1,5), 10) (20, 20) Yours, Lulu... -- mertz@ _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i gnosis _/_/ Postmodern Enterprises _/_/ s r .cx _/_/ MAKERS OF CHAOS.... _/_/ i u _/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/ g s From grante at visi.com Sat Nov 9 20:17:22 2002 From: grante at visi.com (Grant Edwards) Date: 10 Nov 2002 01:17:22 GMT Subject: How to execute a command line in a Python program? References: Message-ID: In article , Mindy wrote: > Hey, in my python program, I want to call another > program or command, say, emacs filename&, os.system("emacs filename&") -- Grant Edwards grante Yow! This is PLEASANT! at visi.com From max at alcyone.com Sun Nov 10 02:10:18 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 09 Nov 2002 23:10:18 -0800 Subject: PEP #99484663 References: Message-ID: <3DCE065A.D770FADF@alcyone.com> Russell Nelson wrote: > In this manner, people who are unable to wean themselves from silly > syntactic block structure tokens will be happy with Python, rather > than continually whinging about how horrible it is that indentation is > meaningful to the program. Indentation in Python is done differently than those other languages. If someone's migrating from one of them, they should learn to use the language they're using, not try to make the language they're using more like what they're used to. This is the some kind of (in my opinion obnoxious) approach that leads Pascal programs to ease into C with the likes of #define begin { #define end } Program in the language you're using. The proper answer to "How do I make language X (which I'm learning) more like language Y (which I'm used to)?" is "Learn language X separately from language Y." -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ You win the victory when you yield to friends. \__/ Sophocles Maths reference / http://www.alcyone.com/max/reference/maths/ A mathematics reference. From hungjunglu at yahoo.com Wed Nov 20 14:19:03 2002 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 20 Nov 2002 11:19:03 -0800 Subject: Python as first language (Re: static variables?) References: <3DDAFA97.92B70465@alcyone.com> <3DDB3373.2578CEC0@alcyone.com> Message-ID: <8ef9bea6.0211201119.2f846d0c@posting.google.com> On Tuesday 19 November 2002 11:37 am, Michele Simionato wrote in comp.lang.python: > A simple trick to simulate static variables by passing an optional > mutable object is the following: > > def f(x,i=[0]): # i[0] is the "static" variable > i[0]+=1 > return x+i[0] > > print f(0),f(0),f(0) #--> 1,2,3 Erik Max Francis wrote in message news:<3DDB3373.2578CEC0 at alcyone.com>... > Oh, of course; there's really no question why this is the case in the > current implementation. My point is that there is no real a priori > reason why mutable default arguments couldn't do the equivalent of > > def f(x=None): > if x is None: > x = SomethingMutable > ... > because it's the easiest obvious implementation -- but there's no reason > in and of itself that it _must_ be done that way. Sorry for digressing, but this reminds me of an old debate on whether Python is suitable as the first language to teach. Well, the thing is that Python works with "name binding". And the concepts of name spaces, name binding, objects, mutability, etc. are just a bit non-obvious. Once a person understands these things, or if a person knows about pointers, hashmaps and memory structure, everything becomes clear. But for someone not familiar with either of these sets of concepts, Python can be hard to explain. After many years in the Python world and having seen so many debates, I still have to say that Python is not good as the first programming language to teach. >From the perspective of someone who is in the working world, I'd like to see Python being taught in colleges/universities, but not as the first language. Rather, I'd imagine some sort of Python workshop course, where students are assigned different topics, and then do some presentations to the class. Python is valuable as a door opener to many fields in modern software development. But I have my reservations about its suitability as the first language to learn. Maybe it's just me, but I have been horrified by programmers writing a few lines of code, without realizing their few lines of code can actually have severe impact on the RAM or the harddrive. I still feel more comfortable if the new generation of programmers starts with a language closer to the machine level, where one can kind of "feel" the bits and bytes. Just my 2 cents. :) Hung Jung From sismex01 at hebmex.com Wed Nov 13 17:26:53 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 13 Nov 2002 16:26:53 -0600 Subject: My (late) beef with Simple Generator syntax (PEP 255) Message-ID: > From: Cameron Horn [mailto:camhorn at mac.com] > Sent: Wednesday, November 13, 2002 4:26 PM > > On Wednesday, Nov 13, 2002, at 02:19PM, wrote: > > >> From: Cameron Horn [mailto:camhorn at mac.com] > >> Sent: Wednesday, November 13, 2002 4:20 PM > >> > >> On Wednesday, Nov 13, 2002, at 02:16PM, David Eppstein > >> wrote: > >> > >> >On 11/13/02 2:11 PM -0800 Cameron Horn wrote: > >> >>> What I wonder is, why does it need to be a generator? > >> What's wrong with > >> >>> def foo(): return ( ) > >> >>> ? > >> >> > >> >> You're right if it's a one-time thing. However, if I've got a > >> >> scaffolding like this, then it matters. > >> >> > >> >> def process_generator(function): > >> >> for x in function(): > >> >> print x > >> > > >> >How does the function foo() I defined above fail to work in this > >> >scaffolding? > >> > >> In the "TypeError: iteration over non-sequence" sort of way. > >> > > > >An empty tuple is a sequence also; > > > >the "return ( )" thing is returning an empty tuple, > >not "None". You can make it clearer by using > >"return tuple()" rather than "return ()". > > Oops. Missed those parentheses. Then it is completely > useful, unless you end up using the "next" method. > In that case, if you reckon you're going to use .next() directly, then you should change 'foo' to something like the following: def foo(): return iter(tuple()) It's going to return a valid iterator which is going to try to iterate through an empty tuple, so it's going to raise StopIteration the first time you call .next(). HTH -gustavo From aleax at aleax.it Thu Nov 21 09:21:13 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 21 Nov 2002 14:21:13 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: Message-ID: Paul Foley wrote: > On Thu, 21 Nov 2002 10:36:24 +0800, Maptek wrote: > >> Even if Python and Ruby have or will have the _capabilities_ that Lisp >> has, (Python (will (never (be (lisp))))). > > Then it'll never have the _capabilities_ that Lisp has; because the > syntax is the major source of those _capabilities_ that distinguish > Lisp from lesser languages. It seems to me that Dylan is a creditable attempt to deny this assertion -- Dylan has no lisp-oid syntax, yet Dylan's capabilities do appear to be quite similar to Lisp's at least at the level of approximation that "major source" would seem to entail. Alex From see_reply_address at something.invalid Sun Nov 17 21:49:10 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Mon, 18 Nov 2002 15:49:10 +1300 Subject: pythonic way to optimize access to imported value? References: Message-ID: <3DD85526.6020606@something.invalid> Bengt Richter wrote: > I assumed that it is possible to release all references to an imported module, so that > the garbage collector can eliminate it from memory That won't happen -- the module remains in the global list of modules maintained by the interpreter, even if all other references to it go away. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From donn at u.washington.edu Tue Nov 26 13:03:10 2002 From: donn at u.washington.edu (Donn Cave) Date: 26 Nov 2002 18:03:10 GMT Subject: if : References: Message-ID: Quoth Carl Banks : | Duncan Booth wrote: |> If you have more than one or two patterns, then you should really be |> thinking about a loop rather than a long list of if statements: |> |> PATTERNS = [ |> (regex1, action1), |> (regex2, action2), |> # ... |> ] |> |> for regex, action in PATTERNS: |> match = regex.match(string) |> if match: |> action(match) |> break |> |> I don't see any need for assignment in an 'if' here. | | Other people often clamor for assignment if here, because the way you | did is an unnatural and circumlocative way to do something most | people, myself included, want to do as a sequential piece of code. I think I can see that. Not that there isn't any place for table driven procedures, but it isn't ideal for everything. I wouldn't go so far as to say it makes sense to therefore give assignments a value - don't like that idea at all - but ironically it seems to me that the main argument for it stems from a weakness in Python that isn't shared by languages like C that actually have this feature. If instead of Python we were looking at a language that were more specifically aimed at text analysis and a little less scrupulously explicit, I could imagine the results of a match turning up in magic state variables, like if (line ~ /^\(.*\): \(.*\)$/) { tag = $1 val = $2 } ... In C, everything is naturally explicit, but the function value per se is often just a boolean status and the data is returned by other means. if (regexp(line, "/^\(.*\): \(.*\)$/", &rv)) { tag = rv.group[0]; val = rv.group[1]; } Of course it's part of the attraction that Python relieves us of pointers and magic state variables, but in this matter it's kind of unfortunate that the function value is the function return, so to speak. Status has to be communicated through special data values like None, or like the negative return of string.find(). That can't be helped, but where reaches a sufficient level of annoyance, seems to me the general outlines of the OOP solution are fairly obvious - if rv.match(line, "/^\(.*\): \(.*\)$/"): tag = rv.group[1] val = rv.group[2] In other words, an object that stores the result of a computation and returns its status (and maybe stores that, too, for its __nonzero__.) Donn Cave, donn at u.washington.edu From mhammond at skippinet.com.au Wed Nov 27 17:29:00 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Wed, 27 Nov 2002 22:29:00 GMT Subject: Passing COM IDispatch from C to PythonCOM In-Reply-To: References: Message-ID: Jon Redgrave wrote: > I have a C program that has an IDispatch pointer to a COM object. > I want to run an embedded python script that uses this IDispatch pointer > (using Mark Hammond's excellent win32all), but do not know how to pass it to > the script. > > PythonCOM appears to wrap IDispatch's in PyIDispatch object, How do I wrap > it, or can I somehow pass it another way (as an int??) and wrap it in > Python? You need pass the object to: PYCOM_EXPORT PyObject *PyCom_PyObjectFromIUnknown(IUnknown *punk, REFIID riid, BOOL bAddRef = FALSE); defined in pythoncom.h Mark. From martin at v.loewis.de Fri Nov 29 16:05:25 2002 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 29 Nov 2002 22:05:25 +0100 Subject: catch output of threads References: <87of88723i.fsf@flibuste.net> <87el946qjl.fsf@flibuste.net> Message-ID: William writes: > It's why i cannot use this method... I specialy want to catch the output > to don't mix the ouput from all the threads. > > Is there a way to redefine print ? Yes, but you need to modify the interpreter source code. There is no way in pure Python. Regards, Martin From gerhard.haering at gmx.de Wed Nov 6 04:19:39 2002 From: gerhard.haering at gmx.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Wed, 6 Nov 2002 10:19:39 +0100 Subject: how to use smtp starttls() encryption? In-Reply-To: <8f41cfd.0211051623.1d024e29@posting.google.com> References: <8f41cfd.0211051623.1d024e29@posting.google.com> Message-ID: <20021106091938.GB390@gargamel.ghaering.test> * Xu, C.S. [2002-11-05 16:23 -0800]: > Gerhard, > > > 'Sending out' is configured differently than receiving mail. Note that > > in my example, I sent mail to your domain, using your smtp server, > > which is thus already the 'final destination'. > > > > No relaying involved here. The main point of SMTP auth is to prevent > > unauthorized relaying, and therefore you require it only for mail to > > domains other than yours. > > > > I did notice that, so I tried > s.sendmail('testpythonsmtp at offleasecomputer.net', > 'somebody at hotmail.com', 'test') > It also works. This did include relaying, right? Yes. > My question is, what if other people run the same script on their computer, > the people don't know the password to my email account. Can they still send > out emails? Looks possible, because the script didn't send out password at > all. Depends on your mail server configuration. See below for mine. > Then what's the point to use TLS to prevent spamming? That's probably not the main point. You could read the RFC for a rationale, I suppose. Though you could get authorization in using starttls if you used client certificates, that's probably not the most common scenario. I believe people use SMTP AUTH (provided via login in smtplib) to get, well, uhm, authorized SMTP ;-) > Another questions is, will starttls() tackle with those servers with SSL > encryptions? With whatever OpenSSL supports (SSLv2, SSLv3, TLS). > To my knowledge, TLS is the next generation of SSL. Yeah, the STARTTLS extension was called ...TLS to reflect that already. > Even the recentest doc on python.org doesn't have any explanation on > starttls() yet, :-( You must have used the time machine the wrong way: http://www.python.org/doc/current/lib/SMTP-objects.html My Postfix configuration (with default comments). Especially the comments show how to properly configure an SMTP server to prevent spamming: [...] # TRUST AND RELAY CONTROL # The mynetworks parameter specifies the list of "trusted" SMTP # clients that have more privileges than "strangers". # # In particular, "trusted" SMTP clients are allowed to relay mail # through Postfix. See the smtpd_recipient_restrictions parameter # in file sample-smtpd.cf. # # You can specify the list of "trusted" network addresses by hand # or you can let Postfix do it for you (which is the default). # # By default (mynetworks_style = subnet), Postfix "trusts" SMTP # clients in the same IP subnetworks as the local machine. # On Linux, this does works correctly only with interfaces specified # with the "ifconfig" command. # # Specify "mynetworks_style = class" when Postfix should "trust" SMTP # clients in the same IP class A/B/C networks as the local machine. # Don't do this with a dialup site - it would cause Postfix to "trust" # your entire provider's network. Instead, specify an explicit # mynetworks list by hand, as described below. # # Specify "mynetworks_style = host" when Postfix should "trust" # only the local machine. # # mynetworks_style = class # mynetworks_style = subnet # mynetworks_style = host # Alternatively, you can specify the mynetworks list by hand, in # which case Postfix ignores the mynetworks_style setting. # # Specify an explicit list of network/netmask patterns, where the # mask specifies the number of bits in the network part of a host # address. # # You can also specify the absolute pathname of a pattern file instead # of listing the patterns here. Specify type:table for table-based lookups # (the value on the table right-hand side is not used). # #mynetworks = 168.100.189.0/28, 127.0.0.0/8 #mynetworks = $config_directory/mynetworks #mynetworks = hash:/etc/postfix/network_table mynetworks = 192.168.2.0/8, 127.0.0.0/8 # The relay_domains parameter restricts what clients this mail system # will relay mail from, or what destinations this system will relay # mail to. See the smtpd_recipient_restrictions restriction in the # file sample-smtpd.cf for detailed information. # # By default, Postfix relays mail # - from "trusted" clients whose IP address matches $mynetworks, # - from "trusted" clients matching $relay_domains or subdomains thereof, # - from untrusted clients to destinations that match $relay_domains # or subdomains thereof, except addresses with sender-specified routing. # The default relay_domains value is $mydestination. # # In addition to the above, the Postfix SMTP server by default accepts mail # that Postfix is final destination for: # - destinations that match $inet_interfaces, # - destinations that match $mydestination # - destinations that match $virtual_maps. # These destinations do not need to be listed in $relay_domains. # # Specify a list of hosts or domains, /file/name patterns or type:name # lookup tables, separated by commas and/or whitespace. Continue # long lines by starting the next line with whitespace. A file name # is replaced by its contents; a type:name table is matched when a # (parent) domain appears as lookup key. # # NOTE: Postfix will not automatically forward mail for domains that # list this system as their primary or backup MX host. See the # permit_mx_backup restriction in the file sample-smtpd.cf. # relay_domains = $mydestination So basically, I allow relaying only from clients in the local network and from localhost (192.168.2.0/8 and 127.0.0.0/8) and I relay only for $mydestination, which is my domain. HTH & HAND, -- Gerhard From jkraska at san.rr.com Thu Nov 21 02:38:22 2002 From: jkraska at san.rr.com (Courageous) Date: Thu, 21 Nov 2002 07:38:22 GMT Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DDA7260.4050905@nyc.rr.com> <3DDBD838.10406@nyc.rr.com> Message-ID: > Macros in LISP may make it possible to write "extremely readable code" >-- but what level of LISP expertise is required to write those macros? > > If you have to supply the macros ahead of time, the users aren't >learning LISP, they are learning "MacroExtendedLISP"... A number of "standard constructs" used routinely in LISP are actually macros in some standard distributions, such as Franz. One of the genuinely useful capabilities of LISP is the ability to define domain- specific languages. Although certain negatives do apply, of course. C// From theller at python.net Wed Nov 20 05:32:01 2002 From: theller at python.net (Thomas Heller) Date: 20 Nov 2002 11:32:01 +0100 Subject: Understanding PyEval_InitThreads References: Message-ID: <7kf83526.fsf@python.net> Gernot Hillier writes: > I can't answer your question exactly - but I personally would suggest to not > create a new thread state but doing it this way: > > Py_BEGIN_ALLOW_THREAD > call_some_c_code(_save) > Py_END_ALLOW_THREAD > > > If you don't understand this, please note that Py_BEGIN_ALLOW_THREADS > expands to "{ PyThreadState *_save; _save = PyEval_SaveThread();". > > call_some_c_code() has to pass the PyThreadState* to > call_back_into_python(). There you should do s.th. like this: > > void call_back_into_python(PyThreadState *s) > { > PyEval_PyEval_RestoreThread(s) > // do your work > PyEval_SaveThread(); > } Unfortunately it won't work this way. Think of call_some_c_code() being the C standard library's qsort function, and call_back_into_python() is the function pointer I gave qsort to do the comparison. There's no way to pass the thread state to the callback function! Storing the thread state in a global variable would be possible, but in this case it wouldn't be thread safe, I assume, and *only* work if the callout into C is done by my extension module. Thanks, Thomas From skip at pobox.com Sat Nov 23 12:23:29 2002 From: skip at pobox.com (Skip Montanaro) Date: Sat, 23 Nov 2002 11:23:29 -0600 Subject: Python IRC dictatorship In-Reply-To: References: <29304.91T434T13743504threeseas@earthlink.net> <743utuoi3l31t8e8tt9v3sncosuk2gqi02@4ax.com> <1239.92T1047T4844497threeseas@earthlink.net> Message-ID: <15839.47505.501354.247912@montanaro.dyndns.org> John> x = [] John> y = [] John> x.append(1) John> print y I'm sure John meant x = [] y = x x.append(1) print y ;-) Skip From brian_l at yahoo.com Fri Nov 8 13:28:41 2002 From: brian_l at yahoo.com (Brian Lenihan) Date: 8 Nov 2002 10:28:41 -0800 Subject: PySol Windows binaries, anyone? References: Message-ID: Jarek Zgoda wrote in message news:... > Dnia 7 Nov 2002 20:15:59 -0800, brian_l at yahoo.com (Brian Lenihan) pisze > na grupie comp.lang.python: > > > http://homepage.mac.com/brian_l > > Sorry, 404 Not Found... > That must have been an outage at mac.com (that's an ell in my name not a one). I should have said what is there: patches to get pysol working and binaries and source for the pysolsoundserver which has been patched to play MP3s (non VBR). > -- > Zdr?wko > Jarek Zgoda From lbrannma at cablespeed.com Thu Nov 7 17:09:29 2002 From: lbrannma at cablespeed.com (Lance) Date: Thu, 7 Nov 2002 14:09:29 -0800 Subject: embedding error Message-ID: Hi, The code in section 5.3 of the Python "Extending and Embedding the Python Interpreter" won't compile for me. I get a link error, LINK : fatal error LNK1104: cannot open file "python22_d.lib" I include stdafx.h and python.h at the top of my C program. Python22_d.lib is not on my machine. I'm running a recent release of PythonWin. Any suggestions would be appreciated. Thanks, Lance From donn at u.washington.edu Tue Nov 12 19:04:43 2002 From: donn at u.washington.edu (Donn Cave) Date: 13 Nov 2002 00:04:43 GMT Subject: Convert type() to string? References: Message-ID: Quoth "Robert Oschler" : | I want to be able to print out the type() of a string for a "structure | walker" I'm writing. I need to be able to prepend a string of pad | characters to the type() so the following: | | print padstr + type(x) | | won't work because type() does not return a string. What's a good way to do | this? I'm using Python 2.1 + Python 2.2 (2.1 for Jython). Arguably the best way might be "don't do that!" and do print padstr, type(x) instead. But anyway, the "print" command in effect uses the str() function to make type(x) into a string, and so can you. The alternative would be repr(), which is an interesting philosophical dilemma but not an interesting practical one, since they come out the same in this case. Donn Cave, donn at u.washington.edu From wilk-spamout at flibuste.net Thu Nov 28 08:53:20 2002 From: wilk-spamout at flibuste.net (William) Date: 28 Nov 2002 14:53:20 +0100 Subject: Distributing python applications for Windows users References: Message-ID: <87el95ls1b.fsf@flibuste.net> martyn_quick at yahoo.co.uk (Martyn Quick) writes: > What's the best way to distribute an application written in Python > (consisting of quite a few modules and using Tkinter/Pmw for GUI) so > that it can be used by someone who is using MS Windows without > requiring them to install Python itself? http://starship.python.net/crew/theller/py2exe/ Convert python scripts into standalone windows programs it's very easy -- William Dode - http://flibuste.net From peter at engcorp.com Tue Nov 26 23:14:35 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 26 Nov 2002 23:14:35 -0500 Subject: PyGTA Announcement: next meeting is Thursday December 12, 8-10 pm Message-ID: <3DE446AB.1AFDAB7B@engcorp.com> I'm pleased to announce that next meeting of PyGTA, the Toronto-area Python and Zope user group, will be on Thursday December 12. It will be held at the 519 Church St. Community Centre, near Wellesley, from 8 to 10 p.m. This is the same location as last time. Please visit http://web.engcorp.com/pygta/wiki/NextMeeting for other details of the meeting, as usual. As usual we're extending an invitation to you to come and present for 5-10 minutes on your own Python activity if you believe it will be of interest to others... just let us know ahead of time so we can leave time for it. In addition, note our new Mailman-based mailing lists, described at http://web.engcorp.com/pygta/wiki/MailingLists . The old announcement list has been replaced, and there is a general list for group discussion purposes as well. -Ian Garmaise and Peter Hansen, PyGTA organizers From gminick at hacker.pl Wed Nov 27 14:01:34 2002 From: gminick at hacker.pl (Wojtek Walczak) Date: Wed, 27 Nov 2002 19:01:34 +0000 (UTC) Subject: do you guys help newbies?? References: Message-ID: Dnia Wed, 27 Nov 2002 16:20:13 -0000, Simon Brunning napisa?(a): > See . Thanks! Great article. Now the code looks like this: --- import sys def prompt(): return raw_input("Put a digit here: ") try: a = prompt() while 1: a = a.replace(' ','') if a[0] == '-' and a[1:].isdigit(): a = int(a) break elif not a.isdigit(): a = prompt() else: a = int(a) break except: print sys.exc_info()[1] sys.exit() --- ...and it's not too bad example of reliable code getting input from users ;) -- [ ] gminick (at) underground.org.pl http://gminick.linuxsecurity.pl/ [ ] [ "Po prostu lubie poranna samotnosc, bo wtedy kawa smakuje najlepiej." ] From george at omniti.com Wed Nov 20 19:27:28 2002 From: george at omniti.com (George Schlossnagle) Date: Wed, 20 Nov 2002 19:27:28 -0500 Subject: embedding python interpreter Message-ID: <0401714B-FCE8-11D6-A760-000393B2B3C0@omniti.com> Hi, I'm trying to embed a python interpreter into a c daemon to allow for drop in python modules. What I have seems to work but doesn;t seem to be the 'right' way to do it. I allow two config options in my user config file, one for specifying a module to import, and another that has a function which is the callback called from the daemon. I do my import as: int python_import(char *module) { PyObject *pModule, *pName; pName = PyString_FromString(module); pModule = PyImport_Import(pName); if(pModule == NULL) { fprintf(stderr, "Failed to load \"%s\"\n", module); return NULL; } return 1; } (This is called from a lex/bison parsed config file once, the interpeter is already started). Then on certain input, this callback is called, with the function name (as module.name, since multiple callbacks can be registered): int python_log(char *func, char *sender, char *group, char *message) { int retval; char *ptr; PyObject *pFunction, *pFunctionName, *pSender, *pGroup, *pMessage; PyObject *pModuleName, *pDict, *pArgs; pSender = PyString_FromString(sender); pGroup = PyString_FromString(group); pMessage = PyString_FromString(message); ptr = strrchr(func, '.'); if(ptr == NULL) { fprintf(stderr, "Function call must be .\n"); return NULL; } pFunctionName = PyString_FromString(ptr + 1); pModuleName = PyString_FromStringAndSize(func, ptr - func); pDict = PyModule_GetDict(PyImport_Import(pModuleName)); Py_DECREF(pModuleName); if(pDict == NULL) { return NULL; } pFunction = PyDict_GetItem(pDict, pFunctionName); if(pFunction == NULL) { fprintf(stderr, "Function not found\n"); return NULL; } pArgs = PyTuple_New(2); PyTuple_SetItem(pArgs, 0, pSender); PyTuple_SetItem(pArgs, 1, pGroup); PyTuple_SetItem(pArgs, 2, pMessage); PyObjectCallObject(pFunction, pArgs); Py_DECREF(pArgs); return 1; } This seems to be the wrong way to find the correct PyDict object to get pFunction from. It seems wrong to have to strrchr my function name to get a module. It seems like there should be a way to get the symbol table for my current scope. It seems that this should be the acse, but I can't figure out how.... Any advice on doing this more correctly would be greatly appreciated. Thanks! George From loewis at informatik.hu-berlin.de Tue Nov 5 05:53:36 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 05 Nov 2002 11:53:36 +0100 Subject: How does Python handle probing to see if a file already exists? References: Message-ID: "Christopher R. Culver" writes: > However, translating that directly into Python doesn't work because if > Python can't find a file to open, it doesn't just return 0, it gives an > error and exits. How can I write this functionality in Python so that it > returns 0 and continues, or does Python have a totally different way of > handling this problem than C? The set of error conditions is nearly identical between C and Python, as Python adds only a thin wrapper around the C library. However, the way in which errors are reported to the program is completely different: C uses return values and implicitly-changing global variables (errno); Python uses exceptions. In the specific case, what you see is the IOError exception. If it is not caught, it causes a program exit, with an error message (which we call 'traceback'). If you expect certain errors to happen, you can prepare for that in the program: try: f = open('/usr/bin/foo','r') except IOError: some code here There are variations to this try-except statement, see http://www.python.org/doc/current/ref/try.html In this case, the most common variations would be try: f = open('/usr/bin/foo','r') except IOError, exc: if exc.ENOENT: # expecting that the file does not exist some code here else: # some unexpected error: re-raise raise if you want to process only a single case of IOError, and try: f = open('/usr/bin/foo','r') except IOError: some code here, f is still unassigned else: normal processing, can use f. if you can execute the normal processing only if opening succeeded. Regards, Martin From nospam at bigfoot.com Mon Nov 4 12:30:02 2002 From: nospam at bigfoot.com (Gillou) Date: Mon, 4 Nov 2002 18:30:02 +0100 Subject: MySQLdb and threads Message-ID: Hi, I plan to make SQL queries in different threads of an application using MySQLdb. Can I use the same Connection object in all threads (each thread having its own cursor) for the queries ? Or should I use a different Connection object for each thread ? TIA for your hints ! --Gilles From tismer at tismer.com Thu Nov 21 16:18:21 2002 From: tismer at tismer.com (Christian Tismer) Date: Thu, 21 Nov 2002 22:18:21 +0100 Subject: SHA-2 state of the art? References: <3DDCE92C.70803@tismer.com> <200211220806.29617.rjones@ekit-inc.com> Message-ID: <3DDD4D9D.7030008@tismer.com> Richard Jones wrote: > On Fri, 22 Nov 2002 1:09 am, Christian Tismer wrote: > >>Hi friends, >> >>I am looking for implementations of SHA-256 >>and SHA-512, and I found CryptKit so far. >>http://eevolved.com/cryptkit/ >>Does anybody know of alternative activities? > > > shax-py from http://philosophysw.com/software/ > > via > > http://www.amk.ca/cgi-bin/pypi.cgi?:action=display&name=shax-py&version=0.9 Hey Rich, you're alive! thanks a lot, I'm looking into this as well. 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 pager +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 claird at lairds.com Fri Nov 8 09:08:43 2002 From: claird at lairds.com (Cameron Laird) Date: Fri, 08 Nov 2002 14:08:43 -0000 Subject: Ethics in abstract disciplines (was: Making a better textbook (was Re: The Deitel book)) References: <87b0ada6.0211011453.1df4d216@posting.google.com> <815e8a38.0211071038.208c7577@posting.google.com> Message-ID: In article , Charles Krug wrote: . . . >Interesting. I doubled in both Math and CS. Half of the CS courses had >an ethics component, while none of the maths did. > > >Which only makes sense. I've never heard of a fudged mathmatical model >used to support the desired conclusion of a sponsor with deep pockets. > >Have you? > > I don't understand this description. It certainly interests me, though. I take it that "CS" here means the kind of soft- ware engineering and technology that's typicall taught in college. And you're seriously saying that sections on ethics appeared in half of your classes? Can you give a few examples of such content? I know of abundant ethical questions spe- cific to mathematicians. I can supply plenty of examples of "fudged mathematical model[s]", if that'll help. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From csshi99 at yahoo.com Mon Nov 11 16:58:32 2002 From: csshi99 at yahoo.com (Mindy) Date: Mon, 11 Nov 2002 13:58:32 -0800 (PST) Subject: Question about drawing simple graph in Python? In-Reply-To: Message-ID: <20021111215832.92778.qmail@web21209.mail.yahoo.com> > Have a look at: > http://home.hccnet.nl/a.vredegoor/cartesian/cartesian.py > > It's a kind of virtual "millimeter" paper, it can be > used to draw > points, line pieces and edges between points. If the > "withaxes" and > "withgrid" arguments are not set to "yes" it > produces the kind of > output as described above. Thanks so much. This really produces the graph with edges and nodes. But I have two more questions. 1) How to stick a name to the node? For example, the current edge is just a line like: ------------> But I want there're nodes' names attached to each node, such like: pt1--------->pt2 How to draw the above edge? 2) I met such situation: I have edges (pt1,pt2) (pt2,pt3) (pt1,pt3) But when I draw, I only get: pt1----->pt2------>pt3 which doesn't show there's an edge between (pt1,pt3). Because the line between pt1 and pt2 overlaps with the lines between pt1,pt2 and pt2,pt3. How to fix this? THanks for more help! ===== Cheers -Mindy __________________________________________________ Do you Yahoo!? U2 on LAUNCH - Exclusive greatest hits videos http://launch.yahoo.com/u2 From tdelaney at avaya.com Sat Nov 23 19:22:06 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Sun, 24 Nov 2002 11:22:06 +1100 Subject: ~~~ Python Use Question ~~~ Message-ID: > From: questions at smartcardware.com [mailto:questions at smartcardware.com] > Apart from the basic question "Is Python a good scripting language for a game" to which the answer is an empathic "Yes" ;) - and has been stated elsewhere you can easily embed Python into C/C++ - much more so than most scripting languages ... Surrounding your subject with things like ~~~ (or any repeated sequence of non alphanumeric characters) is likely to get your message marked as spam by many systems. Tim Delaney From max at alcyone.com Wed Nov 27 05:05:54 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 27 Nov 2002 02:05:54 -0800 Subject: Python Tutorial Was: Guido's regrets: filter and map References: <698f09f8.0211261046.582254a5@posting.google.com> <3DE40E21.A547F49E@alcyone.com> <698f09f8.0211270143.5a3b9f0f@posting.google.com> Message-ID: <3DE49902.BE880724@alcyone.com> Jeremy Fincher wrote: > Since they operate on any sequence, they should be methods of any > sequence. As functions, yes, they operate on all sequences, but they > only return lists. As methods, map/filter would return sequences of > the same type they operated on, which is (IMO) far more appropriate. > > In short, why should a map on a string return a list instead of a > string? Why should a filter on a binary tree return a list instead of > another binary tree? > But I think it would be more appropriate for map/filter to return > sequences of the same type as their argument sequences, not just > return lists blindly. And that requires that map/filter be methods, > not functions over sequences. Yes, it does, but it also means that everyone who ever wants to implement a sequence type needs to define __filter__ and __map__ methods (say) or you can't do filtering and mapping with them. Filter and map are general algorithms over sequence types -- all you need to use them is iteration, which is what all sequence types have in common. The fact that filter and map return lists regardless of the original sequence type is simply a necessary evil, because it means that it can now do something meaningful for _all_ sequence types, whether or not those particular custom types had any special dispensation for filtering or mapping. With your approach, if someone makes a sequence-compatible type but doesn't give me the right methods, I'm out of luck, even though it's about _algorithms_ not about methods. Filter and map are about generalized ways of dealing with sequences. They end up returning newly-created sequence types, and since the standard sequence type in Python is a list, they return lists. If you want to turn that back into a custom sequence type, you're more than welcome to do it; in your example, you can just do ''.join(map(..., S)) if you want to apply map to a string S and then return it back into a string. If you can only use filter and map when the appropriate method is defined in the custom type, then you're leaving yourself in a situation where you can't use filter/map over any sequence even though there's no logical reason why you shouldn't. All that a sequence type needs to define is a __getitem__ method with the appropriate semantics; you're saying you'd need to define __filter__ and __map__ (say), and if you take this argument to the fullest, a whole slew of other methods as well. Filter and map can _operate_ on any sequence, but they return lists since that's the logical generic sequence type to return. If you want to turn that back into some other custom sequence type after the fact, just go ahead. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ I'm crying everyone's tears \__/ Sade Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From tim.one at comcast.net Thu Nov 21 23:06:40 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 21 Nov 2002 23:06:40 -0500 Subject: Will python binaries compiled on vs.net? In-Reply-To: <3ddcb049$1@post.ulj.menatepspb.com> Message-ID: [Alexander Semenov, tries compiling Python w/ VC 7] > Ok. I just tried to compile python with VC7 > (ftp://ftp.sav.vens.ru/python). > I used recent cvs snapshot. I follow exactly > \dist\src\PCbuild\readme.txt. > Now I've some questions. > > 1. All but bsddb compiled without errors. > db.1.85.win32.zip compiled ok, but python/bsddb project complains to > unknown symbols u_long, u_int etc in db.h I solve problem by copying > dist\bsddb\PORT\win32\include\compat.h to dist\bsddb\include > Am I right? Why it didnt noted in readme? CVS isn't stable (by definition), and someone broke bsddb entirely earlier this week. It's in the process of getting moved to a newer version of the Sleepycat software. You're much better off building from a stable CVS tag. For example, the 2.2.2 release was tagged r222. Nobody would *want* a distribution from a non-stable state. If you do that, note that the bz2 module didn't exist then, and a different version of Tcl/Tk was in use. > 2. There are some warnings. Is it normal? No. We shoot for a warning-free build under MSVC. > For examle: > dist\src\Objects\longobject.c(1252) : warning C4244: '=' : conversion > from 'stwodigits' to 'digit', possible loss of data > dist\src\Objects\longobject.c(1271) : warning C4244: '=' : conversion > from 'stwodigits' to 'digit', possible loss of data Doesn't happen under MSVC 6; these should get repaired. Patches on SourceForge would be appreciated! > 3. Ok, I compiled it. I've got a bunch of *.lib and *pyd, python[w].exe. > What's next? How I can make distribution? I saw *.wse scripts for Wise > Installation System, but it is far from freeware. Don't ask me -- it's your distribution . > I look for some easy used tool or script. There's a patch on SourceForge with a more fleshed-out Inno Setup script (more fleshed-out than the python.iss in the PCbuild directory), if you'd like to pursue that route. > 4. Help. As far as I can see, it's doesnt possible to build help > for windows distribution (html) in windows. I've never done it, and don't know whether it's possible. Fred builds the HTML docs on a Linux box, and gives me a tarball to fold into the PLabs Windows installer. Note that Doc/tools/ contains prechm.py, which is most of what's needed to build an HTML Help file from the HTML docs instead; this is better on Windows, but we never found time to complete it. > I found win32 port for latex2html, but Makefiles in > /Doc uses sh scripts, and I didnt realize how I can do it. I > know about cygwin, but my personal preference is dont use it. Sorry, can't help you with this. > I think some of this questions are trivial and it's much simpler > ask it here and get momental points to my stupidity, and then > try to dig into complex ones. There are few simple issues remaining if you want to pursue this. I hope you do, though! The more Python distros built on free tools, the better. From andreas.ames at tenovis.com Thu Nov 21 04:56:19 2002 From: andreas.ames at tenovis.com (Andreas Ames) Date: 21 Nov 2002 10:56:19 +0100 Subject: Howto wait for multiple queues (Queue.py)? In-Reply-To: References: Message-ID: <87lm3nqm9o.fsf@sinon.fr.de.tenovis.com> Alex Martelli writes: > ...this doesn't follow -- just make all requests to a thread onto > a single Queue (tag the requests with 'kind' or whatever as needed) > and live happily. A Queue instance *IS* implicitly, automatically > and intrinsically "synchronized" -- several threads can be reading > and/or writing to the same Queue instance and you're guaranteed that > they'll never interfere with each other. That's just about the > whole POINT of the Queue class. Sorry, this confuses me a bit. If you understood my mail such that I want to synchronize the access of several threads to one queue, my mail must have been totally ambiguous. What I really want to achieve is that several threads can consume items from several (possibly identical) _sets_ of queues. As I read the docs and looked at the source in Queue.py I don't doubt that this queue implementation is threadsave. What I don't understand is the reasoning, *why* every thread should only have exactly one input queue. This has several disadvantages from my point of view. Several threads can't share the same input queue and I can't distinguish between several input channels within one thread. For example in my case the threads should have input channels for commands and for events (such as command responses or unsolicited events). Furthermore there can be different functional units which write commands and/or events to the same thread. It is clear to me that this can be achieved by giving the different commands/events different types/kinds and use one input queue for all of them. But I have at least two reservetions against this: - The single input queue could be a bottleneck. If you choose to avoid the bottleneck by providing several threads which understand the same commands, the producers have to decide about the scheduling, i.e. which thread gets which command. - It seems more intuitive to me to have different input channels for different purposes. This is comparable to the 'select()' function which is widely used. If you say, there is no good implementation for waiting on several queues in python, then ok, in this case I admit that using a single input queue per thread might be the way to go (I'm also not satisfied by the three alternatives I have enumerated in the original post; I think I will try alternative 3 for now). cheers, andreas From tim_sleptsov at fromru.com Wed Nov 6 12:58:56 2002 From: tim_sleptsov at fromru.com (Timofey Sleptsov) Date: Wed, 6 Nov 2002 20:58:56 +0300 Subject: Python and Tktable Message-ID: <20021106205856.7de663f9.tim_sleptsov@fromru.com> Hello All! I am try to use Tktable library with python, but without any result ;( For example, i type it: Python 2.2 (#1, Mar 29 2002, 17:58:00) [GCC 2.95.3 20010315 (release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Tkinter >>> root = Tkinter.Tk() >>> root.tk.eval('package require Tktable') Traceback (most recent call last): File "", line 1, in ? TclError: couldn't load file "/usr/lib/Tktable2.7/Tktable.so.2.7": /usr/lib/Tktable2.7/Tktable.so.2.7: undefined symbol: tclStubsPtr >>> And get error message. Strange, but TkTable work fine with tcl/tk. Also same situtation i have with BLT library. What i do wrong? -- Best regards Timothey Sleptsov From zeitlin at parthe.lpthe.jussieu.fr Fri Nov 15 07:22:01 2002 From: zeitlin at parthe.lpthe.jussieu.fr (Vadim Zeitlin) Date: Fri, 15 Nov 2002 12:22:01 +0000 (UTC) Subject: wxPython program failing after upgrade References: Message-ID: On Wed, 13 Nov 2002 19:26:49 -0500, Blake Garretson wrote: > I upgraded to wxPython 2.3.3.1 using the precompiled win32 binary, and now > my wx program won't work. (I previously used 2.3.2.1) I'm using a DC > client to draw some graphics, and it fails when it goes to refresh the > screen. Here's the error that shows up in a popup dialog: > > """ > c:\projects\wx\src\msw\dcclient.cpp(216): assert "wxFalse" failed: wxPaintDC > may be created only in EVT_PAINT handler! > Do you want to stop the program? > """ The assert tries to tell you that there is an error in your program: it is using wxPaintDC outside of EVT_PAINT handler which is forbidden. Although it might work in your case on your platform, there is no warranty that it works on all of them. Simply use wxClientDC instead of wxPaintDC outside of EVT_PAINT. Regards, VZ -- GCS/GM d? H+ s++:-- p2 au--- a- w+ v C+++ UBLS+++ P- L++ N++ E--- W++++ M? V-- -po+ R++ G`` !tv b+++ D--- e++++ u++ h--- f+ r++ n- y? From duanek at chorus.net Thu Nov 7 16:27:01 2002 From: duanek at chorus.net (Duane Kaufman) Date: 7 Nov 2002 13:27:01 -0800 Subject: Windows COM and Python Objects question Message-ID: <59023571.0211071327.5cb69e0f@posting.google.com> Hi, I'm a newbie when it comes to COM and Python, so please bear with me if this question has a simple answer. I would like to expose Python's wonderful zipfile module capabilities to the Windows Scripting Host through a COM object. Taking a lead from Hammond & Robinson's 'Python Programming on Win32' book, I tried to expand upon the example in Chapter 12, where Python's string module is exposed. The problem is, the zipfile module uses _objects_ as return values in certain cases, requiring the passing of objects _back_ to my Python COM module to get some types of information (the ZipFile object, for example), and I don't know how to unpack these (along with their arguments) and use them. Any pointers, links, or example code will be appreciated! Thanks, Duane From rmunn at pobox.com Wed Nov 27 11:19:38 2002 From: rmunn at pobox.com (Robin Munn) Date: Wed, 27 Nov 2002 16:19:38 GMT Subject: Issue with new-style classes and operators References: <3DE215D1.D9A3FEF9@jandecaluwe.com> <5ApE9.52343$744.1917235@news1.tin.it> <3DE49BB7.80D199FB@jandecaluwe.com> Message-ID: Jan Decaluwe wrote: > Alex Martelli wrote: >> >> Jan Decaluwe wrote: >> [foo.__add__ treated differently than foo + 4] >> > >> > I don't think is can be the intention. Or can it? >> >> Yes it can. The idea is that operators should rely on special >> methods defined by the TYPE (class) of the object they're working >> on, NOT on special methods defined just by the OBJECT itself and >> not by its class. > > But what makes operator methods so special that they should be treated > so differently from ordinary methods? > > As far as I am concerned, operator syntax is just convenience, not > concept. The line between operators and ordinary methods is thin > and arbitrary. > > For example, take 's.extend(x)', with s a list. The documentation states > that it is the same as 's[len(s):len(s)] = x'. Another way to > do it is 's += x'. > > Yet, if you try it with my example class, the 'extend' would work fine, > and while the 2 operator-style statements would give a type error. > What's logical about that? I would agree with this. I was experimenting with subclassing list the other day and discovered to my surprise that overriding setitem() and setslice() had no effect on l.extend(x). This struck me as violating the Principle of Least Surprise, *especially* since the documentation had said that l.extend(x) was equivalent to l[len(l):len(l)] = x. This feels like a wart that needs to be fixed. I don't know what the right answer will be. Maybe behavior needs to change in some way, or maybe the documentation needs to be fixed to explain *in detail* what actually happens when you subclass built-in types. But this has been bugging me, and I think I want to see it fixed somehow. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From mcfletch at rogers.com Fri Nov 29 10:41:17 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 29 Nov 2002 10:41:17 -0500 Subject: Parser building in Python References: <20021129141633.GB29515@k6.in-berlin.de> Message-ID: <3DE78A9D.5040209@rogers.com> There are a number of parser-generator systems for Python: http://www.python.org/cgi-bin/moinmoin/LanguageParsing I'm the author of one of them (well, two I suppose, but one (mcf.pars) is now long-since obsolete), so any analysis I gave regarding which is "best" would be considered suspect ;) . Feel free to add your own analysis to the Wiki if you feel it's appropriate. HTH, Mike ml wrote: >Hi, > >I like to write a parser in Python. The language itself is >not LALR(1), but I could do some tricks to make it LALR(1). >What are the best tools to write lexers and parsers in >Python? Maybe sth. similar to ANTLR? > >Thanks in advance! > > > > -- _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From aleax at aleax.it Wed Nov 13 07:27:25 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 13 Nov 2002 12:27:25 GMT Subject: __getattr__ and others References: Message-ID: Grzegorz Dostatni wrote: > I want to create an object that (at runtime) is called with an arbitrary > function with arbitrary number of arguments. Haveing this call it will > forward it through xml-rpc to the server, execute it and return the > results. > > I am missing something simple - here is what I have: > > def calling(self, method="", *args, **kwargs): > print "calling method ", method > print "With arguments", args, kwargs > > def __getattr__(self, name): > return lambda s=self, m=name, *args, **kwargs: apply(s.calling, > (m, ) + args, kwargs > > This works as expected for (o is the instance of the object) > > 1. o.hello = OK. Returns the lambda function. > 2. o.hello(keyword="Argument") = OK. that works. > 3. o.hello(3, keyword="Argument") = This does not work. > 4. o.hello(3) = This does not work again. > > I have to do something like o.hello(o, "hello", 3) to get what I want. > Does anyone have an idea how to make it more consistent with normal > calling style? I see it has already been pointed out to you that there are problems with your lambda definition, when called with positional arguments. The good news is that, in recent versions of Python, you don't need the "default-arguments hack" to have a nested function know about local variables of outer functions in which it's nested -- such a "closure" is now entirely automatic. Therefore, and without any need for lambda's and apply's, you could just code: def __getattr__(self, name): def closure(*args, **kwds): return self.calling(name, *args, **kwds) return closure *However* -- take care! If you code such an unconditional __getattr__, instances of your class WILL claim they have ANY special method Python asks about -- consistent with the specification you give about an *arbitrary* function, but not necessarily with what you really mean. For example: >>> class tricky: ... def calling(self, method, *args, **kwds): ... print 'calling', method, args, kwds ... def __getattr__(self, name): ... def closure(*args, **kwds): ... return self.calling(name, *args, **kwds) ... return closure ... >>> t = tricky() >>> print t calling __str__ () {} Traceback (most recent call last): File "", line 1, in ? TypeError: __str__ returned non-string (type NoneType) >>> t claims it has a special-method __str__ (via that __getattr__, of course), but it doesn't, really -- tricky.calling is not acceptable in the role of special-method __str__ because it does not return a string. If you're SURE you want to forward special-method calls to some xml-rpc server, OK -- but in this case the tricky class is still not fully specs-compliant (it doesn't forward __getattr__, nor __setattr__ and __delattr__, which are special-cased; nor does it forward 'calling', because that's its own attribute). In the more likely case in which you want to except special-names from your __getattr__ behavior, make sure its return statement is guarded by an appropriate conditional, e.g. if name.startswith('__') and name.endswith('__'): raise AttributeError, name return closure (Raising AttributeError is what __getattr__ must do in order to communicate "no, I don't have this attribute"). Alex From nelson at crynwr.com Mon Nov 18 17:04:17 2002 From: nelson at crynwr.com (Russell Nelson) Date: 18 Nov 2002 17:04:17 -0500 Subject: python gui rant References: <3dd217e2$0$231$4d4ebb8e@news.nl.uu.net> Message-ID: "Gumuz" writes: > i am using wxPython at the moment as my python gui. Coming from a nice IDE > like Delphi it's really frustrating to get a nice layout together. I tried > some tools. The one i liked most, because of it's simplicity was wxGlade, > but still... it's not there yet. I might have missed something here and I > don't want to complain, but I think that a good, robust gui-designer will > open up a lot of posibilities for python. i might give it a shot! gtk, glade, libglade, and pygtk work for me. http://pygps.org/ -- -russ nelson http://russnelson.com | Crynwr sells support for free software | PGPok | it's better to be free 521 Pleasant Valley Rd. | +1 315 268 1925 voice | than to be correct. Potsdam, NY 13676-3213 | +1 315 268 9201 FAX | From martin at v.loewis.de Sun Nov 3 18:14:09 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 04 Nov 2002 00:14:09 +0100 Subject: Extending distutils ?? References: Message-ID: "Thomas Weholt" <2002 at weholt.org> writes: > Distutils is great, but adding a few features would make it almost perfect. > Since we allready got a documentation package in the standard distro why > can't Distutils generate documentation using pydoc in the process of > generating a package for distribution? All distutils questions have a simple answer: Nobody contributes anything. You can make a difference (actually, a context diff would do :-) Regards, Martin From martin at v.loewis.de Thu Nov 7 16:11:41 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 07 Nov 2002 22:11:41 +0100 Subject: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up References: Message-ID: bokr at oz.net (Bengt Richter) writes: > Ok, sorry, does > BIT31 = 1L<<31 > work? Not if you assume the original complaint from Jon Ribbens: If long literals become an error in some future Python release, this code will stop working. Regards, Martin From anton at vredegoor.doge.nl Wed Nov 6 12:08:40 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 06 Nov 2002 18:08:40 +0100 Subject: using the PSF license for one's code References: <918bc22f.0211051301.2010d077@posting.google.com> <3dc867de$0$24754$7b0f0fd3@reader.news.newnet.co.uk> <918bc22f.0211060732.47b2198d@posting.google.com> Message-ID: On 6 Nov 2002 07:32:46 -0800, donnal at donnal.net (Donnal Walter) wrote: >For entities like PSF that distribute a lot of copies of their >software, it probably makes sense to write their own specific >licenses, but for everyone else (like me) it seems to boil down to >choosing GPL or BSD. Who would have guessed that it could be this To me it isn't that simple. From my perspective the GPL is using the same kind of "weapons" to defend it's followers against the "evil" closed sourcerers. Using the same kind of weapons as the enemy risks becoming oneself that what is feared. I think this is meant by "not resisting evil" and "turning the other cheek" and such ideas as one can find in the old books. So the GPL is the enemies weapon turned around and used against the enemy itself. Just read the legal language inside the document to proove this. The BSD is of a somewhat less radical nature in that it is trying to defend the authors against users trying to legally attack them. It could be described as a shield. But we know how murky "defense only" arguments can get. There also is the option of completely giving away all rights to the code -placing it in the public domain- which can be compared to having no defense at all, like "turning the other cheek". This is dangerous too because although one can give code away, some legal attacks might succeed in linking the code to the author again and even sue the author because the users were not properly warned against possible dangers arising out of using the code. So to me the license one uses is an indication of what moral level one is currently acting on. For me this means that although I see that it is better to not resist evil I am still not wise enough to not step aside if someone is hitting me, so that means it's BSD for me now, and sometimes public domain if I am in a philosophical mood. AV. 1 Corintians 6:13 From stephen.tubbs at paretopartners.com Fri Nov 1 15:12:51 2002 From: stephen.tubbs at paretopartners.com (Stephen) Date: 1 Nov 2002 12:12:51 -0800 Subject: Python 2.1, COM (Excel), and Threads... References: <24420294.0210311031.18f8b3e0@posting.google.com> Message-ID: <24420294.0211011212.32ef8e33@posting.google.com> Mark Hammond wrote in message news:... Thanks, works like a charm! This last bit is a little ominous ... > > Storing a thread-created COM object in your instance (ie, self.excel) is > a recipe for disaster, but I haven't time to go there now! > > Mark. .. Is there a description or example in one of your books? Stephen From jadestar at idiom.com Wed Nov 27 15:01:44 2002 From: jadestar at idiom.com (James T. Dennis) Date: Wed, 27 Nov 2002 20:01:44 -0000 Subject: do you guys help newbies?? References: Message-ID: <1038427304.67233@smirk> malik m wrote: > hi yea i messed up here's the code sorry about the html too i was > using it through hotmail while i learnd and still am learning how to > use newsgroups.... > #chapter 3 test control structures 3.3 > print "hello, this program will tell me how many miles per gallon your > car drives by the \n amount of miles entered by the user along with > the size of his/her tank." Clearly this is From Deitel(TM)'s _Python:_How_To_Program_ That's a book that spoonfeeds the prospective programmer. It's not held in high regard among Pythonistas. One of my complaints is that the text is pretty unclear (at least in the early chapters) about the nature of Python's exception handling. In several places the Dietel book refers to various conditions which "cause a program to terminate with an error" (or words to that effect). In most books on Python the authors make it clear that exception handling is a fundamental control structure in Python. Thus it should have been covered in this chapter. Also all references to abnormal terminations from programming or data errors should refer to the specific exception that is being raised. (That critique is for the rest of the readership: Let me explain for you, Malik: When you make a mistake in Python, such as divide by zero or try to use a string as a number then Python will "raise an exception." By default exceptions are reported as an error, and the program exits at that point. When a Python program terminates due to an exception, it prints some debugging information called a traceback. Good books on Python programming explain this in the first or second chapter. When ever you're trying to get help with a python script in a newsgroup or on a mailing list, you should post the plain text of a *small and relevant* fragment of your code and, if possible a capture of the traceback. (Under UNIX a quick way to capture the traceback is to use a command like: foo.py 2> ~/tmp/foo.err; that is redirect 'stderr' to a file). It's also possible for your program to catch specific types of exceptions that you know might be caused by specific blocks of your code. This is perfectly normal under python and should NOT be avoided. However it should be done carefully, so you don't make your programming errors harder to find). > #initialize variables > totalMilesDriven = 0 #total miles driven > totalGallonsPerTank = 0 #total gallons per tank > counter = 0 #bogus counter > #processing phase > gallonsPerTank = raw_input("Enter how many gallons your tank holds, -1 > to end:") > gallonsPerTank = int(gallonsPerTank) This should be something more like: try: gallonsPerTank = int(gallonsPerTank) except ValueError: gallonsPerTank = -1 # Take an invalid input as a call to exit. ... or (better yet): TankSize = "Enter how many gallons your tank holds, -1 to end:" while 1: gallonsPerTank = raw_input(TankSize) try: gallonsPerTank = int(gallonsPerTank) break except ValueError: print "Invalid Response! Please try again." (Actually this code is still a little weak because it will reject floating point numbers. But it will have to suffice for pedagogical purposes). > milesDriven = raw_input("enter how many miles driven, -1 to end:") > milesDriven = int(milesDriven) See above. You have to validate your inputs. Generally it's wise to isolate you input validation code into a function. This allows your main program code to focus on the main task at hand (hiding the details of validation from maintainers and readers of that code) and helps reduce the chance that you'll duplicate that code in multiple places in your program (as you've done below, within the same prompts and raw_input functions inside your while loop). Actually it's even better to create a class (object template). That class (or functions within it) would then be responsible for it's own validation. However, that is probably overkill for such a simple exercise. The question becomes, "who" (which object/class) would be responsible for the actual inputs. I don't like the idea of hiding the raw_input() calls inside of an object's initializer. Of course raw_input() is not used much in real Python programming because usually some other interface is being implemented (CGI forms processing, GUI, network, file, or database, for some examples). I'm not going to speculate on an OO design for this exercise. > while gallonsPerTank or milesDriven != -1: This looks wrong. I think you mean to say: while gallonsPerTank != -1 and milesDriven != -1: ... Because your conditional expression will be short-circuited any time gallonsPerTank set bound to *any* value other than a Python "false" (numeric zero, empty string, tuple, etc). In any other case (gallonsPerTank is set to any non-zero or non-empty value) then the next expression will be evaluated and that result will be returned for the expression as a whole. So your loop won't exit until gallonsPerTank is 0 (or empty) and milesDriven is anything other than -1. > averagea = milesDriven / gallonsPerTank Most people want floating point (non-integer) results from averages. So: averagea = float(milesDriven) / gallonsPerTank ... will *coerce* (force) the whole expression to return a floating point value. Normally I'd complain about your failure to check for gallonsPerTank being zero. Ironically the erroneous while condition actually guards against that. However, when you change the while condition to something that expresses your intent, then you could have a case where gallonsPerTank == 0 You can handle this one of three ways: 1) use a conditional before the division: if gallonsPerTank: averagea = float(milesDriven) / gallonsPerTank else: ### What? import sys averagea = sys.maxint ### You got infinite mileage from "no gas"? 2) use Python's exeption handling? try: averagea = float(milesDriven) / gallonsPerTank except ZeroDivisionError: import sys averagea = sys.maxint ### See above about this absurdity. ... I think you'll see the problem with both of these approaches. You can't have a valid mpg calculation if you had NO gasoline. That leaves us with: 3) treat 0 (zero) as an invalid value for gallonsPerTank. (Go back to your gPT input function and change it to something like: while 1: gallonsPerTank = raw_input(TankSize) try: gallonsPerTank = int(gallonsPerTank) if gallonsPerTank == 0: print "Can't get any mileage with no gasoline" print "... unless you're on a bicycle" print "... or in a rowboat ;)" continue break except ValueError: print "Invalid Response! Please try again." > counter = counter + 1 > print "your miles per gallon are", averagea > totalMilesDriven = totalMilesDriven + milesDriven > totalGallonsPerTank = totalGallonsPerTank + gallonsPerTank Don't you mean just totalGallons or totalGallonsConsumed? > gallonsPerTank = raw_input("Enter how many gallons your tank > holds, -1 to end:") > milesDriven = raw_input("enter how many miles driven, -1 to end:") See above for my comment on duplicating your input code and thus having multiple places where you'd need to maintain any validation code. This is called "cut & paste" programming --- and is a BAD thing. Here's sample function for you to use: def GetGallonsPerTank(prompt="Enter tank capacity in gallons, -1 to exit"): while 1: response = raw_input(prompt) try: r = int(response) if r <= 0: print "Are you on a bicycle?" continue break except ValueError: print "Must enter an integer" return r ... (untested). If we create another input function for GetMilesDriven() it will be almost the same. That's irritating (more code duplication). If the code were *exactly* the same we could use one function for both inputs. If there's enough similarity (and a reasonable assurance that the validation requirements for the different variables won't diverge too much in the future, we could encapsulate the differences into parameters or help functions and pass those to our common function as arguments. So we might have: def GetValidInput(prompt, validate, errormsg): while 1: response = raw_input(prompt) try: return validate(response) except ValueError: print errormsg ... along with functions for ValidateTankCapacity() and ValidateMileage() which might look something like: def ValidateTankCapacity(proposed): r = int(proposed) if r <= 0: raise ValueError return r ... etc. You'd call this with statements like: inputPrompt = "Enter Gas Tank Capacity, -1 to exit: ", invalidMsg = "Must enter a whole number!" tankCapacity = GetValidInput(prompt, ValidateTankCapacity, invalidMsg) inputPrompt = "Enter Mileage Driven, -1 to exit: ", mileageDriven = GetValidInput(prompt, ValidateTankCapacity, invalidMsg) Again, all of this is probably overkill for this exercise. > #termination phase > if counter != 0: > average = float( totalMilesDriven ) / float( totalGallonsPerTank ) Only need to coerce one of these to a float. > print "The total miles per gallon is", average > else: > print "No data entered" From pearu at cens.ioc.ee Sun Nov 17 18:11:31 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Mon, 18 Nov 2002 01:11:31 +0200 (EET) Subject: Get Stdout from external script startet through python In-Reply-To: Message-ID: On 16 Nov 2002, Christian Rapp wrote: > I need to start an external script from inside python. This works just fine. > The called script produces some output on StandardOut, that I need within > the python-script. How do I get this Output into python? As already mentioned by other authors in this thread, os.popen and its extensions are the answer. Let me add here also commands.getoutput (and its extensions) as another alternative. But may I extend the question to extension modules, that is, how to get the (stdout or stderr) output that originates, say, from a fprintf(stdout, ...) statement in an Python/C extension module? This questions has been raised also in f2py-users mailing list where there was a wish to catch the stdout of a Fortran subroutine, wrapped to Python. So far I have only an idea that this could be achieved 1) by determining the pty (with os.ttyname(sys.stdout.fileno())) where these messages go; 2) and then using socket and termios modules to get the Fortran or C messages. How to get 2) to work, I haven't figured out yet. But it seems to be possible, in principle. For example, ttysnoop does this. So, any hints how to do that using Python tools and as an ordinary user (e.g. ttysnoop requires changes to /etc/inittab but it has other goals..), would be appreciated. Pearu From jepler at unpythonic.net Tue Nov 12 22:01:05 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 12 Nov 2002 21:01:05 -0600 Subject: pitfall for your amusement In-Reply-To: References: <20021112204601.21703.65547.Mailman@mail.python.org> Message-ID: <20021112210104.A2387@unpythonic.net> On Tue, Nov 12, 2002 at 06:52:02PM -0800, Terry Hancock wrote: > What would I have to do for this to be a problem? (as it happens, I have used > this kind of default before, so I would like to understand the pitfall!) Mutate the list in the function, as def stupid(i, l=[]): l.append(i) return l >>> stupid(1, []) [1] >>> stupid(1) [1] >>> stupid(2, []) [2] >>> stupid(2) [1, 2] Jeff From hancock at anansispaceworks.com Tue Nov 12 21:52:02 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 12 Nov 2002 18:52:02 -0800 Subject: pitfall for your amusement In-Reply-To: <20021112204601.21703.65547.Mailman@mail.python.org> References: <20021112204601.21703.65547.Mailman@mail.python.org> Message-ID: On Tuesday 12 November 2002 12:46 pm, python-list-request at python.org wrote: > If you are collecting pitfalls, here's my least favorite: "never use a > mutable object as a default value". A classic example: > > def badfunc(alist=[]): > ? ?... > > The default value of alist will not stay [] (an empty list) but instead > is affected by whatever you pass in for "alist". Very tricky and > unpleasant. > > Here's my usual solution: > def okfunc(alist=None): > ? ?alist = alist or [] > ? ?... Hmm. I don't see this: >>> def spam(eggs, ham=[]): ... print "%s and %s" % (eggs, ham) ... >>> spam('eggs') eggs and [] >>> spam('eggs', 'ham') eggs and ham >>> spam('eggs') eggs and [] >>> spam('eggs', ham=['more ham']) eggs and ['more ham'] >>> spam('eggs') eggs and [] >>> spam('eggs', ham=['more ham']) What would I have to do for this to be a problem? (as it happens, I have used this kind of default before, so I would like to understand the pitfall!) Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From adalke at mindspring.com Tue Nov 19 00:01:07 2002 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 18 Nov 2002 22:01:07 -0700 Subject: simple text editor w/ D&D of hyperlinks Message-ID: <3DD9C593.9080102@mindspring.com> I want a text editor where I can drag a hyperlink from Mozilla onto it and have the editor include that URL along with a hyperlink. For example, suppose I have just simple text (no hyperlinks) like this -------------------|--------------------- | [open] [save] | B i U [Times] [14] |----------------------------------------- | Here are some of the on-line strips I like | | Nukees - | Sluggy Freelance - | ... Now I drag the URL 'http://www.nukees.com/' from the browser to just to the right of "Nukees -". I want the result to look like -------------------|--------------------- | [open] [save] | B i U [Times] [14] <--- tool bar |----------------------------------------- | Here are some of the on-line strips I like ] can edit | ] all of | Nukees - _http://www.nukees.com/_ ] <-- this text | Sluggy Freelance - ] | .... ] where the URL for nukees.com is hot linkable, eg, underlined and in blue (with a change in color during mouse-over), where I can drag&drop it onto the browser and have it go to that page, or I can click on it and have a browser window open to that page (ie, through 'webbrowser.py' in the standard library). I can't figure out how to do this in Qt nor in wxWindows. The only rich text editors for Qt is "QTextEditor" which will underline links in HTML but won't tell you what was pressed. (There's also a QTextBrowser which lets you follow links but doesn't let you edit.) In addition, if I insert a URL manually, as "
" then insert a character in the middle, the two sides are marked for hypertext but the part just added wasn't. Eg, if I add "spam" to the URL I get _http://www.nu_ spam _kees.com/_ with "spam" in black and the rest in underlined blue. Beyond this, I would like to support importing links to local files, resolving some URLs as images (rather than just the name of the link), flagging those links that have changed, pulling down a mirror of the pages linked to (for off-line reading), etc., which means fine grained control of how to handle those hyperlinks. Yet QTextEditor doesn't really allow for insertion of things like images into the document ("A more complete API that supports setting margins, images, etc., is planned for a later Qt release"). Any suggestions on how to do this? (Besides writing my own rich text editor with proper key-binding support for X/Mac/Win!) I'll even try looking at an alternate GUI library -- I tried wxPython but my task seemed even less likely to be possible. Andrew dalke at dalkescientific.com From antonio.p at libero.it Sun Nov 24 16:33:06 2002 From: antonio.p at libero.it (Antonio.P) Date: Sun, 24 Nov 2002 21:33:06 GMT Subject: Python and gd library - Thank to all References: Message-ID: Thank to all for the aswers. I looked "python and gl-lib" and not "python +gd" in google so I had not found so much :-P The old gd-lib 1.8 can create and manipolate low quality images jpg but the new gd-lib 2.0 can create and manipulate high quality jpg. Hi hope to find a python implementation of the new gd-lib... sooner or later :-) From TOGLIMIcuni at programmazione.it Wed Nov 6 15:39:52 2002 From: TOGLIMIcuni at programmazione.it (Antonio Cuni) Date: Wed, 06 Nov 2002 20:39:52 +0000 Subject: loggin out automatically References: <1036253358.19897.0@doris.uk.clara.net> <3DC718BE.7060706@cyberspace.org> <3DC853DF.6060509@cyberspace.org> Message-ID: trewornan wrote: > I am responsible for maintaining a PC in a hotel which is available for > use of guests, basically just e-mail and web browsing. We are currently > using a program called "timewatcher" which allows me to provide "access > codes" each code providing a particular period of access - 20, 30, 60 > min or whatever You could use this script as the default shell for guests; it automatically kills bash after a fixed amount of time: import os import time import signal MAX_LOGIN_TIME = 5 # seconds pid = os.fork() if pid == 0: # the child os.execv('/bin/bash', ['/bin/bash']) else: # the parent time.sleep(MAX_LOGIN_TIME) os.kill(pid, signal.SIGTERM) Ciao Anto -- "Computer science is not about computers any more than astronomy is about telescopes." -- EW Dijkstra From printers at sendme.cz Fri Nov 29 09:12:47 2002 From: printers at sendme.cz (A) Date: Fri, 29 Nov 2002 15:12:47 +0100 Subject: Is there a bright future for open software projects? Message-ID: <3DE783EF.16478.4666187@localhost> Hi all, For some time I am thinking about what firms or programmers can afford to develop open/free software. I myself have been using free programming languages ( Perl and now Python) for about 4 years.But it seems to me very difficult to develop free software because either I can program only when I have free time and then the development is going very slowly or someone must pay for the software anyway because programmers must also earn money to live and then why and who should pay for free software? And my question: Is it possible to develop open(FREE) software that is better or at least of same quality like paid software? What companies like ActiveState.com or similar live on if they offer free software? Best regards and thanks to all who still develop FREE software. Ladislav From ebe at offworld.com Mon Nov 18 12:13:22 2002 From: ebe at offworld.com (ebe) Date: Mon, 18 Nov 2002 17:13:22 -0000 Subject: Insanely simple problem somehow appears impossible References: Message-ID: <7d9C9.1654$p_2.164894@newsfep1-win.server.ntli.net> Thanks for the reply Alex. I was already using this code and I still had a problem. I think I have found the solution to the problem and will post the results here in case someone else wonders what's going on. I solved the problem by changing the message handler for the window class from a message map system to a WindowProc function. The reason why PumpWaitingMessages was stalling was because it seems that windows messages were not being handled, and therefore never being removed from the message queue. Consequently the function never returned as there were always messages waiting. "Alex Martelli" wrote in message news:QgxB9.18105$744.647072 at news1.tin.it... > ebe wrote: > > > I am using the win32 extensions to implement a simple message loop. What I > > want to do is respond to messages if they are incoming, but process an > > application update function if there are no messages. > > You can pattern a solution for this based on the code you'll find at: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82236 > > > Alex > From python at rcn.com Sat Nov 9 20:34:58 2002 From: python at rcn.com (Raymond Hettinger) Date: Sat, 9 Nov 2002 20:34:58 -0500 Subject: indexed looping, functional replacement? References: <3fe406f0.0211091037.2795e538@posting.google.com> <9Xcz9.15450$XO.672555@news2.tin.it> Message-ID: > > I would like a simpler approach to avoid having to manually maintain > > an index, maybe functional if possible. > > In Python 2.3, the enumerate built-in will do just that: > > [alex at lancelot alf]$ python2.3 > Python 2.3a0 (#4, Nov 6 2002, 09:18:17) > [GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> for x in enumerate('ciao'): print x > ... > (0, 'c') > (1, 'i') > (2, 'a') > (3, 'o') > >>> In Python 2.2.2, you can roll your own enumerate: >>> from __future__ import generators >>> def enumerate(seq): i = 0 for elem in seq: yield (i, elem) i += 1 >>> list(enumerate('later dude')) [(0, 'l'), (1, 'a'), (2, 't'), (3, 'e'), (4, 'r'), (5, ' '), (6, 'd'), (7, 'u'), (8, 'd'), (9, 'e')] Raymond Hettinger From anthony at interlink.com.au Fri Nov 1 08:06:13 2002 From: anthony at interlink.com.au (Anthony Baxter) Date: Sat, 02 Nov 2002 00:06:13 +1100 Subject: What the heck has happened to PythonWin??? In-Reply-To: Message-ID: <200211011306.gA1D6EN13136@localhost.localdomain> >>> Robin Munn wrote > The way to be a guinea pig is simple: > > 1. Go to http://spambayes.sourceforge.net/ > 2. Follow the CVS instructions to get the most recent code > 3. Sign up on the spambayes mailing list > 4. Run around on your hamster^H^H^H^H^H^H^Hguinea-pig wheel! There's now an 'applications' page on the spambayes web site with pointers to what you need to do. From maney at pobox.com Sat Nov 23 14:24:33 2002 From: maney at pobox.com (maney at pobox.com) Date: Sat, 23 Nov 2002 19:24:33 +0000 (UTC) Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DD8F24F.6050006@web.de> <3DDA7260.4050905@nyc.rr.com> <2259b0e2.0211210838.7647301a@posting.google.com> <2259b0e2.0211220946.5f61f641@posting.google.com> <3DDE711E.3010005@web.de> <2259b0e2.0211230554.1cde87bb@posting.google.com> Message-ID: Michele Simionato wrote: > language, according to different phylosophies. Here it is the solution > I came out in Python in two seconds of thinking, the "natural" > solution at this stage of my knowledge of Python: > > def print_OS_evaluation(): > "Gives a thought evaluation of operating systems" > > import sys > > def GoodBox(): > print "This is a good box" > > def BadBox(): > print "This is a bad box" > > def UnknownBox(): > print "This is not a box" > > printEvaluation={ > 'linux2':GoodBox, > 'sunos5': GoodBox, > 'win32':BadBox}.get(sys.platform,UnknownBox) > > return printEvaluation > > The code is pretty obvious ... Seems overelaborated to me. Why in the world invent functions to print a string? (of course it is even sillier to invent entire classes to print a string, but that seems to have been an unstated requirement for the Java examples: goodness increases with classes, whether sensible or not?) def print_OS_evaluation(): import sys osGood = 'a good box' osBad = 'not a box' osUnknown = 'unknown' osEvaluation = { 'linux2': osGood, 'sunos5': osGood, 'win32': osbad } return 'This is %s' % osEvaluation.get(sys.platform, osUnknown) Or to be really analogous to the Java versions, change 'return' to 'print'. Is this less extensible than the far more elaborate 'best' Java version? My take on it is that that SOO+PS version is certainly the most over-built, adding layers of complexity that the problem description certainly doesn't require in order to... well, to what? It allows extension, but how is it easier to extend that than the above? Why, it requires you to modify two things in two separate files! It does allow easier customization of behavior per-OS, but since there's no need for that, this seems like premature overgeneralization, which may be the root of most OO programming evil. :-/ Not that I'm opposed to generalizing a solution in general, but as the Java examples demonstrate pretty clearly, there is usually a cost associated. AndOfCourse those examples did have the unstated requirement of being "classy" in order to allow the predetermined hierarchy to be imposed on them. Which is a complaint I've had with a large portion of all OO examples that are designed to meet pedagogical ends without also being required to be sensible. Remember all those stunningly stupid attempts to shoehorn animals as classes into a pretty single-inheritance hierarchy of classes? Pfui! > Very ugly, but these languages (I refer to the old Basic of the early > 80's I learned as my first programming language, or Fortran 77 which > is unfortunately still too much used in the scientific environment) > don't allow you to do much more than that. You cannot simply *think* > of another solution. I thought there were ways to install tables of data in both [fairly] early Basics as well as FORTRN, but they were both a long time ago and I may be mixing in memories of improved versions of both (Ratfor, mostly, in the case of FORTRN). > On the other hand, was I working in Pascal or C, where "case" and > "switch" constructs exist, I would have certainly used them. The code > would have been less ugly, and more adapted to these languages, not > simply a translation from Basic. With less excuse, but I follow your thinking. This problem would certainly have become an exercise in switch in any C language text. > When I learned Python I discovered dictionaries and I immediately get > in love with them; I started using dictionaries from my first > programs. I could probbaly tell an anlogous story with a few substitutions. "associative arrays" and "AWK" would seem to be the key ones. :-) > I want to comment on OOP, too. As a I said in a previous posting, I > am still in the process of learning OOP. At this state of my > knowlegde, I tend to think that OOP is a great idea, but sometimes > overkill and too verbose. I remain very pleased that I took some time to learn about OOP by diving into a Smalltalk implementation. I have always thought that it was good to be forced to use OO methods, at least for an experienced procedural programmer, but seeing just how an ideological purity leads to contrived solutions that just aren't needed in a mixed-mode language seems more and more relevant these days. > That's the reason why even if the original > code in http://csis.pace.edu/~bergin/patterns/ppoop.html used a > class, I prefer to use a function instead. It seems to me that, for > simple tasks, functions are still better and easier to grasp. When there's no reason to invent a class except that the pure OO language *requires* all functions to be hidden away inside one class or another... This is exactly the problem with language purity; I suppose Lisp would be the poster child for an escape from such problems, but like you and others who have spoken up here, I have never found it an approachable one. Form *is* liberating, at least as long as it manages not to be excessively restrictive. Or, as Joel's characters put it, balance is the way... > Of course objects have their advantages, but if I don't plan to > inherit from a class doing the job of print_OS_evaluation, why should > I use a class at all ? Ah. Classes are also useful as an organizing principle - they give a form to the solution that it might not otherwise have, or which anyway would not be so visible. A problem whose solution needs one small lookup table wrapped with very little code behind a single, simple interface needs little if any such elaboration. Like any form, classes can be ill-suited to some problems, so it's good to be able to choose *not* to use them. > Functions are shorter and easier to maintain, in my view. Still, the > biggest issue I have with OOP is a syntactical one: too verbose for > my taste. If OOP is too verbose, then either it's being applied where it is not a good choice - those Java examples fit here - or perhaps the language manages to support OOP badly. Or both. From 2002 at weholt.org Tue Nov 26 07:55:54 2002 From: 2002 at weholt.org (Thomas Weholt) Date: Tue, 26 Nov 2002 13:55:54 +0100 Subject: Simple SQL-statements into Python classes Message-ID: Has anybody made an attempt at converting simple SQL-statements ( mainly plain selects ) into Python objects? I'm thinking of trying to make a parser that takes the most basic version sql-statements (select, insert, update, delete) and convert them into a python class with methods like load, insert, save and delete. If anybody has anything similar or have opinions on this matter, please let me know. Best regards, Thomas From tismer at tismer.com Thu Nov 7 13:59:57 2002 From: tismer at tismer.com (Christian Tismer) Date: Thu, 07 Nov 2002 19:59:57 +0100 Subject: PySol Windows binaries, anyone? Message-ID: <3DCAB82D.3060008@tismer.com> Dear Python Community, my wife is unhappy. She used to play PySol for years. Recently, I tried to install the latest version, but didn't get it to work. Unfortunately, I wiped the old installation before. :-( It is known that Markus lost his Windows stuff, there is no more an installer (no problem), and a couple of Windows specific functions are missing. That's the problem. Does somebody have a working PySol for me? Or maybe one of the last working installers is still around? I'd also put this on my website for people to download. Markus seems to be no longer reachable by email. As the last resort, I also could write the missing C functions, but I really hope somebody has them still around. I'm also not sure what else is missing. many thanks in advance - 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 pager +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 max at alcyone.com Sat Nov 9 22:46:02 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 09 Nov 2002 19:46:02 -0800 Subject: Why is Python popular, while Lisp and Scheme aren't? References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <3DCD8571.6CACEA04@alcyone.com> Message-ID: <3DCDD67A.8B8DEE97@alcyone.com> Syver Enstad wrote: > On another note, I think the Smalltalk method call (keyword message > send) > syntax is fabulously readable, why haven't anybody picked that up? > Code like this is marvelously more understandable than the usual > position based argument list that one uses in Lisp and C. > > Ex: > > aCircle paintOn: aCanvas at: aPoint Objective-C uses basically this same syntax, albeit surrounded by brackets. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Can I walk with you / Through your life \__/ India Arie Kepler's laws / http://www.alcyone.com/max/physics/kepler/ A proof of Kepler's laws. From beyer at incent.com Sun Nov 10 01:01:45 2002 From: beyer at incent.com (Hugh Beyer) Date: Sun, 10 Nov 2002 01:01:45 -0500 Subject: PyUnit lacks gravity? Message-ID: I'm trying out PyUnit as a framework for my tests and am finding it tough going... I'm sorry but it doesn't seem like TSTTCPW to *me*. Right now I think I'm creating tests correctly and a test suite correctly, but when I run it with a TextTestRunner instance I get the following dump: Traceback (most recent call last): File "C:\\Jumanji\\AdSelectorTest.py", line 355, in ? unittest.main() File "C:\Python21\lib\unittest.py", line 663, in __init__ self.runTests() File "C:\Python21\lib\unittest.py", line 700, in runTests result = self.testRunner.run(self.test) File "C:\Python21\lib\unittest.py", line 603, in run result.printErrors() File "C:\Python21\lib\unittest.py", line 568, in printErrors self.stream.writeln() File "C:\Python21\lib\unittest.py", line 513, in writeln self.write('\n') # text-mode streams translate to \r\n if needed File "C:\PYTHON21\Tools\idle\PyShell.py", line 676, in write self.shell.write(s, self.tags) File "C:\PYTHON21\Tools\idle\PyShell.py", line 662, in write self.text.mark_gravity("iomark", "right") AttributeError: 'None' object has no attribute 'mark_gravity' Last I checked, gravity here was Earth normal. I'm running unitttest.main() to set up the suite, but I get the same error if I create and run the test suite myself. Any ideas what's going wrong? This is python2.1 running in IDLE on a Win2000 system. Thanks. Hugh From nhodgson at bigpond.net.au Sun Nov 3 01:01:56 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sun, 03 Nov 2002 06:01:56 GMT Subject: Using windll with complex data types References: <8beb91f5.0211020556.30107507@posting.google.com> <0qxMNUAyh+w9EwJw@jessikat.fsnet.co.uk> <8beb91f5.0211021858.4739bd5f@posting.google.com> Message-ID: Ben C: > API short int __stdcall GetVersion( VERSION *lpVersion ); > ... > # If I Feed This Into The Builtin Struct Function > struct.unpack( 'l', '\x03\x00\x02\x00' ) Which is likely to mean version 2.0.3 as version numbers often encode their parts in separate bytes. > # I End Up With A Nonsense Number > (131075,) == 0x20003 Neil From gerhard.haering at gmx.de Wed Nov 20 20:07:55 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: Thu, 21 Nov 2002 02:07:55 +0100 Subject: DNS server in python In-Reply-To: <200211211106.44776.bhards@bigpond.net.au> References: <200211211106.44776.bhards@bigpond.net.au> Message-ID: <20021121010755.GB1172@gargamel.ghaering.test> * Brad Hards [2002-11-21 11:06 +1100]: > So I'm looking for a DNS server in python, if it is already written. > [...] Twisted (http://www.twistedmatrix.com/) claims to support both DNS clients and servers. Twisted is an asynchronous framework for writing network clients and servers. This means you have to build your app around the concept of event handlers. Judging from the sample code (I've not yet used it in real life), this isn't more difficult than the simple-minded create-a-new-thread-for-every-new-connection approach I did for my servers. But it's quite a different way of writing networked apps that requires getting used to. -- Gerhard PS: I've recently read a related interesting article by one of the folks behind Twisted - "Threads considered harmful": http://www.kuro5hin.org/story/2002/11/18/22112/860 From tjreedy at udel.edu Fri Nov 15 12:56:09 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 15 Nov 2002 12:56:09 -0500 Subject: A really bad idea. References: Message-ID: "Paul Foley" wrote in message news:m2of8rgg5j.fsf at mycroft.actrix.gen.nz... > >>>> a = [(1,2,3,4),(5,6,7,8)] > >>>> zip(zip(a)) > > [(((1, 2, 3, 4),),), (((5, 6, 7, 8),),)] > > How did you get that? I get > > >>> a = [(1,2,3,4),(5,6,7,8)] > >>> zip(a) > [(1, 2, 3, 4), (5, 6, 7, 8)] On what system/build? Cutting and pasting your entered data... Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a = [(1,2,3,4),(5,6,7,8)] >>> zip(a) [((1, 2, 3, 4),), ((5, 6, 7, 8),)] >>> zip(*a) [(1, 5), (2, 6), (3, 7), (4, 8)] TJR > > and, not surprisingly, > > >>> zip(zip(a)) > [(1, 2, 3, 4), (5, 6, 7, 8)] > > so it works there. And now > > >>> b = zip(*a) > >>> b > [(1, 5), (2, 6), (3, 7), (4, 8)] > > and > > >>> c = zip(*b) > >>> c > [(1, 2, 3, 4), (5, 6, 7, 8)] > > and > > >>> c == a > 1 > > > > Oh, I see; I wrote a zip function in my startup file before it was a > builtin, and I've never taken it out...the builtin version does as you > say in the first example (but why? Looks like a bug, to me!) > > -- > Whenever you find that you are on the side of the majority, it is time > to reform. -- Mark Twain > > (setq reply-to > (concatenate 'string "Paul Foley " "")) From nikolai.kirsebom.NOJUNK at siemens.no Wed Nov 6 08:41:41 2002 From: nikolai.kirsebom.NOJUNK at siemens.no (Nikolai Kirsebom) Date: Wed, 06 Nov 2002 14:41:41 +0100 Subject: RecordSet (ADO) with stored procs References: <9seiru8fasolrqd9ntpgb0pp0lsl7fr83c@4ax.com> Message-ID: Yes I'm very interested. Been away for some time - thats reason for no response. Thanks for all response. On Tue, 29 Oct 2002 17:53:35 GMT, Syver Enstad wrote: >nikolai.kirsebom.NOJUNK at siemens.no writes: > >Replace: >> cmd.CommandText = '_GetUserName' >with: >cmd.CommandText = '{call _GetUserName(?, ?, ?, ?, ?, ?)}' > >Replace : >> cmdCommandType = constants.adCmdStoredProc >with >cmdCommandType = constants.adCmdText > >If I don't remember wrongly you can then just refresh and assign to >the in parameters. > >By the way: >I have a pretty complete pure python implementation of the v.2.0 >db-api that is based on ADO. If you are interested, I can fish it out >from somewhere. It has a pretty complete unit testing suite, so that >you can see how it is supposed to be used. From wlfraed at ix.netcom.com Thu Nov 21 21:03:11 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Thu, 21 Nov 2002 18:03:11 -0800 Subject: Popular conceit about learning programming languages References: <3d5b5ad8.0211080454.50bc6128@posting.google.com> <2259b0e2.0211210838.7647301a@posting.google.com> Message-ID: <093kra.3n3.ln@beastie.ix.netcom.com> Brad Hards fed this fish to the penguins on Thursday 21 November 2002 02:55 pm: > > The big thing I don't yet really get is OO. I don't see solutions in > terms of classes yet. In the natural language analogy, this is the > equivalent of never come across a tonal language (for those not > familiar, this is very roughly where the meaning (in a denotational > sense, not just a connotational sense) of a sound varies with how it > is pronounced - the same sound with a rising frequency might be a > verb, while a flat frequency might be a noun). No OO is a big hole, > and while I can program using classes (in C++ and Python) a little > bit, I don't really "see the solution" in those terms yet. > Unfortunately, OO is not a language specific feature... It is a whole philosophy of how to look at a problem. While not easily done, one /can/ apply OO to even FORTRAN applications. I'll admit I tend to have difficulty applying OO to abstract things (like records in a database ). Much easier to learn by applying to real-world objects. Are you familiar with RPN calculators? (mainly because I don't want hassle with the ugliness of arithmetic/algebraic/algebraic-with-parens processing). The simplest RPN calculator has a 4-entry stack, a display, 10 digit buttons, a decimal button, four functions, clear, and an enter button. Objects are: button, stack, display. Stack object has "methods" "push" and "pop" (with internal data for the stack itself) push does: shift the stack data save new value display.display(value) pop does: str = stack value shift stack data (duplicate top of stack) return str Display object has "display" method (do whatever is needed to drive display) Button object has sub-classes of "digit" (include decimal here for simplicity), "operator", "enter", "clear" Digit buttons, when pressed perform essentially the following: str = stack.pop append