From db3l at fitlinxx.com Wed May 23 16:39:02 2001 From: db3l at fitlinxx.com (David Bolen) Date: 23 May 2001 16:39:02 -0400 Subject: threads References: Message-ID: "lrobb" writes: > I have a global timer thread that cycles an event every 20 minutes. > > When I stop the program via (Ctrl-C), this thread doesn't die. > > How can I stop him? Python will do an explicit .join() operation on every thread object that is alive as it tries to exit, except for those that are marked as "daemon" threads. There are two main possibilities: * Provide a mechanism to notify your timer thread that it should exit (the thread itself has to exit, it can't be externally killed) and use it when you are stopping. * Declare the thread to be a daemon (use the setDaemon Thread method) when it starts and then Python will ignore it on exit and leave it up to the OS to clean up (which is probably just fine in your case since it doesn't sound like the thread is managing resources that you need to wind down "nicely" or anything) > According to the threading docs, I can't : > "Python's Thread class supports a subset of the behavior of Java's Thread > class; currently, > there are no priorities, no thread groups, and threads cannot be destroyed, > stopped, > suspended, resumed, or interrupted" > > Whats up with that? You can't externally kill a thread (there have been various discussions here about that, but it's generally not a good idea because it can lead to inconsistent process state) but you can have a thread do any of these things to itself. Typically, a mechanism is implemented (via events, or queues, or some other communication scheme) by which a thread is notified from the main application that it should (stop, suspend, resume, etc...). -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From charlie at begeistert.org Sat May 19 10:09:36 2001 From: charlie at begeistert.org (Charlie Clark) Date: Sat, 19 May 2001 16:09:36 +0200 Subject: pythonic tree-walking idioms References: Message-ID: Tim Peters wrote: > [Fredrik Lundh] >> os.path.walk is pretty unpythonic, imo [1]. > > Mine too, and, luckily for us , also Guido's: last time this > came up, > he said he considers os.path.walk to be a youthful indiscretion. I'm > sure it > will never go away, but I never steer people toward it either. > Thanx for the tip. I was wondering why I never understood os.path.walk and always religiously copy, paste and change what I think is appropriate. Tell Guido he's forgiven!! Charlie From cwebster at nevada.edu Sun May 27 13:28:57 2001 From: cwebster at nevada.edu (Corran Webster) Date: Sun, 27 May 2001 10:28:57 -0700 Subject: Powersets of a list? References: <9els3j$2kap$1@ID-11957.news.dfncis.de> Message-ID: <270520011028579603%cwebster@nevada.edu> In article , Walter Vannini wrote: > This also seems to do it: > > def PowerSet2( PowerSetSoFar, element): > return [i+j for i in PowerSetSoFar for j in [ [], [element] ] ] > > def PowerSet( set ): > return reduce (PowerSet2, set, [ [] ]) > > print PowerSet([1,2,3]) Refining this a bit and putting it into one function gives: def PowerSet(list): PowerSetSoFar = [[]] for element in list: PowerSetSoFar += [i+[element] for i in PowerSetSoFar ] return PowerSetSoFar which may be the best solution offered so far. For MacPython 2.1 on a 400 Mhz B&W G3 running OS X, this is comparable to or slightly better than the recursive algorithm given by David Urlich. Running the same code on the same machine using Unix Python compiled for OS X, the above code is the fastest by a small but distinct margin. What is more interesting, perhaps, is that the times were more than twice as slow in the Unix version, expect for Emile's algorithm which ran faster! Moral: your mileage may vary. Corran (but list comprehensions are nice) ---- MacPython results: range(15): bitshifting1 4.4 bitshifting2 4.95 recursive1 0.333333333333 recursive2 0.283333333333 comprehension1 0.283333333333 comprehension2 0.266666666667 bitshifting1 4.51666666667 bitshifting2 4.68333333333 recursive1 0.35 recursive2 0.266666666667 comprehension1 0.266666666667 comprehension2 0.283333333333 range(18): recursive1 6.06666666667 recursive2 2.3 comprehension1 2.33333333333 comprehension2 2.23333333333 recursive1 2.83333333333 recursive2 2.33333333333 comprehension1 2.35 comprehension2 2.21666666667 Unix Python results: range(15): bitshifting1 3.56 bitshifting2 7.09 recursive1 0.69 recursive2 0.65 comprehension1 0.75 comprehension2 0.54 bitshifting1 3.74 bitshifting2 6.87 recursive1 0.69 recursive2 0.72 comprehension1 0.63 comprehension2 0.54 range(18): recursive1 7.22 recursive2 7.22 comprehension1 7.96 comprehension2 6.88 recursive1 7.46 recursive2 6.77 comprehension1 7.73 comprehension2 6.63 ---- import time # Emile van Sebille def toggle(pattern): if pattern[-1] == 0: pattern[-1] = 1 else: pattern[-1] = 0 pattern[:-1] = toggle(pattern[:-1]) return pattern def genNibbles(qty): rslt = [[0]*qty] for i in xrange(2**qty - 1): rslt.append(toggle(rslt[-1][:])) return rslt def bitshifting1(set): incl = genNibbles(len(set)) sq = range(len(set)) rslt = [] for i in incl: sset = [] for j in sq: if i[j] == 1: sset.append(set[j]) rslt.append(sset) return rslt # Alex Martelli def bitshifting2(L): N = len(L) return [ [L[i] for i in range(N) if X&(1L< <9biukr$lu8$1@nntp9.atl.mindspring.net> <9cqpq9$dvm$1@nntp9.atl.mindspring.net> <9d53ku$o9j$1@slb6.atl.mindspring.net> <9d5rc6$l5q$1@nntp9.atl.mindspring.net> <9d61os0i05@news2.newsguy.com> <9d92fo01thk@news2.newsguy.com> Message-ID: "Rainer Deyke" writes: > "Douglas Alan" wrote: > > Regarding the parentheses thing -- I don't know why some people don't > > like that. I think that if people had an open mind, they would see > > that Lisp's notation has its own beauty. On the other hand, many > > people don't have an open mind; for instance, many people I've talked > > to summarily dismiss Python merely on the basis that it uses > > whitespace to determine nesting. > I think it has less to do with abstract "beauty" and more with the > way the human brain processes information. I'm more dyslexic than most, and I can say with surety that for me Lisp's syntax is easier to process than that of most programming languages, with perhaps the exception of Python. > In Python (and to a lesser degree most other programming languages), > the shape of a program gives you a lot of informtion about its > structure. This is certainly true of Lisp too. Because Lisp has so many parentheses, Lisp programmers know that good indentation is very important. Consequently, the parentheses end up looking rather translucent once you get used to the syntax and you end up reading the code a lot like you'd read Python code -- by its shape. > This is not true in Lisp. Given a form '(a b)', you can't even tell > if 'b' is evaluated without looking at 'a'. But all you have to do is look at 'a' to tell what the form is. This makes things easier to process. In Scheme, for instace, you can instantly tell that this is an assignment: (set! long-variable-name1 long-variable-name2) In Python, the equivalent is long_variable_name1 = long_variable_name2 This means that you have to scan down to see the "=" before you even know what kind of statement it is, while in Lisp you know right away. In C, it's even worse, where you have things like longDataTypeName longVariableName; If you've never heard of "longDataTypeName", you might have to stare at the above for quite a bit of time to even be able to figure out what type of statement this is. > More generally, you can't tell if anything is evaluated without > looking every single enclosing form. This is the result of only > having a single all-purpose syntactic form to express anything and > everything. I agree that it would have been better if there had been a different syntax for special forms and for function calls, to make determining the difference between the two a bit easier. Perhaps something like this: [define (fact x) [if (= x 1) 1 (* x (fact (- x 1)))]] Instead of (define (fact x) (if (= x 1) 1 (* x (fact (- x 1))))) |>oug From ron.l.johnson at home.com Wed May 9 00:57:19 2001 From: ron.l.johnson at home.com (Ron Johnson) Date: Wed, 09 May 2001 04:57:19 GMT Subject: socket.recvfrom() & sendto() References: <35jhft8tkhe3japncq3fbbbo0eg4ip5lqa@4ax.com> Message-ID: Courageous wrote: > >>Not to pick a nit, but doesn't execution stall at select() if >>there is no data coming in to the server. For example: a small >>chat server when no one happens to be chatting. > > Asyncronous event-driven programs of this sort typically solve > this by initiating a time thread which then writes a wakeup connect > through one of the file descriptors which select is listening on; > the file descriptor is usually set up early for just this purpose. Ahhh. So many details... -- Ron Johnson, Jr. Home: ron.l.johnson at home.com Jefferson, LA USA http://ronandheather.dhs.org "Is Python better or worse than Perl?" "Perl is worse than Python because people wanted it worse." -Larry Wall, 10/14/1998 From mwh at python.net Sat May 12 08:51:35 2001 From: mwh at python.net (Michael Hudson) Date: 12 May 2001 13:51:35 +0100 Subject: new.instancemethod References: Message-ID: James_Althoff at i2.com writes: > Does anyone know what the "class" argument -- arg 3 -- to > new.instancemethod is for? It doesn't seem to serve any "real" purpose other than documentation. That's probably "real" enough, though. Cheers, M. -- "The future" has arrived but they forgot to update the docs. -- R. David Murray, 9 May 2000 From ben.hutchings at roundpoint.com Fri May 11 17:53:15 2001 From: ben.hutchings at roundpoint.com (Ben Hutchings) Date: 11 May 2001 14:53:15 -0700 Subject: Range Operation pre-PEP References: <98OK6.9793$sk3.2667317@newsb.telia.net> Message-ID: "Fredrik Lundh" writes: > maybe we should ask him: Ben, did you really mean that Python > won't let you abuse lists and tuples? or where you just describing > a well-known best practice? I certainly didn't mean that Python won't let you 'abuse' them (I wouldn't go so far as to say 'abuse', anyway). I only meant that I believed there were differences in intended usage that went beyond mutability. -- Any opinions expressed are my own and not necessarily those of Roundpoint. From scarblac at pino.selwerd.nl Thu May 3 04:29:41 2001 From: scarblac at pino.selwerd.nl (Remco Gerlich) Date: 3 May 2001 08:29:41 GMT Subject: mxDateTime: does strptime not exist? References: Message-ID: Remco Gerlich wrote in comp.lang.python: > The docs also say: "Availability: most modern Unix systems". > Windows simply doesn't have the function. > > Andrew Markebo made a pure Python version you can use (LGPL license): > http://www.fukt.hk-r.se/~flognat/hacks/strptime.py Actually, I didn't notice you were doing it with mxDateTime (the Unix comment is from the time.strptime doc in the Python lib ref). But the answer still mostly holds, I think. The time tuple that strptime.py returns can be converted with DateTime.mktime(tup). -- Remco Gerlich From see at my.signature Thu May 31 23:45:29 2001 From: see at my.signature (Greg Ewing) Date: Fri, 01 Jun 2001 15:45:29 +1200 Subject: wanted. english word. References: <3B15D6C1.9B496BE8@my.signature> <3B16738A.C1EE10C7@san.rr.com> Message-ID: <3B170FD9.E343E30A@my.signature> Darren New wrote: > > My complaint is with the animations that keep going even when the > process they represent isn't. Yes, I agree that kind of animation is worse than useless. Whatever you use to indicate progress, it should represent REAL progress! The tricky part is coming up with a way of measuring progress that is both meaningful and reasonably smooth. I hate it when e.g. the progress bar zips quickly up to about 25%, sits there for half an hour, and then suddenly jumps the rest of the way... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From lac at cd.chalmers.se Wed May 9 07:53:11 2001 From: lac at cd.chalmers.se (Laura Creighton) Date: Wed, 9 May 2001 13:53:11 +0200 (MET DST) Subject: Why aren't we all speaking LISP now? Message-ID: <200105091153.NAA23427@boris.cd.chalmers.se> Datapoint: Most people in the late 1970s and early 1980s at the University of Toronto were not in the computer science program because they wanted to become academics, computer scientists, but rather because they wanted to become programmers. They were in there for the same reason that people studied Dentistry, or Law -- they wanted a Profession, not to be a Law Professor or a Professor of Dentistry. The Computer Science department, at the University of Toronto, on the other hand, was not staffed by Professional Programmers, indeed, as far as I know they did not have a single one on the staff. (But it would be hard for me to find out, as I will explain in a bit.) And as a result, the required Lisp course at U of T was taught by Computer Scientists, who more-or-less Math Academics, to a student body which was comprised of what would become Tim O'Reilly's customer base -- the people who buy all the O'Reilly books. This is an incredibly bad fit. The students, almost without exception, wanted hands-on-experience. They wanted examples. And they wanted to write code. The professors wanted to talk about concepts -- they wanted to do computer science, and (in my view quite reasonably), took the position that if you didn't like this sort of stuff, then you didn't like computer science, and maybe you should do something else. The problem was that although there was, and still is a desparate need for a Professional Faculty of Programming -- there wasn't one. The students had no place else to go. I found all of this out by accident. I was a _physics_ undergraduate major. By the end of first year, all undergraduate physics years had about 45 students in them. (The rest of the 200 people who started out first year had found something else to do.) You knew everybody in your year, the other years, all the grad students and the professors. We had our own study area, a huge room, which had a lock, which we had keys to, where we could keep our stuff, and most of us had keys to the physics buildings, cause we were all supposed to be doing research in them -- the sorts of things that I only later realised other undergraduates did not have at all, and were privledges only given to graduate students. To all extent and purposes we *were* grad students, except that we didn't know all that much. Then something unexpected and interesting happened. The computer science building burnt down. And the computer science grad students had no home. (Some of them had no research as well, that having burnt as well.) So various parts of the rest of the university had to make room for groups of them. In physics, we undergrads got the AI students. They hadn't lost their research, it being done on the DEC 10 where we physicists worked (before we bought our vaxen) so they could use Stanford AI Lisp -- SAIL. So they were happy, and indeed said their new digs were an improvement on the old ones in many ways. And in something like 3 weeks they had transformed absolutely every physicist there who had any interest in computational physics at all into a passionate Lisp enthusiast. But after hacking LISP for a year or so I thought, hmm, I really ought to go take some computer science courses. So I did. BIG SHOCK. There were _thousands_ of computer science undergraduates in every year. Courses were taught in classrooms of size 200. And there were dozens of professors who were all teaching the same course in slightly different ways so that the students produced booklets which ranked them on teaching ability so you could avoid teachers who were considered hard. I only found out about the booklets later, because I used a different strategy -- I asked the AI people `which one of these guys knows the most cool stuff?' and thus ended up in the course taught by the guy with one of the lowest student rankings. I had a great time. Acing the course helped, and having computer science professors suggesting that I change my major to computer science made my already over-large ego swell to unbelievable proportions. (Which made later discovering that nobody outside of the University of Toronto gave a damn about my Lisp Macros a very good thing for me, though unbelievably painful at the time.) But I could immediately recognise that just about every other student in the course was having a very hard time because they needed, not a stiff dose of theory right off the bat, but lessons in how to program in LISP. Most of these people had only ever programmed in one language before, a PL-1 like thing that some U of T professors had written for teaching. And to top it off, the University was just converting from teaching undergraduate computing on punch cards to using terminals. How on earth they taught LISP on punch cards, which they _did_ is beyong me. The very idea is obscene. So we were split into study groups of about 15 and I took mine up to `my office' (desk) and gave a short course in HOW TO PROGRAM in LISP. And discovered that I could not live without my Macro library. And that I had no idea whatsoever what was standard LISP, what was the extentions the AI heads used, and what were physics macros Tim, Mark, Brian and I had made over the summer. But after we worked that out, the rest of the people in my study group didn't have that much trouble with the course, because they could concentrate on the theory and not on how to code. I think that it is very very difficult to learn how to code in LISP if you have only used PL-1, and that only for 6 months at most while getting stiff doses of theory in all your courses at the same time. I remember compiler-writing was a concurrent course, and that they were supposed to write it in the PL-1 variant. (I took that course, but later, and I brought my own physicist friends with me, and we point-blank said that we weren't interested in writing a compiler unless we could do so in LISP. Which the department allowed, in hindsight I think out of astonishment.) If this experience is in any way typical of computer science teaching, no wonder we aren't all using LISP today. I haven't used LISP in 15 years, but I still _dream_ in LISP sometime, and this whole thread has reminded me how much I miss it. I got an incredible rush of pleasure, and _memories_ when I first disovered that in python I could write _this_ apply(eval('widget.' + d['functionName']),(), d['functionArgs']) What sort of teaching did the rest of you that took computer science courses get? Laura Creighton lac at cd.chalmers.se From rnd at onego.ru Wed May 2 00:39:40 2001 From: rnd at onego.ru (Roman Suzi) Date: Wed, 2 May 2001 08:39:40 +0400 (MSD) Subject: Formatting numbers In-Reply-To: Message-ID: On Wed, 2 May 2001, Roman Suzi wrote: Ooops! >Maybe: > print "%i.%02i" % divmod(x, 100) Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/ _/ Wednesday, May 02, 2001 _/ Powered by Linux RedHat 6.2 _/ _/ "Cats have nine lives - but sleep through eight of them." _/ From bit_bucket5 at hotmail.com Sun May 6 10:31:12 2001 From: bit_bucket5 at hotmail.com (Chris Stromberger) Date: Sun, 06 May 2001 14:31:12 GMT Subject: HTMLizing scripts References: <1eremuh.1fo42071y8e8i6N%p.agapow@ic.ac.uk> Message-ID: On Wed, 2 May 2001 23:40:42 +0100, p.agapow at ic.ac.uk (Paul-Michael Agapow) wrote: > >What are people using to make webpages of their scripts nowadays? I've >looking at py2html and it produces handsome results, but it uses regex >and seems (under very quick examination) to have problems on my Mac >under Python 2 ... I've noticed that py2html doesn't always handle comment lines well--sometimes just the first token on a comment line is colorized as a comment. I found a nice short and simple script that seems to work very well. It uses the built in tokenizer module instead of regular expressions. It's at http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52298 -Chris From cribeiro at mail.inet.com.br Thu May 31 18:58:30 2001 From: cribeiro at mail.inet.com.br (Carlos Ribeiro) Date: Thu, 31 May 2001 19:58:30 -0300 Subject: O(n^2) is bad - can it be fixed? Message-ID: <5.0.2.1.0.20010531195829.025f2e60@mail.inet.com.br> Just an idea - isn't a paged array better suited for this kind of stuff? It would scale pretty well. I do remember that Unix has a similar structure for disk block allocation. For small lists a single lookup is needed; for large ones a few extra lookups could be compensated by avoiding the realloc() performance hit. Of course, we assume that the problem is related to the list structure itself. The list elements are still subject to their own allocation policies. Also bear in mind that operations such as insertion and deletion could take a potentially bigger performance hit. However, I feel that such operations should not be an issue anyway, at least for large arrays; the only way we can remotely hope of performing them efficiently (for large lists) is using linked lists, or other more complex data structures. Just my $.02 worth. Carlos Ribeiro From thomas.heller at ion-tof.com Tue May 29 16:08:34 2001 From: thomas.heller at ion-tof.com (Thomas Heller) Date: Tue, 29 May 2001 22:08:34 +0200 Subject: subject encoding: What's =?ISO-8859-1?Q? References: <3b14fbae.947829@news.muenster.de> Message-ID: <9f0vhv$1ma4c$1@ID-59885.news.dfncis.de> "Martin Bless" wrote in message news:3b14fbae.947829 at news.muenster.de... > I've started investigating how Barry Warsaw's 'mimelib' works. > (Version 0.2, http://mimelib.sourceforge.net/). Great, with mimelib I > can build mime-messages from scratch and the package offers a lot to > learn from. For example, the subject of the message can be set by > msg.['subject'] = 'Greetings!' > > However, if I create a message with Outlook Express (Windows) and the > subject has some german Umlaute ("Viele Gr??e"), the subject looks > like this: > Subject: =?ISO-8859-1?Q?Viele_Gr=FC=DFe?= > > (1) What kind of encoding is this? Hhm, especially the =?ISO-8859-1?Q? > part? Somewhere in the RFCs? > > (2) And do we already have a function in the Python lib to generate > this encoding? > Sure, its called mimify.mime_decode_header(text) > Martin > Thomas From lac at cd.chalmers.se Sat May 26 18:36:41 2001 From: lac at cd.chalmers.se (Laura Creighton) Date: Sun, 27 May 2001 00:36:41 +0200 (MET DST) Subject: newbie question Message-ID: <200105262236.AAA05551@boris.cd.chalmers.se> Like this? lac at ratthing-b246:~$ python Python 2.1 (#3, May 26 2001, 17:43:53) [GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2 Type "copyright", "credits" or "license" for more information. >>> front='daily_' >>> back='count' >>> daily_count=12345 >>> eval(front+back) 12345 >>> Laura From andrew_dot_henshaw_at_earthling_dot_net Wed May 2 01:12:25 2001 From: andrew_dot_henshaw_at_earthling_dot_net (Andrew Henshaw) Date: Wed, 2 May 2001 01:12:25 -0400 Subject: what's in a name (was Re: using lambda to print everything ina list) References: Message-ID: "Roman Suzi" wrote in message news:mailman.988716062.28371.python-list at python.org... ...snip... > If Python is going to syntactically support subprocess (thread) scheduling > and synchronization, then all features are to be added at one time, making > them more consistent. Or we will have a very messy language. > > I'd presonally liked features of Occam in Python, but introduced > consistently. > Emphatically seconded. By the way, I have a library of Python 'Occam-like' constructs that I use for multithreading, if anyone is interested. From root at rainerdeyke.com Tue May 1 21:11:50 2001 From: root at rainerdeyke.com (Rainer Deyke) Date: Wed, 02 May 2001 01:11:50 GMT Subject: Surprising (for me) benchmark results... References: Message-ID: "Daniel Berlin" wrote in message news:mailman.988762570.8591.python-list at python.org... > Actually, the sort is probably not the bottleneck. > As the file gets larger, the bottleneck becomes disk time, not sort time. Disk access is O(N); sorting is typically O(N log N). Therefore as the number of entries in the file size increases, the time taken by the sort becomes more significant and the time taken by disk access becomes less significant. This is assuming that the file fits into memory (as was the case here). -- Rainer Deyke (root at rainerdeyke.com) Shareware computer games - http://rainerdeyke.com "In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor From tim.one at home.com Fri May 11 20:20:19 2001 From: tim.one at home.com (Tim Peters) Date: Fri, 11 May 2001 20:20:19 -0400 Subject: Range Operation pre-PEP In-Reply-To: <9dhoak02oav@news1.newsguy.com> Message-ID: [Rainer Deyke] > I can't think of a single function in the standard library which > takes an unbounded number of heterogenous arguments. I can think > of several which take an unbounded number of homogeneous arguments. > 'min' and 'max' for example. [Tim] > ? > > >>> import sys > >>> min(1, 1.0, [1], "one", {1 :1}, sys.stdin) > 1 > >>> > > I suppose those are homogeneous arguments in the sense that they're > all objects, but if that's the degenerate sense we're using then I > don't know what heterogeneous could mean. [Alex Martelli] > Isn't it (Python 2.1 at least) "homogeneous in the sense they're all > COMPARABLE"...? Ya, I suppose that's what Rainer did mean, because he's not in the habit of making vacuous stmts and we have to pick *some* meaning for a word that isn't normally used when discussing Python. It's a peculiar meaning for homogeneous, though, because it's impossible to say whether a collection of objects is "homogeneous" in this sense, given only the collection of objects: it depends also on the uses that will be made of them. Then I still don't like accepting it, because it reduces heterogeneous to meaning "some collection of objects that *can't* be used in a given context" -- and heterogeneous is clearly a wrong word for that. If we're trying to talk about conformance to a protocol, I strongly suggest using variants of "conform" instead . > ... > Python doesn't formally define interfaces/protocols ("yet", he > adds hopefully:-), but "informally" it has them -- here, it seems > to me that the objects min/max accept need to "implement > OrderedComparable" (be adaptable to protocol "compare by > < &c") in the typical informal Python sense of interfaces and > protocols/'implements' and 'adaptable to'... Heh heh: I just looked at the implementation. Turns out that a given collection of objects may be "homogeneous" for min() but not for max(), or vice versa: min() only invokes __lt__, max() only __gt__. If Python needs one of those but doesn't find it, it will try the other one with the arguments swapped: class C: def __init__(self, i): self.i = i def __lt__(self, other): return self.i < other.i def __repr__(self): return "C(%d)" % self.i c6, c42 = C(6), C(42) print min(c6, c42) print max(c6, c42) prints C(6) C(42) despite that only __lt__ is defined. But give C a silly __gt__ too: def __gt__(self, other): raise ValueError("screw you!") and it displays C(6) Traceback (most recent call last): File "minmax.py", line 16, in ? print max(c6, c42) File "minmax.py", line 12, in __gt__ raise ValueError("screw you!") ValueError: screw you! So the definition of "max homogeneous" gets correspondingly more convoluted. not-to-say-useless-ly y'rs - tim From sasha at spuni.is Sat May 26 11:54:32 2001 From: sasha at spuni.is (Sasa Zivkov) Date: Sat, 26 May 2001 15:54:32 -0000 Subject: Distributed computing in Python - Callback howto ? In-Reply-To: Message-ID: Hi, What options one have for distributed computing in Python ? I would like to do something like: def call_me_back(): print "callback" s = ServerOnAnotherMachine("hostname.domainname") s.RunLongRunningProcess(call_me_back) ServerOnAnotherMachine is a class that represents connection to a server. RunLongRunningProcess is a method implemented on server. What I want is to pass a callable object to the long running process so it can notify my client code about the progress. I have tried XML-RPC but it appears not to support callbacks. Maybe SOAP or Corba or something else ? -- Sasa From kkto at csis.hku.hk Tue May 22 22:47:48 2001 From: kkto at csis.hku.hk (Isaac To Kar Keung) Date: 23 May 2001 10:47:48 +0800 Subject: O(n^2) is bad - can it be fixed? References: <3B09FBF9.8691EBFE@accessone.com> <9ed4kr01877@enews1.newsguy.com> <7iheydfza5.fsf@enark.csis.hku.hk> Message-ID: <7ieltgg4rv.fsf@enark.csis.hku.hk> >>>>> "Ben" == Ben Hutchings writes: Ben> As the list buffer grows, realloc() will at some point find that Ben> the only place to put it is at the top of the heap. Once it's Ben> there, further realloc() calls will grow the heap and will not need Ben> to move the buffer. However, other systems - those with a shared Ben> memory space, or without a smart implementation of realloc() - are Ben> likely to behave differently. Yes, I postulated that before. But it is proven otherwise by my last example. (Did you see why I have two arrays growing rather than just one?) Regards, Isaac. From nessus at mit.edu Fri May 4 02:49:58 2001 From: nessus at mit.edu (Douglas Alan) Date: 04 May 2001 02:49:58 -0400 Subject: Choosing a programming language as a competitive tool References: Message-ID: "Steven D. Majewski" writes: > On Fri, 4 May 2001, Courageous wrote: > > IMO, Lisp is "inherently difficult" the same way Perl is. Sitting down > > and reading Lisp code written by various programmers will often > > result in reading what appears to be almost another language each > > time. > That's not a bad comparison: to Perl. But as a few others have said: > Writing Perl is easy -- it's going back and reading what you've > written 6 weeks later that's tough! ( Someone else (Tim?) said: I > find it easier to read someone else Python code than to read my own > Perl code 6 months later. ) Lisp is definitely easier to write than > to read. I still think Python is easier. But Lisp is probably > easier, or at least not more difficult than most. I just can't see this comparison of Lisp to Perl. Lisp was the easiest language I ever learned, except for Python, which was about equivalently easy. I can pick up Lisp programs I wrote 20 years ago and read them like I wrote them yesterday -- and I haven't programmed in Lisp in 16 years. It is elegant, flexible, and powerful. Some people don't like it because it has a funny syntax. Everyone is entitled to their opinion, but I find that a bit superficial of a reason. Once you get used to Lisp's syntax, it becomes very natural. Perl, on the other hand, I find to be the most atrocious thing on the planet. It's completely baroque and convoluted. Programs I wrote yesterday seem like I wrote them 20 years ago. |>oug From cmedcoff at home.com Wed May 23 12:03:12 2001 From: cmedcoff at home.com (Charles Medcoff) Date: 23 May 2001 09:03:12 -0700 Subject: Extending Python with C/C++ on a win32 platform References: Message-ID: <1a241b9d.0105230803.1eebf403@posting.google.com> I'm probably not the best guy to respond but I've dabbled at this and here is what I've learned. I wrote a very simple extension using SWIG and I suggest that this is an easier way to start. I wrote some C++ classes and used swig to generate code for an extension DLL and a shadow class (the SWIG doc's explain this) and found that it was pretty straight forward. Now my "toy attempts" where some pretty simple examples but I found that I didn't have to write any code specific to Python, SWIG just took care of all of that. I put it all into a VC++ 6 project and compiled. Out popped my DLL, I put it in the PYTHONPATH and I was off and running. I'll go back and see if I can find my code and email it to you if I find it. Good Luck, Charles Medcoff From nick at microsoft.com Thu May 17 10:56:12 2001 From: nick at microsoft.com (Nick Benton) Date: Thu, 17 May 2001 15:56:12 +0100 Subject: Final CfP: BABEL Workshop on Multilanguage Infrastructure and Interoperability Message-ID: <3b03e694@news.microsoft.com> BABEL'01 FINAL CALL FOR PAPERS First Workshop on Multi-Language Infrastructure and Interoperability http://research.microsoft.com/~nick/babel01.htm Satellite to PLI'01 Firenze, Italy, 8th September 2001 Submission Deadline: 1st June 2001 ** The Submission Site is now open ** http://cmt.research.microsoft.com/BABEL01/ AIMS AND SCOPE Recent years have seen a resurgence of interest in multi-language tools and intermediate languages, and in interoperability between programs and components written in different programming languages. Shared infrastructure such as code generators, analysis tools and garbage collectors can greatly ease the task of producing a high-quality implementation of a new programming language, whilst being able to interoperate easily with code written in existing languages is essential for such an implementation to be useful in practice. This workshop aims to bring together researchers and developers working on multi-language integration. Contributions are welcome on topics including, but not limited to: * Compilation of high level languages to common executable formats such as Sun's Java Virtual Machine, the DRA's ANDF or Microsoft's .NET Common Language Runtime. * Defining and using bindings for component middleware such as OMG's CORBA or Microsoft's COM. * Language constructs to support interoperability between different languages, particularly from different paradigms (e.g. OO/functional). * Multi-language backends for compilation and/or analysis (e.g. MLRISC, FLINT, C--, TAL, SUIF). * Type theoretic and semantic foundations for multi-language work. * Multi-language development environments and tools (e.g. debuggers, profilers). Submissions may address any programming paradigm. Experience papers which describe the use of multiple languages in application development are also welcome. Authors unsure of the appropriateness of a potential submission should email the PC chair (nick at microsoft.com). PROGRAMME COMMITTEE Nick Benton (chair) Microsoft Research Fergus Henderson University of Melbourne Andrew Kennedy (organiser) Microsoft Research Greg Morrisett Cornell University Martin Odersky Ecole Polytechnique Federale de Lausanne John Reppy Bell Labs Andrew Tolmach Portland State University David Wakeling University of Exeter INVITED SPEAKERS Zhong Shao Yale University IMPORTANT DATES Deadline for submission 1st June 2001 Notification of acceptance 9th July 2001 Final version due 10th August 2001 SUBMISSION DETAILS Papers should be at most 14 pages and should be submitted in Ghostscript-compatible PostScript or PDF format and be printable on both US letter and A4 paper. Authors are strongly encouraged to use ENTCS style files (see http://math.tulane.edu/~entcs/). Papers should be submitted electronically via the submission site at http://cmt.research.microsoft.com/BABEL01/ Submissions should not overlap significantly with work which has already been published or submitted to any other conference or journal. An informal proceedings will be published as a technical report and distributed at the workshop. It is intended that a final proceedings will be published in a volume of ENTCS. From pearu at cens.ioc.ee Sun May 20 09:10:12 2001 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Sun, 20 May 2001 15:10:12 +0200 (EET) Subject: ANN: PyVTK Message-ID: I am pleased to announce first release of PyVTK-0.3: http://cens.ioc.ee/projects/pyvtk/ PyVTK provides tools for manipulating VTK files in Python: VtkData - Create VTK file from Python objects. It fully supports VTK File Formats Standard 2.0. The features includes: *** ascii and binary output *** DataSet formats: StructuredPoints, StructuredGrid, RectilinearGrid, PolyData, UnstructuredGrid *** Data formats: PointData, CellData *** DataSetAttr formats: Scalars, ColorScalars, LookupTable, Vectors, Normals, TextureCoordinates, Tensors, Field PyVTK is tested to work with Python versions 2.1, 2.0, and 1.5.2. Thanks, Pearu Peterson

pyvtk 0.3 - Manipulate VTK files in Python (21-May-01) From wolfson at uchicago.edu Fri May 25 01:03:44 2001 From: wolfson at uchicago.edu (Ben Wolfson) Date: Fri, 25 May 2001 00:03:44 -0500 Subject: [FP] Rewriting name bindings as expressions References: Message-ID: <20010525.000344.771151432.2660@bur-jud-175-024.rh.uchicago.edu> In article , "Dr. David Mertz" wrote: > Greg Ewing wrote: >> ans = [y+1 for x in range(10) for y in (x*x,)] > > Wow. Richard had written me before posting to the list, and I did not > have any idea for improving on his examples. I don't think this form > would have ever occurred to me... but now that I see it, I am simply > shocked by its obviousness and clarity. Another one that doesn't really rebind y is ans = [y(x)+1 for y in (lambda a: a*a,) for x in range(10)] -- Barnabas T. Rumjuggler I had a son once, I ain't got no son today My son is gone now, my son is gone, oy weh -- Joe Frank, "Woman and Bull in a Paint Factory" From graham_guttocks at yahoo.co.nz Tue May 1 20:10:26 2001 From: graham_guttocks at yahoo.co.nz (Graham Guttocks) Date: Tue, 1 May 2001 17:10:26 -0700 (PDT) Subject: function to check whether a variable already exists? In-Reply-To: Message-ID: <20010502001026.37179.qmail@web10301.mail.yahoo.com> Lyle Johnson wrote: > if not globals().has_key("NEWSRC"): > NEWSRC = os.path.expanduser("~/.newsrc") This is easy enough I suppose, thanks all! Regards, Graham __________________________________________________ Do You Yahoo!? Yahoo! Auctions - buy the things you want at great prices http://auctions.yahoo.com/ From vonWedel at lfpt.rwth-aachen.de Fri May 25 01:36:04 2001 From: vonWedel at lfpt.rwth-aachen.de (Lars von Wedel) Date: Fri, 25 May 2001 07:36:04 +0200 Subject: Python and Autoconf References: <3B0AACD0.654DE0A5@enabledventures.com> Message-ID: <3B0DEF44.CBE3811@lfpt.rwth-aachen.de> Hi, Martin von Loewis wrote: > While I believe that you can solve your problems with autoconf, you > may consider using distutils for the Python parts. That has a > convenient procedure for building and installing Python libraries, > both for Python and C modules. > > [...] > > You can still integrate distutils nicely into a make(1) driven build > procedure, see Python 2.1 for an example. Is there any way to properly integrate distutils as part of an automake driven process, too? I.e. would it respect settings for compilers, directories and such? Lars -------------- next part -------------- A non-text attachment was scrubbed... Name: vonWedel.vcf Type: text/x-vcard Size: 289 bytes Desc: Card for Lars von Wedel URL: From Gareth.McCaughan at pobox.com Thu May 24 17:03:25 2001 From: Gareth.McCaughan at pobox.com (Gareth McCaughan) Date: Thu, 24 May 2001 22:03:25 +0100 Subject: What can you do in LISP that you can't do in Python References: <3B0C6440.388358B7@my.signature> <9eieut$8ov@dispatch.concentric.net> Message-ID: Paul Foley wrote: [Mikel Evins:] > > (let* ((count 0) > > (incrementer #'(lambda () (setq count (1+ count))))) > > (defmacro counting-setq (var val) > > `(progn > > (funcall ,incrementer) > > (setq ,var ,val) > > ,count))) > > > What it does is this: it defines a new version of SETQ called > > 'counting-setq'. This new operation does the same thing that SETQ does: it > > sets the value of a variable. But it does something else, too: it counts how > > many times you call it and saves the current count in a variable that nobody > > but counting-setq can see or affect. When it sets a variable it increments > > the current count and then returns it. > > No it doesn't; it returns the number of times it got called prior to > this particular expansion. Er, no. The incrementer gets called by the expanded code, not by the macro expander. (counting-setq foo 1) ==> (progn (funcall incrementer) (setq foo 1) count) (modulo symbol capture). The incrementing happens at runtime. The mistake you said Mikel was making is a common one, but he didn't make it. :-) -- Gareth McCaughan Gareth.McCaughan at pobox.com .sig under construc From mal at lemburg.com Tue May 15 07:37:21 2001 From: mal at lemburg.com (M.-A. Lemburg) Date: Tue, 15 May 2001 13:37:21 +0200 Subject: how to store a date in a file with mxDateTime References: Message-ID: <3B0114F1.32431A0F@lemburg.com> Scott Hathaway wrote: > > Here is what I am trying to do: > > 1. store a date in a file. > 2. compare the dates to see if today + 15 days is greater than the date > from the file. > > (I am implementing a timeout in a program if not registered). > > I am using the mx.DateTime library, but I cannot seem to get the following > comparision to work because the dateFromFile is a string. > > todayPlus15Days = DateTime.today() + 15 > if (todayPlus15Days > fileFromDate): You have to convert the string fileFromDate to a DateTime instance first... e.g. DateTimeFrom(fileFromDate) should do the trick in most cases. > I have tried the RelativeDateFrom(fileFromDate) method and > DateTimeFrom(fileFromDate) method without success. > > Can anyone help? -- Marc-Andre Lemburg ______________________________________________________________________ Company & Consulting: http://www.egenix.com/ Python Software: http://www.lemburg.com/python/ From boswell at ugcs.caltech.edu Tue May 22 20:01:51 2001 From: boswell at ugcs.caltech.edu (Dustin Boswell) Date: Tue, 22 May 2001 17:01:51 -0700 Subject: is it safe to stop a thread? Message-ID: <3B0AFDEF.44E29573@ugcs.caltech.edu> I'm writing a client that needs to access various web sites periodically, but the problem is that every once in a while a network glitch will happen so that urlopen() hangs forever (hitting CTRL-C shows it was on a read() ). This is similar to using Netscape and having to click "stop" and then "reload" on a page that won't fully load. I would like to keep using urllib to do my web interface (as opposed to doing low level asynchronous sockets) and so my first thought is to use threads. The "threading" module doesn't allow stopping, so that seems useless. But the "thread" module DOES. Am I going to get myself into trouble starting and stopping threads that are busy doing network i/o? If the number of parallel connections remains small (like around 10), would you maybe suggest separate processes (which CAN be stopped)? Has anyone out there written a robust web crawler in Python that got around this problem? Thanks for any advice. -Dustin. From tim at worthy.demon.co.uk Fri May 25 03:17:46 2001 From: tim at worthy.demon.co.uk (Tim Howarth) Date: Fri, 25 May 2001 08:17:46 +0100 Subject: List append vs add Message-ID: <7a3014804a%tim@worthy.demon.co.uk> Is there any difference in result, performance or stylistic approval ('niceness') of; list.append('fred') compared with, list+=['fred'] -- ___ |im ---- ARM Powered ---- From cmg at uab.edu Wed May 30 15:19:03 2001 From: cmg at uab.edu (Chris Green) Date: 30 May 2001 14:19:03 -0500 Subject: speeding up string.split() References: Message-ID: scarblac at pino.selwerd.nl (Remco Gerlich) writes: > Chris Green wrote in comp.lang.python: >> I've tried w/ python 2 and 1.5.2 and the differences between perl and >> python remain huge ( about 5s:1s python:perl ). > > "Huge". It's 4 seconds on 300,000 lines. Since this sort of thing is Perl's > special expertise, I'll admit that I think that Perl has the edge > here. Values of huge depend o > > But does that matter for your application? If it means a minute on each > daily run, it's not worth a Usenet thread :-) I'm currently implementing it in C with a python user interface to a command line app ( unoptimized perl takes a bit too long ). It's minutes on each run everytime I have to do a search ( usually with a cgi ). There are 300,000 lines every 30 minutes so time adds up quickly in an interactive mode, especially to do multiple day investigations. Theres only so many cups of coffee a day I can go get while doing a search :). I do appreciate a lot of the insights on this thread though that have helped me learn more python :). > >> The string is +'d together for usenet purposes > > Hmmmmm. Actually, what happens when you remove the '+' and replace it with a > simple backslash? Two literals in a row may form one literal, but two > strings with a '+' need to be added together every time. I think that this > *may* make a (small) difference. Wouldn't expect it to be at all > significant. Yes, I could have saved a long thread had I written a \ - I've only got a couple thousand lines of python under my belt yet and I use too many languages and broke it up in a way to make it readable (artificially). -- Chris Green From mwh at python.net Thu May 17 18:22:37 2001 From: mwh at python.net (Michael Hudson) Date: 17 May 2001 23:22:37 +0100 Subject: $PYTHONHOME References: <3B03E650.6D33B050@cornell.edu> Message-ID: Matthew Hirsch writes: > I'm using Python on a hp-unix machine. This is what I get when I > type python at the prompt (I added it to my path already). > > $python > Could not find platform dependent libraries > Consider setting $PYTHONHOME to [:] > Python 1.5.2 (#1, Jan 3 2000, 15:54:36) [GCC 2.95.2 19991024 > (release)] on hp-uxB > Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam > >>> > > The python directory is under /usr/local/. I found a directory > /usr/local/python-1.5.2/lib/python1.5/plat-hp-uxB. I'm guessing that > this is the directory for the platform dependent libraries. I tried > adding $PYTHONHOME=/usr/local to my .profile but it didn't make a Try making that $PYTHONHOME=/usr/local/python-1.5.2 ? > difference. Is there a root profile that I need to change? Don't think so. Cheers, M. -- All parts should go together without forcing. You must remember that the parts you are reassembling were disassembled by you. Therefore, if you can't get them together again, there must be a reason. By all means, do not use a hammer. -- IBM maintenance manual, 1925 From sdm7g at Virginia.EDU Fri May 4 11:20:14 2001 From: sdm7g at Virginia.EDU (Steven D. Majewski) Date: Fri, 4 May 2001 11:20:14 -0400 (EDT) Subject: Choosing a programming language as a competitive tool In-Reply-To: Message-ID: Personally, I find Lisp much easier than Perl (especially since I avoid it whenever possible, so I've never really mastered it -- just keep a nodding acquaintence so I can read the scripts I do run into. ) I would agree with all you've said. I just meant: I think Lisp IS easier to write than to read -- especially someone else's lisp code, because styles and idioms can vary a lot. ( The disparity isn't as great as with Perl, but some of the reasons are the same. ) What easier for folks may vary depending on what they already know and how similar what they are learning is to that previous knowledge. ( So *SOME* folks might find Perl easier, even if *I* don't. ) And I was arguing against Courageous' description of Lisp as difficult: despite that personal-fudge-factor cited above, there's NO WAY you can say that Lisp is an order of magnitude more difficult that other stuff -- Java, C++, Perl -- that are widely used, so the argument that Lisp doesn't get used because it's inherently difficult to learn doesn't hold water. ( And if it does seem difficult to some folks it probably, it's more likely a problem with how it's taught than the language itself. ) I think except for the personal-fudge-factor effect, we're in agreement! -- Steve Majewski On 4 May 2001, Douglas Alan wrote: > "Steven D. Majewski" writes: > > > On Fri, 4 May 2001, Courageous wrote: > > > > IMO, Lisp is "inherently difficult" the same way Perl is. Sitting down > > > and reading Lisp code written by various programmers will often > > > result in reading what appears to be almost another language each > > > time. > > > That's not a bad comparison: to Perl. But as a few others have said: > > Writing Perl is easy -- it's going back and reading what you've > > written 6 weeks later that's tough! ( Someone else (Tim?) said: I > > find it easier to read someone else Python code than to read my own > > Perl code 6 months later. ) Lisp is definitely easier to write than > > to read. I still think Python is easier. But Lisp is probably > > easier, or at least not more difficult than most. > > I just can't see this comparison of Lisp to Perl. Lisp was the > easiest language I ever learned, except for Python, which was about > equivalently easy. I can pick up Lisp programs I wrote 20 years ago > and read them like I wrote them yesterday -- and I haven't programmed > in Lisp in 16 years. It is elegant, flexible, and powerful. Some > people don't like it because it has a funny syntax. Everyone is > entitled to their opinion, but I find that a bit superficial of a > reason. Once you get used to Lisp's syntax, it becomes very natural. > > Perl, on the other hand, I find to be the most atrocious thing on the > planet. It's completely baroque and convoluted. Programs I wrote > yesterday seem like I wrote them 20 years ago. > > |>oug > -- > http://mail.python.org/mailman/listinfo/python-list > From kevin04107 at hotmail.com Thu May 24 11:12:46 2001 From: kevin04107 at hotmail.com (k) Date: Thu, 24 May 2001 15:12:46 GMT Subject: Won't use global symbol table? References: <20010522.194123.1450573622.7698@kanchenjunga.mindspring.com> <9efubv023eo@enews1.newsguy.com> Message-ID: This code should do what you intended to do: x = None def f(): global x try: if (x): pass # throws an exception if x does not exist. except: x=1 return x K. "Alex Martelli" wrote in message news:9efubv023eo at enews1.newsguy.com... > "Rob Nikander" wrote in message > news:20010522.194123.1450573622.7698 at kanchenjunga.mindspring.com... > > Shouldn't I be able to say this is a module... > > > > x = None > > def f(): > > # global x > > if not x: > > x = 1 > > return x > > > > Unless I uncomment that global line I get the error: > > > > File "ubtest.py", line 6, in f > > if not x: > > UnboundLocalError: local variable 'x' referenced before assignment From fredrik at pythonware.com Fri May 11 06:51:54 2001 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 May 2001 10:51:54 GMT Subject: Range Operation pre-PEP References: <98OK6.9793$sk3.2667317@newsb.telia.net> Message-ID: Douglas Alan keeps on babbling: > >> In what way did I misrepresent Ben's original claim? I did not. > > > you wrote: > > >> Ben claimed that tuples should only be used when you know how many > >> elements there will be, and that lists should only be used for > >> homogeneous data of unknown length. > > > ben didn't use "should only". you made that up. > > I did not. It is clear from the context that this is what he > intended. did you read his followup message? you're saying that "lists are normally used" is the same thing as "lists should only be used"? that's weird. (but alright, his followup was in response to someone who basically agreed with him, so maybe you didn't bother to read further down that thread...) maybe we should ask him: Ben, did you really mean that Python won't let you abuse lists and tuples? or where you just describing a well-known best practice? > > no, I'm saying that anyone who has written or studied real-life > > python programs knows that tuples don't work well as containers, and > > lists don't work well if you try to use them as records. that's a > > fact, not an opinion. > > A fact, eh? And would you be so kind as to explain this fact. if you're so experienced in Python as you say you are, maybe you can prove me wrong, by posting some code where you use lists and tuples the "wrong" way, and show that it won't work better if done the other way around. (where "better" means better from a software engineering perspective: performance, memory usage, code size, readability, support for different python versions, scalability, maintainability, etc). > When have I ever "trolled"? I have only expressed my opinion, which > is reasonably well-informed, and, I think, worth considering. good for you. Cheers /F From xyzmats at laplaza.org Wed May 30 13:25:26 2001 From: xyzmats at laplaza.org (Mats Wichmann) Date: Wed, 30 May 2001 17:25:26 GMT Subject: Mandrake 8.0 and Idle References: Message-ID: <3b152bf8.15672295@news.laplaza.org> On 30 May 2001 07:54:01 -0400, Alex wrote: > >> When I launch idle under either Gnome or Kde the text is so small it's >> unreadable. It appears to be only idle thats affected > >Have you tried setting the font in ~/.idle? Put something like this in >there: > >[EditorWindow] >font-size = 12 >font-name = -Adobe-Courier-Bold-R-Normal--12-120-75-75-M-70-ISO8859-1 There's also a site-wide config file wherever IDLE got installed called config-unix.txt. I've fount the default font choice to be too small for a "typical" (whatever that means) Linux install. Try 12 as suggested above, at least as a starting point. Quality of fonts is another issue entirely, to generalize, most public-domain fonts aren't very good, and there's quite a bit of work going on on that, both in making better fonts and in rendering the ones we do have a bit better. Mats Wichmann (Anti-spam stuff: to reply remove the "xyz" from the address xyzmats at laplaza.org. Not that it helps much...) From tim.one at home.com Wed May 30 15:27:44 2001 From: tim.one at home.com (Tim Peters) Date: Wed, 30 May 2001 15:27:44 -0400 Subject: Python celebrities photos In-Reply-To: Message-ID: [Oleg Broytmann] > ,,, > I am looking for photos of other our celebrities: Tim Peters, Barry > Warsaw, Jeremy Hilton (in random order, really) and other. Can anyone > provide pointers or just send photos? Thanks in advance. There's a picture of Barry in the top left corner at: http://www.wooz.org/users/barry/ BeOpen.com had the only known photographs of Fred, Jeremy and (an actor hired to play the role of) me. If the PSF ever gets enough funds, perhaps we can buy them back. we-hack-python-photography-is-beyond-us-ly y'rs - tim From meh9 at cornell.edu Mon May 28 17:57:58 2001 From: meh9 at cornell.edu (Matthew Hirsch) Date: Mon, 28 May 2001 21:57:58 +0000 Subject: vi setup for pyton Message-ID: <3B12C9E6.5BFB8FB2@cornell.edu> Hi, I'm trying to setup vi for python. How do I setup vi so that a tab will be four spaces? Thanks, Matt From rnd at onego.ru Tue May 15 11:45:06 2001 From: rnd at onego.ru (Roman Suzi) Date: Tue, 15 May 2001 19:45:06 +0400 (MSD) Subject: Do I really need to learn Java? In-Reply-To: <9dre5f03c@news2.newsguy.com> Message-ID: On Tue, 15 May 2001, Alex Martelli wrote: > "Alan Gauld" wrote in message > news:3B0130D9.38EC274C at bt.com... > > Roman Suzi wrote: > > > I also know that some Java programmers like Java. > > > > Only some? Seems like all the Python programmers I've > > met like Python. Maybe thats a significant difference? > > It may be, but, in the abstract (evincing only from > this couple of tidbits), it's hard to infer exactly > what. Suppose there is a large job-market for Java > programmers, because lots of places are developing > Java programs commercially (for whatever reason). > > Then, the people who end up working as Java coders > may include both those who like the language AND > some who don't but DO like the easy money to be made. > > On the other hand, suppose there is no such job > market for some other programming language, say > for example Intercal. In this case, only the > people who *really LOVE* Intercal will bother to > "be Intercal programmers": there is absolutely no > "side benefit" (such as salaries:-) in so being. > > Then, from the two facts: > only some Java programmers like Java > all the Intercal programmers love Intercal > one should deduce: there is a large job market > for Java programmers, but not for Intercal ones. > > I'm not saying this applies to Python, by any > means -- but, take care in inferring from partial > data such as programmers' liking, or not, the > language they happen to use:-). How true. But by liking Intercal we also like to see more jobs for Intercal programmers! (And hopefully then we could make (easy?) money & like the tool). Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From dalke at acm.org Thu May 3 01:20:16 2001 From: dalke at acm.org (Andrew Dalke) Date: Wed, 2 May 2001 23:20:16 -0600 Subject: do...until wisdom needed... References: <9be84s0q12@news1.newsguy.com> <9bfjoc0cjh@news2.newsguy.com> <9bfq560noo@news2.newsguy.com> <87n19fvdzo.fsf_-_@elbereth.ccraig.org> <9biukr$lu8$1@nntp9.atl.mindspring.net> Message-ID: <9cqpq9$dvm$1@nntp9.atl.mindspring.net> Me: >> Perhaps, but my feeling is that the level of training you need >> for that is greater than most of my clients - chemists and >> biologists - want to go through. Note that since I've never >> used a language (other than Tcl?) with these sorts of macros >> I don't have specific knowledge of the pros and cons. Douglas Alan replied: >Procedural macros are best left to the experienced professional >programmer to implement. The more casual programmer can significantly >benefit from the work of the expert, though. Hmmm. I am an experienced professional programmer, at least for my field. And I don't want to touch procedural macros. From what I've heard from others in private mail, too often non- "experienced professional programmers" end up making their own dialect, and the result is a Babel of code. As one person commented to me: ] If you give people extensible syntax, and Andrew and I adopt ] different dialects of python, then instead of getting a bug ] fix, I will get, '`I am sorry, but I don't have time to learn ] your macro system.' or even worse, `I haven't used regular ] python for so long, that I forget how it works'. This is ] precisely what happened to me [..when I..] decided writing my ] own lisp macros to do physics in was a good idea. It was a ] terrible, terrible, horrible mistake. I doomed myself to ] doing ALL the physics in the world. My main expertise is developing infrastructures that allow widely different tools to interoperate. As such, I aim to reduce the amount of variety so people can work on getting their research done, not figuring out how to use the tools. Nearly everything I hear suggest that procedural macros don't help reduce complexity. I still maintain that having the Python source code available gives at least comparable advantages to procedural macros. If someone wants to implement new behaviour, it can be done without all that much work. The big advantage is that all of these changes don't get propagated willy-nilly. Either you take the hit of distributing a new Python-derived language (as with Alice) or it's good enough that Guido accepts it into the core, in which case it isn't a dialect. In either case, it makes you think strongly about the worth of the new language extension. Yes, doing this required using a non-Python language for the implementation, but as I've said I don't believe in restricting myself to one language. Yes, it reduces the ability of just anyone to modify the language, but you are already saying the only ones qualified to change a language are "experienced professional programmer"s, and they should have no problem with C. Yes, it calls for more work to implement, but I'm not convinced it should be easy. Other ways to get around the lack of procedural macros were mentioned (besides changing the language core): - calling a library function to parse an alternate language - importing the new code via a modified import hook (this could be made easier with the work on a library to build ASTs for Python) - writing a C extension which uses the metaobject interface, as with the Persistence type in Zope. (This can only change the object behaviour.) So who all is affected by the lack of procedural macros in a way that cannot be supported by one of these mechanisms? I suspect it's a small audience. Not to say it wouldn't be an influential audience, just that it would be small. > The same thing is often true for classes That's true. My clients don't have much of a problem using classes/instances, but the ones without much CS training are somewhat hesitant writing their own classes. But the complexity of classes seems to be much less than procedural macros, since people who aren't professional programmers can still learn to write them well enough. Me: >> I can also point out the almost complete nonexistence of a major >> package in computational chemistry or biology written in a language >> supporting hygenic/procedural macros as an indicator that >> *something* prevents their wider use in my field. >There aren't any widely used languages that have procedural macros >other than Lisp and its variants. That's almost my point, but the other way around. If procedural macros are the cat's meow then you'ld think that someone else beside the Lisp'ers would implement it. So either a) new ideas take a long time to become mainstream, so wait another decade, b) the rest of the world is too ignorant/ conservative/ unambitious/ etc. c) there is a problem with the usefulness of procedural macros in mainstream development or d) it cannot be done in any language other than Lisp. My perception of things weighs things more towards c). It seems that you weigh b) stronger than I do, with some complaint about a). I still can't figure out how address the d) part without basically quoting everything, in which case it's identical to having a function that parses a string and exec's the result. >And Lisp only really ever caught on in AI circles >and for teaching programming at finer institutions of higher >education. The reasons for that are complex and I think don't say >much about the pros and cons of procedural macros, or even of Lisp in >general. "finer institutions of higher education"? Seems a rather biased phrase. Bet my alma mater's football team could beat yours! :) And its music department, and its film school, and its synchronized swimming team, and its hospitality management program, and its school of library science ... oh yeah, and its magnet lab (sorry, that's an eight year old jibe :) Andrew "Go 'Noles!" Dalke dalke at acm.org From nomad*** at ***freemail.absa.co.za Thu May 24 04:11:51 2001 From: nomad*** at ***freemail.absa.co.za (nomad) Date: Thu, 24 May 2001 10:11:51 +0200 Subject: extending Python with C anywhere (was Re: Extending Python with C/C++ on a win32 platform) References: <9ege3v02q8p@enews1.newsguy.com> Message-ID: <9agpgtkubpmsrskbkaevp9iqvfr9gvdo6h@4ax.com> On Wed, 23 May 2001 15:31:55 +0200, "Alex Martelli" wrote: >"nomad" wrote in message >news:r84ngtod7bv9qsnevj2sou9sm10a8umqa0 at 4ax.com... > ... >> Are there any other good tutorials, or examples, that are >> aimed at developing extension win32, or even better VC++6? Also, if I > >Easiest is the Boost Python Library at www.boost.org. I > Extensive and very useful example > >But I see that some of the docs are updated to suggest >the two-steps initialization for portability, anyway. > > >There -- hope this helps! > > >Alex > > Thanks to all who responded to my extension question - I will take it all under my belt and give up sleep for the weekend. I must now leave the office to by some really strong coffee..... Thanks again. -- Nomad - always happiest learnin' new stuff.... From paulp at ActiveState.com Tue May 29 12:04:18 2001 From: paulp at ActiveState.com (Paul Prescod) Date: Tue, 29 May 2001 09:04:18 -0700 Subject: Against PEP 240 References: Message-ID: <3B13C881.5021667E@ActiveState.com> This seems like a pretty emotional argument to me. I don't see any technical justifications. Robin Becker wrote: > > I am strongly opposed to the intent of PEP 240. I would prefer the > literal floats to remain. Let those that want infinite precision pay the > price by adding an 'R' to their literals. Why should those that want correct answers pay the syntactic price rather than those that want performance? > This PEP seems purely biassed > towards the needs of naive programmers and I feel that is wrong; this > whole industry has grown up with the old style (and coped quite well). > If naive users are to be the only designers we'll end up badly. Naive users are not the only design target but I think that there is a certain logic in preserving the *simplest syntax* for the naive users and using more sophisticated syntaxes for more complicated ideas. -- Take a recipe. Leave a recipe. Python Cookbook! http://www.ActiveState.com/pythoncookbook From gustav at morpheus.demon.co.uk Wed May 2 18:27:30 2001 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: 02 May 2001 23:27:30 +0100 Subject: ANN: mxNumber -- Experimental Number Types, Version 0.2.0 In-Reply-To: <3AEF2713.E978A3A4@lemburg.com> References: <3AEF2713.E978A3A4@lemburg.com> Message-ID: <3danwg8w.fsf@morpheus.demon.co.uk> "M.-A. Lemburg" writes: > Paul Moore wrote: > > >python > > ActivePython 2.1, build 210 ActiveState) > > based on Python 2.1 (#15, Apr 19 2001, 10:28:27) [MSC 32 bit (Intel)] on win32 > > Type "help", "copyright", "credits" or "license" for more information. > > >>> import mx.Number > > >>> mx.Number.Integer(1500) <= 1 > > 1 > > >>> mx.Number.Integer(1500) <= mx.Number.Integer(1) > > 0 > > > > Does this count as "strange behaviour"? Surely mx.Number.Integer > > values should compare properly with Python integers? > > They do... I get these results with stock Python 2.1: > > >>> from mx.Number import * > >>> Integer(1500) <= 1 > 0 > >>> Integer(1500) <= Integer(1) > 0 Um. I didn't think that ActiveState's version should give differences like this - they're both version 2.1. If this is a genuine difference between the ActiveState version and the one available from python.org, that's a *major* issue! I'll see if I can get the time to install a "stock" Python 2.1 alongside the ActiveState one, and see if I can reproduce this difference. Paul From kkto at csis.hku.hk Fri May 25 23:51:58 2001 From: kkto at csis.hku.hk (Isaac To Kar Keung) Date: 26 May 2001 11:51:58 +0800 Subject: O(n^2) is bad - can it be fixed? References: Message-ID: <7ik834daxt.fsf@enark.csis.hku.hk> >>>>> "Tim" == Tim Peters writes: >> The problem is that whatever the mapping, there is a possible case in >> which copying and reallocation is done basically everytime. Tim> We could, e.g., always round the list size up to the next higher Tim> power of 2. That way the capacity is implicit. We're unlikely to, Tim> though. No, this does not help the situation when the size of the list goes repeatedly below and above the threshold. Tim> Except that it rarely happens at all -- don't overblow this. Yes, it rarely happens. But is the solution really so difficult that we have any excuse not doing it right? Tim> The third possiblity is the one you're not ready for yet: Python is Tim> neither a C library nor an OS, neither is it obligated to provide Tim> theoretically optimal performance in every conceivable case. I see this as a fundamental design problem: it ties the conceptual list to physical memory allocation. The user should have their own right to say that the list is to step between 397 and 398 elements (or whatever number they are in mind), and the performance of the library shouldn't be in completely different orders (e.g., from constant time, linear space to linear time, quadratic space) in such cases. This would make Python completely useless. Tim> Python lists are wonderfully zippy and compact as-is, and doing Tim> anything that hurts either of those would be a net loss for the Tim> vast majority of Python users. The answer is far from the difficulty you've implied. Lists normally contain some hundreds of bytes, and adding 4 bytes there is not that much for anybody. Extra space allocation to the list itself only happens on on PyMem_REALLOC, not if you have initially created the list of the right size. If we ever start doing realloc, it is likely that we continue reallocating anyway. And we can have a compilation flag that activate the structure that don't do geometric scaling by themselves. I don't see how this can possibly "hurt the vast majority of Python users". Regards, Isaac. From BPettersen at NAREX.com Thu May 10 13:23:01 2001 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 10 May 2001 11:23:01 -0600 Subject: ODBC question from Python Newbie Message-ID: > From: uncleleo [mailto:uncleleo at billsfan.net] > > I was attempting to insert a row into a Microsoft SQL server > table. Using > the Sam Rushing's ODBC with DynWin. Inside this table are 3 > fields and all > of them varchars. One of the fields was intended to hold a > root directory, > e.g. c:\service\system.py. > > >>> sql.query('insert into app..application (Designator, > Script) values > (8885551212, c:\\service\\test.py)') > 37000 > [Microsoft][ODBC SQL Server Driver][SQL Server]Line 1: > Incorrect syntax near > 'c:'. > native error 170 > > This one errors. [etc.] Sql strings need to be in single quotes: sql.query("""insert into app..application (Designator, Script) values (8885551212, 'c:\\service\\test.py') """) -- bjorn From Bill.Scherer at VerizonWireless.com Thu May 3 13:24:28 2001 From: Bill.Scherer at VerizonWireless.com (Scherer, Bill) Date: Thu, 3 May 2001 13:24:28 -0400 (EDT) Subject: How to tell a Python program where a shared library is? In-Reply-To: <3AF18F93.4E0784B0@erols.com> Message-ID: use the env. var. PYTHONPATH set it to the dir your module is in. Alternatively, run Python interactively and: >>> import sys >>> sys.path [.... put your module in one of the directories in the resulting list. William K. Scherer Sr. Member of Applications Staff - Verizon Wireless Bill.Scherer_at_VerizonWireless.com On Thu, 3 May 2001, Edward C. Jones wrote: > Suppose I have a shared library, say "mymodule.so". How do I tell a Python > program where "mymodule.so" is? If necessary I can change the PATH environment > variable. How is this done? > > Thanks, > Ed Jones > > > -- > http://mail.python.org/mailman/listinfo/python-list > From aleaxit at yahoo.com Tue May 22 04:50:44 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 22 May 2001 10:50:44 +0200 Subject: cStringIO rules (was Re: O(n^2) is bad - can it be fixed?) References: <3B09FBF9.8691EBFE@accessone.com> Message-ID: <9ed99001e43@enews1.newsguy.com> "Chris Tavares" wrote in message news:aVnO6.8300$9D5.805877 at newsread2.prod.itd.earthlink.net... ... > Another solution would be to use something that IS expected to act like a > buffer - the cStringIO module. The interface is a little different - this > one works like a file: Good point! So I added it to my little measurement script: def AppendTest(listorarray): head = repr(listorarray) start = time.clock() for i in range(0, 100): for x in range(0, 2000): listorarray.append(' ') # print i stend = time.clock() print "%s: %.2f" % (head, stend-start) def AppendTest1(listorarray): head = repr(listorarray) start = time.clock() for i in range(0, 100): for x in range(0, 2000): listorarray.write(' ') # print i stend = time.clock() print "%s: %.2f" % (head, stend-start) AppendTest([]) AppendTest(array.array('c')) AppendTest1(cStringIO.StringIO()) and, whaddyaknow...: D:\py21>python oaat.py []: 1.96 array('c'): 1.57 : 0.86 D:\py21>python oaat.py []: 1.96 array('c'): 1.57 : 0.87 D:\py21> Bingo, another "almost a factor of 2" speedup. Interesting!-) Guido's optimization anecdote may need updating:-). Alex From bos at hack.org Sat May 12 04:32:48 2001 From: bos at hack.org (Rikard Bosnjakovic) Date: Sat, 12 May 2001 10:32:48 +0200 Subject: ordinal not in range(128) References: <3AFBA4BA.B0DDD7B4@teleatlas.com> Message-ID: <3AFCF530.AACF5D8E@hack.org> Ralf Claus wrote: > can you tell me something about this error ? ... > How can i solve this problem ? What error? What problem? What error message? -- Rikard Bosnjakovic - http://bos.hack.org/cv/ - ICQ: 1158217 Anyone sending unwanted advertising e-mail to my address will be charged $250 for network traffic and computing time. By extracting my address from this message or its header, you agree to these terms. From gardner at cardomain.com Sat May 26 01:36:02 2001 From: gardner at cardomain.com (Jonathan Gardner) Date: Fri, 25 May 2001 22:36:02 -0700 Subject: Python vs. Perl In-Reply-To: <20010525202633.R690@xs4all.nl> References: <01052215095105.01539@avatar.cardomain.com> <01052510254209.08900@avatar.cardomain.com> <20010525202633.R690@xs4all.nl> Message-ID: <01052522360200.17547@avatar.cardomain.com> On Friday 25 May 2001 11:26 am, Thomas Wouters wrote: > On Fri, May 25, 2001 at 10:25:42AM -0700, Jonathan Gardner wrote: > > I'm not trying to rile anyone up, I just want to have someone show me > > how Python excels at dictionaries. Frankly, I find python's syntax a > > bit burdensome and wordy. > > You find Python's dict syntax wordy ? Huh ? It's probably the most > consise part of Python ( barring augmented assignment (+=) > :) Okay, you guys got me with the (1, 2):'something' thingy there. That is totally NOT possible in any way shape or form in perl without doing some weird stuff. I mentioned earlier that Perl will burn you when you try to use references as keys. What I meant by wordy is not the simple and basic operations of accessing the value of a key or getting the keys or getting the values... those are straigthforward. However, its the other stuff you do with them, like taking slices or whatever... my mind is dead now... I render this point, along with the others, as conclusive evidence that Python is Better Than Perl (TM). Now I have to hit the books and learn the language. =) BTW - the code that I am working on in the sidelines would be alot simpler if keys could be references! Now I am going to recode it all in Python. Sockets anyone? -- Jonathan Gardner Software Engineer, CarDomain Networks (425) 820-2244 x123 gardner at sounddomain.com From donn at u.washington.edu Mon May 7 19:19:58 2001 From: donn at u.washington.edu (Donn Cave) Date: 7 May 2001 23:19:58 GMT Subject: socket.recvfrom() & sendto() References: <9d6r8d$67o$1@nntp6.u.washington.edu> <4VEJ6.39240$2U.16140998@news2.rdc2.tx.home.com> Message-ID: <9d7aiu$9ic$1@nntp6.u.washington.edu> Quoth grante at visi.com (Grant Edwards): | In article <4VEJ6.39240$2U.16140998 at news2.rdc2.tx.home.com>, Ron Johnson wrote: ... |> So my fundamental question is: how does select() support multiple |> non-blocking TCP sockets, when you can only bind 1 socket to a port? | | The socket you bind to the port is the one that listens for | connections. You call accept() on that one socket you bound to | the port. When a connection request arrives, the accept() call | returns a _new_ socket that's connect to the IP/port address | that sent the request. If you call accept() again *on the same | socket you did the first time* it will wait for another request | to arrive and return another new socket connect to the new | requestor. | | Now you've got three open sockets: the first on that's doing | the listening for new conection requests and the two others | that are connected to something out on the 'net. You do read() | and write() calls on the latter two, and accept() calls on the | former. OK, any decent Berkeley socket implementation will support read() and write() on sockets, but with the Python socket object you must use recv() and send(). And not recvfrom() and sendto(), as suggested by the subject line. That's the source of some confusion in this thread - recvfrom() suggests the connectionless datagram protocol, as in socket.SOCK_DGRAM. With streams, as in socket.SOCK_STREAM, you can use recv(). recvfrom() may work, at least for the common implementations, but you won't get a returned address and don't need one anyway. Donn Cave, donn at u.washington.edu From akuchlin at mems-exchange.org Wed May 9 16:11:46 2001 From: akuchlin at mems-exchange.org (Andrew Kuchling) Date: 09 May 2001 16:11:46 -0400 Subject: Unix [was: do...until wisdom needed...] References: Message-ID: <3dlmo62sfx.fsf@mems-exchange.org> "Steven D. Majewski" writes: > I was seeing pretty massive migration to windows and NT > (well -- in the case of NT, at least a lot of *thinking* > about migrating, if not actual movement) riding on the > back of cheap commodity x86 computers. I suspect that, if Linux hadn't been written, the resolution of the AT&T vs. Berkeley lawsuit would have let some BSD-derived system fulfill the same role. (Someday I have to borrow the time machine and incite someone to write a free Unix for the 386 when it first came out. Unix + X would have been serious competition for Windows 3.x, and we might not be in so much of a software monoculture right now.) --amk From nessus at mit.edu Sat May 5 16:10:57 2001 From: nessus at mit.edu (Douglas Alan) Date: 05 May 2001 16:10:57 -0400 Subject: Choosing a programming language as a competitive tool References: <9cvphc$6f0$3@slb4.atl.mindspring.net> Message-ID: "Andrew Dalke" writes: > I tried learning Lisp from an essay in Douglas Hofstadter's > "Metamagical Themas." I learned to car, cdr and setq, and that was > about it. I couldn't see how to apply that to problems I wanted to > solve (probably because the essays didn't talk about I/O) so I put > it aside for a while. Sounds more like a criticism of Computer Science than of Lisp. Douglas Hofstadter's column was designed to teach you interesting concepts in Computer Science, rather than how to do anything practical. If you'd read a good book on practical programming in Lisp (I don't know if there are any), then you'd probably feel differently. > It's the same reason people use MS Windows over Unix, (or > Unix over VMS for you DEC lovers :) Windoze over Unix? Ugh! Not me. I can't get anything done with Windoze, except spend all day rebooting it. |>oug From dontspamsetzer at nwlink.com Wed May 9 22:10:58 2001 From: dontspamsetzer at nwlink.com (Matt Setzer) Date: Wed, 9 May 2001 19:10:58 -0700 Subject: yesterday's date References: <9dco8r$uno$1@nntp2-cm.news.eni.net> Message-ID: <3af9f8a4_1@news.nwlink.com> Subtract one day (in seconds) from the value returned by time.time(), then convert it to a string. >>> import time >>> ticks = time.time() >>> time.asctime(time.localtime(ticks - 24 * 60 * 60)) 'Tue May 08 19:08:08 2001' >>> "LC" wrote in message news:9dco8r$uno$1 at nntp2-cm.news.eni.net... > Can someone help or direct me in how I can retrieve the exact date one day > ahead? For example if today is 05-09-01, how can I find 05-08-01. I've tried > subtracting one day but when the date is 05-01-01, I get 05-00-01 instead of > 04-30-01. Any information would be appreciated. TIA > > Leo Chen > > From aleaxit at yahoo.com Tue May 1 15:42:24 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 1 May 2001 21:42:24 +0200 Subject: [Python-iterators] Re: PEP 234: Iterators References: <20010501111513-r01010600-c09ebb63@213.84.27.177> Message-ID: <9cn3gd0kkk@news1.newsguy.com> "Guido van Rossum" wrote in message news:mailman.988716782.29093.python-list at python.org... [snip] > iterators. E.g. here's an iterator that gives the even-numbered items > of an argument iterator: > > class EvenIterator: > > def __init__(self, it): > self.it = it If I understand the PEP correctly, wouldn't self.it = iter(it) be better here? Idempotent if 'it' is already an iterator, good if 'it' is a sequence instead? Alex From Davidl at niospammyraqia.com Fri May 4 09:11:50 2001 From: Davidl at niospammyraqia.com (David Lees) Date: Fri, 04 May 2001 09:11:50 -0400 Subject: Threading Question References: <3AF2343B.4A95E856@nospmmytheworld.com> Message-ID: <3AF2AA96.9012690D@niospammyraqia.com> The code I am actually working on is for handeling sockets. I am pretty careful and am passing things in a threadsafe manner between them. Is there any way I can release the lock without writing C code? david lees Erno Kuusela wrote: > > In article <3AF2343B.4A95E856 at nospmmytheworld.com>, David Lees > writes: > > | I am struggling to improve the performance of some python code that has > | 2 threads and runs on a dual processor linux (redhat 7.0) box. I am > | using Python 2.1 and can not seem to get the cpu utilization up above > | 40% for each processor. > > python has a single global interpreter lock, so python code cannot > benefit from multiple cpus. google has more information > if you desire it. > > if someone with access to the faq wizard is listening, this should > probably be added to the faq (i didn't see it there, at least). > > -- erno From dsavitsk at e-coli.net Fri May 4 11:46:31 2001 From: dsavitsk at e-coli.net (dsavitsk) Date: Fri, 4 May 2001 10:46:31 -0500 Subject: Windows editor? References: <3af2c38f.341431824@News.CIS.DFN.DE> Message-ID: wrote in message news:3af2c38f.341431824 at News.CIS.DFN.DE... > On Fri, 04 May 2001 01:21:48 GMT, "Brandon J. Van Every" > wrote: > > >What's a good Python editor for programming under Windows, specifically > >Windows 2000? According to Google archives it seems this question hasn't > >been asked in awhile. > > > > > >-- > >Cheers, www.3DProgrammer.com > >Brandon Van Every Seattle, WA > > > Best one for Windows is PythonWin. I thought this was the *only* answer ... > Sadly, there are no plans to update it. is this true? i'm not going to get stuck using some sort of Python .Net crap am i? doug From jkraska1 at san.rr.com Tue May 1 01:09:45 2001 From: jkraska1 at san.rr.com (Courageous) Date: Tue, 01 May 2001 05:09:45 GMT Subject: who uses Python or Ruby, and for what? References: <9ckva0$qu6$1@news.fas.harvard.edu> <9clfip$pnl$1@nntp9.atl.mindspring.net> Message-ID: >>So, at the risk of being accused of trolling, let me rephrase the >>question-- is anyone using Python or Ruby for anything substantial and >>product-quality, or are these languages only good for writing quick >>little unsupported hacks? Microforte corporation uses Python to extend Big World. Their product is a $7,000,000 investment of resources, and licenses for quite a premium. http://www.microforte.com C// From nperkins7 at home.com Sat May 5 14:14:52 2001 From: nperkins7 at home.com (Nick Perkins) Date: Sat, 05 May 2001 18:14:52 GMT Subject: ActiveState Package Repository down? References: <0BVI6.73057$HF.15816535@news4.rdc1.on.home.com> Message-ID: HTTP 405 - Resource not allowed Internet Explorer ... it's not just you. From lentugo at web.de Tue May 22 17:24:24 2001 From: lentugo at web.de (Ulrich Goertz) Date: Tue, 22 May 2001 17:24:24 -0400 Subject: Tkinter question: menu.add_checkbutton and Win2000 Message-ID: <3B0AD908.6833B6B3@web.de> Hi, I am experiencing a strange behavior of the checkbutton entry in a menu in a Windows2000 box, with Python 2.0 and Tkinter. I hope that someone here has an idea, what might go wrong. I use the Menu.add_checkbutton method to add a checkbutton to a menu. The checkbutton basically works, but it is not displayed correctly. The entry consists of three parts: the indicator (a tick under Windows) which shows the state of the button - the label - and possibly the "accelerator" which shows a shortcut for this button ("Ctrl-A"). In my case, the indicator and the label somehow overlap: either the tick is not displayed correctly, or (after pointing (not clicking) the mouse to the button) the tick covers part of the first letter of the label. This problem occurs even in the simplest test programs. Apart from that, the button is fully functional, so this is a minor issue, but it is still quite annoying. Most so because I have no idea where to look for a solution: is this a Tkinter or a Tk or a Windows issue? (Under Linux and on one Windows95 machine everything worked fine.) Is there a possibility to change the width of the three columns in the checkbutton entry? Any comments appreciated. Ulrich From xyzmats at laplaza.org Tue May 8 12:20:08 2001 From: xyzmats at laplaza.org (Mats Wichmann) Date: Tue, 08 May 2001 16:20:08 GMT Subject: build problem: Python 2.1 on IRIX Message-ID: <3af81b2c.11949202@news.laplaza.org> I've got an old SGI Indy (IRIX 6.2) that I keep around for some testing purposes. Trying to build up 2.1 I ran into some trouble - wondering if anyone has any thoughts.... the binary and libraries built okay, but the setup.py step tipped over as in the following snippet. I have a suspicion: some SGI machines are /not/ 64-bit, even though running what looks like a 64-bit capabable OS (IRIX 6.x). I've run problems with that before. Python 2.0 runs cleanly, but then this is a new step. -- mats PYTHONPATH= ./python ./setup.py build Traceback (most recent call last): File "./setup.py", line 14, in ? from distutils.command.build_ext import build_ext File "/home/mats/src/Python-2.1/Lib/distutils/command/build_ext.py", line 21, in ? extension_name_re = re.compile \ File "/home/mats/src/Python-2.1/Lib/sre.py", line 90, in compile return _compile(pattern, flags) File "/home/mats/src/Python-2.1/Lib/sre.py", line 134, in _compile p = sre_compile.compile(pattern, flags) File "/home/mats/src/Python-2.1/Lib/sre_compile.py", line 368, in compile code = _code(p, flags) File "/home/mats/src/Python-2.1/Lib/sre_compile.py", line 349, in _code _compile_info(code, p, flags) File "/home/mats/src/Python-2.1/Lib/sre_compile.py", line 238, in _compile_info lo, hi = pattern.getwidth() File "/home/mats/src/Python-2.1/Lib/sre_parse.py", line 173, in getwidth self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint)) OverflowError: long int too large to convert make: *** [sharedmods] Error 1 Mats Wichmann (Anti-spam stuff: to reply remove the "xyz" from the address xyzmats at laplaza.org. Not that it helps much...) From m.hadfield at niwa.cri.nz Thu May 10 18:37:44 2001 From: m.hadfield at niwa.cri.nz (Mark Hadfield) Date: Thu, 10 May 2001 22:37:44 +0000 (UTC) Subject: Python Risk References: Message-ID: <001b01c0d9a1$d20fd970$d938a8c0@Hadfield> From: "Bjorn Pettersen" > So you would want to add _all_ that syntax just to save a single '\' > character in typing . Surely you mean a single '\\'. The Python interpreter obviously agrees with me that strings look better without '\'s where possible (oops sorry I mean '\\\'s'): >>> "\"" '"' >>> '\'' "'" > I mean how often do you have quotes in your > strings... Quite often when constructing command lines for os.system etc. But then I use Windows. And-anyway-Fortran-does-it-that-way'ly y'rs --- Mark Hadfield m.hadfield at niwa.cri.nz http://katipo.niwa.cri.nz/~hadfield National Institute for Water and Atmospheric Research -- Posted from clam.niwa.cri.nz [202.36.29.1] via Mailgate.ORG Server - http://www.Mailgate.ORG From unknown at lee-morgan.net Thu May 24 02:30:52 2001 From: unknown at lee-morgan.net (Lee Morgan) Date: 24 May 2001 16:30:52 +1000 Subject: GNU/Linux vs. Windows as Python platform In-Reply-To: "Tim Peters"'s message of "Fri, 18 May 2001 03:56:06 -0400" References: Message-ID: "Tim Peters" writes: > > Well, that, plus for applications period. I don't count developer tools as > applications in this sense: if you ever want to something *other* than > program with your box, Windows is simply loads more fun. Heh: just last > week I was watching some streaming video on my Windows box at work, and Guido > looked over my shoulder and exclaimed "computers can do that now?!". yeah, roll on www.khronos.org... > > they're-still-rebuilding-linux-kernels-trying-to-get-zip-drives-and- > usb-ports-to-work-ly y'rs - tim > > -- Lee Morgan From gtcopeland at earthlink.net Thu May 17 19:46:11 2001 From: gtcopeland at earthlink.net (Greg Copeland) Date: 17 May 2001 18:46:11 -0500 Subject: sys.path after python 2.1? References: Message-ID: "Mark_Pryor" writes: > Greg Copeland wrote in message ... > > > >warning: install: modules installed to '/usr/lib/python2.1/lib-dynload/', > >which is not in Python's module search path (sys.path) -- you'll have to > >change the search path yourself BTW, I did lots of digging and found that the above is nothing more than an installation bug, that is, so says a comment on a reported bug on Source Forge. At any rate, that would explain when messing with the sys.path and/ or using PYTHONPATH doesn't seem to make a difference. > > > >The real issue that I've noticed is that ANY module that is a > >shared object fails to load. For example. I can compile and > >install wxPython without problem, however, if I attempt to use > >the wx module, it says that it's not found. I've tried messing > >around with various items here and there, no matter what, I > >can't seem to get it to function. This doesn't only include > >site modules, rather, even something as simple as importing > >crypt of zlib fails with: ImportError: No module named . > > > >I have some old code that fails to. It says: ImportError: No module named time. > >The odd thing is that time is being imported from the socket module. > > > >I didn't have this problem with 1.5. What's the deal? Help! Where > >do I need to make these changes. BTW, this issue only exists for 2.1. I don't have these problems with 1.5, 1.6, or 2.0. They all work great. 2.1 seems badly broken. > > Hi, > On Windows I do this: > > # from an interactive shell > import sys > import os > sys.path[0] = '' # remove the / in path > < end snip> Thanks. I tried that. In fact, I've tried messing the the path lots using different mechanisms. Thus far, it has no effect. At this point in time, I'm assuming that 2.1 is horrible broken and unfit to be called a "final" release. As far as I can tell, the issue seems to solely resolve around the fact that 2.1 is unable to properly load shared libraries. In fact, these are some of the changes that were being done between 2.0 and 2.1? Right? The fact that this problem didn't exist in previous versions, I think, supports that something was horribly broken in 2.1 as it pertains to shared libraries and Linux. I have reported this bug on Source Forge. I have searched the FAQs and done various web searches on this topic. I can't seem to find anything. I'm assuming because 2.1 hasn't been out long and few people are actually using it yet??? -- Greg Copeland, Principal Consultant Copeland Computer Consulting -------------------------------------------------- PGP/GPG Key at http://www.keyserver.net DE5E 6F1D 0B51 6758 A5D7 7DFE D785 A386 BD11 4FCD -------------------------------------------------- From ben.hutchings at roundpoint.com Wed May 9 20:27:22 2001 From: ben.hutchings at roundpoint.com (Ben Hutchings) Date: 09 May 2001 17:27:22 -0700 Subject: Range Operation pre-PEP References: <3AF8D070.B0ECF09A@my.signature> <9db0u6018es@news2.newsguy.com> Message-ID: Douglas Alan writes: > Speaking of creeping-featurism, how come we have list comprehension, > but not tuple comprehension? Seems inconsistent to me. A list contains a variable number of homogeneous values, e.g. the lines of a file. Lists are like arrays in other languages. A tuple contains a fixed number of heterogeneous values where each element has a distinct meaning e.g. (year, month, day) for a date. Tuples are like data structures or product types in other languages, except that their types and fields are nameless. Comprehensions work with a variable number of homogeneous values, so they produce lists. -- Any opinions expressed are my own and not necessarily those of Roundpoint. From mertz at gnosis.cx Thu May 31 19:24:09 2001 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Thu, 31 May 2001 19:24:09 -0400 Subject: Obsolesence of <> Message-ID: > It is very easy to read "<>" as "is less than or greater than" on the > analogy of ">=" reading "is greater than or equal to." Since all Python > values can be compared, every two unequal things are indeed less than or "Alex Martelli" wrote: | Sorry, you're behind the times: | | Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 | Type "copyright", "credits" or "license" for more information. | Alternative ReadLine 1.1 -- Copyright 2001, Chris Gonnerman | >>> x=2+3j | >>> y=5+8j | >>> x", line 1, in ? | TypeError: cannot compare complex numbers using <, <=, >, >= | | Here, I cannot write x>y, nor xy either, right?-) Yeah. I missed this change. It does reduce the consistency of the iconography. But I still think that the "<>" spelling looks more intuitive than the "!=" spelling by way of its nonetheless greater consistency with the spelling of other operators, as discussed previously. In the end, spelling is arbitrary, of course. But having families of corresponding spellings for corresponding semantics makes it easier to remember a language, and to teach it. FWIW. I'm not really sure I like the change Alex points to. It makes something like the below fail: l = [(1+1j),(2-2j),Klass(),Klass(),Klass,5,4,3,'c','b','a'] l.sort() In a list like this, many of the comparisons have no particular meaning. I have no idea whether an instance of Klass is more than a complex number. And in most cases, I don't even have any idea whether one instance is meaningfully greater than another. But it is nice to have everything have some arbitrary inequality relation in order to create partial orderings on the subsets of things that really do have an order. It makes perfect sense to me to want the numbers and strings to occur in order, even while not caring exactly -where- in the sorted list they occur as a sublist. Is l.sort() a special case that avoids the non-comparison, btw? If so, substitute similar generic comparisons. I don't have 2.1 handy to try out the example. Yours, Lulu... From wolfson at uchicago.edu Tue May 8 13:48:48 2001 From: wolfson at uchicago.edu (Ben Wolfson) Date: Tue, 08 May 2001 12:48:48 -0500 Subject: do...until wisdom needed... References: <9be84s0q12@news1.newsguy.com> <9bfjoc0cjh@news2.newsguy.com> <9bfq560noo@news2.newsguy.com> <87n19fvdzo.fsf_-_@elbereth.ccraig.org> <9biukr$lu8$1@nntp9.atl.mindspring.net> <9cqpq9$dvm$1@nntp9.atl.mindspring.net> <9d53ku$o9j$1@slb6.atl.mindspring.net> <9d5rc6$l5q$1@nntp9.atl.mindspring.net> <9d61os0i05@news2.newsguy.com> <9d92fo01thk@news2.newsguy.com> Message-ID: <20010508.124848.87755422.1040@bur-jud-175-197.rh.uchicago.edu> In article <9d92fo01thk at news2.newsguy.com>, "Alex Martelli" wrote: > IS it widespread? Is the _typical_ CS student, who was taught a CS > course in Scheme at some institution of higher learning, of the "don't > like to have their mind bent" persuasion, to the point of feeling > "resentful of Scheme"?!? Seems a doubtful hypothesis to me -- do others > who know typical US CS graduates first-hand have a more informed > opinion? At the University of Chicago, the first-year programming sequence uses Scheme, C++, and C++ (three quarters). I liked the first quarter far more than the second, and I suspect that were I taking the third I would have liked it more than that,too. I'm not incredibly moved to use Scheme, though, because we didn't really learn how to use the language--nothing about how a package/module system might work--I don't even know if there is one. Nothing about standard libraries. Nothing about user interaction, really, or manipulating files, or a dozen other things. SICP doesn't mention them either. I can't really afford to buy expensive programming books to learn them, interested though I am. -- Barnabas T. Rumjuggler "Et tu, Brute?" sedulous. -- barry in indy, in apihna From akuchlin at mems-exchange.org Mon May 7 11:53:25 2001 From: akuchlin at mems-exchange.org (Andrew Kuchling) Date: 07 May 2001 11:53:25 -0400 Subject: curses -- module cannot be found References: <20010507020143.C375@apone.network.loc> Message-ID: <3du22x2m16.fsf@mems-exchange.org> Kalle Svensson writes: > Not with Python 2.1, AFAIK. 2.1 uses a distutils setup script to > automatically determine what modules to build. The setup.py script *can* guess incorrectly, though, at which point you'd need to edit Modules/Setup. If it guesses wrongly and the original poster believes it should be able to figure out if curses is present, submit a bug report to Python (at http://sourceforge.net/projects/python). --amk From frederic.giacometti at arakne.com Tue May 15 09:06:29 2001 From: frederic.giacometti at arakne.com (Frederic Giacometti) Date: Tue, 15 May 2001 09:06:29 -0400 Subject: Python Un*x build with a Python shared library Message-ID: <3B0129D5.9EB678B1@arakne.com> Hello, Building Python with a shared library on Unix seems to be a recurring issue. I made my homework and scanned the archives. So, let me summarize here what seems to be the issues: When is a unique Python shared library needed? ============================================= -> In situations where Python is embeded in a non-python application, and that the Python thread must be re-entered during callbacks to the application: - the same Python thread must be reentered - there must be a unique Python interpreter lock in the process, and not one different interpreter lock for each copy of the static library that has been duplicated in many places. In such case, using a Python shared library insures that all functions of the process adress the same Python global variables (amongst which the Python interpreter lock, and current thread). Note that on windows, the python library is shared.... At present I know of at least three applications that require Python build on a shared library: JPE (Java-Python extension), Metadynamic (Metaphase-Python integration), and the eMatrix-Python integration (I developped the three of them, actually). What are the problems with building python with a shared library on Unix? =============================================== - Portability, platform-specific features, lack of maturity on some Unix -> Albeit introduced only a few years ago on most Unixes, shared library technology is now reliable and mature on all current Unix platforms (even on HP-UX :)). This should not be an issue anymore on all current Un*x. Issues and impact of a Python shared library build on Un*x ======================================= For what I know: - On Hp/UX and Tru64: works fine - On Linux and FreeBSD: there is the issue with the -export-dynamic option that must be used when building the main executable. Yet, in some situations (e.g. when imbeding Python in Java, as in JPE), you cannot re-link the main executable (Java...). This requires relinking all dynamic Python extension with the Python shared library. Currently, this can be solved by patching the distutil code for this configuration. So, provided that that all dynamic Python extensions are linked to the Python shared library in their build for all platforms (like it is already the case on Windows), everything should be all right. Changes requested on the current Python 2.1 source distribution: ========================================== Changes should be required in only two location: - main Python Makefile - the distutil code that links the dynamic extensions. Progress status: ========== The patch for building Python 2.1 around a 'python2.1' shared library will be requested for running the Java-Python Extension (JPE) on Linux... FG From ddublanc at free.fr Tue May 1 17:08:24 2001 From: ddublanc at free.fr (Dublanc, David) Date: Tue, 01 May 2001 21:08:24 GMT Subject: Differences between Ruby and Python. Message-ID: Hello, I am looking for the differences between Ruby and Python. In which case Ruby is most powerful than Python ? Thanks ! -- David From jkraska1 at san.rr.com Tue May 22 03:44:13 2001 From: jkraska1 at san.rr.com (Courageous) Date: Tue, 22 May 2001 07:44:13 GMT Subject: Messaging in Py? References: Message-ID: <5c6kgt0phdk2mmu8ohipmams74292oc0be@4ax.com> >One reason I'm not enthusiastic about Elvin is that it doesn't >support Python object serialization, only 'primitives' (iirc, >ints, floats, strings -- I guess you could stuff non-bin pickled >objects into string types, but ick!). Take a look at "xml pickle," which pickles a python object to a readible xml representation; it even manages to handle cyclic graphs correctly. >Hey, that's very cool! Maybe you could open source your prototype >and turn it into a community project, ... I've taken step one and created a open source project at sourceforge at http://sourceforge.net/projects/pythonic. Here, I'll be uploading some of my C extensions and things. The reliable UDP messaging layer will have to wait, but I don't see it as much of a problem. C// From mwh at python.net Thu May 10 19:22:49 2001 From: mwh at python.net (Michael Hudson) Date: Fri, 11 May 2001 00:22:49 +0100 (BST) Subject: python-dev summary 2001-04-26 - 2001-05-10 Message-ID: This is a summary of traffic on the python-dev mailing list between Apr 26 and May 9 (inclusive) 2001. It is intended to inform the wider Python community of ongoing developments. To comment, just post to python-list at python.org or comp.lang.python in the usual way. Give your posting a meaningful subject line, and if it's about a PEP, include the PEP number (e.g. Subject: PEP 201 - Lockstep iteration) All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on a PEP if you have an opinion. This is the seventh summary written by Michael Hudson. Summaries are archived at: Posting distribution (with apologies to mbm) Number of articles in summary: 228 40 | [|] | [|] | [|] | [|] [|] | [|] [|] 30 | [|] [|] | [|] [|] | [|] [|] | [|] [|] | [|] [|] 20 | [|] [|] [|] [|] | [|] [|] [|] [|] | [|] [|] [|] [|] [|] | [|] [|] [|] [|] [|] [|] | [|] [|] [|] [|] [|] [|] 10 | [|] [|] [|] [|] [|] [|] [|] | [|] [|] [|] [|] [|] [|] [|] [|] [|] [|] [|] | [|] [|] [|] [|] [|] [|] [|] [|] [|] [|] [|] [|] | [|] [|] [|] [|] [|] [|] [|] [|] [|] [|] [|] [|] | [|] [|] [|] [|] [|] [|] [|] [|] [|] [|] [|] [|] 0 +-007-024-010-001-010-010-044-023-019-010-002-012-017-039 Thu 26| Sat 28| Mon 30| Wed 02| Fri 04| Sun 06| Tue 08| Fri 27 Sun 29 Tue 01 Thu 03 Sat 05 Mon 07 Wed 09 A fairly quiet, but interesting fortnight (and I don't mean the sarcastic replies to the Homepage virus). A few build problems and bugs fixed, and one very involved discussion (cf. most of the rest of this summary). * type == class? * Guido posted a message from Jim Althoff describing the metaclass system used in Smalltalk: He also mentioned a problem that is bound to bite any attempt to heal the type/class split in Python. If there are to be no special cases in the type system then classes and types in particular should be instances. This sounds innocuous, but consider: class MyDictType(DictType): def __repr__(self): return "MyDictType(%s)" % DictType.__repr__(self) The code is hoping that, as in today's Python, DictType.__repr__ will return an unbound method - the __repr__ method of vanilla dictionaries, so that output of the form MyDictType({1:2}) will be given. But DictType is now an instance, so there's another interpretation for DictType.__repr__ - the bound DictType's own __repr__ method! This is a fundamental problem; currently "class.attr" and "instance.attr" have different meanings in Python, and any attempt to conflate the notions of "class" and "instance" is bound to run aground. Guido proposed some hairy disambiguation rules in the above-linked message, but no-one was particularly enthused about them, possibly because no-one could really get their head round them. The long term solution is to change the syntax for getting - or removing entirely - unbound methods. As far as anyone can make out, all that unbound methods are used for is called superclasses' methods from overriding methods, so if one can find another way of spelling that, then removing unbound methods entirely could be contemplated. So the discussion on that went around for a bit, with no really new compelling ideas surfacing. There was some support for some kind of souped up super.foo() construct: To me, the most plausible ideas came from Thomas Heller: and from Paul Dubois, who suggested nicking the feature renaming feature from Eiffel: though the best syntax for the latter is far from clear. There's also the king-sized issue of backwards compatibility; to a first degree of approximation, *all* Python code that uses inheritance would need to be updated to accommodate changes in the meaning of "class.attribute". Another __future__ statement, maybe? * data.decode * Marc-Andre Lemburg asked if it might be an idea if string objects sprouted an .decode method: After some umming and arring and accusations of bloat, this got BDFL approval, and should appear in CVS imminently. * Moving MacPython to sourceforge * Jack Jansen posted notice that he intends to move the MacPython code over to sourceforge: It will be nice to finally have all the code in the same place! Cheers, M. From anma3000 at yahoo.com Wed May 9 14:32:44 2001 From: anma3000 at yahoo.com (toto tuto) Date: Wed, 9 May 2001 11:32:44 -0700 (PDT) Subject: I'm new and need some help!!!!! Message-ID: <20010509183244.13714.qmail@web10301.mail.yahoo.com> Hi my name is Andres Pinzon and i'm writting from Colombia. Lately i've been interested on Python because i've heard about its "power". Someone told me Python is a very good starting language to a person like me (you know i'm a beginner). I don't know much about programming, hardly i do some HTML and "Basic" stuff; what i'd like to know is: if is it possible to become a "Python Programmer" just with this? and where can i find some REAL basic tutorials. THANK YOU.. Andres Pinzon PD.. BY the way! I'd like to keep in touch with "someone outthere", for some "guidance" __________________________________________________ Do You Yahoo!? Yahoo! Auctions - buy the things you want at great prices http://auctions.yahoo.com/ From robin at jessikat.fsnet.co.uk Thu May 31 14:33:02 2001 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 31 May 2001 19:33:02 +0100 Subject: 2.1 strangness In-Reply-To: <15126.34635.67975.31473@beluga.mojam.com> References: <15126.34635.67975.31473@beluga.mojam.com> Message-ID: In message <15126.34635.67975.31473 at beluga.mojam.com>, Skip Montanaro writes >>>>>> "Robin" == Robin Becker writes: > > Robin> from httplib import * > > Robin> class Bongo(HTTPConnection): > Robin> pass > ... > Robin> NameError: name 'HTTPConnection' is not defined > >It was a brain fart on my part when creating httplib.__all__. >HTTPConnection was not included in that list. I will check in a fix. >In the 2.1 release __all__ was defined as > > __all__ = ["HTTP"] > >I have changed that to > > __all__ = ["HTTP", "HTTPResponse", "HTTPConnection", "HTTPSConnection", > "HTTPException", "NotConnected", "UnknownProtocol", > "UnknownTransferEncoding", "IllegalKeywordArgument", > "UnimplementedFileMode", "IncompleteRead", > "ImproperConnectionState", "CannotSendRequest", >"CannotSendHeader", > "ResponseNotReady", "BadStatusLine", "error"] thanks; I'm still a bit puzzled as to the exact semantics. It just looks wrong. Is __all__ the only way to get things into the * version of import? Presumably HTTPConnection is being marked as a potential global in the compile phase. -- Robin Becker From support at internetdiscovery.com Thu May 24 19:57:07 2001 From: support at internetdiscovery.com (Mike Clarkson) Date: Thu, 24 May 2001 23:57:07 GMT Subject: table widget? References: <3B0C31C8.35D882F3@student.kuleuven.ac.be> Message-ID: <3b0d7a15.2467433@24.0.228.33> On Wed, 23 May 2001 21:56:42 GMT, Stijn Gunst wrote: >hi > >i can't find a tablewidget for Python (not even in the Pmw megawidget >module) >how should i visually represent sql-data with those modules? a array of >editboxes seems a bit cumbersome There is a good table widget for Tk called TkTable. You could load the extention from Tkinter using root.tk.eval() and use tk.eval to manipulate it. it should also be relatively straight forward to extend the Tkinter code to "wrap" TkTable. Mike. From rnd at onego.ru Tue May 22 04:03:37 2001 From: rnd at onego.ru (Roman Suzi) Date: Tue, 22 May 2001 12:03:37 +0400 (MSD) Subject: Variable inheritance In-Reply-To: Message-ID: On Tue, 22 May 2001, Oleg Broytmann wrote: > On Tue, 22 May 2001, Roman Suzi wrote: > > MI is in most cases bad. Why not aggregation instead? > > You are certainly wrong! Multiple Inheritance is just plainly > excellent!! > Whan I used Borland Pascal (for about 10 years) I missed MI very badly. > When switched to Python I was excited to use MI. I use it quite often these > days, pretty happily and successfully! :) Can anyone provide an example where MI is used for right purpose, not just to quickly hack something? Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From theller at python.net Mon May 28 12:46:10 2001 From: theller at python.net (Thomas Heller) Date: Mon, 28 May 2001 18:46:10 +0200 Subject: include files with a package References: Message-ID: <3B1280D2.D7C52813@python.net> "Mike C. Fletcher" wrote: > > For python files loaded directly from disk, see the __file__ variable in > your module. Unfortunately, this variable has a habit of being available or > not depending on the phase of the moon (mostly when you pack Python packages > into an exe with Py2EXE or McMillan Installer). This is probably because the __file__ attribute doesn't make too much sense on a module imported from an archive, but OTOH too much breaks if __file__ is not present ;-) Maybe a _documented_ way to determine whether the module is loaded from disk or from an archive would make sense? > When using those, you need > hacks to figure out the .exe's directory (which is, with all known versions > of those systems, sys.path[0] if you don't muck around with the path). Funny, I was thinking about removing this entry from sys.path in py2exe. My plans were to run the py2exe-packed executable with an empty sys.path, and if the script would add something to sys.path this would enable loading modules from the file system... Thomas From just at letterror.com Fri May 18 03:40:44 2001 From: just at letterror.com (Just van Rossum) Date: Fri, 18 May 2001 09:40:44 +0200 Subject: Evaluating python - a question References: Message-ID: <3B04D1F9.875E4C2E@letterror.com> Christian Tanzer wrote: > > Other than that, the suggestion to use accessor methods, instead of > > accessing the datamembers directly, is probably another good tip. > > Accessor methods won't do anything to prevent typos -- you have an > equal chance of mistyping the name of the accessor as mangling the > attribute name. Equal chance of mistyping, yes, but the point was that a typo in an accessor method triggers an exception, whereas simply setting an attribute does not: class Foo: def __init__(self): self.foo = 1 def setFoo(self, value): self.foo = value f = Foo() f.fooo = 2 # no exception f.setFooo(2) # boom Just From pmoscatt at bigpond.net.au Tue May 29 04:37:51 2001 From: pmoscatt at bigpond.net.au (Peter Moscatt) Date: Tue, 29 May 2001 08:37:51 GMT Subject: TIX - I need help Installing References: <3b11ef7b.35957276@24.0.228.33> <1RpQ6.85565$ff.643188@news-server.bigpond.net.au> <3b12d391.8465901@24.0.228.33> Message-ID: Thanks Mike, Still unsure if I need to install each and ecery version of tcl or will just installing tcl 8.2.0 sufice ?? By compiling the Python patches within Tix, will this then update the original version of Python that resides in my /usr/bin directory ? Pete Mike Clarkson wrote: > On Mon, 28 May 2001 10:34:37 GMT, Peter Moscatt > wrote: > >> >> >>G'Day Mike, >> >>Gee... tell ya what... if you could shed some light on this for me it >>would be greatly appreciated. > ... >>Current issue: >>In the Tix install guide it indicates that I must have installed > > Not *must* - *may*. Tix will work with Tk 8.0.5 or greater. > > The current release of Tix should work with the latest stable > release of Tk (8.3.3), and definitely works woth 8.3.2. For Tk > reasons, the best earlier releases were 8.2.3 and 8.0.5. > > If you are using the Python 2.0, you'll have to apply the patches to > Python that are distributed with Tix 8.1.1, and then compile Tcl, Tk > and Tix from sources following the instructions in Modules/Setup. > > Mike. > > From parkw at better.net Sun May 13 15:36:13 2001 From: parkw at better.net (William Park) Date: Sun, 13 May 2001 15:36:13 -0400 Subject: getting the output from os.system() In-Reply-To: <9dmlv6$8q3$1@talia.mad.ttd.net>; from sagracoi@larural.es on Sun, May 13, 2001 at 09:15:39PM +0200 References: <9dmlv6$8q3$1@talia.mad.ttd.net> Message-ID: <20010513153613.A3085@better.net> On Sun, May 13, 2001 at 09:15:39PM +0200, Jos? Mar?a y Sagrario wrote: > Hi everyone, > > When I execute something using os.system(), I cant get the output that is > produces into a variable, it just goes to the standar output, the screen. > > What I am actually trying to do is making a python script to execute another > one, and getting the output that it produces... Exactly, the error mesages > that python generates when something goes wrong... Read docs on popen(), popen2(), popen3(), ... I forget whether they're under 'os' or 'popen2' module. --William Park, Open Geometry Consulting, Mississauga, Ontario, Canada. 8 CPU cluster, (Slackware) Linux, Python, LaTeX, vim, mutt From BPettersen at NAREX.com Thu May 31 18:55:48 2001 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 31 May 2001 16:55:48 -0600 Subject: No swap function in Python? Message-ID: <6957F6A694B49A4096F7CFD0D900042F27D41A@admin56.narex.com> > From: Ben Wolfson [mailto:wolfson at uchicago.edu] > In article , "Remco Gerlich" > wrote: > > > > A swap function is impossible in Python. A function cannot > rebind names > > in the caller's namespace. This is why del is a statement and not a > > function, for instance. > > >>> a = 10 > >>> b = 5 > >>> def swap(**d): > assert len(d) == 2, 'Only swaps two variables!' > import sys > loc = sys._getframe(1).f_locals > k1, k2 = d.keys() > loc[k1] = d[k2] > loc[k2] = d[k1] > > >>> swap(a=a, b=b) > >>> print a, b > 5 10 > >>> But... def foo(): a = 10 b = 5 swap(a=a, b=b) print a,b foo() still prints 10 5... real-locals-aren't-writable'ly y'rs -- bjorn From jkraska1 at san.rr.com Sat May 12 12:37:20 2001 From: jkraska1 at san.rr.com (Courageous) Date: Sat, 12 May 2001 16:37:20 GMT Subject: Python Inheritance - A C example (without third party libraries) References: <3afcd971@news.iprimus.com.au> <%jaL6.1674$Yu6.413931@newsc.telia.net> Message-ID: >> There are no classes in C. > >note that you can implement Python classes in C. see >Python/exceptions.c for an example. Of course; I was simply trying to get his attention enough that he looked at actual source. "Segmented structures with known signatures and function pointer dispatch elements" are something he needs to learn about. C// From bos at hack.org Sun May 20 22:51:24 2001 From: bos at hack.org (Rikard Bosnjakovic) Date: Mon, 21 May 2001 04:51:24 +0200 Subject: crontab in python References: <9e9o5r$j3l$1@pegasus.tiscalinet.it> Message-ID: <3B0882AC.E3AEF808@hack.org> FrancescO wrote: > there's a module that work like crontab? What functionality are you looking for? Some sort of module that works like cron (that uses crontab)? I don't really understand the question. -- Rikard Bosnjakovic - http://bos.hack.org/cv/ - ICQ: 1158217 Anyone sending unwanted advertising e-mail to my address will be charged $250 for network traffic and computing time. By extracting my address from this message or its header, you agree to these terms. From rnd at onego.ru Wed May 2 12:12:17 2001 From: rnd at onego.ru (Roman Suzi) Date: Wed, 2 May 2001 20:12:17 +0400 (MSD) Subject: PEP 234: Iterators In-Reply-To: Message-ID: On Wed, 2 May 2001, Bjorn Pettersen wrote: >Perhaps it's only a matter of naming? How about itemIterator(), >valueIterator(), etc (or itemiter() if you don't like camelcase) What if... for v in dict.iter("value"): for i in list.iter() for i in someobject.iter("somevalue") for line in file.iter("line") for block in file.iter("block", 12) ... ? This user the same keyword for all methods and allows for more flexibility, default arguments, etc. > >-- bjorn > > Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/ _/ Wednesday, May 02, 2001 _/ Powered by Linux RedHat 6.2 _/ _/ "Cats have nine lives - but sleep through eight of them." _/ From grante at visi.com Thu May 31 13:05:47 2001 From: grante at visi.com (Grant Edwards) Date: Thu, 31 May 2001 17:05:47 GMT Subject: need code to gen all bit possibilities for 64 bits References: <9f4ipd$reu@freepress.concentric.net> Message-ID: In article , Tim Roberts wrote: >> I need code to generate bit configs for 64 bits. I know that this could >>be big. I would like to be able to start and stop at a certain point and >>write the results to a file to input to another program. > >The easiest way to generate all possible 64-bit patterns is to count: > >i = 0L >while i < (2L ** 64L): print i > >Printing 18 quintillion numbers is going to take a very, very, VERY long >time. At one per microsecond, I get about 500,000 years. I think the while loop above is going to run longer than 500,000 years. :) -- Grant Edwards grante Yow! Look! A ladder! Maybe at it leads to heaven, or visi.com a sandwich! From aleaxit at yahoo.com Wed May 2 08:15:39 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 2 May 2001 14:15:39 +0200 Subject: Tabs and spaces (style) References: Message-ID: <9cotpn01aa8@news2.newsguy.com> "Tim Peters" wrote in message news:mailman.988766523.12963.python-list at python.org... > I see Guido used his time machine to ensure that his Style Guide has *never* > recommended mixing tabs and spaces. Cool! Yep. For a while, some trace of the meta-past may linger, for example in Google caches, such as: http://www.google.com/search?q=cache:www.python.org/doc/essays/styleguide.ht ml but we can hope that the Time Machine's upcoming release 2.2 will be enhanced to ameliorate such ghost-effects... Alex From grante at visi.com Wed May 30 23:31:00 2001 From: grante at visi.com (Grant Edwards) Date: Thu, 31 May 2001 03:31:00 GMT Subject: Socket Question References: Message-ID: On Wed, 30 May 2001 19:11:57 -0700, Daniel Klein wrote: >Just when I thought I wouldn't have to learn something else... :-) > >I've been going thru the socket tutorial in Mark Lutz's PP2E >(great book btw). It appears that the buffer limit for recving >data is 1k. What type of sockets are you using? TCP? UDP? >I tried recving more and it just truncates it. Is this a >function of sockets in general or is there some setting I can >tweak to force it to accept more? If you're using UDP, you can't generally count on chunks larger than 512 bytes working. If you're using TCP, the size of the chunks you read may vary. You have to deal with the data stream being delivered in whatever size chunks please the intervening software and hardware (regardless of what size chunks with which it was written). -- 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 mkent at atlantic.net Fri May 18 11:14:14 2001 From: mkent at atlantic.net (MikeK) Date: 18 May 2001 08:14:14 -0700 Subject: Q: Passing an object of class UserList to writelines() Message-ID: I created a class derived from UserList to let me easily read a file into a list, and write the list back to the file. I want one of my 'FileListClass' objects to work just like a list, and be treated just like a list. However, when I try to pass one of my 'FileListClass' objects to the 'writelines' method of an 'os.popen' class object, I get the following error: TypeError: writelines() requires list of strings This tells me that when I pass my 'FileListClass' object to 'writelines', 'writelines' is seeing the object, not the data part of the object. I'm doing something wrong, possibly in the definition of my 'FileListClass'. Any ideas? I'm fairly new to Python, and readily admit that I don't have a firm grasp on writing a Python class. From wjdandreta at worldnet.att.net Mon May 21 19:59:57 2001 From: wjdandreta at worldnet.att.net (William Dandreta) Date: Mon, 21 May 2001 23:59:57 GMT Subject: How to make Python easier? References: <4hhO6.34841$4f7.2653314@bgtnsc06-news.ops.worldnet.att.net> Message-ID: <1_hO6.34747$t12.2682714@bgtnsc05-news.ops.worldnet.att.net> Your right, I guess my suggestion should be directed towards IDLE. >Python, the language, doesn't have cursors, doesn't have help >pages, nor menus, nor a context into which to get "context sensitive >help". What you are thinking of is an integrated development >environment (IDE), not a language. > >C// > From atodd at spam.free.email.com Wed May 2 19:22:05 2001 From: atodd at spam.free.email.com (Andy Todd) Date: Wed, 02 May 2001 23:22:05 GMT Subject: Inheritance Confusion Message-ID: All, I apologise in advance for being a mere procedural programmer in the wonderful world of oo, but I am confused. My following script doesn't do what *I* expect it to, can someone please help me by explaining why; -- class A: def __init__(self): self.x = "blah blah" class B(A): def _init__(self): A.__init__(self) self.y = "boo boo" >>> wibble=B() >>> dir(wibble) ['x'] -- What happened to self.y that I assigned in the __init__ method of class B? By observation I assume that the line - self.y = "boo boo" - is not being executed, but no exceptions are raised. Maybe I'm missing the point or trying to use the wrong structure or technique, if anyone can point me to decent web primers on this I'd be very grateful. Regards, Andy -- "No matter what the weather, you and the clouds will still be beautiful" Remove spam.free to email me From robin at stop.spam.alldunn.com Thu May 17 03:52:41 2001 From: robin at stop.spam.alldunn.com (Robin Dunn) Date: Thu, 17 May 2001 00:52:41 -0700 Subject: Embedding SSL in Python References: <3B030E1D.73B1F221@jump.net> Message-ID: > Has anyone had any success building POST for https by linking > something like cURL and OpenSSL with Python? I need to make > ssl POSTs under w2000 and I don't mind embedding Python (all > but the ssl POST is python and I'm not keen to change that). > A while back I built _socket.pyd for Python 2.0 with the SSl options enabled and linked to OpenSSL. I'm using it to do XML-RPC over SSL, works great. One of these days I'll have to do it for Python 2.1 too. You can get it here: http://alldunn.com/python/ -- Robin Dunn Software Craftsman robin at AllDunn.com Java give you jitters? http://wxPython.org Relax with wxPython! From root at rainerdeyke.com Tue May 15 19:20:58 2001 From: root at rainerdeyke.com (Rainer Deyke) Date: Tue, 15 May 2001 23:20:58 GMT Subject: Do I really need to learn Java? References: Message-ID: "Simon Brunning" wrote in message news:mailman.989942515.14877.python-list at python.org... > (snip) > > > In this case, only the > > people who *really LOVE* Intercal will bother to > > "be Intercal programmers": there is absolutely no > > "side benefit" (such as salaries:-) in so being. > > The way you phrase this would imply that there are some programmers who > *don't* love INTERCAL. Some mistake, surely? Some would say Malbolge makes Intercal redundant, although I'll take Brainf*ck and Unlambda over either. -- Rainer Deyke (root at rainerdeyke.com) Shareware computer games - http://rainerdeyke.com "In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor From thomas.heller at ion-tof.com Fri May 11 08:51:28 2001 From: thomas.heller at ion-tof.com (Thomas Heller) Date: Fri, 11 May 2001 14:51:28 +0200 Subject: Class/type unification and reference to unbound methods References: Message-ID: <9dgn77$i5iam$1@ID-59885.news.dfncis.de> [...] > class A: > def spam(self): > ... > > class B(A): > def spam(self): > ... > > class C(A): > def spam(self): > ... > > class D(B, C): > spam = C.spam > > This is akin to feature renaming as supported by Eiffel and comes in > handy when one class is found in the inheritance chain repeatedly. > Such renaming also is useful with extensive use of mixins. IMO the above would continue to work even if C.spam would be a function instead of a bound method. Today it would look like this: class D(B, C): spam = C.spam.im_func (Although the above looks somewhat strange to me...) Thomas From spahievi at vega.bg Sun May 20 12:40:14 2001 From: spahievi at vega.bg (Niki Spahiev) Date: Sun, 20 May 2001 19:40:14 +0300 Subject: Tkinter wm_withdraw doesn't work In-Reply-To: References: <7iitiwxnpa.fsf@enark.csis.hku.hk> Message-ID: <14532443431.20010520194014@vega.bg> 5/20/2001, 15:54:04, Carl Fink wrote: CF> Does wxPython have the same "You must also learn C" restriction? It has C++ manual with Python specific notes. -- Best regards, Niki Spahiev From shredwheat at mediaone.net Wed May 16 12:29:06 2001 From: shredwheat at mediaone.net (Pete Shinners) Date: Wed, 16 May 2001 16:29:06 GMT Subject: Touching Files On Windows References: Message-ID: "Ben" wrote > Is there a way to touch files under windows using python? I can return > the values as a tuple ... but it is immutable > > Any suggestions greatly appreciated. hey ben, i can't say i quite understand you question. you've really lost me with the returning a tuple? anyways, from what i know, to touch a file means to update a files timestamp if it exists, or just create a 0-byte file if it doesn't exist. def touch(filename): open(filename, 'a') that should be all you need. if you are asking for something esle, i'm afraid i don't quite understand that that is. From see at below Thu May 24 05:50:00 2001 From: see at below (Paul Foley) Date: 24 May 2001 21:50:00 +1200 Subject: What can you do in LISP that you can't do in Python References: <3B0C6440.388358B7@my.signature> <9eieut$8ov@dispatch.concentric.net> Message-ID: On 24 May 2001 07:58:21 GMT, mikel evins wrote: > I don't know the answer to the question in the subject line. I'm a fan of > both LISP and Python, considerably more experienced in LISP than in Python > (but I've written nontrivial programs in both). But as a fun intellectual > exercise I thought I'd try to think of a typically LISPy kind of thing that > I don't know how to do in Python, and see whether someone who knows Python > better does know how to do it. > Here's the Common Lisp code: > (let* ((count 0) > (incrementer #'(lambda () (setq count (1+ count))))) > (defmacro counting-setq (var val) > `(progn > (funcall ,incrementer) > (setq ,var ,val) > ,count))) > What it does is this: it defines a new version of SETQ called > 'counting-setq'. This new operation does the same thing that SETQ does: it > sets the value of a variable. But it does something else, too: it counts how > many times you call it and saves the current count in a variable that nobody > but counting-setq can see or affect. When it sets a variable it increments > the current count and then returns it. No it doesn't; it returns the number of times it got called prior to this particular expansion. I.e., the result won't be easily predictable. It *may* do something like what you say it does in interpreted code, if the expansion isn't being cached somewhere; it'll certainly return constant (but probably not very easily predictable) values in compiled code. Constant zeros if you just compile code using this thing in a fresh Lisp image. -- Qui beneficium dedit, taceat; narret qui accepit -- Seneca (setq reply-to (concatenate 'string "Paul Foley " "")) From Gareth.McCaughan at pobox.com Mon May 14 15:58:43 2001 From: Gareth.McCaughan at pobox.com (Gareth McCaughan) Date: Mon, 14 May 2001 20:58:43 +0100 Subject: Bubblesort (was: Re: Why aren't we all speaking LISP now?) References: <9dgl1m$a2d$1@foo.telia.com> Message-ID: Stefan Axelsson wrote: > I was going to keep quiet since I'm going away for the week and won't > be here to keep the argument going, but I cannot hold my peace! ;-) > > In Haskell a quick sort is: > > qsort [] = [] > qsort (x:xs) = qsort[y | y <- xs, y < x] ++ [x] ++ qsort[y | y <- xs, y >= x] > > Evidently doable from memory... And the above code could well be read > out aloud and make sense, almost even to a rank beginner. In Python it's def sort(xs): xs = xs[:] xs.sort() return xs which is just as doable from memory and likely to be much faster and less wasteful of memory. :-) Seriously: yes, that Haskell code is very elegant. But it's not a good sorting routine. Consider the behaviour if you hand it an already-sorted list; observe that it traverses the input twice when it need do so only once; see how much unnecessary memory it allocates. If you use Haskell to write a *real*, production-quality, sorting routine, does it actually come out any better than Python? Some languages (I shan't start a flame war by naming them here) are painstakingly optimized to make it easy to almost-solve problems with them. I don't think that's a good way to be... -- Gareth McCaughan Gareth.McCaughan at pobox.com .sig under construc From michael at stroeder.com Thu May 24 09:48:37 2001 From: michael at stroeder.com (Michael =?iso-8859-1?Q?Str=F6der?=) Date: Thu, 24 May 2001 15:48:37 +0200 Subject: Question on how to supress console logging from BaseHTTPServer Module? References: <3B0C6378.ABDBBC48@raqia.com> Message-ID: <3B0D1135.BCACD279@stroeder.com> David Lees wrote: > > self.log_request(code) > > which I can comment out to get rid of the console output. This seems a > bit crude. Is there a better way to suppress the logging output? Override method log_request() and redirect to log files. Believe me, you will need the log output. Ciao, Michael. From alan.gauld at bt.com Tue May 15 09:36:26 2001 From: alan.gauld at bt.com (Alan Gauld) Date: Tue, 15 May 2001 14:36:26 +0100 Subject: Do I really need to learn Java? References: Message-ID: <3B0130D9.38EC274C@bt.com> Roman Suzi wrote: > I also know that some Java programmers like Java. Only some? Seems like all the Python programmers I've met like Python. Maybe thats a significant difference? :-/ Alan G. From thomas at cintra.no Tue May 8 09:41:03 2001 From: thomas at cintra.no (Thomas Weholt) Date: Tue, 8 May 2001 15:41:03 +0200 Subject: XML based information system References: Message-ID: > Maybe you'd be interested to look at 4Suite and 4SuiteServer > (http://www.4Suite.org). It looks very similar to what you're trying to > achieve here. I've looked briefly at it, but I want a system with features like CVS integrated into it too, along with encryption, digitally signed documents, messaging etc. which 4Suite+ didn't seem to have. Another reason for doing much of it from scratch was that I needed to learn to use PostgreSQL, XML and XSLT better, and felt that would be achieved bettet if I didn't base my work on someone else ideas. Anyway, thanks for the tip. Thomas From aleaxit at yahoo.com Mon May 28 15:56:17 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 28 May 2001 21:56:17 +0200 Subject: Indentation style... References: Message-ID: <9eual8013si@enews1.newsguy.com> "Ken Peek" wrote in message news:th50hmsve0ap07 at corp.supernews.com... ... > I therefore withdraw my post-- and recant my beliefs on this issue. Because of > this discussion, I also plan on changing the way I write source code (to use *WOW*! This must be the 7th or 8th time I've witnessed this happen in almost 20 years spent on various kinds of Usenet-like electronic discussion networks -- somebody who had strongly held opinions on an issue actually *changing his mind* because of ensuing discussion. Ken, you must definitely be an exceptional kind of person. My plause and admiration go to you. Alex From aleaxit at yahoo.com Tue May 1 15:13:35 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 1 May 2001 21:13:35 +0200 Subject: function to check whether a variable already exists? References: Message-ID: <9cn2030ik5@news1.newsguy.com> "Graham Guttocks" wrote in message news:mailman.988735442.13417.python-list at python.org... > Can anyone tell me how to wrap the following in a function as to > avoid typing this try, except sequence for every variable whose > existence I want to check? > > For example, > > try: > if NEWSRC:pass > except NameError: > NEWSRC = os.path.expanduser("~/.newsrc") > > It seems tricky, because you can't just pass a function NEWSRC because > if it doesn't first exist NameError will immediately be raised. No, but you _can_ pass 'NEWSRC' -- the quotes are what allows that! So, specifically: if vars().has_key('NEWSRC'): # the variable exists works. Wrapping it in a _function_ is harder, because you need to have the function identify the caller's vars(), and if the function needs to bind the variable among the caller's locals() in particular, it may be close to unfeasible or require too much "black magic". Alex From d98aron at dtek.chalmers.se Fri May 25 16:40:34 2001 From: d98aron at dtek.chalmers.se (Fredrik Aronsson) Date: 25 May 2001 20:40:34 GMT Subject: speeding up string.split() References: Message-ID: <9emg02$t6o$1@nyheter.chalmers.se> In article , Chris Green writes: > Is there any way to speed up the following code? Speed doesn't matter > terribly much to me but this seems to be a fair example of what I need > to do. > > In the real data, I will be able to have a large array and use > map rather than do it line by line but, I doubt this will change > things much for the better. In my case, it actually made it worse... and the reason is probably that map and list comprehensions builds a new list. So, if you are only going to extract data and not build a new list, it's prbably faster with normal indexing. > I've tried w/ python 2 and 1.5.2 and the differences between perl and > python remain huge ( about 5s:1s python:perl ). Yep, perl is optimized for text processing. >From "man perl": Perl is a language optimized for scanning arbitrary text files, extracting information from those text files, and printing reports based on that information.... > > The string is +'d together for usenet purposes > > #!/usr/bin/python > from string import split > > for i in range(300000): > array = split('xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy 6' + > '1064 80 54 54 1 1 14:00:00.8094 14:00:00.8908 1 2') [perl snipped] The best speedup I saw was by using string methods, time was cut down to about half. YMMW /Fredrik -- results -- running on a constant string 100000 times... original 4.63118143082 [4.543, 4.645, 4.638, 4.670, 4.659] in_func 4.38402023315 [4.317, 4.408, 4.414, 4.390, 4.391] splitting_on_space 4.64088983536 [4.643, 4.647, 4.640, 4.642, 4.633] running on a real 10000 item array... normal_for 15.3752954006 [15.440, 15.350, 15.388, 15.346, 15.353] index_for 16.7716764212 [16.876, 16.843, 16.685, 16.771, 16.683] index_for_using_xrange 16.8590580225 [16.830, 16.781, 16.769, 16.780, 17.135] index_for_local_var 15.8590993881 [15.728, 15.895, 15.892, 15.883, 15.896] map_split 22.4902464151 [22.262, 22.339, 22.727, 23.051, 22.073] map_split_local_var 22.2637700081 [22.089, 22.436, 22.830, 21.799, 22.166] string_method 7.49720318317 [7.569, 7.486, 7.481, 7.481, 7.469] list_comp_split 19.7473443985 [19.551, 19.909, 20.321, 19.301, 19.653] -- code (not usenet friendly... long lines) -- from time import time # probably better to use the profile module... but this is simple. from string import split # create long list... large_list = 'xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy 61064 80 54 54 1 1 14:00:00.8094 14:00:00.8908 1 2' * 10000 # Functions def in_func(): for i in range(100000): array = split('xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy 61064 80 54 54 1 1 14:00:00.8094 14:00:00.8908 1 2') def splitting_on_space(): for i in range(100000): array = split('xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy 61064 80 54 54 1 1 14:00:00.8094 14:00:00.8908 1 2',' ') def normal_for(): for i in large_list: array = split(i) def index_for(): for i in range(len(large_list)): array = split(large_list[i]) def index_for_using_xrange(): for i in xrange(len(large_list)): array = split(large_list[i]) def index_for_local_var(): mylist = large_list mysplit = split for i in range(len(mylist)): array = mysplit(mylist[i]) def map_split(): for array in map(split,large_list): pass def map_split_local_var(): mysplit = split mylist = large_list for array in map(mysplit,mylist): pass def string_method(): for i in large_list: array = i.split() def list_comp_split(): for array in [l.split() for l in large_list]: pass funcs = [in_func,splitting_on_space, normal_for,index_for,index_for_using_xrange,index_for_local_var, map_split,map_split_local_var,string_method,list_comp_split] #Timings... def avg(list): from operator import add return reduce(add,list)/len(list) times = {} def process_time(name,diff): times.setdefault(name,[]).append(end-start) print name, avg(times[name]), print "[" + ", ".join(["%.3f" % t for t in times[name]]) + "]" for l in range(5): print "\n\nRun no.",l+1 start = time() for i in range(100000): array = split('xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy 61064 80 54 54 1 1 14:00:00.8094 14:00:00.8908 1 2') end = time() process_time("original",end-start) for func in funcs: start = time() func() end = time() process_time(func.func_name,end-start) From rnd at onego.ru Tue May 1 02:50:50 2001 From: rnd at onego.ru (Roman Suzi) Date: Tue, 1 May 2001 10:50:50 +0400 (MSD) Subject: With or Using Message-ID: On Tue, 1 May 2001, Greg Ewing wrote: > wrote: >> Rather than typing jim each time, >> jim.born=1960 >> jim.haircolour='Brown' >> jim.eyecolour='Green' > >def with(subject, **args): > for attr, value in args.items(): > setattr(subject, attr, value) Or, if subject allow it: def with(subject, **args): subject.__dict__(args) # or special method could be used > >jim = person() >with(jim, > born = 1960, > haircolour = 'Brown', > eyecolour = 'Green') > > Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/ _/ Tuesday, May 01, 2001 _/ Powered by Linux RedHat 6.2 _/ _/ "Caterpillar: Scratching post." _/ From whisper at oz.nospamnet Mon May 14 23:32:54 2001 From: whisper at oz.nospamnet (David LeBlanc) Date: 15 May 2001 03:32:54 GMT Subject: sgmllib.py not good at handling
References: <9donkd$235k$1@news4.isdnet.net> <9dovbc01e33@news2.newsguy.com> Message-ID: <9dq816$eb5$3@216.39.170.247> In article <9dovbc01e33 at news2.newsguy.com>, aleaxit at yahoo.com says... > "Chris Withers" wrote in message > > So is SGML a subset of XML? > > No! The reverse. But sgmllib does NOT cover all of SGML > (not even any _substantial_ fraction of it: SGML is really > huge, which is why it was subsetted to produce XML!-), just > what little of it is needed to parse typical HTML, as > the library reference manual says. > > > Alex Well, technically speaking, XML is an _aspect_ of SGML, while HTML is an _application_ of SGML. (In order to make XML a proper subset of SGML, the SGML standard itself was modified a bit - sorry, don't recall all the details off-hand any more.) XML is a fairly substantial subset of SGML which removed (imho somewhat too much) elements of SGML that made it very difficult to implement; for example, tag minimization and omitted tags which made for ambiguous parsing among other ills and which also infected HTML. (A couple of examples where I think they went too far is with removing conditionals and some content types.) XML is turning out to be the "killer application" (actually subset) for SGML since it's made markup languages vastly more popular and widespread then SGML ever was, again due to XML's vastly easier implementation and thus lower cost. (Some claim that there is not yet a 100% conforming implementation of SGML, and the equivelent of XSL-FO, DSSSL, for sure has never been 100% implemented due to it's byzantine complexity and (imho) reliance on Lisp.) Oops, we now return you to your regularly scheduled Python... Dave LeBlanc From jkraska1 at san.rr.com Sun May 13 20:10:34 2001 From: jkraska1 at san.rr.com (Courageous) Date: Mon, 14 May 2001 00:10:34 GMT Subject: Nested Scopes ... next tail recursion? References: Message-ID: >Best guess is slim. It's rarely requested, and AFAIK there are no active >Python developers who program in a style helped by this gimmick As a sidenote, IIRC stackless consumes stack space pretty slowly. :-) C// From SchmidtRW at y12.doe.dov Fri May 4 08:58:33 2001 From: SchmidtRW at y12.doe.dov (Russ Schmidt) Date: 4 May 2001 12:58:33 GMT Subject: Windows editor? References: Message-ID: "Brandon J. Van Every" wrote in : > What's a good Python editor for programming under Windows, specifically > Windows 2000? According to Google archives it seems this question hasn't > been asked in awhile. > > Ultraedit works well for me. -- Russ Schmidt (idt at y12.doe.gov) BWXT Y-12 L.L.C. Oak Ridge, Tennessee 37831-2009 From grumble at usa.net Sun May 27 18:33:03 2001 From: grumble at usa.net (jcm) Date: 27 May 2001 22:33:03 GMT Subject: speeding up string.split() References: Message-ID: <9ervav$qu9$1@news.mathworks.com> Remco Gerlich wrote: ... > Hmmmmm. Actually, what happens when you remove the '+' and replace it with a > simple backslash? Two literals in a row may form one literal, but two > strings with a '+' need to be added together every time. I think that this > *may* make a (small) difference. Wouldn't expect it to be at all > significant. It'd be Nice if the Python parser (or bytecode-compiler or whatever non-runtime thing is most appropriate) would translate the addition of two string literals into a single string. Or maybe it does this already? I haven't tried. From tdelaney at avaya.com Tue May 15 21:25:13 2001 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 16 May 2001 11:25:13 +1000 Subject: inclusive-lower-bound, exclusive-upper-bound (was Re: Range Operation pre-PEP) Message-ID: > [Greg Ewing] > > * Allow implicit line continuations anywhere you have what > > is obviously a syntactically incomplete structure (e.g. > > an expression ending with a binary operator). > > [Andrew Maizels] > > I've thought about that, but I'm not sure how well this > will fly with > > the average programmer. I think Icon does this. > Note that Python used to require explicit continuation on > every continued > line. Implicit continuation was added later (when in the midst of an > unclosed bracketing-- ({[ --structure). That change was more > popular even > than adding ">>" to "print" . > > The odd thing is you can't win: people will screw up no > matter what you do > about this, until there's a smart language-aware editor. My feeling on this is that *any* syntactically-incomplete statement should be allowed to extend to the next line. For example, any statement which requires a colon at the end (for, if, etc). if a == 1 and b == 2 and c in [ 1, 2, 3 ]: do_something() There we have two syntactically-incomplete statements: the list, and the if:. However, there may well be situations I haven't thought of where such a rule would cause semantic differences - can anyone think of any? Tim Delaney From shaleh at valinux.com Fri May 4 11:30:16 2001 From: shaleh at valinux.com (Sean 'Shaleh' Perry) Date: Fri, 04 May 2001 08:30:16 -0700 (PDT) Subject: Where O Where Could My VARIABLE Be? In-Reply-To: <5.0.2.1.0.20010504072855.009fb450@thewebsons.com> Message-ID: >#!/usr/bin/python > > import cgi, os > import string > import smtplib > > print "Content-type: text/html\n\n" > file = open("outfile.txt", "r") > line = file.readline() > file.close() > print line #### note this is the only additional line > server = smtplib.SMTP("localhost") > server.sendmail("beno at thewebsons.com", "beno at thewebsons.com", line) > server.quit() right before the server.sendmail() line, do 'server.set_debuglevel(1)'. That should give you some more info. From sheila at spamcop.net Mon May 7 01:37:44 2001 From: sheila at spamcop.net (Sheila King) Date: Mon, 07 May 2001 05:37:44 GMT Subject: Choosing a programming language as a competitive tool References: <9d3t3901nlq@news1.newsguy.com> <9d55e1$qel$1@slb1.atl.mindspring.net> Message-ID: On Sun, 6 May 2001 21:36:14 -0600, "Andrew Dalke" wrote in comp.lang.python in article <9d55e1$qel$1 at slb1.atl.mindspring.net>: :Please, not "vector"! A vector is a measurement with a direction :and a magnitude, as with velocity or force. Or it's a :coordinate in some space. When I came across "vector" as :used in computer science I was confused because I thought it :was a way to do vector math. Even now I still have to look :twice at a library to figure out which use is which. That's only in physics and engineering. In mathematics, a vector is an element in a vector space (or linear space), which is a set having the following properties: under some addition operation for all elements in the set, and a multiplication operation for a scalar (real number) times an element in the set, we have, for x, y in the set and for any arbitrary b, and c in the Reals: x + y = y + x (x + y) + z = x + ( y + z) there is a zero vector, 0, such that x + 0 = x c(x + y)= cx+cy (b+c)x = bx + cx b(cx) = (bc)x 0x = 0 and for some identity element in the set, 1, we have 1x=x Any set having all of these properties is a vector space (or linear space), and each element in the space is a vector. An example is the set of ordered pairs, (x,y) where x and y are elements of the real numbers. Maybe a better example, though, instead of listing all these properties, would be to simply remind you of matrix multiplication. Something like this: A = [2 1 3 -4] so A is a 2 by 2 matrix B = [0 4] So B is a 2 by 1 matrix AB = [4 -16] Matrices like B and AB, which look like columns are often called "column vectors". This is the type of vector, I believe, that we are referring to when we refer to "lists" as "vectors" in computer science. When I teach a vector class to my C++ high school students, I tell them that it has nothing to do with the vectors that they learned about in physics, and there is an audible sigh in the room. I have shown them the matrix multiplication, and told them that the n by 1 matrices are called column vectors, and the 1 by n matrices are often called row vectors. I encourage them to think of vectors that way. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From greg at electricrain.com Thu May 31 14:47:44 2001 From: greg at electricrain.com (Gregory P. Smith) Date: Thu, 31 May 2001 11:47:44 -0700 Subject: py2exe - too many Tk files In-Reply-To: ; from nperkins7@home.com on Mon, May 28, 2001 at 01:34:47AM +0000 References: <9er9j50uv7@enews1.newsguy.com> <9errhd01gl6@enews1.newsguy.com> Message-ID: <20010531114744.A19652@zot.electricrain.com> > ..what is up with all those Tk demo files in there? > Doesn't py2exe pick and choose only needed Tk files? > Surely a simple app could do with only a small subset > of the Tcl/Tk files that I find included in the 'dist'.. > > Can I, (how can I) trim down those (almost 2MB) Tcl/Tk files? > Do I have to do it manually, if so, how do I know which files are needed? Deleting the following doesn't cause a problem for me. There are probably others that can go as well. YMMV. tcl\tk8.3\demos tcl\tk8.3\images tcl\tcl8.3\dde1.1 tcl\tcl8.3\encoding tcl\tcl8.3\http1.0 tcl\tcl8.3\http2.3 tcl\tcl8.3\msgcat1.0 tcl\tcl8.3\opt0.4 tcl\tcl8.3\reg1.0 tcl\tcl8.3\tcltest1.0 -- Gregory P. Smith gnupg/pgp: http://electricrain.com/greg/keys/ C379 1F92 3703 52C9 87C4 BE58 6CDA DB87 105D 9163 From eric at badtux.org Tue May 22 11:02:17 2001 From: eric at badtux.org (Eric Lee Green) Date: Tue, 22 May 2001 15:02:17 GMT Subject: Python & Linux ? References: <3B0A0C89.1070108@bigpond.net.au> <3B0A469E.5080806@bigpond.net.au> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Tue, 22 May 2001 10:59:43 GMT, Peter Moscatt wrote: >Hi Remco, > >Yea, ya right.... it's difficult coming in from one enviroment (Win) to >a new one which is totally different. >So, if Linux programs aren't installable as such, what does the Software >Manager do. I thought it got the RPM files, uncompressed them then >installed ?? Correct. You can create installable RPM files from your Python programs. See http://www.rpm.org for more information. Do note that it's some major voodoo, but has some interesting benefits too, such as being able to set up a 'depends' so that a user can't install your Python program without having the Python interpreter already installed. However, do note that doing this without also providing the classic Unix 'tarball' format for other Unix variants (and for Linux variants such as Debian and Slackware which do not have 'rpm') will result major flamage. If there's interest, I am the person who created the Red Hat 'rpm's for the BRU-Pro product (R.I.P.), which was written largely in Python, and can easily give some tips on how to build rpm's for Python programs. Do note that rpm-building is an advanced topic, there's no automated tools for doing it, creating the .spec files for doing it is major voodoo, and as a beginner you're better off sticking with just writing your programs and tarballing them if you want to distribute them to other people. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.5 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE7Cn5s3DrrK1kMA04RAoG4AKCoLDe7nhFvjmZsjLOK8nUP8lSrMgCgzKfH twfkLqYaDyI3RxjGZ9ukkHY= =BN8a -----END PGP SIGNATURE----- From aleaxit at yahoo.com Fri May 18 04:52:50 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 18 May 2001 10:52:50 +0200 Subject: GNU/Linux vs. Windows as Python platform References: <97WM6.478$uk2.228879@news1.rdc2.pa.home.com> Message-ID: <9e2nsv02p29@enews1.newsguy.com> "Terry Reedy" wrote in message news:Z14N6.2752$uk2.728676 at news1.rdc2.pa.home.com... > > "Terry Reedy" wrote in message > news:97WM6.478$uk2.228879 at news1.rdc2.pa.home.com... > > Has anyone (reading this) had experience with running Python under both > > Windows and Linux/Unix on the same machine (or equivalent machines)? If > > so, have you noticed any advantages either way? (Other than the issue of > > prebuilt versus compile-your-own binaries.) > > Someone emailed 'Is this a troll'? No. I currently have a Win98 machine > and wonder if there might be good enough reasons to add Linux to this or my > next machine, perhaps within the next year. > > By binaries, I was thinking of extension modules like PIL, wxPython, etc > for which the developers have often made Windows binaries but not > everything else. > > Summary of what read so far. Answer depends on priority. For heavy-duty > standalone Python programs, running under Linux might well give more room > and more speed. For application automation, Windows/COM still easily beats > Linux. One option that wasn't covered so far is the possibility of running both Linux AND Windows together in the same box. Which is what I intend to do for MY next box -- it will run Linux (Mandrake 8 I believe) as its main system, and have Win4Lin on top so I can keep running a few "indispensable" things I only have for Windows (the game "Stars!", an occasional need for a Visual C++ session, &c). There are many alternative solutions to achieve a similar end, which many be a worthwhile one for many uses. Alex From mac4-devnull at theory.org Sat May 19 03:41:54 2001 From: mac4-devnull at theory.org (Neil) Date: Sat, 19 May 2001 14:41:54 +0700 Subject: random numbers, threads and reproducibility References: Message-ID: <3b06e73d$0$331$8eec23a@newsreader.tycho.net> Requiring a threaded program to be 100% reproducable is a tall order. There are a lot of factors involved. If your program simply requires that each thread gets the same 'random' number sequence, then I would implement this by giving each thread its own whrandom instance, which is what you sugest below :-) Neil In article , "eloy" wrote: > > Greetings! > > I am developing a small class framework for Genetic Algorithms in > Python, and wishing to create some threads, I face a problem: > > One of the requirements I want to keep is reproducibility. A > genetic algorithm is a stochastic (i.e., random) procedure, and I print > the random seed at the start of each run of a expreriment, so I can > reproduce the run later and be sure it will reach the same results. But > threads are not deterministic (I think), so the sequence of calls to the > whrandom... functions would not be the same. > > A possible solution that came to me is to pass a random seed > (based on a random number) to each thread as it is created, and > instantiate a different whrandom object in each one. > > The question is: is there a better way to do this in Python? > > Thanks for your time. > > -- Eloy R. Sanz > > _____________________________________________________________________ > ---- Eloy Rafael Sanz Tapia -- ersanz at uco.es -- ma1satae at uco.es ----- > ------------------ http://www.uco.es/~ma1satae ---------------------- > ----------- GPG ID: 190169A0 / finger eloy at rabinf50.uco.es ---------- > C?rdoba _ Espa?a _______________ Debian 2.2 GNU/Linux 2.2.19 rabinf50 > From aleaxit at yahoo.com Wed May 30 17:16:54 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 30 May 2001 23:16:54 +0200 Subject: Why PEP 245?? References: <9f298b$98n$1@slb6.atl.mindspring.net> <9f2jk301tcl@enews2.newsguy.com> Message-ID: <9f3o330alg@enews2.newsguy.com> "Terry Reedy" wrote in message news:bR7R6.15127$lP5.7725689 at news1.rdc2.pa.home.com... > > I use COM a lot, and I can vouch for a similar effect *when interface > > design doesn't badly violate the ISP* (when it does, interfaces become > > > a mistery -- the interface of 'file-like objects' is wide enough to break > > the ISP, so it takes investigation in each case to determine exactly what > > ISP??? In most contexts, Internet Service Provider, but here, interface S?? > P?? Interface Segregation Principle. Sorry, it was silly of me to assume any TLA (Three Letter Acronym) would be recognizable without explanation -- there's just far too much overloading of them! Alex From jdf at pobox.com Thu May 10 02:03:40 2001 From: jdf at pobox.com (Jonathan Feinberg) Date: 10 May 2001 02:03:40 -0400 Subject: Reading & Writing Python OK, Now I need to Speak It References: <3AFA1BF5.2377412F@home.com> <01af01c0d911$7af6a5f0$d938a8c0@Hadfield> Message-ID: m.hadfield at niwa.cri.nz ("Mark Hadfield") writes: > "double-ugh" > > Come to think of it, don't you guys have a president with a name > like that? Don't remind me. -- Jonathan Feinberg jdf at pobox.com Sunny Brooklyn, NY http://pobox.com/~jdf From new_name at mit.edu Thu May 31 07:51:13 2001 From: new_name at mit.edu (Alex) Date: 31 May 2001 07:51:13 -0400 Subject: Coddling emacs References: Message-ID: Wow, bitter, aren't you. :) Alex. From skip at pobox.com Thu May 31 16:10:11 2001 From: skip at pobox.com (Skip Montanaro) Date: Thu, 31 May 2001 15:10:11 -0500 Subject: No swap function in Python? In-Reply-To: <3B15FD21.42CA2660@europem01.nt.com> References: <3B150A65.5D4986FC@europem01.nt.com> <20010530173327.C690@xs4all.nl> <3B15FD21.42CA2660@europem01.nt.com> Message-ID: <15126.42275.229864.904422@beluga.mojam.com> me> LOAD_FAST b me> LOAD_FAST a me> STORE_FAST b me> STORE_FAST a ... Gawain> Furthermore, as Aahz Maruch alludes to in another follow-up Gawain> post, an "atomic" swap might also be useful when writing Gawain> multi-threaded applications. To get true atomicity (at the Python VM level) you'd have to define a new byte code for such an operation. Furthermore, a swap bytecode would have to work with a fixed number of arguments (typically two) and would have to be exposed as a statement or at least an operator (hey, once they finish deprecating <> as a comparison operator, we could reuse it as the swap operator - wouldn't that work wonders for Mailman!). Finally, note that swap(a,b) is just a special case of the current tuple pack/unpack operation, so you'd add no new functionality to the language aside from the atomic nature of the swap - and then only if you added the new byte code instead of implementing it as a series of two loads and two stores. It's not clear that with all the stuff you'd need to do that it would be worthwhile, though if the atomicity argument is that important to you, then make your case to Guido. -- Skip Montanaro (skip at pobox.com) (847)971-7098 From footech at get2net.dk Tue May 1 05:27:31 2001 From: footech at get2net.dk (Mikkel Rasmussen) Date: Tue, 1 May 2001 11:27:31 +0200 Subject: Spam collection Message-ID: Disclaimer: This is not just for Python programmers (since I use Python I thought it would be nice to co-operate with other Python programmers). I have thought about sharing my spam collection with others for use in developing a better spam filter. We need a large collection of spam to be able to do various forms of analysis on it. I don't know if such a collection already exists. If so, I would like to add mine. My spam filter "idea" is to use keywords, because I use Outlook and Outlook does not give any other possibilities (as far as I know). The problem is in choosing the best keywords without using *any* word that occurs in a non-spam message. We probably also need a definition of spam. A tentative definition could be "irrelevant messages" where irrelevant gives a subjective perspective. My spam might not be your spam :-) Any further ideas? Mikkel Rasmussen From charlie at begeistert.org Sat May 19 10:05:20 2001 From: charlie at begeistert.org (Charlie Clark) Date: Sat, 19 May 2001 16:05:20 +0200 Subject: Playing with Dict - Can anyone see a way around this? References: <3B069A99.18AF2522@student.gu.edu.au> Message-ID: s713221 at student.gu.edu.au wrote: > Somebody mentioned in this group a couple of months ago, the > posibility > of making [].keys, [].items and [].values directly scriptable, so you > could iterate over them either by calling them, or by treating them as > lists. I've taken their suggestion as far as I can go as an exercise > in > curiosity, but have run into a little bit of a problem. I took their > suggestion of making keys, values and items, classes rather than > functions. > >From what I understand you should check out the looping PEP on the Python website. Looping through dictionaries are scheduled for the next release. Charlie From hannah at schlund.de Thu May 3 12:15:18 2001 From: hannah at schlund.de (Hannah Schroeter) Date: 3 May 2001 18:15:18 +0200 Subject: Choosing a programming language as a competitive tool References: <3dlmoflsjv.fsf@ute.cnri.reston.va.us> Message-ID: <9cs06m$57o$1@c3po.schlund.de> Hello! In article , Brett g Porter wrote: >[...] >* Clients often balk at the idea of a language that doesn't compile to >binary code. Oh, that explains the Java hype (most implementations use that bytecode) and the Lisp hatred (most good implementations generate native code)? >[...] Kind regards, Hannah. From thomas at cintra.no Wed May 23 05:56:31 2001 From: thomas at cintra.no (Thomas Weholt) Date: Wed, 23 May 2001 09:56:31 GMT Subject: problems using % in strings with %(var)s replacements Message-ID: Say I got a string s = "%(number)s among 50% are efficient for %(customer_name)s." I want to replace 'number' with 42 and 'customer_name' with Acme Inc. Trying to do a simple >>> s % {'number':42,'customer_name':'Acme Inc.'} Traceback (most recent call last): File "", line 1, in ? TypeError: not enough arguments for format string >>> I see the % in 50% is the problem but how can I use the %-char in strings and still use %(...)s replacements?? Thomas From maus at netz.klinik.uni-mainz.de Mon May 14 10:57:39 2001 From: maus at netz.klinik.uni-mainz.de (Christian Maus) Date: Mon, 14 May 2001 16:57:39 +0200 Subject: problem writing to file Message-ID: <3AFFF263.A9923451@netz.klinik.uni-mainz.de> Hi, I have a strange problem when I try to write to a file. I created a list named named new_ldapentries. I create a file object in write mode: testfile = open('/tmp/testfile', 'w') then I go through the elements of my list and try to write them to the file: for i in range(len(new_ldapentries)): testfile.write(new_ldapentries[i]) testfile.close() When I run the script I get the following error: Exception in Tkinter callback Traceback (innermost last): File "/usr/lib/python1.5/lib-tk/Tkinter.py", line 764, in __call__ return apply(self.func, args) File "python/emailmanager.py", line 333, in writeLDAPentry testfile.write(new_ldapentries[line]) TypeError: read-only buffer, instance The strange thing is when I replace the new_ldapentries[line] with any String like 'hello' everything works fine. Has anybody a idea where I made a mistake? Thanks in advance, christian -- Networking Group, Hospital of Johannes Gutenberg-University Obere Zahlbacher Stra?e 69, 55101 Mainz, Germany tel: +49 (0)6131 17-7193 FAX: +49 (0)6131 17-477193 From claird at starbase.neosoft.com Mon May 14 15:01:46 2001 From: claird at starbase.neosoft.com (Cameron Laird) Date: 14 May 2001 14:01:46 -0500 Subject: What can you do in LISP that you can't do in Python References: Message-ID: <0776735BD56C5470.3107E8C892DA30DA.1C1CDE9F91728011@lp.airnews.net> In article , Steven D. Majewski wrote: > > >I was about to bring up Turing Completeness, but Alex beat me to it! > >But for an example to consider: > > Pretend for a moment that you had a problem where you absolutely >required something like Lisp macros. > > In python, you could always the the equivalent behaviour with a >python function that outputs a new python module that could be >imported. Programs that write programs isn't a feature that only >Lisp can do. > > However, because of Lisp's trivial syntax, as well as functions >designed for reading lisp expressions, processing Lisp code is >trivially easy. Lisp macros are written in a sort of substitution >template. > > Doing the same thing in Python requires a Python parser. Of course, >you just happed to have access to the one built into Python from >the parser module. ( "import parser" ) > However, other than occasionally eval-ing small expressions, I >think most Python programmers would, rather than write some sort >of textual code processing, would use the reflective features of >the language manipulate classes, functions, code-objects, et.al. >at a different level. > > I haven't followed Dylan for a while (Dylan is a language that's >sort of like an Object-oriented Scheme in it's semantics, but with >a more "algolish" syntax ) but, long ago, there was discussion of >a macro system for Dylan, which was planned to be a non-textual >transformation of deeper structures from the parse tree. > > If you were going to do macros for Python, that would be the way >to do it -- however, I wonder if that style of macro would ever >feel as natural as Lisp's. I suspect that Python programmers would >STILL try to find another way to do it. > > There's a lot more to a computer language that a list of features! . . . I have a pet belief that hygienic macros as practiced in Lisp are somewhat overdone (I know my own fondness for extreme factorization), and of material interest largely for a single category of use: "self-modifying" code which amounts to initialized method definition. Exactly the same calculations are available in a purely run-time formulation, withOUT macro funniness, but at the cost of more run-time calculation. Until I have more evidence to the contrary, I expect correct macro usage to be a performance optimization. Python admits fine, powerful metaprogrammability. It needn't apologize. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From dalke at acm.org Sun May 6 23:36:14 2001 From: dalke at acm.org (Andrew Dalke) Date: Sun, 6 May 2001 21:36:14 -0600 Subject: Choosing a programming language as a competitive tool References: <9d3t3901nlq@news1.newsguy.com> Message-ID: <9d55e1$qel$1@slb1.atl.mindspring.net> Alex Martelli: >Actually, I think the choice of "list" as the name of the Python >structure is somewhat misleading (and that 'array' or 'vector' >might have been better), as 'list' mostly means (even in other >programming communities) something closer to what _Lisp_ >means by it... and, Lisp was there first:-). Please, not "vector"! A vector is a measurement with a direction and a magnitude, as with velocity or force. Or it's a coordinate in some space. When I came across "vector" as used in computer science I was confused because I thought it was a way to do vector math. Even now I still have to look twice at a library to figure out which use is which. > No biggie, but I >_have_ seen newbies temporarily confused by thinking that >Python lists were, well, lists, and that there seemed to way to >have a vector/array...:-). I can say that I've rarely come across people who've had problems understanding what is meant by list. Outside of CS I think "array" doesn't have a close association to what Python calls a list. From my Bartlett's "Familiar Quotations", some of the uses of array are: Battle's magnificently stern array! - Byron, "Childe Harold's Pilgrimage" My silks and fine array, - Blake, "Poetical Sketches" And named a trysting day, And bade his messages ride forth East and west and south and north, To summon his array. - Macaulay, "Lays of Ancient Rome" Where lies the land to which yon ship must go? Fresh as a lark mounting at break of day, Festively she puts forth in trim array. - Wordsworth, "Where List the Land" Even Solomon in all his glory was not arrayed like one of these. - Matthew 6:29 (I figured this was more interesting than just quoting the definition from a dictionary :) Andrew dalke at acm.org From graham_guttocks at yahoo.co.nz Tue May 1 12:43:40 2001 From: graham_guttocks at yahoo.co.nz (Graham Guttocks) Date: Tue, 1 May 2001 09:43:40 -0700 (PDT) Subject: function to check whether a variable already exists? Message-ID: <20010501164340.83624.qmail@web10306.mail.yahoo.com> Can anyone tell me how to wrap the following in a function as to avoid typing this try, except sequence for every variable whose existence I want to check? For example, try: if NEWSRC:pass except NameError: NEWSRC = os.path.expanduser("~/.newsrc") It seems tricky, because you can't just pass a function NEWSRC because if it doesn't first exist NameError will immediately be raised. Regards, Graham __________________________________________________ Do You Yahoo!? Yahoo! Auctions - buy the things you want at great prices http://auctions.yahoo.com/ From jasonbail at aol.com Sun May 27 19:31:01 2001 From: jasonbail at aol.com (Jasonbail) Date: 27 May 2001 23:31:01 GMT Subject: newbie question References: <9epjrk$ggq$2@newshost.accu.uu.nl> Message-ID: <20010527193101.18520.00003023@ng-mq1.aol.com> >> I'm fairly new to programming, > >> My questions is, is there anyway to create a reference to a pre-existing >> variable by using variables? > >> for example if I have a variable daily_count > >> can I access that variable by using "daily_" and "count" thats stored in >other >> variables? > >Since you are new to programming, I think the best answer here would >be to ask you some more questions. The most important one in these cases >is always: > > Why would you want to do that? Well let me first say that I have a tendency to leap first and then try to figure out if I will be able to land safely. The idea behind my post was that I was in the process of creating a simple app when I noticed that the majority of the code I was using to create the gui was nearly identical. It stood to reason then that I could I define a function that I could then use to configure the widget and that all I had to do was pass along the name of the widget that would need configuring. And to do that I would need to store the name in a variable to pass along to the function, which it would then configure and at a later point I could re-configure to my hearts content. Of course I don't need to do that. It took me almost the entire night to wrap my head around the thought that I could create a method and that by creating an instant of the method I would then be able to do what I originally planned on doing. (sorry if I butcher the terminology here, I'm still working on that) Some of this is very confusing at first. The reason why I didn't go to far in to explaining what I was doing is that because I knew I was new to this, I knew that there was probably a better way, but that wasn't what I was looking for. Sometimes people will try answering my problem rather then my question. Which I dislike because regardless of my intent I still want to know the answer to my question (which in this case several people, I'm happy to say, have answered.) >In Python, variables (attributes, etc, in python terminology, names) are >always references to *objects*. The only way you can approach objects is >to go through these names in some fashion. The objects contain the data >and define the behavior, however. The names may refer to one object now, >and another in the future. Multiple names can refer to the same object. >This distinction between names and the objects they refer to is very >important in Python, so you make sure you clearly understand this. It >is not extremely difficult to understand and to deal with once you >understand, but it is a common problem for many that are new to Python. > I didn't quite see that until you pointed it out. After reading your post I do see your point and I think I was probably to reserved here. I will try to be a little bit more verbose on my questions in the future. Thanks for the feedback, and I will take you up on the clarification as soon as I understand enough to form a coherent question. :) Jason From loewis at informatik.hu-berlin.de Tue May 1 16:22:50 2001 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 01 May 2001 22:22:50 +0200 Subject: xml.parsers.expat References: Message-ID: "Richard Townsend" writes: > I can't get the example program in section 13.4.3 of the Python Library > Reference to work. It gives: > > ImportError: No module named parsers.expat > > I have tried it using Python 2.0 on Windows, Linux and HPUX and get the same > error. Most likely, pyexpat has not been compiled on Linux and HPUX. I'm surprised it fails on Windows, though - where did you get your Python binary from? > On Linux and HPUX, I have modified the Modules/Setup file to link in the > expat library, but it didn't make any difference. Just modifying it certainly won't help - you have to rebuild and reinstall Python, it it can't hurt to verify that pyexpat has been build. Does a simple "import pyexpat" succeed? > Should this example work with Python 2.0 ? Certainly. Regards, Martin From phd at phd.fep.ru Tue May 29 07:11:31 2001 From: phd at phd.fep.ru (Oleg Broytmann) Date: Tue, 29 May 2001 15:11:31 +0400 (MSD) Subject: Against PEP 240 In-Reply-To: Message-ID: On Tue, 29 May 2001, Roman Suzi wrote: > I wonder, why at all need such things? Are there any standard library for > inf-precision in current Python version? If so, was it tested long > enough? > > (If such standard library exists, please, remind me it's name. Thanks) mpz -- GNU arbitrary magnitude integers. This is a wrapper for GNU mp (multiprecision) library. Oleg. ---- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From mal at lemburg.com Thu May 3 13:11:26 2001 From: mal at lemburg.com (M.-A. Lemburg) Date: Thu, 03 May 2001 19:11:26 +0200 Subject: idiom: concatenate strings with separator References: Message-ID: <3AF1913E.A71D9CB1@lemburg.com> Harald Kirsch wrote: > > Recently I started using code like this > > l = [] > for x in somethings: > y = massage(x) > l.append(y) > > return string.join(y, my_favorite_separator) > > to produce strings made of substrings separated by something. Note > that with immediate string concatenation its hard to avoid the > separator either in front or at the end of the produced string. > > Nevertheless I wonder if something like > > s = "" > sep = "" > for x in somethings: > y = massage(x) > s = s + sep + y > sep = my_favorite_separator > > return s > > is faster or uses less memory than the previous solution. The fastest and most memory efficient solution is probably using cStringIO: import cStringIO sep = "-" temp = cStringIO.StringIO() write = temp.write for x in items: write(sep) write(x) temp.seek(len(sep)) return temp.read() PS: But Lutz Ehrlich would have told you that too ;-) -- Marc-Andre Lemburg ______________________________________________________________________ Company & Consulting: http://www.egenix.com/ Python Software: http://www.lemburg.com/python/ From debl at nospmmytheworld.com Fri May 4 00:40:48 2001 From: debl at nospmmytheworld.com (David Lees) Date: Fri, 04 May 2001 04:40:48 GMT Subject: Threading question Message-ID: <3AF232D6.60A2C1CC@nospmmytheworld.com> I am struggling to improve the performance of some python code that has 2 threads and runs on a dual processor linux (redhat 7.0) box. I am using Python 2.1 and can not seem to get the cpu utilization up above 40% for each processor. Here is a simple example that shows the essence of the problem. This is my first try at dual processor code and the performance indicates I am doing something wrong. The thing that really seems strange and makes me wonder if the problem is python's implementation of threads or something wierd in RedHat 7.0 linux, is that when I run as a single tread I see 'top' flipping back and forth between the 2 cpus, utilizing each at 99% and the other at 0. Any advice is welcome. Thanks in advance. david lees ------------- def load(n): sum=0.0 for i in range(n): sum = sum+math.sqrt(i)**3.5 #junk that loads the cpu if __name__=='__main__': num=string.atoi(sys.argv[1]) thread_1=threading.Thread(target=load,args=(num,)) thread_1.start() thread_2=threading.Thread(target=load,args=(num,)) thread_2.start() print 'Threads started' From lac at cd.chalmers.se Wed May 30 15:51:19 2001 From: lac at cd.chalmers.se (Laura Creighton) Date: Wed, 30 May 2001 21:51:19 +0200 (MET DST) Subject: clicking on the link ``Please use the Google Groups advanced search form. '' Message-ID: <200105301951.VAA22008@boris.cd.chalmers.se> in http://www.python.org/search/search_news.html How hard would it be to make that produce a form that already has comp.lang.python filled in so to save me the typing? Laura From fredrik at pythonware.com Wed May 2 11:49:43 2001 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 02 May 2001 15:49:43 GMT Subject: who uses Python or Ruby, and for what? References: <9cnj6f$re0$1@newsy.ifm.liu.se> Message-ID: Thomas Bellman wroter: > > > Python has always had iterators, implemented as forward-only > > sequences. > > The iterator was then the integer you passed to __getitem__()? > Many people would consider that a *very* limited form of > iterator. the iterator is the object that responds to __getitem__(lastindex+1), not the loop variable itself. (see fileinput for one example). > > > The new iterator model doesn't add anything that > > you haven't been able to do before; it just makes things a bit > > easier to implement and use. > > The ability to have several independent and concurrent iterators > for a single sequence object was not there. At least not if you > wanted it to be efficient. And several other things you can do > with proper iterators were more than "a bit" more difficult to > implement. well, a generic "use new-style iterator as forward sequence" wrapper is 10 lines, so it cannot be that hard... class Iterator: def __init__(self, obj): self.obj = obj def __getitem__(self, index): if self.obj is not None: try: return self.obj.next() except StopIteration: self.obj = None raise IndexError > Sure, you could *implement* iterators in Python, but that's > not the same as there *being* iterators. maybe not, but for something that doesn't exist, they've sure served me well over the last six years ;-) Cheers /F From db3l at fitlinxx.com Fri May 4 19:47:21 2001 From: db3l at fitlinxx.com (David Bolen) Date: 04 May 2001 19:47:21 -0400 Subject: Simple Dictionary Question References: <5.0.2.1.0.20010504115631.00a0c810@thewebsons.com> Message-ID: Ben Ocean writes: > At 01:51 PM 5/4/2001 -0700, you wrote: > >You need to include more of your script (maybe the whole thing). > >There is no clue about what v is supposed to be, or what i is > >supposed to be, or what the script is trying to do. > > Oops. > >>> > for i in form.keys(): > v = form[i].value > save.append(i + ": " + v + "\n") > if form.has_key("token"): > if i == "bladename": > bladename = v > if i == "bladephone": > bladephone = v > if i == "bladeemail": > bladeemail = v > if i == "token": > token = v > <<< > The *blade* things are keys: I need to extract their values. The variables > will be set only if *token* is set. Why can't I extract the value of the > variables? If you really want to see the whole script, here it is. Thanks > in advance for your help, Hmm, well, you still haven't precisely said what the failure mode is - what do you mean by "extract their values"? Are you saying that you did get a dictionary "form" that had a key "token" and one or more of the other keys and your local variables didn't get set appropriately? And if so, how did you check the problem - for example, I see where you output the contents of the form() dictionary by using "save", but looking through your script for references to bladename itself, I see: > print "Please tell us your name: size=20>
" which gets it into the form submission: > blade = string.join(aaaa, bladename, bbbb, bladephone, cccc, > bladeemail, dddd) > line = string.join(blade, line) > import smtplib > server = smtplib.SMTP("localhost") > server.sendmail("beno at thewebsons.com", "beno at thewebsons.com", "Subject: > Blade Chevy Car Inquiry\n\n%s" % line) So the only place I think you could verify that bladename had a value was when you tried to use it in mail, but as you've seen in the separate thread, nothing is going to show up because "line" is not a well-formed RFC822 message format. So I don't see where you could ever expect to see the output value of bladename (either in the mail or in any diagnostic HTML output). So are you really sure the problem is where you think it is? :-) The code itself looks like it'll probably do what you want, although it does seem a bit convoluted to me. Instead of retrieving keys directly, you nest a series of comparisons over an iteration of the keys. And you check both for the token key (as well as then compare against each possible key you are looking for) each pass through the loop. So IMHO, the code is making it a little difficult to easily grasp what it is intended to do. There's plenty of alternative approaches, but one that might be a bit clearer could be: token = form.get("token",None) if token: bladename = form.get("bladename",None) bladephone = form.get("bladephone",None) bladeemail = form.get("bladeemail",None) which would result in token having a value or None if it wasn't present, and if token had a value, the blade* variables having appropriate values or None (adjust defaults as necessary). Although as you have more variables you'd probably just want to use your own dictionary or other indexed data structure than manually writing distinct variables. You could still use a separate loop to create the "save" string if you needed it beyond debugging. -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From vonWedel at lfpt.rwth-aachen.de Sun May 20 09:07:20 2001 From: vonWedel at lfpt.rwth-aachen.de (Lars von Wedel) Date: Sun, 20 May 2001 15:07:20 +0200 Subject: Python and Computer Algebra Systems --- is it done? References: <2tefgtoavdpm1i976oj4fckb38108tp1e4@4ax.com> Message-ID: <3B07C187.5370CB7A@lfpt.rwth-aachen.de> Hi, There is a GNU project on CA functionality called Ginac. It is basically a C++ library with objects such as terms and equations. Looks good and seems to be actively developed. Recently, someone posted a Python binding to this library. Have a look at: http://www.ginac.de Lars jm7potter at hotmail.com wrote: > > Hello all, > > I am new to Python and this may be old news to everyone else, > but here goes. > > I would like to use Python to do symbolic calculations like one may do > with Maxima, Derive, Maple, Mathematica, MuPad, or other such > packages. > > I do know that Scientific Notepad uses the Maple kernel or the MuPad > kernel to do the actual math work. Perhaps Python could use the Maxima > kernel? > > The question is really --- has anyone yet used Python to do any > symbolic math? > > Thanks in advance, > > Joe Potter > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: vonWedel.vcf Type: text/x-vcard Size: 342 bytes Desc: Card for Lars von Wedel URL: From aleaxit at yahoo.com Tue May 29 11:29:24 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 29 May 2001 17:29:24 +0200 Subject: Cost of raising exceptions. References: Message-ID: <9f0f73027rg@enews2.newsguy.com> "Allan Crooks" wrote in message news:mailman.991144423.30414.python-list at python.org... ... > Are raising exceptions a costly operation? Up to a point. > But since that has a high overhead, the hasNext() method is a way of > detecting the end. My query is, if developing something similar for > Python, is raising an exception a good way to halt or not? Just consider that THIS is how Python's for statement ALWAYS works internally: it exits when it gets an IndexError from the sequence it's indexing... Let's take a concrete example. For some peculiar reason I want to compute summations of numbers of the form 17/d, where d = i modulo X, for i from 0 to N-1 included, but simply skipping the cases where the divisor d would be 0 (which will be one in every X numbers, of course). How slow would it be to do it the simplest obvious way: def with_exceptions(N,x): result = 0L for i in range(N): try: result += 17/(N%x) except ZeroDivisionError: pass return result versus a way that checks carefully instead: def without_them(N,x): result = 0L for i in range(N): divisor = N%x if divisor!=0: result += 17/divisor return result ??? It's simpler to measure (with care:-) than to worry and/or wonder...: import time def dotimes(N,x): start1 = time.clock(); r1=with_exceptions(N,x); stend1 = time.clock() start2 = time.clock(); r2=without_them(N,x); stend2 = time.clock() print "%d/%d: %d==%d, with ex:%.2f without:%.2f" % ( N, x, r1, r2, stend1-start1, stend2-start2) if __name__=='__main__': dotimes(1000*1000, 17) dotimes(1000*1000, 7) dotimes(1000*1000, 3) D:\py21>python execos.py 1000000/17: 3000016==3000016, with ex:11.64 without:9.14 1000000/7: 5571423==5571423, with ex:16.14 without:8.62 1000000/3: 8333325==8333325, with ex:26.15 without:7.40 So: if we're having an exception about one time in 20, the cost of the exceptions-in-loop approach is about 20%. If one time in 7, exceptions are about twice as costly as checks in this case. If one in 3, exceptions cost a slow-down of over 1 in three. But this is for reasonably light other-operations and rather frequent 'exceptions'. In most cases, the real costs are not so terrible -- particularly if the checking approach should incur substantial overhead at each pass through the loop while the exception approach only pays (albeit a higher cost) on rare occasions... you might even end up with exceptions being faster!-) In the end, you're better off programming with the single main goal of SIMPLICITY. If somebody may want to check "is there more stuff?" WITHOUT consuming a next-item, then giving them a .hasNext() method to call will be a good thing, saving the contortions of trying to get-next, and undo, within a try/except/else. That is generally a better goal to keep in mind than marginal performance issues... *KEEP IT SIMPLE* and be happy. Exceptions will be good if they enable for-loop usage, too... client-code for iteration doesn't get much simpler than that:-). But for that you need specifically to raise IndexError within __getitem__ when you have no more items (it gets better in 2.2 with iterators, though... you won't any more have to fake being random-access when you aren't:-). Alex From phd at phd.fep.ru Fri May 4 09:29:20 2001 From: phd at phd.fep.ru (Oleg Broytmann) Date: Fri, 4 May 2001 17:29:20 +0400 (MSD) Subject: how to resolve name from Python 1.5.*? In-Reply-To: Message-ID: On Fri, 4 May 2001, Roman Suzi wrote: > How do I get a list of IP-address(es) corresponding to a given name socket.gethostbyname Oleg. ---- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From nelson at crynwr.com Thu May 3 15:20:38 2001 From: nelson at crynwr.com (Russell Nelson) Date: 03 May 2001 15:20:38 -0400 Subject: repeat/while? Message-ID: Is there any enthusiasm for repeat/while in Python? It would replace the following ideom: while 1: line = sys.stdin.readline() if not line: break pass # handle line here with this: repeat: line = sys.stdin.readline() while line: pass # handle line here Semantics are unchanged. If Python had a goto, it could also be expressed like this: goto entrypoint while line: pass # handle line here entrypoint: line = sys.stdin.readline() Or should I write this up as a PEP? -- -russ nelson will be speaking at http://www.osdn.com/conferences/handhelds/ Crynwr sells support for free software | PGPok | Mailing lists should not set 521 Pleasant Valley Rd. | +1 315 268 1925 voice | Reply-To: back to the list! Potsdam, NY 13676-3213 | +1 315 268 9201 FAX | http://russnelson.com/rt.html From aidan.finn at ucd.ie Tue May 1 06:24:05 2001 From: aidan.finn at ucd.ie (Aidan Finn) Date: Tue, 01 May 2001 11:24:05 +0100 Subject: Spam collection References: Message-ID: <20010501.112405.1237379107.14619@hyppia.ucd.ie> In article , "Mikkel Rasmussen" wrote: > My spam filter "idea" is to use keywords, because I use Outlook and > Outlook does not give any other possibilities (as far as I know). The > problem is in choosing the best keywords ... You might try the rainbow text classifier (http://www.cs.cmu.edu/afs/cs/project/theo-11/www/naive-bayes.html) to find discover the most informative words for junk e-mail. There are some papers on using baysian classification to do this kind of filtering. The paper "A Bayesian Approach to Filtering Junk E-Mail" and kushmericks adeater system spring to mind. If your interested these can probably be found on citeseer (http://citeseer.nj.nec.com/cs). Let me know if this is useful. AF From arildh at stud.cs.uit.no Sun May 20 10:07:14 2001 From: arildh at stud.cs.uit.no (Arild Hansen) Date: Sun, 20 May 2001 16:07:14 +0200 Subject: "import termios" problem In-Reply-To: References: Message-ID: Nevermind, I figured it out. A. Hansen On Sun, 20 May 2001, Arild Hansen wrote: > OK, I'll try again and be somewhat more specific about the problem. I run > Python on the following i386 platform: > > Python 2.0 (#1, May 13 2001, 14:22:01) > [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-81)] on linux2 > > where > > Linux version 2.4.2-2 (root at porky.devel.redhat.com) (gcc version 2.96 > 20000731 (Red Hat Linux 7.1 2.96-79)) #1 Sun Apr 8 20:41:30 EDT 2001 > > > Python was patched with ipv6 support, compiled from source and installed > without any problems. It runs just fine except when I try to import the > termios module. I then get the following error: > > >>> import termios > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named termios > >>> > > When upgrading from Redhat 7.0 to Redhat 7.1 I also re-installed python > (same version) to get ipv6 support. Before I had no problems importing the > termios module, but now I have. I have been looking into the problem > without any luck yet. I have no problems importing the TERMIOS module. If > anybody can point me in the right direction I'll appreciate it a lot. > Thx, > > A. Hansen > > > > > > > From robin at jessikat.fsnet.co.uk Mon May 21 06:22:42 2001 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 21 May 2001 11:22:42 +0100 Subject: property collections References: <9e90k20aiu@enews1.newsguy.com> Message-ID: In article <9e90k20aiu at enews1.newsguy.com>, Alex Martelli writes >"Robin Becker" wrote in message >news:g44pZKATy8B7Ewa2 at jessikat.fsnet.co.uk... > ... >> My solutions seem to involve elements which need to refer to the parent >> and thus create a loop. > >Not sure I understand your general problem, but, regarding >this last item, have you tried the (new in 2.1) weak refs...? > > >Alex well now I would certainly use weak refs if that were feasible for all, but some people are still using 1.5.2 and so I still have to worry about memory loops. Weak refs are exactly the python only solution for this sort of acquisition style object. -- Robin Becker From donn at u.washington.edu Fri May 11 16:06:26 2001 From: donn at u.washington.edu (Donn Cave) Date: 11 May 2001 20:06:26 GMT Subject: why os.environ dictionary remembers previously set variables?? References: Message-ID: <9dhgo2$quk$1@nntp6.u.washington.edu> If you execute your python program from a csh script, that script will invoke .cshrc, and that would account for the behavior you describe. In most cases, shell scripts are better written for the Bourne shell (sh). To make sure they actually run that way, make the script executable (chmod +x) and put #!/bin/sh right at the top. If you're not sure whether .cshrc is being executed again, put an echo command in it. Donn Cave, donn at u.washington.edu ---------------------------------------- Quoth ed_tsang at yahoo.com: | Hi I use the code | print os.environ['THARN'] | print os.environ['CTF'] | if os.environ.has_key('THARN') and os.environ.has_key('CTF'): | print "\nEither THARN or CTF shall be set not BOTH" | print "before starting the Test Harness." | sys.exit(1) | elif os.environ.has_key('THARN'): | tharn = os.environ['THARN'] | print 'THARN' | elif os.environ.has_key('CTF'): | tharn = os.environ['THARN'] | print 'CTF' | else: | print "\nEnvironment variable THARN must be set" | print "before starting the Test Harness." | sys.exit(1) | to do wset a local global thanr variable. | | In the .cshrc file in my home directory , I had: | setenv THARN /vobs/qa/stf/ctf/src/ctf | set in the first run of my script. | It prints the correct content of tharn. | Then I exit the process, unset tne variable using | unsetenv THARN | setenv CTF /vobs/qa/stf/ctf/src/ctf | and uses echo to make sure THARN is gone while CTF is set. | Then I run the script again.. t my dismay, it prints both CTF and | THARN having the value: | | /vobs/qa/stf/ctf/src/ctf | /vobs/qa/stf/ctf/src/ctf | | Either THARN or CTF shall be set not BOTH | before starting the Test Harness. | I then go to delete the .pyc file and run it again same thing | happens!!! | I use echo again and the system shows THRAN is gone while CTF is here | which is expected... then why the heck python remembers the the alst | one and just append the new environment variable??? | | What to do?? should I expliciltly delete all the variables in | os.environ dict before exiting.. As you know it depends on user to | set CTF ,THRAN , BOTH (error) or none at all (error). The latter use | are error cases. | | thanks From kalle at gnupung.net Mon May 7 04:12:35 2001 From: kalle at gnupung.net (Kalle Svensson) Date: Mon, 7 May 2001 10:12:35 +0200 Subject: curses -- module cannot be found In-Reply-To: ; from jedi@ccrypt.net on Sun, May 06, 2001 at 08:10:45PM -0700 References: <20010507020143.C375@apone.network.loc> Message-ID: <20010507101235.A14089@father> Sez jedi at ccrypt.net: > my experience under unix is that you need to edit the Setup file under the > Modules directory and enable support for curses in order for it to be a > loadable module. Not with Python 2.1, AFAIK. 2.1 uses a distutils setup script to automatically determine what modules to build. Peace, Kalle -- Email: kalle at gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD [ Not signed due to lossage. Blame Microsoft Outlook Express. ] From Gareth.McCaughan at pobox.com Sat May 26 15:50:53 2001 From: Gareth.McCaughan at pobox.com (Gareth McCaughan) Date: Sat, 26 May 2001 20:50:53 +0100 Subject: Long names are doom ? References: <3B0EEAE7.FAD87BD@aol.com> <9enjr8$r4s$1@slb6.atl.mindspring.net> Message-ID: "Rainy" wrote: > What's the big problem with implementing this: > > my variable = 2 > > my result = my variable * 3 > > def my function(some variable): > return some variable / 8 > > ? > > I know there is something seriously wrong with this, because otherwise > it'd be done already in some language (and afaik it isn't). So what > exactly is wrong? It has been dpne. Algol 68 (maybe other versions of Algol too; I don't know) permits variable names with spaces. As Alex said, old FORTRAN systems just ignored whitespace, but that's not quite the same. I think I would find things like the result = first argument and unused bitmask if number in interesting numbers: hard to read (the "and" on the first line, and the "in" on the second, are keywords). Maybe in languages with fewer keywords it might be different, but I doubt it. There are almost bound to be keywords you'll want to use as elements in names (some things that are keywords in many languages: "for", "and", "if", "do", "class"). If the usual way of combining words to make names is sticking spaces in between, then using those words will be painful. In more "normal" languages we combine words like_this, likeThis, like-this, like.this or however, and then you don't get the inconsistency and dislocation when you need to call a function "do list loop if not in class". :-) -- Gareth McCaughan Gareth.McCaughan at pobox.com .sig under construc From tdelaney at avaya.com Fri May 11 01:18:42 2001 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 11 May 2001 15:18:42 +1000 Subject: Speeding up application startup Message-ID: > On startup my application reads a text file that contains around 15000 > regular expressions which i then need to compile for use > during the course > of my program. It takes around 15 seconds for this to be > done on my 900mhz > machine. Any suggestions for speeding this up? Without seeing the code, there are only a few general suggestions we can make. If you post the relevant bits of code we can probably help a lot more ... First suggestion is to profile the app to see what is taking the most time - reading in the expressions or compiling them, or possibly something else. This will tell you what is more important to optimise. Second suggestion is to not compile the expressions at startup. Read them in at startup, but only compile each one as you need it. Just for fun, keep track of which ones actually get compiled during an invocation of the program, and how many times ;) This is a simple case of spreading the compilation time over longer periods. Another question is whether you can get away with not reading the entire file in at startup, but I expect that realistically you do need to. In that case, consider the method you are using to read in the file. I presume you are using readlines() or xreadlines() (one expression per line). Can you can get away with fewer expressions. It may be quite possible to combine many expressions into one (that's the power of regular expressions). I presume the list of 15000 has been automatically generated from elsewhere. In that case they are probably fairly simplistic. However, I wouldn't want to go through a list of 15000 regexes and try to combine them. How are you storing the regexes in memory? Are they in a list, appended one at a time? A dictionary? An array? Heaven forbid, are you adding tuples together? Try a few different methods for each action and profile them. Tim Delaney From paulp at ActiveState.com Mon May 14 23:34:48 2001 From: paulp at ActiveState.com (Paul Prescod) Date: 14 May 2001 22:34:48 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (May 14) Message-ID: <0B32C50ABEE6AE0A.74F9E787F2935C1C.B16A278EE605321B@lp.airnews.net> Bill Gates calls Python, "an extremely well-designed language"! No, Bill Gates doesn't, but one of his two partners on the first Microsoft BASIC interpreter does. Monte Davidoff, who programmed floating point arithmetic for that first MS product, is now into Python. http://www.theregister.co.uk/content/4/18909.html Chris Abraham announces foundation of the Zope Python User's Group: http://www.zpug.org/ Mark Lutz, one of Python's writers-in-residence, interviewed on O'Reilly. Slashdot picks up the interview. http://python.oreilly.com/news/python_0501.html http://slashdot.org/developers/01/05/11/0021241.shtml A thread on range-generation shortcuts reveals deep truths about the future of iterators and inconsistencies in Python's implementation of filter: http://groups.google.com/groups?ic=1&th=771b2135332fffae In the same thread, Alex Martelli describes the reason that Python does not include the top index in slices and ranges: http://groups.google.com/groups?ic=1&selm=9db4i801beb%40news2.newsguy.com Only a few weeks after the release of PyGame, a game-development framework for Python, Pete Shinners releases a game based on it. The game is written in concise, readable Python code: http://shredwheat.zopesite.com/solarwolf Several people send John Flynn code emulating two of his favorite features from Delphi, property handlers and event handlers. http://groups.google.com/groups?ic=1&th=5e36e9393ed06770 Skip Montanaro asks about converting between 8-bit strings and Unicode strings and learns about the Python's Unicode design. http://groups.google.com/groups?ic=1&th=e05ff0346d9e47d1 Daniel Klein asks whether Python's survival is dependent on Guido's interest and ability to avoid buses. Various posters describe why Python is safe no matter what happens to any individuals: http://groups.google.com/groups?ic=1&th=e0a0d70bc71cedc3 How do threads, processes, message queues and IDEs interact on Windows? A "Python DoEvents" thread reveals all. http://groups.google.com/groups?ic=1&th=771b2135332fffae ======================================================================== 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 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 Michael Hudson continues Andrew Kuchling's marvelous tradition 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.de/oo_python.html Python FAQTS http://python.faqts.com/ Python To-Do List anticipates some of Python's future direction http://www.python.org/cgi-bin/todo.py Python Journal is at work on its second issue http://www.pythonjournal.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python 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://purl.org/thecliff/python/url.html 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. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning, 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. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From dnew at san.rr.com Thu May 31 12:54:52 2001 From: dnew at san.rr.com (Darren New) Date: Thu, 31 May 2001 16:54:52 GMT Subject: Obsolesence of <> References: <9f447j$fpt$1@brokaw.wa.com> Message-ID: <3B16775D.1BF893A2@san.rr.com> D-Man wrote: > The Pascal-ish inequality operator ('<>') has effectively been > deprecated in favor of the Algol-ish (C-ish) inequality operator > ('!='). > if not ( 1 < input() < 10 ) : > print "You didn't enter a number between 1 and 10, try again" Heh. Pascal is deprecated, but COBOL is still cool. ;-) -- Darren New / Senior MTS & Free Radical / Invisible Worlds Inc. San Diego, CA, USA (PST). Cryptokeys on demand. This is top-quality raw fish, the Rolls-Rice of Sushi! From mickey at sirius.tm.informatik.uni-frankfurt.de Fri May 11 03:35:21 2001 From: mickey at sirius.tm.informatik.uni-frankfurt.de (Michael Lauer) Date: 11 May 2001 09:35:21 +0200 Subject: 'from ... import *' woes... Message-ID: <3afb9639@nntp.server.uni-frankfurt.de> Good morning, I have a strange problem... Consider the following program which implements a stack: ------------------------------- #!/usr/bin/env python Stack = [] def push(data): global Stack Stack = [data] + Stack def pop(): global Stack top, Stack = Stack[0], Stack[1:] return top ------------------------------ When I use this program via 'import', it functions as follows: ------------------------------------------ Python 2.1 (#1, Apr 21 2001, 03:38:10) [GCC 2.95.2 19991024 (release)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import stack >>> stack.Stack [] >>> stack.push("Hallo") >>> stack.Stack ['Hallo'] >>> stack.pop() 'Hallo' >>> stack.Stack [] >>> ------------------------------------------- Ok, this is what I did expect. Now please see what happens if I use from ... import * ------------------------------------------- Python 2.1 (#1, Apr 21 2001, 03:38:10) [GCC 2.95.2 19991024 (release)] on linux2 Type "copyright", "credits" or "license" for more information. >>> from stack import * >>> Stack [] >>> push("Hallo") >>> Stack [] >>> pop() 'Hallo' >>> -------------------------------------------- So... what is happening here ? Why is the Stack display as an empty list although a value is 'pushed' and I can 'pop' that value... ? Yours, :M: From greg at C800000-A.potlnd1.or.home.com Thu May 17 04:38:21 2001 From: greg at C800000-A.potlnd1.or.home.com (greg jorgensen) Date: Thu, 17 May 2001 08:38:21 GMT Subject: HTTPS - example code anywhere? In-Reply-To: <3AFB528F.4157353C@jump.net> References: <3AFB528F.4157353C@jump.net> Message-ID: On Thu, 10 May 2001, Dick Norton wrote: > I need to do a post to an HTTPS url and look at the result. > > I'd very much like to use Python and was wondering if anyone > could point me at some sample code for this task. I am as yet > only able to find the odd one line reference to such. The urllib module is what you want. See the library documentation at python.org. David Beazley's book "Python Essential Reference" is handy as well. Greg Jorgensen Portland, Oregon, USA gregj at pobox.com From zope at thewebsons.com Fri May 4 14:59:06 2001 From: zope at thewebsons.com (Ben Ocean) Date: Fri, 04 May 2001 11:59:06 -0700 Subject: Simple Dictionary Question Message-ID: <5.0.2.1.0.20010504115631.00a0c810@thewebsons.com> Hi; I have this in a cgi script: >>> if form.has_key("token"): if i == "bladename": bladename = v if i == "bladephone": bladephone = v if i == "bladeemail": bladeemail = v if i == "token": token = v <<< Now, if the form has *token* it may have the others; if the others are present *token* will be as well. For some reason if mare than key *token* is present, the whole thing falls apart and all the values get set to None. Why? TIA, BenO From aahz at panix.com Thu May 10 23:52:36 2001 From: aahz at panix.com (Aahz Maruch) Date: 10 May 2001 20:52:36 -0700 Subject: Need suggestion to speed up code... References: Message-ID: <9dfnm4$4gn$1@panix6.panix.com> In article , Roy Smith wrote: > >I need to split up a string into a list of fields. The strings are value >lists from SQL statements, and look something like this: > >(1, 'foo', 'bar', 34, 3.14159, 'an imbedded comma, this sting has', 'this >one isn''t so easy either') > >If it wasn't for the fact that I need to handle commas and quotes imbedded >in quoted strings, it would be trivial -- just a call to string.split. >But, as it is, the best I can figure out is to walk the string, character >by character, keeping track of what state I'm in (parsing an integer, >parsing a floating point, or parsing a quoted string). It works, but >profiling shows it's the bottleneck in my whole program. There are regular expressions that will handle this, but you should probably consider one of the text processing tools available. One of the standard recommendations is mxTextTools. If you take a look at the Vaults of Parnassus, you're likely to find other options. -- --- Aahz <*> (Copyright 2001 by aahz at pobox.com) Androgynous poly kinky vanilla queer het Pythonista http://www.rahul.net/aahz/ Hugs and backrubs -- I break Rule 6 "Everyone is entitled to an *informed* opinion." --Harlan Ellison From phd at phd.fep.ru Thu May 31 11:08:53 2001 From: phd at phd.fep.ru (Oleg Broytmann) Date: Thu, 31 May 2001 19:08:53 +0400 (MSD) Subject: In Python 2.0 this works without "apply". In-Reply-To: <200105311502.RAA00926@boris.cd.chalmers.se> Message-ID: On Thu, 31 May 2001, Laura Creighton wrote: > Please write me the line of code. Mine doesn't work. (Please note - I am replying to the newsgroup, too) class XXX: def __init__(self, **kw): print kw class YYY(XXX): def __init__(self, **kw): XXX.__init__(self, **kw) yyy = YYY(a=1, b=2, c='3') Worked in 2.0. Oleg. ---- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From jpetzold at twmi.rr.com Tue May 8 22:43:00 2001 From: jpetzold at twmi.rr.com (the_2nd_coming) Date: Wed, 09 May 2001 02:43:00 GMT Subject: How do you set up a stack? References: <3y1K6.28593$q7.286847@typhoon.mw.mediaone.net> <9qehft8gspqhtpb50d3men0j12r7mnkp7i@4ax.com> Message-ID: > f=raw_input('>') > print eval(f) Thanks, while I know I should not feel stupid, since I am a newbie, I still feel stupid :-) I appreciate it. Jeremy From mlh at idi.ntnu.no Mon May 28 21:14:39 2001 From: mlh at idi.ntnu.no (Magnus Lie Hetland) Date: Tue, 29 May 2001 03:14:39 +0200 Subject: Spatial Python, anyone? References: <9etvu4$1g1$1@tyfon.itea.ntnu.no> <3B12D20B.80FFB8BD@ActiveState.com> Message-ID: <057801c0e7dc$bbe91550$156ff181@idi.ntnu.no> From: "David Ascher" > > Magnus Lie Hetland wrote: [...] > > I don't know much about R*, but I did consider doing A* in Python, and > gave it up because of the lousy performance of that kind of algorithm. > Are A* and R* relatives? If you mean A* as in the heuristic search method -- no. (Or, at least, they have to be extremely distant relatives.) If there is another A*, then maybe. R* is a version of the R-tree for spatial indexing. And I'm not planning on implementing it in Python -- but using existing C-implementations *in* Python, tying it to other things (that will also probably be done in C...) > In general, my conclusion after doing numerical work for a while is that > the desire to look at algorithms crucial to your research as black boxes > is futile. Depends on how central they are :) To me, the R*-tree is just a storage/retrieval mechanism with certain desirable properties. Just like I don't generally care about how regular expression matching or hash tables are implemented, as long as they work as expected, I'm happy ;) > In the end, I always had to dig into the details of the > algorithms because they were either never black-boxable or > the black-box versions didn't do a good enough job. Well, well. Performance fine-tuning etc. can come later in my case. I'm mainly want to experiment a bit. > I wish you another conclusion, though. =) Thanks :) > -- David Ascher > ActiveState -- Magnus Lie Hetland http://www.hetland.org "Reality is that which, when you stop believing in it, doesn't go away." -- Philip K. Dick From tim.one at home.com Sun May 13 16:32:05 2001 From: tim.one at home.com (Tim Peters) Date: Sun, 13 May 2001 16:32:05 -0400 Subject: pprint.isrecursive: is it ever recursive? (a bug?) In-Reply-To: Message-ID: [Roman Suzi] > I was looking at pprint code and out of curiosity tried > to repr self-referencing list: > > >>> import pprint > >>> l=[1,2] > >>> l[0]=l > >>> pprint.isreadable(l) > 0 > >>> pprint.isrecursive(l) > 0 > >>> l > [[...], 2] > >>> pprint.saferepr(l) > '[, 2]' > >>> > > > However, it seems to me that isrecursive(l) must be 1, not 0. > Or do I misunderstand it's meaning? Na, isrecursive() appears to be broken bigtime. I opened a bug report for you: http://sourceforge.net/tracker/index.php?func=detail&aid=423781& group_id=5470&atid=105470 From fgeiger at datec.at Fri May 25 02:06:06 2001 From: fgeiger at datec.at (Franz GEIGER) Date: Fri, 25 May 2001 08:06:06 +0200 Subject: Python or C? References: <20010524233446.05514.00001446@ng-cf1.aol.com> Message-ID: <9eksnl$7eq$1@newsreaderg1.core.theplanet.net> You could write a COM server in Python, which is a matter of a few lines, and connect you VB client to this server. If it has to be a DLL you can write it in VB and test it *within* your app. It has not necessarily to be written in C or VC. Regards Franz GEIGER "E Mo 6283" wrote in message news:20010524233446.05514.00001446 at ng-cf1.aol.com... > Before I start to learn Python, I would like to know which would be better to > write DLL files to link to a Visual Basic program, C or Python? From amdescombes at diligo.fr Wed May 23 06:31:15 2001 From: amdescombes at diligo.fr (Andre M. Descombes) Date: Wed, 23 May 2001 12:31:15 +0200 Subject: Reinitializing the python interpreter form Java Message-ID: <9eg3fs$aaq$1@wanadoo.fr> Hi, I am using Jython as a script language from within Java, I compile a Python program using the PythonInterpreter.exec method (so it runs faster), and then use PythonInterpreter.get to get an address to a PyObject and then use __call__ to call the code. The problem is I would like to execute some functions several times, and I would like to be able to save the state of the global variables, so I can later restore it (on a different day for example). I tried using getLocals and setLocals with no success. Does anybody know how to do this? Thanks, Andre M. Descombes From emile at fenx.com Thu May 17 11:14:51 2001 From: emile at fenx.com (Emile van Sebille) Date: Thu, 17 May 2001 08:14:51 -0700 Subject: Equivalent 2->> print '%d %d' %(l[i], for i in range(2))? References: <3B03E5AB.8757BF2@psi.ch> Message-ID: <9e0q44$dl99$1@ID-11957.news.dfncis.de> >>> l = [1,3,5,7] >>> print '%d '*len(l) % tuple(l) Emile van Sebille emile at fenx.com --------- ----- Original Message ----- From: "Jorn Verwey" Newsgroups: comp.lang.python Sent: Thursday, May 17, 2001 7:52 AM Subject: Equivalent 2->> print '%d %d' %(l[i], for i in range(2))? > How can I avoid typing %(l[0],l[1]) in the following case? > ->> l=[4,14] > ->> print '%d %d' %(l[0],l[1]) > > would like something more in the line of: > > ->> print '%d %d' %(l[i], for i in range(2)) > > for longer lists. > > Thank you, > > Jorn > > -- > Jorn Verwey > PSI - Life Sciences WMSA/B14 > CH 5232 Villigen PSI > Switzerland > tel. +41 56 310 4246 > fax. +41 56 310 3132 -o) > jorn.verwey at psi.ch /\\ > jorn.verwey at bigfoot.com _\_v > > From fredrik at pythonware.com Thu May 24 15:03:32 2001 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 May 2001 19:03:32 GMT Subject: Tkinter: runtime widget naming? References: <9ejhc0$ac8$1@agate.berkeley.edu> Message-ID: <8WcP6.12298$sk3.3324380@newsb.telia.net> sternber at socrates.Berkeley.EDU wrote: > I'm translating a Tk system that does alot of this: > > set b ".mybutton" > ... > button $b ... > > What is a good way to do this in Python? There is, of course, > > b = "mybutton" > ... > exec( b + "= Button(...)" ) > > Is there a better way? see: http://www.pythonware.com/library/tkinter/introduction/x147-more-on-widget-names.htm Cheers /F From thomas.heller at ion-tof.com Tue May 29 14:21:25 2001 From: thomas.heller at ion-tof.com (Thomas Heller) Date: Tue, 29 May 2001 20:21:25 +0200 Subject: Py2Exe, lessons from use... References: Message-ID: <9f0p91$1lliv$1@ID-59885.news.dfncis.de> "Mike C. Fletcher" wrote in message news:mailman.990695801.20305.python-list at python.org... > Disclaimer: > The following is written very late at night, assume there are errors and > omissions. There is no guarantee, implicit or explicit that the methods > described below are, in any way, reliable, useful, or intelligible. Use at > your own risk. > > I have recently been experimenting with Py2EXE for packaging up a rather > large application including: [...] > > Python Imaging Library > > The python imaging library requires a number of plug-ins to be of any use. > Here's a simplified main script which seems to work for a simple PIL-based > application... > > import thumbnail > import ArgImagePlugin, BmpImagePlugin, CurImagePlugin, DcxImagePlugin, > EpsImagePlugin,\ [...lot of other modules snipped] > > Where thumbnail is a simple script importing Image. As you can see, > specifying all of those plug-ins on the command line would be somewhat > annoying. (py2exe does not find the plugins because they are imported with __import__, but you already knew this.) You can create a setup.cfg file and list the modules in this way: --- setup.cfg file --- [py2exe] includes=ArgImagePlugin,BmpImagePlugin,CurImagePlugin,DcxImagePlugin,... --- EOF --- Due to a bug in py2exe, the whole list must be ON ONE LINE, and there must not be any whitespace. I will fix this in the next release. > I have not been able to figure out how to stop Py2EXE from > finding the TK and TCL directories using the above imports. I just excluded > the tcl directory in my .tar command for packaging the application. There's > probably a better approach. The '-e Tkinter' command line switch should have done the trick. > > > win32com > Basically, using the latest CVS version of py2exe, I specified a command > line argument -i win32com.gen_py.* which attempts to include all of the > modules in the gen_py directory. During operation of the program, a new > gen_py directory will be created and the generated modules will be saved > there. I spent some time trying to figure out what was going on when I got > errors reporting that an integer could not be properly converted when > loading from the gen_py directory. Eventually I modified my distribution > archive to prevent the gen_py directory from being included, this seemed to > solve the problem, though I never did track down the reason it occurred. > Bottom line, don't include the gen_py directory in your distributions. With > the activexwrapper included, this seemed to allow for proper operation. I will look into this. It is currently not really satisfying. > > > General comments: > The "command line" focus for the system is difficult to work with when > creating large applications. I wound up creating batch files to automate > the publishing process, and including all of the dependencies into my main > script, which slows down startup time somewhat. > I would really prefer to specify the files for scanning within the setup > module, leaving the command line for "end-user" options. Using setup.cfg as > mentioned in the documentation didn't seem to work, I didn't have time to > track down why not. See above. But wait: It is possible to enable additional keyword parameters for the setup-function by using a custom Distribution class. Importing py2exe could replace distutil's standard Distribution class by an extended one, but is this really the way to go... > There needs to be a mechanism for differentiating critical and trivial > output while running distutils commands. A mode that printed (only) those > files actually copied into the archive and those copied to the destination > directory would be useful. Similarly, one which suppresses the "X not > copied to directory y, source yada, yada" warnings so that build failures > and files actually copied can be seen would be useful. This is normal distutils behaviour, and as such difficult to change from py2exe. > > > Py2EXE is very useful (as was the McMillan installer which I was using for > previous projects), allowing executable python applications makes using > python in the workplace possible (I tried getting a colleague to set up his > machine for this application as a set of python modules, he ran into some > weird win 32 COM error, we never did get it fixed). Thanks to all involved. > > Enjoy yourselves, > Mike Thanks again for the extensive review, Mike. This is the kind of feedback which will (hopefully) improve this little utility. Thomas From greg at pdxperts.com Sun May 20 23:23:55 2001 From: greg at pdxperts.com (Greg Jorgensen) Date: Mon, 21 May 2001 03:23:55 GMT Subject: htmllib question In-Reply-To: <1rpud365gc.fsf@video.bsd.uchicago.edu> References: <1rpud365gc.fsf@video.bsd.uchicago.edu> Message-ID: On 20 May 2001, John Hunter wrote: > I have some html that I need to parse. I want to call some function > on all of the html unless it is in PRE tag. Then I just want to > output it verbatim. This may be more simplistic that you want. Then again it may be a workable solution. --- import re f = open('somthing.html', 'r') rgx = re.compile(r'(

.*
)', re.DOTALL+re.IGNORECASE) chunks = rgx.split(f.read()) f.close() for chunk in chunks: if chunk[0:5].lower() == '
':
        # do something with preformatted chunk
    else:
        # do something with non-pre chunk
---

Greg Jorgensen
PDXperts LLC
Portland, Oregon, USA
gregj at pobox.com






From thomas at xs4all.net  Wed May 23 14:56:23 2001
From: thomas at xs4all.net (Thomas Wouters)
Date: Wed, 23 May 2001 20:56:23 +0200
Subject: Python 2.0 quick reference...
In-Reply-To: ; from tim.one@home.com on Fri, May 18, 2001 at 04:52:54AM -0400
References: <31575A892FF6D1118F5800600846864D78BC26@intrepid> 
Message-ID: <20010523205623.C690@xs4all.nl>

On Fri, May 18, 2001 at 04:52:54AM -0400, Tim Peters wrote:
> [Simon Brunning]
> > ...
> > I'm not familiar with Lynx. Which is consultant-speak for 'I've never
> > heard of it'. Could someone point me at it? (I did a quick google, but
> > most of the links point at some obscure browser.)
> 
> Bingo.  Lynx is an obscure text-only browser, hence Andrew's suggestion to
> use Lynx for obtaining a plain-text version of your quick reference guide.

Note that there is also 'links', which is basically a non-obscure text-only
browser. It has menus and all those things you windows weenies seem to
include in the 6 food groups... :)

-- 
Thomas Wouters 

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!



From tdelaney at avaya.com  Tue May 15 20:17:00 2001
From: tdelaney at avaya.com (Delaney, Timothy)
Date: Wed, 16 May 2001 10:17:00 +1000
Subject: General...
Message-ID: 

> Hello,
> 	I love all these speed debates but if speed were our 
> only concern we would 
> all be writing in assembly for all non internet based programs...!
> 
> 	Thank you,
> 	Vincent A. Primavera

Note: I am agreeing with the spirit of Vincent's post here for those who
can't tell ;)

I wouldn't say that. There are very few assembly programmers on any platform
who can out-optimise a decently-optimising C compiler over the scope of an
entire project. Sure - they may be able to do better on small, tight parts
of the code - but the entire code base? Nah. Add in the extra time it takes
to code up and optimise, and you might as well be coding in Python ...

What's that I hear? This program is only going to be run once, but will take
a long time to run? Which will take more time in total? Coding in assembly,
testing, [recoding it right, testing, ...], finally running it once, or
coding in C, testing, [recording, testing, ...] finally running it once, or
coding in Python, testing, [recoding, testing, ...] and running it once?

Or a program that will exist for a long time, being run regularly? Will the
program *ever* need to change? (Answer to rhetorical question ... "Yes").
Who is going to do the maintenance? (Answer to rhetorical question ...
"Hopefully, not me!"). Is assembly or Python going to require the greater
effort to modify? Are many of the optimisations going to be thrown out
because the maintainer doesn't understand them? (Answer to rhetorical
question ... "Yes").

There is definitely a place for optimised assembly code. For example, I use
VirtualDub for part of the process of making VCDs. I greatly appreciate that
many of the filters are written in optimised assembly - in some cases this
as much as doubles the frame rate. The program is written in C, but specific
parts (some filters, some specific parts of the actual application) are
written in hand-optimised assembly.

This is IMO the model that should be followed for all projects, and Python
is a shining example. Write it in a high-level language, then find out what
is too slow. If possible, optimise it in the same language. If you can't see
any non-obscure way to optimise it further, look at moving that part to a
lower-level language (in Python's case, writing a module/class, etc in C).

Tim Delaney



From davygrvy at pobox.com  Thu May 31 18:27:47 2001
From: davygrvy at pobox.com (David Gravereaux)
Date: Thu, 31 May 2001 15:27:47 -0700
Subject: crossing boundaries into Tcl
Message-ID: 

Hi All,

Being a Tcl-Head, python is new to me.

I just got tclpython from ->
  http://jfontain.free.fr/tclpython.htm
  http://jfontain.free.fr/tclpython-2.0.1.tar.gz

After a few edits to work on windows, I tried it, but no return value is sent
back to Tcl:

D:\itcl_exp>tclsh84
% load tclpython20.dll
% set i [python::interp new]
python0
% $i eval {import sys ; sys.version}
% $i eval {sys.version}
% $i eval {_}
python0: Traceback (most recent call last):
  File "", line 1, in ?
NameError: name '_' is not defined
%

Yet from the python shell:

D:\Python21>python
ActivePython 2.1, build 210 ActiveState)
based on Python 2.1 (#15, Apr 23 2001, 18:00:35) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.version
'2.1 (#15, Apr 23 2001, 18:00:35) [MSC 32 bit (Intel)]'
>>> _
'2.1 (#15, Apr 23 2001, 18:00:35) [MSC 32 bit (Intel)]'
>>>


In the source code for tclpython, is a note that states a small patch is needed
to python to enable return values:

        /* in ceval.c, eval_code2():
            case POP_TOP:
                v = POP();
                // (this line added) store result in _ global variable
                PyDict_SetItemString(f->f_globals, "_", v);
                Py_DECREF(v);
                continue;
        */

I would not like to patch python to run it from Tcl, if at all possible.  How
can I grab the result of an operation called by PyRun_String()?  Is it lost
forever in the POP when v decremented?  I really have no clue what I'm doing :)

TIA,
--
David Gravereaux 


From aleaxit at yahoo.com  Wed May  9 04:48:32 2001
From: aleaxit at yahoo.com (Alex Martelli)
Date: Wed, 9 May 2001 10:48:32 +0200
Subject: do...until wisdom needed...
References:  <9be84s0q12@news1.newsguy.com>  <9bfjoc0cjh@news2.newsguy.com>  <9bfq560noo@news2.newsguy.com>  <87n19fvdzo.fsf_-_@elbereth.ccraig.org>      <9biukr$lu8$1@nntp9.atl.mindspring.net>  <9cqpq9$dvm$1@nntp9.atl.mindspring.net>  <9d53ku$o9j$1@slb6.atl.mindspring.net>  <9d5rc6$l5q$1@nntp9.atl.mindspring.net> <9d61os0i05@news2.newsguy.com>  <9d92fo01thk@news2.newsguy.com> 
Message-ID: <9db08u017gs@news2.newsguy.com>

"John Flynn"  wrote in message
news:mf5K6.3221$ZJ.121045 at ozemail.com.au...
    ...
> [*] Alex: since you can't quite finger your personal reasons for not
wanting
> to use Lisp/Scheme - even though they were strong early influences, I
wonder
> whether, rather than being permanent, early influences (like old clothes
and
> old loves) become something that one "grows out of".

Maybe.  Lisp is what got me hired for my first job (at Texas
Instruments), but the software for my thesis had been first
prototyped in APL, then recoded in Fortran and VAX assembly,
and what that software "compiled" was AHPL, a hardware
description language with some similarities to APL.  A good
Pascal implementation was what I really yearned for, and I
was one of the very first Borland customer as soon as Turbo
Pascal got launched -- by that time I was with IBM Research,
struggling to get Pascal/VS accepted in a community more
used to Fortran, PL/I, APL2, and some 370 assembly language
where needed.  I count my first meeting with Rex (the
original internal name of what later became Rexx) as one
of these "early influences" too, as Mike Cowlishaw worked
in another European research centre for IBM, so that
community looked upon it with some favour (is there an
IH syndrome to oppose to NIH?-) -- the 370-assembly sources
for that interpreter were truly masterful, as I recall.
Meanwhile I had met with non-imperative-oriented languages,
particularly Sequel (later to become SQL) and Prolog, some
FP (Backus', and a thing called DWIM, IBM internal only I
believe), and back to Fortran too for "supercomputing"
(vectorized & parallelized numerical computation)...

Given this congeries of programming-language styles I was
influenced by, early on, I guess it DOES count as something
of a confirmation of your hypothesis that later I found
myself relying on C and C++ more than any other language
for my daily work, for years... C++ is still what I mostly
get paid for, actually.  Hard to find languages farther from
all poles in that "early influences" set -- Fortran & its
variants, APL & ditto, Lisp & ditto, PL/I, assembly ones,
Pascal & friends, scripting (Rexx), SQL, Prolog, FP...


> The fact that you chose a _completely_ unfamiliar language - Modula-2 -
> tends to support the hypothesis...

Hmmm, I saw it as an evolution of my beloved Pascal, actually.

Looking back over those early years, scripting languages, or
Pascal and variations thereof when scripting was not feasible,
was what I used by choice, when I had no external constraints,
nor special reasons to use special-purpose approaches such
as SQL or Prolog.


Alex





From sk at gluit.de  Fri May 18 11:45:27 2001
From: sk at gluit.de (Stefan Kirchberg)
Date: Fri, 18 May 2001 17:45:27 +0200
Subject: Ternary Operator
Message-ID: <3B054397.71A1A29F@gluit.de>

Hi,

I just read section 4.16 of The Whole Python FAQ
(http://www.python.org/doc/FAQ.html#4.16). It states that as an
equivalent to C/C++'s
        a? b : c
expression, the Python expression
        a and b or c
has a flaw if b evaluates to 0 (false) and the expression
        (a and [b] or [c])[0]
being a possible solution. Unfortunately, the latter one seems
kind of obfuscated to me...

Now, how about
        [b,c][not a]
-?

Maybe this one's just frequently asked... but I didn't find it
in the FAQ :-)

Stefan

---
Stefan Kirchberg  -- sk at gluit.de


From emile at fenx.com  Sat May 26 10:29:37 2001
From: emile at fenx.com (Emile van Sebille)
Date: Sat, 26 May 2001 07:29:37 -0700
Subject: Making a dict from two lists/tuples
References: <87u22bw197.fsf@womble.dur.ac.uk> <9eip7i0s67@enews1.newsguy.com> <9ej1bl$36fcc$1@ID-11957.news.dfncis.de> <9ej4b401cvs@enews1.newsguy.com> 
Message-ID: <9eoesl$cv7h$1@ID-11957.news.dfncis.de>

"Jonathan Feinberg"  wrote in message
news:ofsgciqx.fsf at pobox.com...
> "Alex Martelli"  writes:
>
> > temp=[decorate(x) for x in beep]
> > temp.sort()
> > beep[:]=[undecorate(x) for x in temp]
>
> I was wondering what a Schwartzian Transform might look like in
> Python. ;)
>

What's that?  ;))

LOL-ly y'rs

--

Emile van Sebille
emile at fenx.com

---------




From not.this at seebelow.org  Thu May  3 00:43:04 2001
From: not.this at seebelow.org (Grant Griffin)
Date: Wed, 02 May 2001 23:43:04 -0500
Subject: Choosing a programming language as a competitive tool
References:  <3dlmoflsjv.fsf@ute.cnri.reston.va.us>   <9cpnn702egu@news1.newsguy.com> 
Message-ID: <3AF0E1D8.63E7B2A8@seebelow.org>

Steve Cooper wrote:
> 
> Do you work for a publically held company?  Does it create software products?
> You don't actually have to answer (obviously :-)), although I confess to
> curiousity.  I'm just trying to bring up the reality that the above two factors
> are powerful, often irresistable forces in creating short-sited environments.

Personally, I think the main cause of short-sightedness is
short-sightedness.  Or maybe "not invented here".  Or maybe
incompetance.  Or maybe laziness.  Or maybe apathy.  Or more likely
inertia.

I've found it amazingly hard to sell Python to people--for "The Amazing
Low Price of Absolutely Free".  You might think something like this
would cost a lot of money.  Or you might think it ran only on Windows. 
Or you might think that it would be hard to learn, or maybe hard to
use.  Or you might even think that it does one thing well, but if you
want to do something else, it's no darn good.  But it's none of those
things.  It's like a Swiss Army Knife, except useful.  (Still, I miss
that toothpick thingy )

So why won't people buy Python--for *free*?!  (OK, maybe I'm just not
the world's greatest salesman .)

Maybe it just comes down to Rule Number 4:

	"Improve your own system, but don't try to improve the Company's
system."

I'm not quite sure why we have Rule Number 4.  I've never figured it
out.  All I can do is tell you that every time I indulge my evangelistic
instincts and violate Rule Number 4, I realize again just how wise Rule
Number 4 really is.

usenet-tends-to-attract-us-rule-number-4-violators-ly y'rs,

=g2
-- 
_____________________________________________________________________

Grant R. Griffin                                       g2 at dspguru.com
Publisher of dspGuru                           http://www.dspguru.com
Iowegian International Corporation            http://www.iowegian.com


From meyer at kampsax.dtu.dk  Mon May 28 09:30:44 2001
From: meyer at kampsax.dtu.dk (Jonas Meyer Rasmussen)
Date: Mon, 28 May 2001 15:30:44 +0200
Subject: Permanently Adding A Directory to Pythonpath
References: 
Message-ID: <9etjsv$quh$1@eising.k-net.dk>

you have to do it in autoexec.bat
add a line something like this:

SET PYTHONPATH=C:\a...;C:\...;C:\..

it should work
"Darren Watson"  wrote in message
news:JBqQ6.6997$lm5.1200570 at news6-win.server.ntlworld.com...
> Hi
>
> I would like to know how to add a directory to my Pythonpath permanently.
I
> have tried appending to sys.path and this works fine during interactive
> work, but I would like to always have a directory available in the path.
>
> I am using ActivePython 2.1 on windows 98
>
> Any help would be appreciated.
>
> --
>
> Darren Watson
>
>
>




From root at rainerdeyke.com  Sun May 27 00:51:40 2001
From: root at rainerdeyke.com (Rainer Deyke)
Date: Sun, 27 May 2001 04:51:40 GMT
Subject: [Q]Python Classes
References: <9epv95$9m8$1@news01.cit.cornell.edu>
Message-ID: 

"Siew-Ann Cheong"  wrote in message
news:9epv95$9m8$1 at news01.cit.cornell.edu...
> In C++, I am used to the construct:
>
> class MyClass
> {
> public:
> MyClass(int data)
> {
> private_data = data;
>
> MyInitialization();
> }


Completely off topic remark: IMO it is better to use the preamble for
initialization, like this:

MyClass(int data)
  : private_data(data)
{
  MyInitialization();
}


> void MyInitialization()
> {
> ...
> }
> private:
> int private_data;
> }

> However, if I try to do the same thing in python,
>
> class MyClass:
> def __init__(self, data):
> self.private_data = data
> MyInitialization()

This line should be:

  self.MyInitialization()

(At the correct indentation level, of course.)

> def MyInitialization(self):
> ...
>
> I get complaints on MyInitialization().



--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor




From aleaxit at yahoo.com  Wed May 23 06:23:29 2001
From: aleaxit at yahoo.com (Alex Martelli)
Date: Wed, 23 May 2001 12:23:29 +0200
Subject: problems using % in strings with %(var)s replacements
References: 
Message-ID: <9eg32n029ef@enews1.newsguy.com>

"Thomas Weholt"  wrote in message
news:jPLO6.2171$556.193068 at juliett.dax.net...
> Say I got a string s = "%(number)s among 50% are efficient for
> %(customer_name)s."
    ...
> I see the % in 50% is the problem but how can I use the %-char in strings
> and still use %(...)s replacements??

Just "double up" the percent-character:

D:\py21>python
Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> s="%(number)s among 50%% are efficient for %(custname)s"
>>> number=23
>>> custname='Alex'
>>> print s%globals()
23 among 50% are efficient for Alex
>>>


Alex





From machin_john_888 at hotmail.com  Wed May 23 18:32:23 2001
From: machin_john_888 at hotmail.com (John Machin)
Date: 23 May 2001 15:32:23 -0700
Subject: extending Python with C anywhere (was Re: Extending Python with C/C++ on a win32 platform)
References:  <9ege3v02q8p@enews1.newsguy.com>
Message-ID: <92ae279c.0105231432.7aab5dde@posting.google.com>

"Alex Martelli"  wrote in message news:<9ege3v02q8p at enews1.newsguy.com>...

[snip]
> Still, if you DO want to use the C-level API, it's not rocket
> science... just a documentation problem.  Building stuff under
> windows has become wonderfully easy thanks to the distutils!-)

Astonishingly easy, even with the Borland compiler --- congrats to the
distutils developers!

> Here's a toy-level example, fully portable to VC++ and
> all other Python-supported platforms.  It's an extension
[snip]
> But the functionality isn't very important -- the key
> is, once having a correct, portable "bill.c" file, how
> do you build it _everywhere_?
> 
[snip]
> 
> There -- a single command did the build AND
> installed the .pyd into our \Python21 directory.
> Ain't it cool?-)
> 
> And now we test (we should really have a unit test
> script of course...:-):

Radically kool, dood ... but "Test before install" might be a
preferred order for some folks. You might even find some wrinklies who
would say "back-up before install".

[snip]
> ::: bill.c
[snip]
>     if(!value) { // deletion

C? Portable? 

OK, enough nit-picking. The other 99% was good value. I'd just like to
add a recommendation to all newbie extension craftspersons:

There is a large quantity of solid well-written robust working C-coded
extensions out there. You don't have to look much further than the
Python source itself, in the modules and objects directories. Think of
a Python construct that's structurally similar to what you want to do,
then go find where it's implemented. For example, you want to parse a
string and return a list of bits and pieces? Study the implementation
of the split method in stringobject.c. The next place to look would be
in the Vaults of Parnassus ... lots of good stuff there too.


From thomas.heller at ion-tof.com  Fri May 18 11:09:39 2001
From: thomas.heller at ion-tof.com (Thomas Heller)
Date: Fri, 18 May 2001 17:09:39 +0200
Subject: Offtopic question (windows, C)
References: <9e38g7$pl67$1@ID-59885.news.dfncis.de> 
Message-ID: <9e3dtv$qfhi$1@ID-59885.news.dfncis.de>

> What about doing the loadlibrary call explicitly in the client code and
> then finding the address of the duplicate name entrypoint.
That would of course work, but I would prefer to do it the implicit way.
Is it still possible?

Thomas




From grante at visi.com  Wed May  9 10:34:00 2001
From: grante at visi.com (Grant Edwards)
Date: Wed, 09 May 2001 14:34:00 GMT
Subject: socket.recvfrom() & sendto()
References:    <3AF8CAA4.1A834B8@my.signature> 
Message-ID: 

In article , Ron Johnson wrote:
>Greg Ewing wrote:
>
>> Ron Johnson wrote:
>>> 
>>> how can the client accept input from the
>>> user at the same time that it is "stalled" at a select() ?
>> 
>> By including the file descriptor from which you're
>> reading user input in the select().
>
>That works on unices, but not on Win32, according to the python.org
>documentation, and my wife wants to play the game on her PC...
>
>Or am I missing something else???

No, you're not.  Win32 has numerous blatant design problems,
and that's one of them.

-- 
Grant Edwards                   grante             Yow!  PIZZA!!
                                  at               
                               visi.com            


From mcalla at home.com  Mon May 14 17:24:30 2001
From: mcalla at home.com (Mike Callahan)
Date: Mon, 14 May 2001 21:24:30 GMT
Subject: String Problem
References: 
Message-ID: 

How about this at first hack:

>>> def func(input, targets, x):
    inputlist = input.split(' ')
    try:
        i = inputlist.index(targets[0])
        j = inputlist.index(targets[1])
    except ValueError:
        return None
    if i > j:
        i,j = j,i
    return ' '.join(inputlist[i-x:j+x+1])
>>> input = "what light through yonder window breaks, tis in the East and
Juliet is the sun"
>>> targets = ('East','yonder')
>>> print func(input, targets, 2)
light through yonder window breaks, tis in the East and Juliet
>>> print func(input, ('light','tis'), 1)
what light through yonder window breaks, tis in
>>>

I am not sure that 10 lines is a mess of code. Of course, you could shorten
it.

Mike

"Colin Meeks"  wrote in message
news:s5XL6.93670$2_.31065520 at news3.rdc1.on.home.com...
> I have the following problem and was wondering how people would go about
> solving it.
>
> I have a variable string with different keywords in it.  What I would like
> to do is trim the string so that it has X words either side of the
requested
> keywords.
>
> i.e. what light through yonder window breaks, tis in the East and Juliet
is
> the sun.
>
> I would like to specify say, Yonder and East and trim the trim to x words
> around it.  So if I wanted 2 words either side I would end up with
>
> "light through yonder window breaks, tis in the East and Juliet"
>
> I'm trying to write a small search engine.  Although I could write a mass
of
> code to do what I want, I was wondering if a regular expression could be
> used, or anything else, similarly simplistic.?
>
> Colin
>
>




From sholden at holdenweb.com  Wed May  9 22:00:09 2001
From: sholden at holdenweb.com (Steve Holden)
Date: Wed, 9 May 2001 22:00:09 -0400
Subject: Range Operation pre-PEP
References: 
Message-ID: <#nIm7WP2AHA.293@cpmsnbbsa09>

"Delaney, Timothy"  wrote ...
[ ... ]
> Well, there would be a simple way to make ranges that conformed to both.
Use
> the mathematical notation for describing inclusive and exclusive bounds
> (although it would be using '..' instead of ',').
>
> If I remember correctly ...
>
> [0..10] - range is 0 to 10
> [0..10) - range is 0 to 9
> (0..10] - range is 1 to 10
> (0..10) - range is 1 to 9
>
Correct me if I'm wrong, but don't the concepts of open and closed intervals
belong to analysis and not discrete mathematics -- in other words, they
apply to infinite sets but not finite ones. An open interval (x,y) is the
set of all numbers strictly greater than x and strictly less than y.
Dedekind will be turning in his grave...

This proposed notation (and you aren't the first to propose it) would be
bizarrely misunderstood by newcomers. I certainly don't want to have to
explain that the same object can be described in four different ways, and
suggest when [1..9] is more appropriate than (0..10) is more appropriate
than [1..10) is more appropriate than (0..9].

So, why have four representations for the same thing?

there-should-be-one-obvious-way-to-do-it-ly y'rs  - steve



From johnroth at ameritech.net  Thu May 24 20:22:57 2001
From: johnroth at ameritech.net (John Roth)
Date: Thu, 24 May 2001 17:22:57 -0700
Subject: new ideas?
References: <9eiis0$1v2e$1@news.nextra.cz> <9ejese$pr5$1@news.mathworks.com>
Message-ID: 

"Joshua Marshall"  wrote in message
news:9ejese$pr5$1 at news.mathworks.com...
> Jan Veleta  wrote:
> > I have found article about some programming language I never heard of.
> > I is called Standard ML, and one of the things which attracted my
attention
> > was
> > that it uses garbage collector while using machine generated code.
>
> > It's syntax is obviously far from python, but maybe some of compiler
gurus
> > may take a look at it, as it can bring some new ideas into python world.
>
> > Maybe it can help even in moving on compiled form of python.
>
> SML's a great language, but these ideas aren't too new.  Compilers for
> Common Lisp (eg.) have been doing this for a while.  My impression is
> that compilers aren't available for Python primarily because nobody's
> put the effort into it.
>
> Also of note is that SML is a statically-typed language, making
> compilation easier.  (Although this doesn't help things from a GC
> point-of-view.)

I would expect to be disappointed in a Python compiler. The reason is
simple: compiled languages are supposed to be fast, but the more
dynamism in a language, the more process time goes into the
operations, and the less goes into the interpreter. If you look at typical
compiled languages, you will find that the efficient parts are the
statically typed stuff - an int is an int, not an object that has to
be dynamically allocated, dispatched and garbage collected. In a
statically typed language, A = B + C can frequently be put into
three or four machine instructions (depending on the architecture). If
you can't depend on a specific name being an int, each and every time,
then you have to generate expensive method calls, etc.

Of course, there are dynamic type determination strategies, etc, but
you're never going to get the raw performance out of compiled Python
that you'd get if you just broke down and put the slow parts in C (or
Assembler, if you're really in a bind, or doing the next great push the
edge shootem up graphic game.

Guido seems to have done a very good job at wringing excess
overhead out of the interpreter. As the optimization people say, the
first thing you look at is choice of algorithm. Only then do you worry
about recoding it in a faster language - that is only going to get you
a linear speedup.

John Roth




From piet at cs.uu.nl  Fri May  4 07:52:47 2001
From: piet at cs.uu.nl (piet at cs.uu.nl)
Date: 04 May 2001 13:52:47 +0200
Subject: help: cgi "post" problem (client side)
References: <9copk9$2ic5$1@news6.isdnet.net>
Message-ID: 

>>>>> "Gilles Lenfant"  (GL) writes:

GL> Hi,
GL> I'm making some CGI tests with Win98 and MS Personal Web Server.

GL> I installed this simple test cgi script:

GL> =======test.py=======
GL> import cgi
GL> cgi.test()
GL> =====================
....
GL> But when I do this through this script, this goes to a deadlock:

GL> =======runcgi.py=======
GL> import urllib
GL> params = {'param1': 'data1', 'param2': 'data2'}
GL> cparams = urllib.urlencode(params)
GL> # Deadlock in next line
GL> fh = urllib.urlopen('http://localhost/cgi-bin/test.py', cparams)
GL> # No deadlock with no "cparams" like this
GL> # fh = urllib.urlopen('http://localhost/cgi-bin/test.py')
GL> =======================

GL> But aren't the HTML and runcgi.py supposed equivalent ?
GL> Did I miss something or should I use Apache or another Web server ?
GL> Thanks in advance for any hint.

It works with Apache (on Windows 2000).
-- 
Piet van Oostrum 
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl


From spooky_jesse at yahoo.com  Tue May 29 09:09:36 2001
From: spooky_jesse at yahoo.com (Jesse Legg)
Date: 29 May 2001 06:09:36 -0700
Subject: macPython: accessing string data in resource files
Message-ID: 

Hey all,

I'm having difficulty figuring out a way in Python to access string
list data ('STR#') stored in a resource file. Is there an equivalent
procedure to the GetIndString which is described in the Text Utilities
routines documentation from Apple?
http://gemma.apple.com/techpubs/mac/Text/Text-285.html

If so, which module is it in? What is/how do I find out it's syntax?
I would be very grateful for any help, I've been doing a lot of
searching for information on this subject.
Thanks in advance,
 Jesse


From fgranger at mac.com  Sat May 26 06:27:11 2001
From: fgranger at mac.com (=?ISO-8859-1?Q?Fran=E7ois_Granger?=)
Date: Sat, 26 May 2001 10:27:11 GMT
Subject: Yielding from interpreter inner loop in MacPython
References: <9dclo1$nrl$1@bob.news.rcn.net>
Message-ID: <1eu0kfu.1f1ud1fnytzdhN%fgranger@mac.com>

Christian Reyes  wrote:

> Is there a way to have the interpreter inner loop yield to other processes
> in MacPython.
> 
> I've been tinkering with MacOS.SchedParams but I'm not noticing any
> performance differences.

I did some testing on this MacOS.SchedParams and, yes, it does not do
much good.

-- 
"La vie est une maladie sexuellement transmissible  dont l'issue est
g?n?ralement fatale." - Inconnu, Signature de Noelle Adam


From ben.hutchings at roundpoint.com  Tue May 22 17:31:02 2001
From: ben.hutchings at roundpoint.com (Ben Hutchings)
Date: 22 May 2001 14:31:02 -0700
Subject: Python & Linux ?
References: <3B0A0C89.1070108@bigpond.net.au> <3B0AAC4D.D99B0BE1@email.mot.com>
Message-ID: 

Mark Wyatt  writes:
> Peter Moscatt wrote:
> 
> > I have just migrated from Win98 over to Linux.  My programming platform
> > under Win98 was VB.
> > Now in Linux, I have decided to program using the Python platform.
> > I have bought myself a get started book and from what I can gather -
> > Python is a Interpreter and not a Compiler, therefore only being able to
> > develop scripts instead of installable programs.

> This Microsoft Guy (sorry, don't have the article, and memory is not
> what it was) went on to say that Compiler or Interpreter is a false
> opposition. I hadn't thought of it like that, but it is true.

If you mean that dividing languages into 'compiled languages' and
'interpreted languages' is making a false distinction, then I would
agree.

If you mean that compilers and interpreters are much the same thing, I
strongly disagree; I think there's a clear distinction.  An
interpreter runs programs written in a particular language, whereas a
compiler translates programs from one language into another.  A
processor (possibly together with support code from an OS) is an
interpreter for a particular machine code.  So eventually every
program must be run by an interpreter.

> As I said earlier a lot (but not all) of the Pascal systems of the
> time compiled source code to p-code, and interpreted p-code. This,
> in principle, is the same general scheme as compiling byte-code and
> interpreting that, which many modern languages, or more exactly,
> modern implementations of languages, do. So they actually have both.

Sure - they combine the interpreter and compiler in one program.
That doesn't mean that you can't identify two different things
happening in that program.


> Now, what's a script? In UNIX parlance a script is a simple, or not
> so simple, program usually to perform some administrative task, or
> tasks.

Also, scripts are written in high-level languages, and their source is
used directly rather than being compiled before use.

> So, probably, if I felt in a nit-picking frame of mind I
> should complain at many of those who say they have written 'hello
> world' programs, that they have written 'hello world' scripts,
> particularly if they ran on UNIX systems and produced their output
> in a shell rather than in their own little window, with decorations
> and buttons to push.


But a script *is* a program, as you said above, so they would be
correct and your nit-picking would be unjustified.

-- 
Any opinions expressed are my own and not necessarily those of Roundpoint.


From Pieter_Claerhout at CreoScitex.com  Mon May 21 11:17:01 2001
From: Pieter_Claerhout at CreoScitex.com (Pieter Claerhout)
Date: Mon, 21 May 2001 17:17:01 +0200
Subject: How hard can this be?
Message-ID: <2B1262E83448D211AE4B00A0C9D61B0301DDDE78@msgeuro1.ste.scitex.com>

I think you're missing a small part here:

>>> import math
>>> if x > 0:
...  print "x is positive"
...
Traceback (innermost last):
  File "", line 1, in ?
NameError: x
>>>

If you just type in this in the Python interpreter, it doesn't know yet
about the variable x, because it doesn't exist yet. You should do something
like:

>>> import math
>>> x = 2
>>> if x > 0:
...     print "x is positive"
...
x is positive
>>>

PS: you can even skip the import of math, because it is not even used in the
example shown above.

Cheers,


Pieter

Pieter Claerhout - Application Support
CreoScitex Europe - www.creoscitex.com


-----Original Message-----
From: Patrick Kirk [mailto:pknews at kirks.net]
Sent: Monday, May 21, 2001 5:13 PM
To: python-list at python.org
Subject: How hard can this be?


  if x > 0:
    print "x is positive"

You would think anyone could enter that but I can't.  I get the following:

>>> import math
>>> if x > 0:
...  print "x is positive"
...
Traceback (innermost last):
  File "", line 1, in ?
NameError: x
>>>

I've tried creating a .py file saying:
  if x > 0:
    print "x is positive"
and importing it but that doesn't work either.

>>> import a
Traceback (innermost last):
  File "", line 1, in
  File "a.py", line 1
    if x > 0:
    ^
SyntaxError: invalid syntax



The worrying thing is that this is copied directly from the tutorial so I
may well be off to Alan gould's site shortly.  But is there something
obvious that I'm missing?

Thanks in advance.


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



From lac at cd.chalmers.se  Sun May 27 07:51:57 2001
From: lac at cd.chalmers.se (Laura Creighton)
Date: Sun, 27 May 2001 13:51:57 +0200 (MET DST)
Subject: help building a chain-of-command (or maybe Object Oriented Recursion)
Message-ID: <200105271151.NAA11683@boris.cd.chalmers.se>

I think my design might be fatally flawed.  I want to lay it out here 
and see what you think.

I want to use Decorators and to add functionality to basic Tkinter
Widgets.  I want to be able to stack them in any arbitrary order, so I
only have to write the have-scrolling-ability object once, and then
both be able to scroll a text widget that has a yellow border (the
border gets scrolled as well) and put a yellow border around a 
scrollable text widget (the border stays put and the text scrolls
around inside it).  I also want to be able to add my decorators dynamically.
You can put a red border around a black border if you want to.

I think I understand how the method parts should go.  Given a list
['BorderDecorator', 'ScrollDecorator', 'ValidationDecorator', `MyMegaWidget',
 'Tkinter.Entry'] and a method object (say 'resetfield'), I march down from
top to bottom asking `do you know how to do that?'  by redefining __getattr__.
If my __getattr__ gets called, you know that this object doesn't know how 
to do that method, so my __getattr__ should just call apply of list[0]
on list[1:].  {I have just reimplemented CAR and CDR and we can now 
proudly say that there is nothing that you can do in Lisp that you can't
do in python.  It's just a simple matter of programming, }.

Eventually the method call succeeds, and you go away happy, or you run
out of methods to call.  I don't know what the advantages of building a
DoesNotImplement object and stick it on the end of every such list I
build vs checking to see if list[0] exists, both ideas occurred to me.

If you want your decorators to either do the whole job or forward it
to somebody else, then you are building the Chain of Command.  If you
want them to do as much as they can and then forward what they can't
on you aren't supposed to call it Chain of Command and the Design
Patterns Smalltalk Companion calls it Object Oriented Recursion.  But
the idea is the same.  

But there is a problem. The Scrollbar Widget and the other Widget
that is going to be scrolled really need to know about each other.
To connect a  scrollbar to a widget, you have to set the widget's
(x or y)scrollcommand callbacks to the set method of the scrollbar, and
set the scrollbar's command to the (x or y)view method of the widget.

I don't think that this means that my design is fatally flawed.   But I
don't know how the creational part of this idea is supposed to go.  If
I could make one, I could use it all right but I don't know how to
go about making one.  Has anybody done this?  Or can anybody tell
right off that I can't do this, no matter how much I want to, and I have
to start over again?

Thanks for listening.
Laura Creighton







From MarkH at ActiveState.com  Mon May 21 21:02:16 2001
From: MarkH at ActiveState.com (Mark Hammond)
Date: Tue, 22 May 2001 01:02:16 GMT
Subject: _winreg troubles!  HELP!
References:  <3B09942F.6030706@ActiveState.com> 
Message-ID: <3B09BB1B.10906@ActiveState.com>

Wolfgang Strobl wrote:

> On Mon, 21 May 2001 22:16:13 GMT, Mark Hammond 
> wrote :


This turns out to be easy:

> hEnvironment = _winreg.OpenKey( h, "Environment", _winreg.KEY_SET_VALUE  )


The docs for _winreg.OpenKey say:

key = OpenKey(key, sub_key, res = 0, sam = KEY_READ) - Opens the 
specified key.


Note that you are passing "KEY_SET_VALUE" as "res", and leaving "sam" 
the default of KEY_READ.

Changing the code to:

hEnvironment = _winreg.OpenKey( h, "Environment",
                                0, _winreg.KEY_SET_VALUE)

Makes it work.

Mark.



From jim.vickroy at noaa.gov  Thu May 10 10:47:22 2001
From: jim.vickroy at noaa.gov (jim.vickroy)
Date: Thu, 10 May 2001 08:47:22 -0600
Subject: Regular expressopn problem
References: 
Message-ID: <3AFAA9FA.97CF9717@noaa.gov>

Hello Martin,

This is what I tried:

>>> import re
>>> parser =
re.compile(r"([0-9A-Ea-e]+-[0-9A-Ea-e]+-[0-9A-Ea-e]+-[0-9A-Ea-e]+-[0-9A-Ea-e]+)")

>>> result =
parser.search('4CA064D0-5653-45E4-9581-9EE9A9B12A49')
>>> result

>>> result.start()
0
>>> result.end()
51
>>>

I do not think you need to "escape" hyphens outside the [] expressions.

BTW, have you looked at xml.sax.  If all you want to do is parse an xml
document, the SAX interface may be easier as it does this sort of parsing for
you.




Martin Bertolino wrote:

> I'm using Python 2.0 to try to parse out some GUIDs from an XML document
> returned from an HTTP server, but I'm having some problems with some regular
> expressions that I believe should match what I'm looking for.
>
> Consider the following input to the parse_token function:
>
> 
>      response_id="E95FA6E0-3944-4945-93CD-4E37EDB807E3"
>             code="0000" result_msg="success">
>                 4CA064D0-5653-45E4-9581-9EE9A9B12A49
>                 
>                 
>                 
>                 
>                  suffix="sr."/>
>                 central
>     
> 
>
> and the parse_token function, whick attempts to get the value of the 
> node,  implemented as follows
>
> import re
>
> def parse_token(output_xml):
>     # v0: token_re =
> re.search(r"([0-9A-Ea-e]+\-[0-9A-Ea-e]+\-[0-9A-Ea-e]+\-[0-9A-Ea-e]+\-
> [0-9A-Ea-e]+)", output_xml)
>     # v1: token_re = re.search(r"([0-9A-Ea-e\-]+)",
> output_xml)
>     token_re = re.search(r"(.+)", output_xml)
>     if token_re:
>         return token_re.group(1)
>     else:
>         raise "unable to parse token out of output xml"
>
> The re.search that is not commented correctly matches the node so it returns
> 4CA064D0-5653-45E4-9581-9EE9A9B12A49. The other two (v0 and v1) do not. I
> tried those two RE on a perl script, and I do get the expected output.
>
> Am I missing something? It seems as if the compile is getting thrown by the
> '-'s in the RE.
>
> Thanks for the help.
>
> Martin Bertolino



From sill at optonline.net  Thu May 31 14:51:36 2001
From: sill at optonline.net (Rainy)
Date: Thu, 31 May 2001 18:51:36 GMT
Subject: python "jump" or "goto" commands?
References: <7b515e0f.0105301414.b14278c@posting.google.com> 
Message-ID: 

On Wed, 30 May 2001 19:46:57 -0500, Skip Montanaro  wrote:
> 
>     eric> I'd like to know if python has commands similar to "jump" or
>     eric> "goto".
> 
> People use try/except to break out of multiple levels of nesting.  For
> instance:
> 
>     class Label(Exception): pass
> 
>     try:
>         for i in range(100):
> 	    for j in range(100):
> 	        if i*j > 2500:
> 		    raise Label
>     except Label:
>         pass
> 

Or a function with a return statement.. that personally feels a cleaner to me.


-- 
The point of philosophy is to start with something so simple as not
to seem worth stating, and to end with something so paradoxical
that no one will believe it.


From schmitt at num.uni-sb.de  Fri May 25 11:05:49 2001
From: schmitt at num.uni-sb.de (Uwe Schmitt)
Date: 25 May 2001 15:05:49 GMT
Subject: win32com question
References: <9el8gl$6d2l5$1@hades.rz.uni-sb.de> <9elo5l0146d@enews2.newsguy.com>
Message-ID: <9elscd$6btcn$1@hades.rz.uni-sb.de>

Alex Martelli  wrote:

| Hmmm, funny.  Try the following...:

| D:\Python21>python
| Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
| Type "copyright", "credits" or "license" for more information.
k
|>>> from win32com.client.gencache import EnsureDispatch as disp
|>>> x=disp('ADODB.Record')
|>>> import win32com.client as w
|>>> w.constants.adOpenDynamic
| 2
|>>>

| Does this work for you?  If not, you seem to have some serious
| installation problem and might want to uninstall your Python
| and install a known-good one (mine is standard 2.1 plus the
| win32all from ActiveState).  But first try removing the gen_py
| directory and running this again -- it might be corrupted,
| or something.

| If this snippet works, then there must be some problems in
| your code before this point...

thanks for your answer, i'll try it tonite.

yours, uwe
-- 
Uwe.Schmitt at num.uni-sb.de      Universit?t des Saarlandes
phone: +49 (0)681/302-2468     Geb. 36.1, Zi. 4.17, PF 151150
                               D-66041  Saarbr?cken
http://www.rocksport.de        http://www.rocksport.de/first_ride.mp3



From zope at thewebsons.com  Tue May  1 15:56:34 2001
From: zope at thewebsons.com (Ben Ocean)
Date: Tue, 01 May 2001 12:56:34 -0700
Subject: PLEASE Help with CGI Problem!
Message-ID: <5.0.2.1.0.20010501125500.00a1aa10@thewebsons.com>

Hi;
I NEED to get data from the buffer after it is sent to me from a foreign 
host. Here's (apparently) how this would be scripted in perl:
 >>>
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
     ($name, $value) = split(/=/, $pair);
     $value =~ tr/+/ /;
     $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
     $FORM{$name} = $value;
}
<<<
How would I script it in Python and what modules must I call?
TIA,
BenO




From dframe at tampabay.rr.com  Thu May 24 22:47:54 2001
From: dframe at tampabay.rr.com (Daniel Frame)
Date: Fri, 25 May 2001 02:47:54 GMT
Subject: Interrupting a GUI function call? (wxWindows Specifically)
Message-ID: <3b0dc444.8335941@news-server.tampabay.rr.com>

Hello Python Gurus,

I have what I think is a simple question, but I can't seem to find the
answer online, or in any Python Books that I have.

Basically, I've constructed a GUI with wxPython which runs a very long
function when a 'START' button is pressed.

Of course, the GUI is 'locked up' until this function completes
itself.  I was wanting to add a 'STOP' button to my application which
would halt this other function if the user got tired of waiting for it
to complete.

Is it possible to accomplish this without resorting to using threads?

If so, How can I have my running function check occaisonally to see if
the stop button was pressed?

I've heard of wxYield, but I can't seem to  implement it properly.

Thanks in advance for any expertise that you can offer.







From fredrik at pythonware.com  Thu May  3 23:44:28 2001
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Fri, 04 May 2001 03:44:28 GMT
Subject: re grouping question
References: <9ct1ii$n8l$0@216.39.162.232>
Message-ID: 

Michael Esveldt wrote:
> I've got the following code:
>
> s = """some text
>  - foo
>  - bar
>  - fnord
> test..."""
> list_re = re.compile(r'( - .+\n)+')
> print list_re.search(s).groups()
>
> which produces, (' - fnord\n',) when what I was expecting was matching
> all the lines. What I'm really looking for is something more like (' -
> foo\n - bar\n - fnord\n',) or (even better) (' - foo\n', ' - bar\n', ' -
> fnord\n').

>>> list_re = re.compile(r'(?s)( - .+\n)+')
>>> print list_re.search(s).groups()
(' - foo\012 - bar\012 - fnord\012',)

>>> list_re = re.compile(r'( - .+\n)')
>>> print list_re.findall(s)
[' - foo\012', ' - bar\012', ' - fnord\012']

Cheers /F




From mwh at python.net  Fri May  4 10:48:43 2001
From: mwh at python.net (Michael Hudson)
Date: 04 May 2001 15:48:43 +0100
Subject: Threading Question
References: <3AF2343B.4A95E856@nospmmytheworld.com>  <3AF2AA96.9012690D@niospammyraqia.com>
Message-ID: 

David Lees  writes:

> The code I am actually working on is for handeling sockets.  I am pretty
> careful and am passing things in a threadsafe manner between them.  Is
> there any way I can release the lock without writing C code?

The lock is released around operations that might block, eg. file or
socket reads.  So your app can probably benefit from threading.  Pure
Python stuff won't.

Cheers,
M.

-- 
  Java is a WORA language! (Write Once, Run Away)
                	-- James Vandenberg (on progstone at egroups.com)
                           & quoted by David Rush on comp.lang.scheme


From andmalc-ns1 at NoSPaMmalcolmson.ca  Mon May 21 15:00:09 2001
From: andmalc-ns1 at NoSPaMmalcolmson.ca (Andrew Malcolmson)
Date: Mon, 21 May 2001 15:00:09 -0400
Subject: client side scripting
References: <3B0587D3.8388C737@student.kuleuven.ac.be> <9e43db01kah@enews1.newsguy.com> <3B05D2EB.9070807@ActiveState.com>
Message-ID: 

Perhaps Python could be installed on demand via Mozilla's XPInstall.


"Mark Hammond"  wrote in message
news:3B05D2EB.9070807 at ActiveState.com...
> Alex Martelli wrote:
>
> > support multiple alternative clientside script languages -- Javascript
> > is all you get (I hope this isn't so any more in Mozilla, but I think
> > it still is).  In any case, ARE you willing to rely on the end-user
>
>
> It still is.  However, Mozilla are definitely working towards that.
> Very recently code was checked in to allow Python access to the Mozilla
> DOM, which is a step in the right direction.
>
> However, even then, the dependency on Python being installed is almost
> certain to exist - it is unlikely Mozilla/Netscape 6+ will install Python.
>
> One-of-these-days ly,
>
> Mark.
>






From pknews at kirks.net  Mon May 21 08:46:06 2001
From: pknews at kirks.net (Patrick Kirk)
Date: Mon, 21 May 2001 13:46:06 +0100
Subject: Newbie question
Message-ID: <9eb2mf$csj$1@newsg3.svr.pol.co.uk>

Hi all,

I have read that Python is a good first language so I downloaded it and am
wading through a tutorial.  But I'm having silly problems that I can't work
out.

I run Win2k.  Python is in a folder called d:\python.  also in there is a
file called 1.py

At the command prpmpt, I cd to d:\python run python and enter python 1.py.
Error message is:

>>> python 1.py
  File "", line 1
    python 1.py
            ^
SyntaxError: invalid syntax
>>>

Clearly I'm doing something wrong but what?

All help appreciated!

--
--
Patrick Kirk
GSM: +44 7712 184 480
ICQ: 42219699

Wise Chinese Proverb:  "If tired of computer winning at real time strategy
games, try it at kick-boxing instead"




From bsass at freenet.edmonton.ab.ca  Wed May 23 23:28:10 2001
From: bsass at freenet.edmonton.ab.ca (Bruce Sass)
Date: Wed, 23 May 2001 21:28:10 -0600 (MDT)
Subject: PYTHONSTARTUP not working on debian?
In-Reply-To: 
Message-ID: 

On Wed, 23 May 2001, Rainy wrote:

> I'm running debian unstable, python 1.5, 2.0 and 2.1(compiled),
> and PYTHONSTARTUP is set to ~/.pythonrc.py, which contains
> line import time. When I start interactive session, and try
> time.time() for example, it gives me a name error, as if
> time isn't imported. What's wrong?

Same setup here, ~/.pythonrc.py looks like this:

---
print "importing os, sys..."
import os, sys

if sys.version[:3] == '2.1':
    print "importing pydoc.help..."
    from pydoc import help
---

It works OK from a text console, or when starting from the commandline
of a Konsole session... but not when started from Konsole's File menu.
So, there is something in how python gets started that affects if
.pythonrc.py is read (guessing, the difference between starting from a
shell commandline and doing "exec python").


- Bruce




From brakedon at hotmail.com  Thu May 24 20:26:03 2001
From: brakedon at hotmail.com (eric_brake)
Date: 24 May 2001 17:26:03 -0700
Subject: create python program files
Message-ID: <7b515e0f.0105241626.738c1498@posting.google.com>

I need help finding a way to create standalone executable files from
python. I have python version 2.1. I have heard of a "freeze.py" file
that could do it but version 2.1 doesn't include this. any help would
be appreciated.

thank you


From sholden at holdenweb.com  Tue May  1 22:15:23 2001
From: sholden at holdenweb.com (Steve  Holden)
Date: Wed, 02 May 2001 02:15:23 GMT
Subject: Formatting numbers
References:  
Message-ID: <%4KH6.58717$qc2.15144507@typhoon.southeast.rr.com>

"Matthew Dixon Cowles"  wrote in ...
> On Tue, 1 May 2001 16:13:30 -0700, Daniel Klein 
> wrote:
> 
> >Given an integer, 12345, how to format this to 123.45 ?
> 
> Here's one way:
> 
> >>> 12345/100.0 
> 123.45
> 
> You need the ".0" or at least the dot in order to force floating-point
> division.
> 
But:

>>> 12340/100.0
123.40000000000001
>>> 12300/100.0
123.0

so this won't be useful in the general case.  One way might be:

>>> def fmt(i):
...      bits = divmod(i, 100)
...      return "%d.%02d" % bits
... 
>>> fmt(12345)
'123.45'
>>> fmt(12340)
'123.40'
>>> fmt(12300)
'123.00'

The locale module also contains number formatting routines IIRC.

regards
 Steve




From aleaxit at yahoo.com  Fri May 11 18:17:48 2001
From: aleaxit at yahoo.com (Alex Martelli)
Date: Sat, 12 May 2001 00:17:48 +0200
Subject: Range Operation pre-PEP
References: 
Message-ID: <9dhoak02oav@news1.newsguy.com>

"Tim Peters"  wrote in message
news:mailman.989607330.30318.python-list at python.org...
> [Rainer Deyke]
> > I can't think of a single function in the standard library which
> > takes an unbounded number of heterogenous arguments.  I can think
> > of several which take an unbounded number of homogeneous arguments.
> > 'min' and 'max' for example.
>
> ?
>
> >>> import sys
> >>> min(1, 1.0, [1], "one", {1 :1}, sys.stdin)
> 1
> >>>
>
> I suppose those are homogeneous arguments in the sense that they're all
> objects, but if that's the degenerate sense we're using then I don't know
> what heterogeneous could mean.

Isn't it (Python 2.1 at least) "homogeneous in the sense they're all
COMPARABLE"...?  min/max USED TO work on all objects, at least
all built-in ones I think, but no more...:

D:\Python21>python
Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> min(1,'a',2.0,3j)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: cannot compare complex numbers using <, <=, >, >=
>>>

vs the old behavior

D:\Python20>python
Python 2.0 (#8, Oct 16 2000, 17:27:58) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
Alternative ReadLine -- Copyright 2001, Chris Gonnerman
>>> min(1,'a',2.0,3j)
3j
>>>


Python doesn't formally define interfaces/protocols ("yet", he
adds hopefully:-), but "informally" it has them -- here, it seems
to me that the objects min/max accept need to "implement
OrderedComparable" (be adaptable to protocol "compare by
< &c") in the typical informal Python sense of interfaces and
protocols/'implements' and 'adaptable to'...


Alex





From nperkins7 at home.com  Wed May 30 18:21:42 2001
From: nperkins7 at home.com (Nick Perkins)
Date: Wed, 30 May 2001 22:21:42 GMT
Subject: Against PEP 240 
References: 
Message-ID: 

I think there must be a better alternative to using rationals by default.

What about decimal representation.  Numbers could be stored as two integers,
i.e.  (base,exp), meaning (base*10^exp).
Multiplication would be very fast, just multiply bases and add exponents.
Of course, addition and subtraction would be a little harder.
Division would sort-of 'break' the system, possibly resulting in a number
that is not representable as a decimal.

Also, what about irrational numbers like pi and sqrt(2)? The rational number
type would not help much there.  I don't even know how you could begin to
'store' irrationals any sort of 'guarranteed accuracy'.

Maybe the best thing would be to have some combination of:
integers, floats, decimals, rationals, ..and maybe others, with the default
for literals like '7.35' being a decimal type.  This would remove the
'surprise' for most occurrences, but would have to be transparently
convertible to either floats or rationals when necessary.  (I think Scheme
has a big set of number types)

On the other hand, the current system has never bothered me.  I enjoy having
tiny inaccuracies hidden from me.  It all depends on coming to peace with
the idea that a float is just a number that is very close to the number that
I want it to be.




From ngps at madcap.dyndns.org  Fri May 11 11:01:46 2001
From: ngps at madcap.dyndns.org (Ng Pheng Siong)
Date: 11 May 2001 15:01:46 GMT
Subject: Question about M2Cryptro and HTTPS downloads
References: <9d9did0d5l@drn.newsguy.com>
Message-ID: <9dgusq$vbo$1@dahlia.singnet.com.sg>

According to Nigel Linnett  :
> 1: open an https page, and provide the authentication information
> 2: keep the session information intact, then open a different page
> (actually the
> file I need to download) and output this file to the filesystem.
> [...]
> after each of those pages, there is a stream of re-direct pages that I
> get sent through.

I don't have a tutorial for doing such things. 

Are you using http[s]lib or urllib?

> Is anyone aware of a tutorial for using M2Crypto for tasks like this, or
> would someone be willing to give me a hand working on this?
> 
> Please cc: nlinnett @ integranetworks . com  (remove the spaces) on
> replies since I don't get to check the newsgroup while at work.
> 
> Thanks in advance.
> 
> Nigel
> 


-- 
Ng Pheng Siong  * http://www.post1.com/home/ngps

Quidquid latine dictum sit, altum viditur.


From victor at prodigy.net  Thu May 24 19:02:20 2001
From: victor at prodigy.net (Victor Muslin)
Date: Thu, 24 May 2001 23:02:20 GMT
Subject: odbc cursor usage question
Message-ID: <3b0d8c85.21402284@localhost>

Sorry for a newbie question, but I am not all that familar with ODBC.
I am using odbc,dbi modules that came with ActivePython 2.1 (build
201) for Windows platforms.

Am I supposed to allocate the cursor before each time before executing
a SQL statement?

	dbconn = odbc.odbc(cs)
	cur = dbconn.cursor()
	cur.execute(sql)
	resultset = cur.fetchall()
	cur.close()

When I try to reuse the cursor as follows:

	dbconn = odbc.odbc(cs)
	cur = dbconn.cursor()
	cur.execute(sql)
	resultset = cur.fetchall()
	cur.execute(sql2)
	resultset = cur.fetchall()
	cur.close()

Python crashes with a segment violation!!! Unfortunately, when I do
not reuse the cursor, there seems to be a memory leak. It appears that
the cursor object is not garbage collected.

Any suggestions would be REALLY appreciated :-)

TIA


From mcalla at home.com  Tue May  8 16:49:58 2001
From: mcalla at home.com (Mike Callahan)
Date: Tue, 08 May 2001 20:49:58 GMT
Subject: Problem with popen with win98 (python 2.0)
Message-ID: 

What am I doing wrong?

import os
>>> os.popen('notepad')
Traceback (innermost last):
  File "", line 1, in ?
WindowsError: [Errno 2] The system cannot find the file specified
>>> os.popen('c:\\windows\\notepad.exe')
Traceback (innermost last):
  File "", line 1, in ?
WindowsError: [Errno 2] The system cannot find the file specified
>>>

Thanks for any help,

Mike





From m.faassen at vet.uu.nl  Tue May 22 18:39:33 2001
From: m.faassen at vet.uu.nl (Martijn Faassen)
Date: 22 May 2001 22:39:33 GMT
Subject: Python IRC?
References: <417.542T477T9623711threeseas@earthlink.net>
Message-ID: <9eepr5$brq$1@newshost.accu.uu.nl>

Timothy Rue  wrote:
> Is there a python irc channel somewhere?

#python at irc.openprojects.net seems to be popular that way. :)

Regards,

Martijn
-- 
History of the 20th Century: WW1, WW2, WW3?
No, WWW -- Could we be going in the right direction?


From grante at visi.com  Tue May 29 13:35:11 2001
From: grante at visi.com (Grant Edwards)
Date: Tue, 29 May 2001 17:35:11 GMT
Subject: [ANN] xio, the cross platform serial IO python module
References: 
Message-ID: 

In article , Pablo Bleyer Kocik wrote:

>Currently, the module implements port creation, opening,
>closing, configuration, reading, writing & status peeking. It
>has been tested under Linux-x86 and Win-9X. It contains a na?ve
>implementation of flow control (and pretty untested -- so
>beware!).

An actual implimentation of flow control or an implimentation
of a wrapper around the flow control provided by the
OS-resident serial drivers?

-- 
Grant Edwards                   grante             Yow!  Am I SHOPLIFTING?
                                  at               
                               visi.com            


From db3l at fitlinxx.com  Tue May 15 15:02:23 2001
From: db3l at fitlinxx.com (David Bolen)
Date: 15 May 2001 15:02:23 -0400
Subject: Removing modules from the global namespace
References: <6957F6A694B49A4096F7CFD0D900042F27D3C0@admin56.narex.com> 
Message-ID: 

Chris Jaeger  writes:

> 	I have a python program that I want to import
> a number of modules into, but I don't know what the
> set of modules are going to be until run-time. Each
> loadable module exports an identical API. My layout
> currently is:

Here's something I just did recently for something similar, although I
insert lazy module definitions (borrowed from DateTime) into a
dictionary for use by the calling module rather than it depending on
dir().  It also skips any files in the directory beginning with "_"
(which covers __init__ and some internal-package only modules I have):

    #
    # -------------------------------------------------------------------
    #

    def find_modules():
	import sys, os, fnmatch, string
	import DateTime.LazyModule

	LazyModule = sys.modules['DateTime.LazyModule']

	# Walk the current directory to identify all management modules,
	# and store a reference to them within the returned dictionary.

	modfiles = filter(lambda x,m=fnmatch.fnmatch:m(x,'*.py'),
			  os.listdir(__path__[0]))

	modules    = {}

	for curmodule in modfiles:
	    modname = os.path.splitext(curmodule)[0]
	    if modname[0] == '_':
		continue
	    else:
		modules[modname] = LazyModule.LazyModule(__name__+'.'+modname,
							 locals(),globals())

	return modules

    #
    # -------------------------------------------------------------------
    #

    modules = find_modules()

    del find_modules


Assuming a package directory (call it "nimgmt") of:

  nimgmt/
    Demo.py
    Disk.py
    Inventory.py
    System.py
    _DBAccess.py
    _RegAccess.py
    __init__.py

then you get the following:

    >>> import nimgmt
    >>> dir(nimgmt)
    ['__builtins__', '__doc__', '__file__', '__name__', '__path__', 'modules']
    >>> pprint.pprint(nimgmt.modules)
    {'Demo': ,
     'Disk': ,
     'Inventory': ,
     'System': }
    >>> 

and thus the calling application can iterate over the supported
modules, and then access them through the dictionary value.  Doing the
access will actually import the module (which will create a module
entry in the global space of the package).

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/


From Jason.Tishler at dothill.com  Tue May 29 13:29:36 2001
From: Jason.Tishler at dothill.com (Jason Tishler)
Date: Tue, 29 May 2001 13:29:36 -0400
Subject: Cygwin Python sys.platform and distutils.util.get_platform() patch
Message-ID: <20010529132936.C498@dothill.com>

I would like to submit the attached patch (i.e., the first attachment)
to Python CVS for inclusion in 2.2.  IMO, this is the right solution for
many reasons.  I have included one example as the the second attachment.
If the patch is accepted, then I will back patch and re-release my Cygwin
Python 2.1 distribution.

Since these two simple changes have possibly far reaching ramifications,
I thought that it would be prudent to solicit feedback before submitting
the patch.  My goal is to eliminate (or at least minimize) the heartache
caused by these changes, if any.

Note that the two parts of the patch are actually independent but
related so I have decided to submit them as one patch instead of two.

The first part changes sys.platform, sys.path, and the platform specific
module directory name as follows:

    $ # before patch
    $ python -c 'import sys; print sys.platform'
    cygwin_nt-4.01
    $ python -c 'import sys; print sys.path'
    [..., '/usr/lib/python2.1/plat-cygwin_nt-4.01', ...]
    $ find /usr/lib/python2.1 -name '*cygwin*' -type d
    /usr/lib/python2.1/plat-cygwin_nt-4.01

    $ # after patch
    $ python -c 'import sys; print sys.platform'
    cygwin
    $ python -c 'import sys; print sys.path'
    [..., '/usr/lib/python2.1/plat-cygwin', ...]
    $ find /usr/lib/python2.1 -name '*cygwin*' -type d
    /usr/lib/python2.1/plat-cygwin

The second part changes sys.path (only when Python is run out of the
build tree) and the directory names used by distutils when building
extension modules:

    $ # before patch
    $ python -c 'import sys; print sys.path'
    [..., '/home/jt/src/Python-2.1/build/lib.cygwin_nt-4.0-1.3.2-i686-2.1']
    $ find . -name '*cygwin*'
    ./build/lib.cygwin_nt-4.0-1.3.0-i686-2.1
    ./build/temp.cygwin_nt-4.0-1.3.0-i686-2.1

    $ # after patch
    $ python -c 'import sys; print sys.path'
    [..., '/home/jt/src/Python-2.1/build/lib.cygwin-1.3.2-i686-2.1']
    $ find . -name '*cygwin*'
    ./build/lib.cygwin-1.3.2-i686-2.2
    ./build/temp.cygwin-1.3.2-i686-2.2

If I don't receive any negative responses to this patch proposal by
2001/6/1 9:00 EDT, then I will submit this patch to the SourceForge
Python Patch Manager.

Thanks,
Jason

-- 
Jason Tishler
Director, Software Engineering       Phone: 732.264.8770 x235
Dot Hill Systems Corp.               Fax:   732.264.8798
82 Bethany Road, Suite 7             Email: Jason.Tishler at dothill.com
Hazlet, NJ 07730 USA                 WWW:   http://www.dothill.com
-------------- next part --------------
Index: configure.in
===================================================================
RCS file: /cvsroot/python/python/dist/src/configure.in,v
retrieving revision 1.218
diff -c -r1.218 configure.in
*** configure.in	2001/05/11 16:10:56	1.218
--- configure.in	2001/05/28 01:10:03
***************
*** 66,71 ****
--- 66,72 ----
  	MACHDEP="$ac_md_system$ac_md_release"
  
  	case $MACHDEP in
+ 	cygwin*) MACHDEP="cygwin";;
  	'')	MACHDEP="unknown";;
  	esac
  fi
Index: Lib/distutils/util.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/distutils/util.py,v
retrieving revision 1.63
diff -c -r1.63 util.py
*** Lib/distutils/util.py	2001/03/23 17:30:26	1.63
--- Lib/distutils/util.py	2001/05/28 01:10:03
***************
*** 62,67 ****
--- 62,68 ----
      elif osname[:3] == "aix":              
          return "%s-%s.%s" % (osname, version, release)
      elif osname[:6] == "cygwin":
+         osname = "cygwin"
          rel_re = re.compile (r'[\d.]+')
          m = rel_re.match(release)
          if m:
-------------- next part --------------
An embedded message was scrubbed...
From: "Mark Hadfield" 
Subject: Cygwin Python, sys.platform & distutils
Date: Sat, 26 May 2001 12:06:20 +1200
Size: 2594
URL: 

From aahz at panix.com  Tue May  8 23:36:06 2001
From: aahz at panix.com (Aahz Maruch)
Date: 8 May 2001 20:36:06 -0700
Subject: Q: socket error in multi-threaded urlopen
References: 
Message-ID: <9dadv6$jp1$1@panix2.panix.com>

In article ,
Seung-won Hwang  wrote:
>
>I'm trying to call urlopen using multiple threads and it gives me the
>following errors. I'm experimenting if I can call hundreds of 'urlopen'
>calls simulataneously. Is there any way to get around this 'too many
>open files' problem in doing so?

I think you don't want to do this.  Use a threadpool.
-- 
                      --- Aahz  <*>  (Copyright 2001 by aahz at pobox.com)

Androgynous poly kinky vanilla queer het Pythonista   http://www.rahul.net/aahz/
Hugs and backrubs -- I break Rule 6

"Don't be so humble -- you are not that great."  --Golda Meir


From s713221 at student.gu.edu.au  Wed May  9 14:06:15 2001
From: s713221 at student.gu.edu.au (s713221 at student.gu.edu.au)
Date: Wed, 09 May 2001 18:06:15 +0000
Subject: How do you set up a stack?
References: <3y1K6.28593$q7.286847@typhoon.mw.mediaone.net> <9qehft8gspqhtpb50d3men0j12r7mnkp7i@4ax.com> <9dad3g$83t$1@apollo.csd.net>
Message-ID: <3AF98717.67080E1F@student.gu.edu.au>

kosh wrote:
> 
> Umm. While this solution will work I think there are some things that need
> to be dealt with. Mainly you need to check f for items that should not be
> in there. eval will evaulatuate any valid piece of python code so the other
> things that can be done are large. This is a fairly large security risk at
> this point I think. At the very least I would check if it has any letter
> characters and if so not run then.

Eval will (should?) only evaluate legal pythonic numeric functions. This
actually covers quite a bit, but unless you define wierd class
structures that overwrite numerical operators to do non-numerical
operations, you shouldn't have to worry too much about using eval.

Simple maths.
>>> eval("1+2")
3

Math with complex numbers (Except "i" is replaced with "j" in python.
Ask the engineers why. *sighs*)
>>> eval("(1+2j)-3j")
(1-1j)

You can also import the math module and use these functions inside the
eval statement.
>>> import math
>>> eval("1+math.sqrt(2)")
2.4142135623730949

However, all of these are dealing with numbers. I'd be interested to see
if someone did have an example of a malicious eval use. (In fact I'd be
downright anxious to know of any eval security weaknesses. *grins*)

I try to eval a non-numerical statement.
>>> eval("print 'hello'")
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 1
    print 'hello'
        ^
SyntaxError: invalid syntax

Now I try a different statement that barfs on a different piece of
syntax.
>>> eval("if 1==1: print 'hello'")
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 1
    if 1==1: print 'hello'
     ^
SyntaxError: invalid syntax
>>>

In order to "evaluate" or execute a string as a command, rather than an
expression, the exec command has to be used. However, if you are really
paranoid, or would like to convert the following complex number
statements "1+32i" to correct python, "1+32j", look up the re module.

Anycase, have fun. You should have a great time with the language, and
with this newsgroup.

Joal Heagney/AncientHart


From dougfort at downright.com  Thu May 31 16:00:34 2001
From: dougfort at downright.com (Doug Fort)
Date: 31 May 2001 21:00:34 +0100
Subject: Need advice: XML-RPC
References: <9f66fq$knt$1@newsreaderm1.core.theplanet.net>
Message-ID: <3b16a2e2_7@news5.uncensored-news.com>

Franz GEIGER wrote:

> I'd like to start to research the world of XML, especially for
> communication and data exchange (guess, this is what XML-RPC means). And
> I'd like to do that using Python.
> Yet I'm a bit uncertain how to tackle this.
> 
> I'm experienced in application programming using MSVC++, Python and MSVB.
> I know HTML and RPC (DCE RPC), COM/DCOM a bit and CORBA too.
> 
> So I am new to XML but not to sw dev.
> 
> Any hint is appreciated.
> 
> Best regards
> Franz GEIGER
> 
> 
> 
> 
> 
Check out the xmlrpc link at PythonWorks.  There are links there to a 
couple of introductory articles on oreilly.net.

 
To see a simple use of xmlrpc in communication check out 
http://pyagent.sourceforge.net


-- 
Doug Fort 
Senior Meat Manager
Downright Software LLC
http://www.downright.com

______________________________________________________________________
Posted Via Uncensored-News.Com - Still Only $9.95 - http://www.uncensored-news.com
   With Seven Servers In California And Texas - The Worlds Uncensored News Source
  


From vdanovich at empireone.net  Thu May 31 14:24:03 2001
From: vdanovich at empireone.net (Vyacheslav Danovich)
Date: 31 May 2001 11:24:03 -0700
Subject: DOCTYPE in XML
References: <88630c8d.0105301259.55d724ab@posting.google.com> 
Message-ID: <88630c8d.0105311024.702fb746@posting.google.com>

Thank you, jj.
This example'd worked fine and I almost started believing that my
problem'd been solved until I introduced the following:


  
]>

	
		blah
		blahblah
		C:\log
		sdanovich at test.com
		vdanovich at empireone.net
		vdanovich at hotmail.com
	
	
		
			Run successfully completed
			&successful_run;
		
		
			Run failed
			&faulty_run;
		
	


and my python code is:

	subject = ""
	text = ""
	doc = Sax2.FromXmlFile(file, validate=0)
	parser = xml.xpath.XPathParser.XPathParser()
	parsed = parser.parseExpression('/smtp/emailing')
	root = xml.xpath.Context.Context(doc.documentElement)
	nodeSet = parsed.evaluate(root)
	Host_Name = parser.parseExpression('/smtp/emailing/host/text()').evaluate(root)
	host = Host_Name[0].nodeValue
	Sender_Name = parser.parseExpression('/smtp/emailing/sender/text()').evaluate(root)
	sender = Sender_Name[0].nodeValue
	Attachment_Name = parser.parseExpression('/smtp/emailing/attachment/text()').evaluate(root)
	attachment = Attachment_Name[0].nodeValue
	Receipients_Name = parser.parseExpression('/smtp/emailing/receipients/text()').evaluate(root)
	receipients = []
	for i in range(len(Receipients_Name)):
		receipients.append(Receipients_Name[i].nodeValue)
	parsed = parser.parseExpression('/smtp/status/sagent/@run')
	root = xml.xpath.Context.Context(doc.documentElement)
	nodeSet = parsed.evaluate(root)
	for i in range(len(nodeSet)):
		print "TEXT: " , text
		if str(nodeSet[i].nodeValue) == str(status):
			Subject_Name = parser.parseExpression('/smtp/status/sagent/subject/text()').evaluate(root)
			subject = Subject_Name[i].nodeValue
			Text_Name = parser.parseExpression('/smtp/status/sagent/text/text()').evaluate(root)
			text = Text_Name[i].nodeValue
	email(host, subject, sender, receipients, attachment, text) 		
			
At the end the values for "text" were the empty string ("")
It seems like the parser doesn't parse the DOCTYPE entities



>jj  wrote in message >news:...
> text = '''
> 
>   
>     Neil Gaiman
>     Glyn Dillon
>     Charles Vess
>   
> 
> '''
> 
> # using Python XML package && 4suite 
> from xml.dom.ext.reader import Sax2
> import xml.xpath
> 
> doc = Sax2.FromXml(text)
> 
> parser = xml.xpath.XPathParser.XPathParser()
> parsed = parser.parseExpression('/collection/comic/@title')
> root = xml.xpath.Context.Context(doc.documentElement)
> 
> nodeSet = parsed.evaluate(root)
> print nodeSet[0].nodeValue
> # writer
> nodeSet =
> parser.parseExpression('/collection/comic/writer/text()').evaluate(root)
> print nodeSet[0].nodeValue
> 
> 
> JJ 
> On 30 May 2001 13:59:21 -0700, vdanovich at empireone.net (Vyacheslav
> Danovich) wrote:
> 
> >Hi folks!
> >
> >When using xml.sax module and the following file is given:
> >
> >
> >  
> >    Neil Gaiman
> >    Glyn Dillon
> >    Charles Vess
> >  
> >
> >
> >and I know the title and the number of the 'comic'
> >How can I find out the value for ?
> >
> >Any help is appreciated!


From akuchlin at mems-exchange.org  Wed May  2 10:44:04 2001
From: akuchlin at mems-exchange.org (Andrew Kuchling)
Date: 02 May 2001 10:44:04 -0400
Subject: Choosing a programming language as a competitive tool
References: 
Message-ID: <3dlmoflsjv.fsf@ute.cnri.reston.va.us>

John Schmitt  writes:
> What I got out of this was that choosing a good programming language can be
> a competitive advantage.  Graham chooses Lisp.  For me this isn't a Lisp

I liked all the comments on Slashdot that said they'd prefer to use
something more common such as C++ because it's too difficult to find
good programmers who can handle Lisp.  Hmmm.... "let's not get good
programmers to make our product in Lisp/Python/whatever; we'll get
some mediocre programmers to make it in C++ and that'll be better for
the company."  Explains a lot about the pathetic state of software,
doesn't it?

--amk


From hanna at chagford.com  Tue May  8 11:56:07 2001
From: hanna at chagford.com (Hanna Joo)
Date: Tue, 8 May 2001 08:56:07 -0700
Subject: how to run a program on server from client wxpython frontend?
Message-ID: <989304912.89878@nntp01.uskonet.com>

Hello

I am writing a small program that will read/write data from postgres on a
linux server. The client machine where the wxpython front end will run is a
windows machine. I am trying to find a way to establish a connection to the
server (user sockets?) and pass the data file that will be processed by
another python program (once I can pass data to the python program on linux
I can do all the writing and reading to the database). Is there a way to
connect to the database straight away? Or should I try to invoke a python
program on the server that will do the database bit? (Eiter way don't know
how to go about it =)

If you have any experience in writing front-ends involving databases I would
really appreciate your input.

(Then again maybe I should just write the whole thing for linux
workstations.. hmph then all problems are solved :)

TIA

Hanna from sunny South Africa




From whisper at oz.nospamnet  Sun May 13 18:17:43 2001
From: whisper at oz.nospamnet (David LeBlanc)
Date: 13 May 2001 22:17:43 GMT
Subject: cgi dat coruption by Internet Explorer 5.0
References: <20010513.085031.1953443376.882@linux.earthlink.net> <9dmeba010f7@news2.newsguy.com> 
Message-ID: <9dn167$qvj$9@216.39.170.247>

In article , 
micheas at earthlink.net says...

> Content-type: text/html
> 
> 
> 
> 
> 
> 
> 
> Is the output of the script.
> should content-type be something else? or should I be specifying the
> encoding with a meta tag? and if so what should it be?
> 
> Thank you very much for your help I have found next to nothing on the web but I
> haven't known exactly what my problem is just the symptoms.
> 
> --Micheas
> 
If that is the whole of the output, try a  closing tag and see 
what happens. 

Seems to me you need to emit more HTTP headers then just content-type, 
but i'm not 100% sure of that. BTW, encoding is:
 transfer-encoding: 

I'd leave transfer-encoding as a last resort though.

Dave LeBlanc


From phd at phd.fep.ru  Thu May 24 05:27:47 2001
From: phd at phd.fep.ru (Oleg Broytmann)
Date: Thu, 24 May 2001 13:27:47 +0400 (MSD)
Subject: OT - Limiting freedom
In-Reply-To: 
Message-ID: 

Exactly in time. Just today someone asked here how to find GPLed code in an
EXE and could anyone to sue.

   http://slashdot.org/articles/01/05/23/1723215.shtml

   "In stark contrast to the plethora of false alarms recently, there's a
pretty clear-cut case that Vidomi, a DVD ripping product by SloMedia, is
composed of a great deal of code from VirtuaDub, a GPLd product. As
SloMedia have refused all requests to either release their source or stop
using the code, the developer is planning to file suit with the aid of the
Free Software Foundation, in what could be the first legal test of the
GPL's enforceability."

Oleg.
----
     Oleg Broytmann            http://phd.pp.ru/            phd at phd.pp.ru
           Programmers don't die, they just GOSUB without RETURN.





From aleaxit at yahoo.com  Sun May  6 12:41:39 2001
From: aleaxit at yahoo.com (Alex Martelli)
Date: Sun, 6 May 2001 18:41:39 +0200
Subject: Choosing a programming language as a competitive tool
References:   <9cvphc$6f0$3@slb4.atl.mindspring.net>  
Message-ID: <9d49ks02aad@news1.newsguy.com>

"Douglas Alan"  wrote in message
news:lc3dajk0ma.fsf at gaffa.mit.edu...
    [snip]
> That's not true -- no one would ever even think of teaching Computer
> Science in Perl,

I'm not too sure, although I have no certain knowledge to the
contrary.  http://www.cse.unsw.edu.au/~cs2041/lec/intro/slide002.html
for example gives me the impression that (at UNSW) CS2041 may
be the third CS course (with the first one in Haskell, and the 2nd
one in Java) and from following slides, particularly the ones about
reading material, it appears to me that it's mostly in Perl.

Rochester's CS190 was said to provide "an intensive and accelarated
introduction to Computer Science using a number of programming
languages including C++, Java, Lisp/Elisp, Perl, Tcl, Latex and others".

I do hope that nowhere is Perl used as the _only_ language in an
_introductory_ CS course, but I wonder...


> Pascal.  Python would also be a good language for teaching Computer
> Science.  (Not as good a language as Scheme, though, which is a
> dialect of Lisp.)
    ...
> Not true.  Python is practically a dialect of Lisp, but with a

So, comparing them as "dialects of Lisp", what do you believe
makes Python not as good as Scheme for teaching CS?

I think it may depend on the students' background and general
attitude.  If the target is somebody with strong mathematical
background and bent, then Scheme's syntactical spareness
may prove advantageous indeed -- easier to lay bare all the
underlying mechanisms, easier to have programs build or
modify programs, no risk of syntax-sugar focus.

But some CS introductory courses might target another kind
of student -- one better served by Python's "prettiness" and
ease of use for many tasks, with the mechanics of OO already
built-in rather than needing to be constructed, but still pretty
well "exposed" and tweakable for didactical purposes.

Maybe it depends on how many _other_ CS courses the typical
student of that introductory course is expected to take over
his or her academic career.  It may make a difference whether
the introductory course is likely to be just the first of many CS
courses, or, at the other extreme, pretty likely to be the only
one, or one of two/three at most.


Alex





From kasper37 at caffeinedreams.com  Tue May 29 14:49:11 2001
From: kasper37 at caffeinedreams.com (kasper37 at caffeinedreams.com)
Date: 29 May 2001 11:49:11 -0700
Subject: combining commands:
References:  <3B133CC2.D902A795@senux.com.NOSPAM>
Message-ID: 

> 
> def sql(sql):
>    // code to connect DB... bla..bal....
>    c.execute(sql)
>    return c.fetchall()
> 
> print sql("SELECT * FROM USER")
> 
> You can edit this for your own use.

This is probably what I will end up doing.  I thought of this after
posting...

> We'd need to know what c was to begin with, but if you're desperate for
> one line, have you tried this to see if it works?

I'm not really desperate for a one liner...just more pleasant code. 
Seeing three lines for every time I want to get the value of a db
entry didn't ring well.

Thanks for your responces.

Dan


From jkraska1 at san.rr.com  Fri May 11 19:55:42 2001
From: jkraska1 at san.rr.com (Courageous)
Date: Fri, 11 May 2001 23:55:42 GMT
Subject: Unix [was: do...until wisdom needed...]
References:  <3AFB68E1.1C524FF2@my.signature> 
Message-ID: 

>But not having it is so rarely a bad idea so rarely, and the
>cost expenditure can't be amortized over such a long period of
>time.

Unless, of course, asteroid "resistance" is merely an expression
of a much more general and useful evolutionary advantage...

C//



From scarblac at pino.selwerd.nl  Sun May 27 17:54:55 2001
From: scarblac at pino.selwerd.nl (Remco Gerlich)
Date: 27 May 2001 21:54:55 GMT
Subject: speeding up string.split()
References: 
Message-ID: 

Chris Green  wrote in comp.lang.python:
> Is there any way to speed up the following code?  Speed doesn't matter
> terribly much to me but this seems to be a fair example of what I need
> to do.
> 
> In the real data, I will be able to have a large array and use
> map rather than do it line by line but, I doubt this will change
> things much for the better.
> 
> I've tried w/ python 2 and 1.5.2 and the differences between perl and
> python remain huge ( about 5s:1s python:perl ).

"Huge". It's 4 seconds on 300,000 lines. Since this sort of thing is Perl's
special expertise, I'll admit that I think that Perl has the edge here.

But does that matter for your application? If it means a minute on each
daily run, it's not worth a Usenet thread :-)
 
> The string is +'d together for usenet purposes

Hmmmmm. Actually, what happens when you remove the '+' and replace it with a 
simple backslash? Two literals in a row may form one literal, but two
strings with a '+' need to be added together every time. I think that this
*may* make a (small) difference. Wouldn't expect it to be at all
significant.

-- 
Remco Gerlich


From crystalc at interlog.com  Sun May  6 19:28:35 2001
From: crystalc at interlog.com (Brian Alexander)
Date: Sun, 6 May 2001 19:28:35 -0400
Subject: curses -- module cannot be found
Message-ID: 

Hello;

The curses module is described in the documentation for P2.1, but cannot be
found when I "import curses". Is there something I haven't done to make it
visible to the interpreter?

Brian.




From tanzer at swing.co.at  Fri May 11 02:28:43 2001
From: tanzer at swing.co.at (Christian Tanzer)
Date: Fri, 11 May 2001 08:28:43 +0200
Subject: Range Operation pre-PEP 
In-Reply-To: Your message of "Thu, 10 May 2001 23:07:54 +0400."
              
Message-ID: 

Roman Suzi  wrote :

> I do not see how syntactical ranges could spoil simplicity!

That's exactly the problem .

-- 
Christian Tanzer                                         tanzer at swing.co.at
Glasauergasse 32                                       Tel: +43 1 876 62 36
A-1130 Vienna, Austria                                 Fax: +43 1 877 66 92




From gaul at spam.utexas.edu  Thu May 10 09:08:28 2001
From: gaul at spam.utexas.edu (Andrew Gaul)
Date: Thu, 10 May 2001 13:08:28 +0000 (UTC)
Subject: int 2 binary: What do you think?
References: <3ae42b7a.4988661@news.muenster.de>
Message-ID: 

In article <3ae42b7a.4988661 at news.muenster.de>, Martin Bless wrote:
>I needed to convert integers to binary representation and couldn't
>find a builtin function. So here's what I came up with. The idea is to
>return a string as short as possible and have positive numbers always
>start with a  "0".
>
>I wonder if there's a better way? 

Here's a shorter implementation; it may be more efficient:

def bin(i):
    l = ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111',
         '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']
    s = ''.join(map(lambda x, l=l: l[int(x, 16)], hex(i)[2:]))
    if s[0] == '1' and i > 0:
        s = '0000' + s
    return s

It'd be nice if an equivalent built-in function was added in a future
version of Python.

-- 
     | a | n | d | r | e | w | @ | g | a | u | l | . | o | r | g |
                      White trash.  Loser.  Geek.


From johngrayson49 at yahoo.com  Wed May  2 18:30:22 2001
From: johngrayson49 at yahoo.com (johngrayson49 at yahoo.com)
Date: Wed, 02 May 2001 22:30:22 -0000
Subject: Fwd:  Re: [Tkinter] Geometry Managers differences
Message-ID: <9cq1pu+sth1@eGroups.com>

--- In python-list at y..., matt at m... (Matthew Dixon Cowles) wrote:
On Wed, 02 May 2001 14:24:17 GMT, Nicola S. 
wrote:

>>hi everyone, what are the differences between the geometry managers
>>in terms of performance?
>
>
>There are more details about how to use the geometry managers in
>Fredrik Lundh's excellent An Introduction to Tkinter:
>
>http://www.pythonware.com/library/tkinter/introduction/index.htm

You can also get chapter 5 of Python and Tkinter Programming
for free:

    http://www.manning.com/Grayson/chapt05.pdf

   John






From sholden at holdenweb.com  Sun May 27 14:13:07 2001
From: sholden at holdenweb.com (Steve Holden)
Date: Sun, 27 May 2001 14:13:07 -0400
Subject: I really like Python but...
Message-ID: 

> From: "Bill Walker" 

> It's absolutely the most thought-out and easy to program language that I
> have tried (starting with Fortran in the 70's up to Java recently);
HOWEVER,
> I
> can't get too excited about it until a true compiler for Python comes
along.
> I'll accept even a decent byte-code compiler that locks up all the
modules,
> dlls, etc, into one exe. No, py2exe doesn't work well; especially with
> tkinter -- leaves out modules.

Have you ever distributed a C or C++ program for the Windows platforms?
Haven't you noticed that can be a problem too, for just the same reasons?

> Without this capability it is just too hard to distribute code to any but
> those that already have Python installed (which are usually other
> programmers.)
>
> Somebody work on this, please...

"Oh, yes, by the way, my back yard is dirty, someone sweep it, please ..."

A constructive proposal to fix this might be better received than a
peremptory command. You do realize that Python is open source, I trust? Work
on it yourself, please ...

regards
 Steve






From sill at optonline.net  Fri May  4 02:18:53 2001
From: sill at optonline.net (sill at optonline.net)
Date: Fri, 04 May 2001 02:18:53 -0400
Subject: Why Does This Variable Vanish?
In-Reply-To: 
References: 
Message-ID: 

In comp.lang.python, you wrote:
>Hi;
>Here's my code:
> >>>
>    import smtplib
>    file = open("outfile.txt", "r")
>    line = file.readline()
>    server = smtplib.SMTP("localhost")
>    server.sendmail("beno at thewebsons.com", "beno at thewebsons.com", line)
>    server.quit()
><<<
>The variable *line* in the 2nd to last line of code doesn't print anything. 
>Now, if I put a *print line* command after *line = file.readline()* it'll 
>print to screen. And if I define *line = "whatever"*  and put it after the 
>*line = file.readline()* statement, in the exact_same_place as the *print 
>line* statement above, then I get an email with *whatever* in the body. So, 
>what in tarnation is going on?? Why doesn't variable *line* persist until 
>the 2nd to the last line of code? This makes no sense to me at all! Your 
>help is appreciated.
>TIA,
>BenO

It works perfectly here, with the line.

>
>


-- 
Lime and limpid green
a second scene
A fight between the blue
you once knew
        - Syd



From coy.krill at verizon.net  Fri May 25 13:28:57 2001
From: coy.krill at verizon.net (Coy Krill)
Date: Fri, 25 May 2001 10:28:57 -0700
Subject: Problem Building Python2.1 on RedHat 7.1
Message-ID: <9em4pa$4kth$1@ID-59852.news.dfncis.de>

I built Python 2.1 for my RH 7.1 laptop just fine back in April using the 
src rpm from tummy.com.  Last night I spent HOURS building/rebuilding it on 
my RH 7.1 desktop and am having a very strange problem.  Here is the 
traceback:

Traceback (most recent call last):
  File "./chkexport.py", line 52, in ?
    shelf = shelve.open(sys.argv[1])
  File "/usr/lib/python2.1/shelve.py", line 158, in open
    return DbfilenameShelf(filename, flag)
  File "/usr/lib/python2.1/shelve.py", line 148, in __init__
    Shelf.__init__(self, anydbm.open(filename, flag))
  File "/usr/lib/python2.1/anydbm.py", line 85, in open
    mod = __import__(result)
  File "/usr/lib/python2.1/dbhash.py", line 5, in ?
    import bsddb
ImportError: /usr/lib/python2.1/lib-dynload/bsddb.so: undefined symbol: 
dbopen

Somehow bsddb.so is getting built without any linkage to libdb.so.2.Anyone 
have any idea what may be causing the problem?  The only difference between 
April and now are the installation of RedHat errata.

Thanks,
Coy


From rnd at onego.ru  Thu May 31 03:09:15 2001
From: rnd at onego.ru (Roman Suzi)
Date: Thu, 31 May 2001 11:09:15 +0400 (MSD)
Subject: Against PEP 240
In-Reply-To: 
Message-ID: 

On Thu, 31 May 2001, Tim Peters wrote:

> [Roman Suzi]
> > Rounding and formating is a MUST in anything nrealy financial ;-)
> > So, lets not put additional burden on the Python and
> > just put "%11.2f" % round(var, 2) were due.
> 
> I doubt that's going to make Clark feel better, as I can't imagine a context
> in which that code snippet would make good sense.  That's the kind of thing
> he's doubtless suffering from:  well-intentioned attempts to worm around
> problems too dimly understood.  "%" alone would introduce one rounding
> error, and that's the best that can be done.  "round()" introduces at least
> two rounding errors of its own (although you can't know that without
> studying the implementation of round()), so all by itself is worse than just
> printing the thing.  Even if Clark sticks to plain "%" and has an exactly
> representable (in binary fp) value, he's still in a x-platform bind; e.g.,
> 
> >>> print "%11.2f" % 100.125
> 
> displays
> 
>      100.12
> 
> on most modern Unix boxes (following 754's nearest/even rounding), but
> displays
> 
>      100.13
> 
> on others and on Windows (following add-a-half-and-chop rounding).  The
> financial world has strict rules about how rounding is supposed to be done
> too.

Wow! Could you please explain what errors round() adds and in the 
following if a solution:

def finance_round(x, z=2):
  """Portable (?) add-a-half-and-chop rounding"""
  p10 = 10.0**z
  return int(x*p10+0.5)/p10

IMHO, UNIX approach is scientifically correct (adds
less noise if large data arrays are rounded before summation), while 
Windows one is more "financially" minded...

I wish Python docs were more specific on the rules 
of formatting "%", round(), etc.

> spend-6-months-writing-accounting-apps-ly y'rs  - tim

It's also interesting to know if "official" rounding rules differ from
country to country, because I was told there is no bookkeeping regulation
(in Russia) on how to round, so bookkeepers are on their own.

Sincerely yours, Roman A.Suzi
-- 
 - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru -
 




From Eugene.Leitl at lrz.uni-muenchen.de  Mon May 21 07:00:40 2001
From: Eugene.Leitl at lrz.uni-muenchen.de (Eugene Leitl)
Date: Mon, 21 May 2001 13:00:40 +0200 (MET DST)
Subject: There's something rotten [VAR: Re: Python STILL prints the wronginternational letters]
In-Reply-To: <3B08EEB9.88F3111B@rk-speed-rugby.dk>
References:  <9e3nda$eb5$k@216.39.170.247>
 <92ae279c.0105181619.5326cbde@posting.google.com> <3B08EEB9.88F3111B@rk-speed-rugby.dk>
Message-ID: 

On Mon, 21 May 2001, Brian wrote:

> Hvorfor kender en amerikaner(?) udtrykket: There's something rotten in
> the state of Denmark? Er det et citat?

Ja, det er: http://www.geocities.com/Athens/Parthenon/9751/hamlet3.html




From bsb at winnegan.de  Tue May  1 20:02:25 2001
From: bsb at winnegan.de (Siggy Brentrup)
Date: 02 May 2001 02:02:25 +0200
Subject: Formatting numbers
In-Reply-To: 
References: 
Message-ID: <87n18w1uum.fsf@winnegan.de>

"Daniel Klein"  writes:

> This is almost embarrasing to have to ask this but I can't seem to find this
> information.
> 
> Given an integer, 12345, how to format this to 123.45 ?

def fixed(i, places=2):
    """12345 -> 123.45"""
    if i >= 0:
        s = '%0*d' % (places+1,i)
    else:
        s = '%0*d' % (places+2,i)
    return s[:-places]+'.'+s[-places:]

>>> print fixed(12345), fixed(12345,6), fixed(-1)
123.45 0.012345 -0.01

HTH
  Siggy
-- 
Siggy Brentrup - bsb at winnegan.de - http://www.winnegan.de/
****** ceterum censeo javascriptum esse restrictam *******




From emile at fenx.com  Fri May 25 09:57:06 2001
From: emile at fenx.com (Emile van Sebille)
Date: Fri, 25 May 2001 06:57:06 -0700
Subject: decode compiled python
References: <3B0E5B5E.17400ACA@abaqus-sn.com>
Message-ID: <9elojg$1pt7$1@ID-11957.news.dfncis.de>

I'd start by looking into http://goebel-consult.de/decompyle/.

HTH,

--

Emile van Sebille
emile at fenx.com

---------
"david winkler"  wrote in message
news:3B0E5B5E.17400ACA at abaqus-sn.com...
> How to decode compiled Python scripts into original textual versions?
> Anyone know of existing code?
>




From pearu at cens.ioc.ee  Sun May 20 09:10:12 2001
From: pearu at cens.ioc.ee (Pearu Peterson)
Date: Sun, 20 May 2001 15:10:12 +0200 (EET)
Subject: ANN: PyVTK
Message-ID: 

I am pleased to announce first release of PyVTK-0.3:

	http://cens.ioc.ee/projects/pyvtk/

PyVTK provides tools for manipulating VTK files in Python:

     VtkData - Create VTK file from Python objects. It fully
         supports VTK File Formats Standard 2.0. The features
         includes:
           *** ascii and binary output
           *** DataSet formats:
                 StructuredPoints, StructuredGrid, RectilinearGrid,
                 PolyData, UnstructuredGrid
           *** Data formats:
                 PointData, CellData
           *** DataSetAttr formats:
                 Scalars, ColorScalars, LookupTable, Vectors, 
                 Normals, TextureCoordinates, Tensors, Field

PyVTK is tested to work with Python versions 2.1, 2.0, and 1.5.2.

Thanks,
	Pearu Peterson

pyvtk 0.3 - Manipulate VTK files in Python (21-May-01) From donn at oz.net Sat May 12 23:02:39 2001 From: donn at oz.net (Donn Cave) Date: 13 May 2001 03:02:39 GMT Subject: Interfacing with terminal programs References: <3afca18b.11011600@news.earthlink.net> Message-ID: <9dktgf$nfo$0@216.39.151.169> Quoth drifty at bigfoot.com (Drifty): | I volunteer at the Open Computing Facility at UC Berkeley | (www.ocf.berkeley.edu) and I am trying to help automate the changing | of user's passwords. We currently have to run two separate | terminal-based programs to change a password and then document the | change in a log file. The problem is that I can't figure out how to | get Python to interface with the terminal program without deadlocking. | I tried using popen2 but it deadlocks when I read from the output fd. | I would get away with just using the input fd if I could, but I have | to make sure the staffer entered their password properly and so I have | to check to see if it prompted for the password of the staffer again | or is ready to take the new password for the user. I assume the | deadlock is caused because of the prompt from the terminal program | isn't letting the output fd know it reached the end of the read. I'm not sure what you mean by that. The usual problem, when you run a program on a pair of pipes, is that the program's output is block buffered when the device is a pipe, and the output you're waiting to read is still in that buffer. A prompt is a bit less likely to have this problem, because in the normal tty context where output is line buffered, you have to explicitly flush output from the buffer to get a prompt. Ptys solve the buffering problem. The stderr stream is usually unbuffered, so it will come right out - but not to the output pipe, if they prompt on stderr. Anyway, the other problem that will come up with a password prompt is the tty ioctl that turns off echo. That will fail on the pipe, which doesn't support tty ioctls. The passwd program should abort at that point. Ptys solve this problem too. | Any suggestions? This has to run on Solaris, so using something like | pty is obviously iffy. I think pty is the only thing that can work. Look for posix.openpty. You'll have to fiddle around with it, ptys are odd devices that are a little more trouble to work with. Donn Cave, donn at oz.net From bh at intevation.de Fri May 4 08:36:35 2001 From: bh at intevation.de (Bernhard Herzog) Date: 04 May 2001 14:36:35 +0200 Subject: implementing module functions==object methods in extension References: Message-ID: <6q8zkdxpd8.fsf@abnoba.intevation.de> "Steve Holden" writes: > [Ferkles about in 1.5.2 library's string module]... > > Yep. Certainly seems better than the previous implementation: > > # Join words with spaces between them > def join(words, sep = ' '): > """... """ > return joinfields(words, sep) > > # Join fields with optional separator > def joinfields(words, sep = ' '): > """... > > (joinfields and join are synonymous) > > """ > res = '' > for w in words: > res = res + (sep + w) > return res[len(sep):] > > I especially don't like the way this builds a string with a separator at the > beginning and then strips it off before returning, but I'm betting this was > more efficient than other choices. Note, that this is just the fallback implementation when the extension module strop can't be found. See the end of string.py (from 1.5.2): # Try importing optional built-in module "strop" -- if it exists, # it redefines some string operations that are 100-1000 times faster. # It also defines values for whitespace, lowercase and uppercase # that match 's definitions. try: from strop import * letters = lowercase + uppercase except ImportError: pass # Use the original, slow versions Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://mapit.de/ From m.faassen at vet.uu.nl Wed May 23 07:28:10 2001 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 23 May 2001 11:28:10 GMT Subject: Python IRC? References: <417.542T477T9623711threeseas@earthlink.net> <9eepr5$brq$1@newshost.accu.uu.nl> Message-ID: <9eg6sa$asq$1@newshost.accu.uu.nl> Ben Hutchings wrote: [snip helpful people] > Oh dear... that was a mistake. > Timothy Rue is an annoying net.kook who used to (and possibly still > does) cause no end of annoyance on Amiga newsgroups with his > blathering about his own ridiculous programming system (VIC), his > delusions of importance and his conspiracy theories. Aah, net.kooks; I used to be well up to date on net.kooks but it seems I'm sadly behind these days. I don't consider it a mistake to help random people asking questions, just because they may turn out to be a net.kook, though. We'll see what happens. The python community is usually very good at handling this kind of thing anyway, and if that failed there's always the PSU. :) [links to his website] This looks definitely incomprehensible enough to be senseless. :) Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From db3l at fitlinxx.com Tue May 29 16:06:27 2001 From: db3l at fitlinxx.com (David Bolen) Date: 29 May 2001 16:06:27 -0400 Subject: parse-time optimizations References: <9ervav$qu9$1@news.mathworks.com> <9evasv$9u8$1@news.mathworks.com> <9f0op4$6b5$1@news.mathworks.com> <9f0svb$9u7$1@news.mathworks.com> Message-ID: jcm writes: > Yes, although that brings us back to one of my original motivations > for wanting to see this optimization--I think it's a better solution > than having string-literal concatenation. I guess I just don't like > having too many wany of doing the same thing, especially in this case > where it involves extra syntax in the language. I'd probably take the opposite tack - to me seeing a "+" for concatenation makes me think of executing code, which I would expect to occur while the code is being interpreted. Parser/compiler level combinations make more sense to me to be distinct from that. It would seem to me to be more of a special case to handle + for two string literal objects at the compilation phase rather than execution time where + would be handled for all other object types. But then again, I personally happen to like string-literal concatenation, so that may color my viewpoint. -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From aleaxit at yahoo.com Tue May 22 11:54:45 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 22 May 2001 17:54:45 +0200 Subject: Variable inheritance References: Message-ID: <9ee24002a5o@enews1.newsguy.com> "Samuel A. Falvo II" wrote in message news:slrn9gkvat.5c8.kc5tja at dolphin.openprojects.net... > On Tue, 22 May 2001 12:23:43 +0400 (MSD), Roman Suzi wrote: > >This is indeed a contra-example and is a bad design, because > >it leeds to combinatorically bloated code, in which you need > >M*N*K... classes to have all kinds of objects. > > Yes. But unless the user (versus the programmer) is responsible for > dynamically creating objects of various types, this simply isn't a problem. > > If the user DOES have some involvement with the creation of objects, then > it's clear that delegation and aggregation are the only reasonable solution > (or, at least, the easiest to implement and maintain). Not necessarily so, in Python. Say the user chooses 'feature-sets' he wants by 'copying' the feature-set names in a GUI from a list to another, e.g. by drag and drop; he may also arbitrarily reorder the list of feature sets he has chosen in terms of priority -- if two chosen feature-sets both provide a way to handle a certain behavior, the user gets to choose which one takes precedence. This might be excellent as a user-interface in a bridge-bidding system to choose sets of bidding conventions, for example. When done, the user writes in a name for the new thingy in an appropriate text-field, and clicks the "Create" button. OK, so now we have a tuple of 'feature-sets' (classes) whose features the user desires in the object he is creating. What is the best way to mix them? Why, multiple inheritance, of course -- what else? class ObjectCreator: class Starter: def __init__(self, name): self.name, self.uniq = name for b in self.__class__.__bases__: getattr(b,'__init__',lambda x:0)(self) def __init__(self): self.classRegistry = {} self.nameRegistry = {} def create(self, name, basestuple): if not self.classRegistry.has_key(basestuple): class Temp((Starter,)+basestuple): pass self.classRegistry(basestuple) = Temp uniq = 0 while self.nameRegistry.has_key((name,uniq)): uniq += 1 name = (name,uniq) result = self.classRegistry[basestuple]('%s_%s'%(name,uniq)) self.nameRegistry[name] = result return result I don't see how aggregation and delegation would be easier to implement and maintain than this simple framework. You can add new potential base-classes anytime, in fact updating the UI is more than a chore than updating the underlying engine (since the latter doesn't need to be updated:-). All the work you would have to code in delicate boilerplate in Python for the delegation is handled by Python itself as it looks for methods and other attributes of the objects so created. And isn't this exactly as it should be? Python gives us a flexible, solid, powerful code reuse mechanism in its inheritance structure. I don't see why one shouldn't take full advantage of it just because of mistaken (or at least SERIOUSLY debatable:-) philosophical ideas on the role of taxonomy in classification!-) Alex From Darren.Watson3 at ntlworld.com Mon May 28 07:28:17 2001 From: Darren.Watson3 at ntlworld.com (Darren Watson) Date: Mon, 28 May 2001 12:28:17 +0100 Subject: Permanently Adding A Directory to Pythonpath Message-ID: Hi I would like to know how to add a directory to my Pythonpath permanently. I have tried appending to sys.path and this works fine during interactive work, but I would like to always have a directory available in the path. I am using ActivePython 2.1 on windows 98 Any help would be appreciated. -- Darren Watson From ron.l.johnson at home.com Wed May 9 00:43:27 2001 From: ron.l.johnson at home.com (Ron Johnson) Date: Wed, 09 May 2001 04:43:27 GMT Subject: socket.recvfrom() & sendto() References: <4f3K6.3300$vf6.407953@news1.rdc1.sdca.home.com> Message-ID: Van Gale wrote: > > "Ron Johnson" wrote: > >> Since the server can send messages to the client at random and >> irregular interevals, how can the client accept input from the >> user at the same time that it is "stalled" at a select() ? > >> The server side I think I understand, at least from the perspective >> of *my* needs: the server sits at a select() until it detects (an) >> incoming message(s) from client(s); it then processes the message, >> sends messages back to the sending client(s) and also possibly other >> clients, then goes back to the select(). > > I think you are understanding the server side correctly, and there's > plenty of server applications in the Medusa package to use as a base for > your > server. One minor point though, the "sending back to the clients" is also > done through the select. Data being sent out from one of your connection > objects sits in a buffer and is sent out in chunks each time the select on > the socket says "ready to send". > > As for the client side, you will need to structure the code in a different > way. It depends more on what GUI package you are using (wxPython?, wxQt?, > tkinter?) than how the server is structured. You might need to use > threads, e.g. a thread handling GUI stuff and another thread handling > communications > with the server. However you end up coding it, you DON'T want > communications with the server to block GUI events. > > Look at rpc_client.py in Medusa for an example of coding an asynchat > client > (although this doesn't do any GUI stuff). I haven't looked at any of the > Python games out there to see if any of them would make a good starting > point (even though I'm in the game development business), but I'd > bet you could find some good starting code there as well. Great. It's all coming into place now. Server Client ------ ------ Medusa Medusa in 1 thread user IO in another thread (If u are a game writer, can u tell me if I am going about this backwards??) Sincere thanks, Ron -- Ron Johnson, Jr. Home: ron.l.johnson at home.com Jefferson, LA USA http://ronandheather.dhs.org "Is Python better or worse than Perl?" "Perl is worse than Python because people wanted it worse." -Larry Wall, 10/14/1998 From lac at cd.chalmers.se Thu May 31 05:26:43 2001 From: lac at cd.chalmers.se (Laura Creighton) Date: Thu, 31 May 2001 11:26:43 +0200 (MET DST) Subject: Anybody know about ... (was book recommendations) Message-ID: <200105310926.LAA28076@boris.cd.chalmers.se> Designing Object-Oriented Software by Rebecca Wirfs-Brock, Brian Wilkerson (Contributor), Lauren Wiener, Rebecca Brock http://www.amazon.com/exec/obidos/ASIN/0136298257/ref=ase_objectmentorinc/104-5732662-8355111 Laura From aleaxit at yahoo.com Sat May 12 11:37:49 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 12 May 2001 17:37:49 +0200 Subject: static attribute References: <9djgnt$570uu$1@hades.rz.uni-sb.de> Message-ID: <9djleu0crr@news1.newsguy.com> "Uwe Schmitt" wrote in message news:9djgnt$570uu$1 at hades.rz.uni-sb.de... > hi, > > i tried to use a static attribute _allNames as follows: > > > class Name: > > _allNames={} > > def __init__(self,name): > self.name=name > _allNames[name]=self > > > X=Name("Xclass") > > but i get NameError.... whats wrong ? You need to set self._allNames[name] = self or equivalently Name._allNames[name] = self An unqualified identifier only ever refers to a local or global variable, *NEVER* to the field of an object or class. Alex From see.below at no.spam.es Sun May 6 04:26:34 2001 From: see.below at no.spam.es (Javier Bezos) Date: Sun, 06 May 2001 08:26:34 GMT Subject: Tkinter families() not working Message-ID: <1eszd45.p7w9if1r7fo26N%see.below@no.spam.es> Hi all, I'm having a problem when I try to get the list of available fonts using the families() function provided by Tkinter. The following program: ---------- from Tkinter import * from tkFont import * root = Tk() f = Font(family="times") print f.actual("family") print names() x = families() # ??? ---------- produces: ---------- Times ('font11003664',) Traceback (most recent call last): File "Programaci?n:Python 2.0:font.py", line 11, in ? x = families() # ??? File "programaci?n:python 2.0:lib:lib-tk:tkFont.py", line 146, in families return root.tk.splitlist(root.tk.call("font", "families")) UnicodeError: ASCII encoding error: ordinal not in range(128) ---------- What's wrong? The following code (I'm using MacPython 2.0) works fine: ---------- import Res fontnames = [] for i in range(1, Res.CountResources('FOND') + 1): r = Res.GetIndResource('FOND', i) fontnames.append(r.GetResInfo()[2]) print fontnames ---------- as well as the line: set c [font families] in wish (tcl/tk). Thanks a lot in advance for the answers. Javier ___________________________________________________________ Javier Bezos | TeX y tipografia jbezos at wanadoo dot es | http://perso.wanadoo.es/jbezos/ From pknews at kirks.net Tue May 22 07:40:14 2001 From: pknews at kirks.net (Patrick Kirk) Date: Tue, 22 May 2001 12:40:14 +0100 Subject: IDLE win't start on Win2k Message-ID: <9edj6u$l14$1@news6.svr.pol.co.uk> Does anyone know how to resolve this problem? I've pasted the tk80.dll into the D:\Python\DLLs folder but it made no difference. Thanks in advance Event Type: Information Event Source: Application Popup Event Category: None Event ID: 26 Date: 22/5/2001 Time: 12:35:18 User: N/A Computer: POD Description: Application popup: pythonw.exe - Unable To Locate DLL : The dynamic link library tk80.dll could not be found in the specified path d:\Python\DLLs;.;C:\WINNT\System32;C:\WINNT\system;C:\WINNT;C:\WINNT\system3 2;C:\WINNT;C:\WINNT\System32\Wbem;C:\Program Files\Microsoft Visual Studio\Common\Tools\WinNT;C:\Program Files\Microsoft Visual Studio\Common\MSDev98\Bin;C:\Program Files\Microsoft Visual Studio\Common\Tools;d:\vc98\bin. From robnospam at jam.rr.com Wed May 16 21:18:49 2001 From: robnospam at jam.rr.com (Rob Andrews) Date: Thu, 17 May 2001 01:18:49 GMT Subject: I'm new and need some help!!!!! References: Message-ID: <3B0325EF.FF449D44@jam.rr.com> You might be looking for something along the lines of the Python Tutor email list, where newbies are treated quite well. Rob toto tuto wrote: > > Hi my name is Andres Pinzon and i'm writting from > Colombia. > Lately i've been interested on Python because i've > heard about its "power". Someone told me Python is a > very good starting language to a person like me (you > know i'm a beginner). I don't know much about > programming, hardly i do some HTML and "Basic" stuff; > what i'd like to know is: if is it possible to become > a "Python Programmer" just with this? and where can i > find some REAL basic tutorials. > THANK YOU.. > Andres Pinzon > PD.. BY the way! I'd like to keep in touch with > "someone outthere", for some "guidance" -- You should have listened when your mother warned you about Useless Python! http://www.lowerstandard.com/python/pythonsource.html From aleaxit at yahoo.com Thu May 3 04:42:35 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 3 May 2001 10:42:35 +0200 Subject: mxDateTime: does strptime not exist? References: Message-ID: <9cr5lq0157i@news2.newsguy.com> "Ruediger Maehl" wrote in message news:newscache$g22rcg$p8$1 at www.dzsh.de... > Hi, > > I am trying to convert a string expression into a > DateTime object and found the strptime constructor > in the docs of mxDateTime. But it throws the > following error (and does not show strptime as > available method in PythonWin's Interactive > Window). A 100%-pure-Python cross-platform strptime is at http://www.fukt.hk-r.se/~flognat/hacks/strptime.py Alex From sasha at spuni.is Fri May 25 05:39:14 2001 From: sasha at spuni.is (Sasa Zivkov) Date: Fri, 25 May 2001 09:39:14 -0000 Subject: Dependency Inversion Principle -- Python Way In-Reply-To: Message-ID: Hi, thanks to all for usefull comments... it really helped! It would be nice to have all Robert C. Martin's articles on OOD revisited from python developers point of view :-) -- Sasa From emarkp at CSUA.Berkeley.EDU Tue May 29 15:06:24 2001 From: emarkp at CSUA.Berkeley.EDU (E. Mark Ping) Date: Tue, 29 May 2001 19:06:24 +0000 (UTC) Subject: ftpmirror.py in other direction? References: <9f0m9d$1jvuq$1@ID-85738.news.dfncis.de> Message-ID: <9f0rvg$216k$1@agate.berkeley.edu> In article , Thomas Wouters wrote: >On Tue, May 29, 2001 at 05:29:17PM +0000, Robert Cowham wrote: > >> Has anyone written a modified version of ftpmirror.py which will mirror a >> local filesystem to an FTP site (e.g. for updating of web site)? > >Why not use one of the many tools that already exist do to exactly that ? >Joe Orton's excellent 'sitecopy': > > http://www.lyra.org/sitecopy/ Perhaps one reason is that the windows port requires you to install cygwin. Sigh. -- Mark Ping emarkp at soda.CSUA.Berkeley.EDU From news at myNOSPAM.org Thu May 3 20:44:17 2001 From: news at myNOSPAM.org (Stephen Hansen) Date: Fri, 04 May 2001 00:44:17 GMT Subject: PEP 234: Iterators References: <9crjks$9kn$1@newsy.ifm.liu.se> Message-ID: Oh. I was confused. Hmm, then I don't see a problem.. both forms end up with the same result, they just support different types of input. That's pythonic :) Give it an object, it returns the iterator; give it a function, and it returns the iterator... the function bit just needs some more information. dict.iteritems/iterkeys/itervalues is still really ugly, though. :) --S :) "Thomas Bellman" wrote in message news:9crjks$9kn$1 at newsy.ifm.liu.se... > "Stephen Hansen" wrote: > > > I'd like to read 'iter(object)' as 'iterate(object)' and 'iter(func, > > sequence)' as 'iterator(func, sequence)' since the latter is making an > > iterator on the fly, and not iterating over it... > > But the former *doesn't* iterate over the sequence. It *also* > instantiates (creates) an iterator. The *for* statement and the > *map()* function iterates; the iter() function (whatever spelling) > doesn't, so it shouldn't be called iterate(). > > > but that really doesn't > > matter, i'd much rather just see 'iterate' for both of them. Perhaps it > > would be better to 'traverse(iterator-object)' and then 'iterator(func, > > sequence)'. In fact, that's my favorite option.. getting rid of the > > excessive use of 'iter' and just calling it 'traverse'. > > Same problem with the name traverse(). > > > -- > Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden > "I don't think [that word] means what you ! bellman @ lysator.liu.se > think it means." -- The Princess Bride ! Make Love -- Nicht Wahr! From tim.one at home.com Wed May 30 16:44:58 2001 From: tim.one at home.com (Tim Peters) Date: Wed, 30 May 2001 16:44:58 -0400 Subject: Python celebrities photos In-Reply-To: <15125.20052.831051.956353@anthem.wooz.org> Message-ID: [Barry A. Warsaw, selling pictures of himself again] > Or equivalently (and more succinctly): http://barry.wooz.org > > There's also some fun ones of lots of Pythonistas at > > http://freeweb.pdq.net/robinf1/spam8pix/ > > Alas, Uncle Tim's paid stand-in isn't in there. He was found the next > day upside down in a snowbank, with his underwear on the outside of > his pants, drunk out of his mind. Tim, did you ever get your money > back from that guy? :) Are you kidding? He got a fat *bonus* for that one! It worked miracles in changing my image from a crotchety old bot to a fun kind of guy you can feel good about leaving your kids with. btw-i'll-pick-up-little-max-on-my-way-back-from-the-methadone- clinic-ly y'rs - tim From klin at palsoccer.com Tue May 1 14:09:58 2001 From: klin at palsoccer.com (Kevin Xin Lin) Date: Tue, 01 May 2001 14:09:58 -0400 Subject: ssl support under windows Message-ID: <3AEEFBF6.18557B3C@palsoccer.com> Hi, Anyone has ever compiled Python under MS-Windows for SSL support? Any idea for pure Python SSL support under Windows? Thanks. Kevin From hungjunglu at yahoo.com Mon May 14 02:04:57 2001 From: hungjunglu at yahoo.com (hungjunglu at yahoo.com) Date: Mon, 14 May 2001 06:04:57 -0000 Subject: Python COM and distribution issues Message-ID: <9dnsi9+4s7e@eGroups.com> Python COM seems to aim for single-machine software design, because in all the examples I have seen the _reg_clsid_ are ALL hard-coded by hand. It's 128-bit all right, but how can anyone be absolutely sure that it won't cause conflict on different machines? It is unrealistic to distribute Python modules and expect the users to perform pythoncom.CreateGuid() and modify the _reg_clsid_ in all the program files. (1) How do people handle the GUID problem? Or do people just hard- code the GUID and hope for the best? (2) Has anyone done Python COM utilities for distribution? How do people handle the GUID (Globablly Unique ID) problem? Has anyone packed Python COM utilities into stand-alone executables (a la py2exe)? (3) I tried to generate GUID dynamically instead of hard-coding, but it broke PythonCom badly. In particular, the object browser does not work anymore, and the whole operating system crashes when using Python COM server objects from Visual Basic. Has anyone had similar problem? If so, any pointer to the solution? If a class is registered or unregistered a few times under different _reg_clsid_, does something in the registry get corrupted? Where is a good starting point to fix these problems? thanks, Hung Jung From see at my.signature Tue May 1 23:56:57 2001 From: see at my.signature (Greg Ewing) Date: Wed, 02 May 2001 15:56:57 +1200 Subject: Hungarian notation (was RE: variable naming...) References: <3AEED769.4C8EB848@alcyone.com> Message-ID: <3AEF8589.68EAC4DB@my.signature> Jan Dries wrote: > > the use of i, j, k, ... for integers (and f, g, ... for real > numbers) has nothing to do with Hungarian notation but comes from > FORTRAN ...which in turn got it from mathematicians, who were using such conventions long before there were any computers. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From neal at metaslash.com Tue May 29 22:49:45 2001 From: neal at metaslash.com (Neal Norwitz) Date: Tue, 29 May 2001 22:49:45 -0400 Subject: PyChecker v0.5 released Message-ID: I was finally able to get version 0.5 out. Just in case this is the first time you are seeing this message, or you forgot what PyChecker is: PyChecker is a tool for finding common bugs in python source code. It finds problems that are typically caught by a compiler for less dynamic languages, like C and C++. Because of the dynamic nature of python, some warnings may be incorrect; however, spurious warnings should be fairly infrequent. The highlights are that code at the module scope is now checked. There is still a problem with class variables and globals that are default parameter values. But other than that, there should be no more spurious Variable unused warnings. Code that makes PyChecker raise an exception should now be caught in most cases and this produces a warning. Please mail me if you find it blowing up on your code. The last line processed is shown in the warning, so if you include some context, I can hopefully fix the problem. Also, PyChecker should really use the files passed on the command line, even if it uses the same module name internally. So it will check your warn.py, not PyChecker's warn.py. Feedback, comments, criticisms, new ideas, better ideas, etc. are all greatly appreciated. Thanks for everyone who has taken the time to mail me. If you can think of common mistakes that are made that PyChecker doesn't find, please let me know. Here's the CHANGELOG: * Catch internal errors "gracefully" and turn into a warning * Add checking of most module scoped code * Add pychecker subdir to imports to prevent filename conflicts * Don't produce unused local variable warning if variable name == '_' * Add -g/--allglobals option to report all global warnings, not just first * Add -V/--varlist option to selectively ignore variable not used warnings * Add test script and expected results * Print all instructions when using debug (-d/--debug) * Overhaul internal stack handling so we can look for more problems * Fix glob'ing problems (all args after glob were ignored) * Fix spurious Base class __init__ not called * Fix exception on code like: ['xxx'].index('xxx') * Fix exception on code like: func(kw=(a < b)) * Fix line numbers for import statements PyChecker is available on Source Forge: Web page: http://pychecker.sourceforge.net/ Project page: http://sourceforge.net/projects/pychecker/ Neal -- pychecker at metaslash.com From parkw at better.net Thu May 3 10:28:49 2001 From: parkw at better.net (William Park) Date: Thu, 3 May 2001 10:28:49 -0400 Subject: Stripping HTML tags from a string In-Reply-To: <9crb9f01cbe@news2.newsguy.com>; from aleaxit@yahoo.com on Thu, May 03, 2001 at 12:18:22PM +0200 References: <9crb9f01cbe@news2.newsguy.com> Message-ID: <20010503102849.B733@better.net> On Thu, May 03, 2001 at 12:18:22PM +0200, Alex Martelli wrote: > "William Park" wrote in message > news:mailman.988837024.29166.python-list at python.org... > [snip] > > Since others gave solutions using 'sgmllib', here are a solution using > > 're' as requested: > > > > >>> pat = re.compile(r' > Parsing HTML with regular expressions is always a rather unpleasant > task since there are SO many durned 'irregularities' that may be > validly present and that you still have to account for. Here, for > example, whitespace _might_ validly be present after the leading > '<' and before the tagname, so one needs to put in \s? to cover > for that. Using sgmllib means reusing all the needed regular > expressions _already_ developed and refined and tested and made > very solid by LOTS of other long-term reuse. Yes, but original poster apparently didn't know how to use 're', and asked for regular expression solution. Normal progression would be to move on to library module for his specific need, after he gets tired of adjusting the regular expressions. (sigh!) --William Park, Open Geometry Consulting, Mississauga, Ontario, Canada. 8 CPUs, Linux, Python, LaTeX, vim, mutt From jkraska1 at san.rr.com Sun May 27 17:10:45 2001 From: jkraska1 at san.rr.com (Courageous) Date: Sun, 27 May 2001 21:10:45 GMT Subject: Python -> C++ compilation References: Message-ID: <3jr2hto59rtet3jdirctr5je378dp82s3n@4ax.com> However, if one is _forced_ to use C++ >because the project is being developed with it, there are 5 options: >1. Write in Python then automatically compile into C++ using some >tool You mean if management _approves of that_, which is doubtful if they are insisting on C++. While I am personally fond of Python, on a more general level if I were tech lead and someone were to use their favorite language in lieu of the project language, I'd relieve them from the project immediately and also raise a major stink. C// From rnd at onego.ru Sun May 20 01:22:34 2001 From: rnd at onego.ru (Roman Suzi) Date: Sun, 20 May 2001 09:22:34 +0400 (MSD) Subject: Python and Ruby , object oriented questions Message-ID: On 20 May 2001, Elf Sternberg wrote: >In article > Paul Prescod writes: > >>There is some truth to this but I don't think it is the whole truth. >>Most people become Python advocates while they still have much larger >>investments in other languages. The new converts are often the most >>vocal, right? > > True. When I shifted over, it was something of a religious >conversion to the point where I felt guilty when I tossed off a 'perl >-pi.bak' construction. > >>It's like political parties. You want your programming language to >>succeed because it captures your beliefs about how the (computer) world >>should work. > > One of the things I've learned over the years is that there >isn't much to languages themselves. I have a bit of trouble wrapping my >head around some language classes, such as those examplified by Haskell, >Scheme, or Forth. But when it comes to the procedural languages (like >C) and those with an object-oriented option (such as C++, Java, Perl, >and Python) I have no trouble with the language _syntax_, because, to be >honest, there isn't much there there. Do I use '==' or '=' (or 'eq'!) >in an if statement, do I use '=' or ':=' in an assignment, what do I use >for scoping: these are all trivial. > > The real barrier to any language is the libraries that come with >it. What made Perl and Python _real_ successes with its users was that >the libraries are similar enough to the C which we had to work with in >the late 1980's. When these languages came along, the regular >expressions were familiar to us and the things we could do were things >we were used to doing. Plus, the authors of these languages had the >foresight to make interfacing with even a poorly-thought-out C interface >a task even a mediocre programmer could accomplish. > > I suspect this is the reason why Java is such a hit among >college students learning a language for the first time, but has had >trouble inroads into the existing Unix/Linux communities. The Java >libraries, however well-conceived and paradigmatically "pure" they may >be, are unfamiliar to those of us who have been programming to the Unix >'C' libraries for so long. > > Any language that hopes to acquire a significant amount of >mindshare must have both a compellingly useful syntax and a library that >the user can readily grasp and do something with. Python and Perl both >succeed in the second, and whether or not they succeed at the first is, >well, a matter of personal preference (and religious wars). UNIX and thus C and Pyhton libs are POSIX-conformant (i.e. standard). Java changes too rapidly to "Write once, run everywhere". And I don't know about you, but after learning Python it is extremely tough to write in Perl again... It's not religious, it's probably objective. > Elf > >-- >Elf M. Sternberg, rational romantic mystical cynical idealist >http://www.halcyon.com/elf/ > >Dvorak Keyboards: Frgp ucpoy ncb. ru e.bu.bj. > Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/ _/ Sunday, May 20, 2001 _/ Powered by Linux RedHat 6.2 _/ _/ "Even Mother Nature doesn't mess with Moderators." _/ From jkraska1 at san.rr.com Tue May 29 21:03:58 2001 From: jkraska1 at san.rr.com (Courageous) Date: Wed, 30 May 2001 01:03:58 GMT Subject: ConfigParser module in 1.52 is buggy? References: <20010529114644.R690@xs4all.nl> <000001c0e834$08b50b80$010010ac@cr706570a> <3B14444D.41072DE2@senux.com.NOSPAM> Message-ID: >There are various versions of Python. And I want my Python program works >on all of them. Which is your prerogative. But on a more abstract level, I believe that applications built for scripting environments should, situation permitting, strongly consider moving the entire scripting environment with the application. C// From ljohnson at resgen.com Wed May 9 17:42:33 2001 From: ljohnson at resgen.com (Lyle Johnson) Date: Wed, 9 May 2001 16:42:33 -0500 Subject: Newbie class instance tracking system References: <9dc7f7$l4j$1@netnews.upenn.edu> Message-ID: > I am new to Python and I am having trouble with the following code. In short, > Why doesn't it work? I thought that variable names "spring into existence" in > a similar fasion to perl... Although Python's error message wasn't very helpful in this case, the problem was that for a new key (or car company name) in the dictionary, you didn't specify the data type (which in your case should be a list). I've modified your code (shown below) to initialize the dictionary entry to an empty list if it encounters a new key; the relevant lines are: if not Maker.all_cars.has_key(carCompany): Maker.all_cars[carCompany] = [] Hope this helps, Lyle class Maker: all_cars={} def __init__(self,carName=None,carCompany=None): self.carName = carName self.carCompany = carCompany if not Maker.all_cars.has_key(carCompany): Maker.all_cars[carCompany] = [] Maker.all_cars[carCompany].append(carName) prelude = Maker(carName='prelude',carCompany='Honda') accord = Maker(carName='accord',carCompany='Honda') for carCompany in Maker.all_cars.keys(): print "Cars from %s:" % carCompany for carName in Maker.all_cars[carCompany]: print " %s" % carName From max at alcyone.com Tue May 1 11:34:01 2001 From: max at alcyone.com (Erik Max Francis) Date: Tue, 01 May 2001 08:34:01 -0700 Subject: Hungarian notation (was RE: variable naming...) References: Message-ID: <3AEED769.4C8EB848@alcyone.com> Roman Suzi wrote: > Probably, hungarian notation is useful for local vars, > for example, I;d rather write: > > for i in range(100): > > or > > for c in "my string": > > -- but these are very limited uses, and probably not even hungarian > any > more. Indeed, those are just common conventions regardless of Hungarian notation. You can tell it's not Hungarian notation when you see variations: for i in range(100): for j in range(100): ... -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ You are free and that is why you are lost. \__/ Franz Kafka REALpolitik / http://www.realpolitik.com/ Get your own customized newsfeed online in realtime ... for free! From d98aron at dtek.chalmers.se Wed May 30 12:12:42 2001 From: d98aron at dtek.chalmers.se (Fredrik Aronsson) Date: 30 May 2001 16:12:42 GMT Subject: Function attributes again References: Message-ID: <9f365q$hre$3@nyheter.chalmers.se> In article , Fernando Rodr?guez writes: > Hi! > > How can I check (from within a function) if it has attributes? I > tried if __dict__ == None in the definition, but it doesn't work: > > def f(a, b): > z = 0 > if __dict__ == None: > __dict__['c'] = 4 > > return z + a + b > >>>> f(8,3) > Traceback (most recent call last): > File "", line 1, in ? > f(8,3) > File "", line 3, in f > if __dict__ == None: > NameError: global name '__dict__' is not defined > > What's going on? O:-) You're trying to access __dict__ as a global variable, but you probably want to access your functions func_dict. >>> def f(): ... print f.x ... >>> f.x=31426 >>> f.func_dict {'x': 31426} /Fredrik hint: dir is handy if you want to know what attributes and functions a class, object or function etc. have. >>> dir(f) ['__dict__', '__doc__', '__name__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name', 'x'] From boud at rempt.xs4all.nl Mon May 28 15:35:09 2001 From: boud at rempt.xs4all.nl (Boudewijn Rempt) Date: 28 May 2001 19:35:09 GMT Subject: Python -> C++ compilation References: Message-ID: <9eu99d$g24$2@news1.xs4all.nl> Roman Suzi wrote: > But if the result will be C++ code, then what is the difference > HOW I've created it? It's up to me if I write it myself or > create/use a tool for code generation. BTW, the later will be > clearer and more structured. Try smugling in generated Java code from Jython apps into a Java project... Generated code is seldom human-maintainable - the Jython generated Java being an example. Note however that I did exactly that: I wanted to embed a Python console in a Java app, and compiled the Jython console demo to Java and included it. Management still doesn't know it ;-). -- Boudewijn Rempt | http://www.valdyas.org From kosh at aesaeion.com Tue May 22 04:46:24 2001 From: kosh at aesaeion.com (kosh) Date: Tue, 22 May 2001 02:46:24 -0600 Subject: Variable inheritance References: <3B0A1E4D.F57BA8A0@thinkware.se> Message-ID: <9ed911$tk3$1@apollo.csd.net> Magnus Lycka wrote: > Roman Suzi wrote: >> Multiple inheritance says it bad design. > > I wouldn't say that in general. But most of the > time, and certainly in this case! > > The reasonable use of multiple inheritance is > for so-called mixin-classes, that gives some > particular behavior to a class. This can be used > to give classes features such as persistence, > automagic logging of some sort, or various support > for debugging etc. > > Basically, inheritance is then used as an > implementation device, and it has nothing to do > with the more abstract _design_ classes. The mixin > does not represent a real world object that would > pop up during requirements capture, analysis or > early design. > Yes that is a great use of MI. Using mixins for behavior is extremely common in zope. It works very nicely be able to gain ACL capability by inherting from the RoleManager or gain full persistance in the ZODB by inheriting from Persist. Mixins work very nicely and I have used that feature fairly commonly since it allows a better abstraction of various workhorse functions from the design. From piet at cs.uu.nl Wed May 30 08:31:36 2001 From: piet at cs.uu.nl (piet at cs.uu.nl) Date: 30 May 2001 14:31:36 +0200 Subject: parse-time optimizations References: <9ervav$qu9$1@news.mathworks.com> <9evasv$9u8$1@news.mathworks.com> Message-ID: >>>>> jcm (J) writes: J> Yea, I guess it's just wishful thinking. Something about J> string-literal juxtaposition doesn't sit right with me. I guess I'm J> used to optimizing compilers, which would transform "a" + "b" into J> "ab" (and 1 + 2 into 3, etc). Having a different syntax specifically J> for string-literal concatenation seems odd (it seems less odd in C J> only because strings are so klunky). "a" "b" should not be considered an optimization, it is just one of the many ways string literals can be written. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From tjenkins at devis.com Wed May 16 16:32:44 2001 From: tjenkins at devis.com (Tom Jenkins) Date: Wed, 16 May 2001 16:32:44 -0400 Subject: Which GUI Lib? References: <9dptcq$eb5$1@216.39.170.247> <9dqg3p$nel$1@news1.xs4all.nl> <9drtau$eb5$9@216.39.170.247> <9dudds$eb5$b@216.39.170.247> <9dugd4$8d9$1@news1.xs4all.nl> Message-ID: <3B02E3EC.20207@devis.com> Boudewijn Rempt wrote: > David LeBlanc wrote: > >>In article , >>jkraska1 at san.rr.com says... >> >>>>How much does a developer's license on Windows cost? >>>> >>>http://www.trolltech.com >>> >>>C// >>> >>> >>> >>I looked there... Windows version is not free - looks to be about $1500. >> > > That's what makes BlackAdder such a good proposition ;-). > There's something to check with BlackAdder and Qt. Borland's Kylix (and forthcoming Delphi 6) uses Qt as its widget set. Borland wraps the Qt widgets in its own framework called CLX. The license you get with Kylix and Delphi 6 would allow you to use Qt only through CLX. Given this wrinkle with Borland, I wonder if there is something similar with BlackAdder? -- Tom Jenkins devIS - Development Infostructure http://www.devis.com From cribeiro at mail.inet.com.br Sun May 6 09:53:33 2001 From: cribeiro at mail.inet.com.br (Carlos Ribeiro) Date: Sun, 06 May 2001 10:53:33 -0300 Subject: Help! Writing COM ActiveDocuments in Python Message-ID: <5.0.2.1.0.20010506104121.00a08e50@mail.inet.com.br> I need some help with Win32 and OLE/COM stuff. I'm trying to write an ActiveX control in Python. The catch is that I want this control to be embeddable, inplace editable, and persistent (able to write itself to a stream). Please understand that I'm trying to write it using only Python (i.e., I dont want to encapsulate a C++ component). If it ends up being impossible for any reason, I'll be happy to do everything in C++ or Delphi anyway. I did some searches, but I could not find any example of this stuff. Do someone have a pointer for this specific kind of application? Another way to do what I want was suggested by Alex Martelli, that is to use MSHTML for this. While it does sound interesting, I was wondering if it is a good idea - it seems to make things more complicated to have the kind of control that I want. Carlos Ribeiro From tdelaney at avaya.com Wed May 2 00:45:59 2001 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 2 May 2001 14:45:59 +1000 Subject: Hungarian notation (was RE: variable naming...) Message-ID: > Sometimes, though, type-related inflections are > needed to distinguish things that would otherwise > have exactly the same name. For example, Object > Pascal code for the Mac abounds with things like > > type > FooHandle = ^FooPtr; > FooPtr = ^FooArray; > FooArray = array[0..9999] of Foo; Very true (oh, how I remember this ... although it was MacPascal, not Object Pascal ;) However, there are three things for this particular case: 1. This is not Hungarian. It is very obvious what each of these are. 2. This is dealing with memory addressing, in particular Handle-based memory management (which is completely different to Handles on Windows for those who don't know, and was a lovely system for reducing memory fragmentation on low-memory systems without virtual memory). 3. These are type definitions, not variable declarations. #2 and #3 combined makes this a perfectly reasonable and *good* thing to do. There are also arguments for naming variables in a similar manner, because it is a description of the *function* of the variable (i.e. this is a pointer to something - you will probably need to dereference it to use it, this is a handle to something, you will definitely have to lock it in place before passing the deferenced pointer as a parameter to a function ...). Tim Delaney From dalke at acm.org Sun May 6 23:09:30 2001 From: dalke at acm.org (Andrew Dalke) Date: Sun, 6 May 2001 21:09:30 -0600 Subject: do...until wisdom needed... References: <9be84s0q12@news1.newsguy.com> <9bfjoc0cjh@news2.newsguy.com> <9bfq560noo@news2.newsguy.com> <87n19fvdzo.fsf_-_@elbereth.ccraig.org> <9biukr$lu8$1@nntp9.atl.mindspring.net> <9cqpq9$dvm$1@nntp9.atl.mindspring.net> Message-ID: <9d53ku$o9j$1@slb6.atl.mindspring.net> Douglas Alan wrote in message ... >"Andrew Dalke" writes: >[whole bunches of stuff deleted] >It wouldn't be small if Python had procedural macros. Most people >would love them -- just like most people love them in Lisp. I guess I'm stuck at the point trying to figure out how procedural macros could be added to Python. Is it at all possible to come up with a hand-waving/straw example? Everything I think of seems to end up with a function that converts a large quoted string into a new Python module, class or function. >Look how long it took OO >to catch on (another invention that grew out of Lisp). Most of the >arguments people make against procedural macros today, people used to >make about about OO. I was under the impression that OO programming grew out of Simula-67. For example, http://www.ifi.uio.no/~kristen/FORSKNINGSDOK_MAPPE/F_OO_start.html or http://jeffsutherland.com/papers/Rans/OOlanguages.pdf . Quoting from the last reference, ] when Tony Hoare imparted his idea of a record class construct in ] ALGOL bulletin no. 21, 1965, they realised they needed some kind of ] object with record class properties. When prefixing was introduced ] in 1966, they had what they were after: an object consisting of a ] prefix layer and a main layer, the former containing references to ] its predecessor and successor and the latter accommodating its ] attributes. Combined with the exploration of string handling and ] input/output for the language by Bjoern Myhrhaug and the concept of ] classes, Simula 67, later renamed Simula was born. >OO was invented in the '70's and it took until the '90's for it to > catch on. Right delta, but it was invented in '60s. As to the later date, I remember when Borland shipped Turbo Pascal 5.5 in May 1989. Its OO ideas were based off of ideas from Apple's Object Pascal, released in '86. I was using Turbo C++ in summer 1991 because Borland shipped Turbo C++ that February. So I would have dated things to "late '80s" and not "'90's". BTW, these Turbo programs are available from community.borland.com. To bad I don't still have my old 8088 :( >> c) there is a problem with the usefulness of procedural macros in >> mainstream development > >They've never been used in "mainstream development" -- except to the >extent that Lisp (and Dylan) have been used for mainstream >development. My apologies for using a loaded word there. I meant something that was the equivalent to "widely used languages" "other than Lisp" (which you include as a widely used language even though it "only really ever caught on in AI circles and for teaching programming"). All quotes yours. >Dylan proves that it can be done. (It's derived from Lisp, but has a >more traditional syntax.) Macros are typically executed at >compile-time, not run-time, which is often necessary for efficiency >reasons. Could you give an example of the Dylan syntax for doing macros? Perhaps this would help with my mental block in understanding how it could/should be applied to Python. >Oh, I was just using a funny phrase like from a TV commercial. Just like "mainstream development"? :) > In any >case, Scheme (a dialect of Lisp) is usually considered state of the >art for teaching Computer Science 101. Scheme is what's used at MIT, >Harvard, Yale, etc. Just to double check, I looked up what language Yale uses for their intro. classes CPSC 110 "Elements of Computing" isn't a programming class http://zoo.cs.yale.edu/classes/cs110/ CPSC 112 "Introduction to Programing" uses Java http://flint.cs.yale.edu/cs112/index.html CPSC 201 "Introduction to Computer Science" uses Haskell, but http://plucky.cs.yale.edu/cs201/ says ] (Previously in this course we used the Scheme programming language. ] In some ways Haskell can be viewed as a strongly-typed variant of ] Scheme.) On a roll, I decided to check out Harvard: CS50 "Introduction to Computer Science I" uses C http://www.fas.harvard.edu/~lib50/ CS51 "Intro. to CS II" uses LISP, C++, and Java http://www.fas.harvard.edu/~lib51/write.cgi Judging from your email address, I'll assume you know about what MIT uses for their intro courses. Andrew Dalke dalke at acm.org From kbk at shore.net Sun May 27 11:14:26 2001 From: kbk at shore.net (Kurt B. Kaiser) Date: Sun, 27 May 2001 15:14:26 GMT Subject: Newbie help with manipulating text files References: Message-ID: <3B111944.A5361B50@shore.net> Laura Creighton wrote: > Hi jk. > > 1. Do you know that the mail you are sending out appears to come as > From: "jk" ? Do you want this? Well, it's better than ungrzr2 at ubatxbat.pbz =) From ahmed.bouferguene at Newlix.com Wed May 23 12:43:08 2001 From: ahmed.bouferguene at Newlix.com (Ahmed Bouferguene) Date: Wed, 23 May 2001 16:43:08 GMT Subject: staticforward and C++ References: <3B0BD8E9.50CE10A7@Newlix.com> <3B0BE4A1.B1B940BD@alcyone.com> Message-ID: <3B0BE881.F21DD879@Newlix.com> hi Erik, as a matter of fact, I have the following situation : staticforward PyTypeObject Testtype ; And then after defining the necessary functions (hashfunc, getattrfunc, ...) I do the dollowing : static PyTypeObject Testtype = { PyObject_HEAD_INIT(NULL) ..... } ; In C, this construction goes smoothly, but not in C++ !? What's the workaround ?? Thanks. Erik Max Francis wrote: > Ahmed Bouferguene wrote: > > > I am trying to write an extension in C++. I sort of follwed the same > > path as when working with C. However, > > > > whenever I tried to compile my code, I got this error : > > > > a.cc:73: redefinition of `struct PyTypeObject Testtype' > > a.cc:23: `struct PyTypeObject Testtype' previously declared here > > > > Is there a trick I am missing !? > > What code you are trying to compile? It's complaining that you're > _defininig_ it twice, which is illegal. > > -- > Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ > __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE > / \ Time is a storm in which we are all lost. > \__/ George Bernard Shaw > 7 sisters productions / http://www.7sisters.com/ > Web design for the future. From nickson at centropolisfx.com Thu May 3 17:26:07 2001 From: nickson at centropolisfx.com (Nickson Fong) Date: Thu, 03 May 2001 14:26:07 -0700 Subject: Tkinter select more than one Message-ID: <3AF1CCEF.ACFFA335@centropolisfx.com> can someone tell me how i can select more than on canvas object at once and move it with the mouse. fing_withtag() - allows only one item? -- thanks (:~~~ (:~~~ (:~~~ NO MORE EGGS ~~~:) ~~~:) ~~~:) JUST BADFROG Tel : (310) 204-7300 Ext 120 Pager : 626-582-5459 Office Fax : 310-204 7301 nickson at centropolisfx.com ubadfrog at yahoo.com From James_Althoff at i2.com Wed May 23 20:26:11 2001 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Wed, 23 May 2001 17:26:11 -0700 Subject: is it safe to stop a thread? Message-ID: Marcin Kowalczyk wrote: >Garbage collection with finalizers and modelling killing threads as >exceptions take care of this. I would think that relying on garbage collection with finalizers as a way of freeing up system resources is not an infallible strategy in the general case since it is possible to use up critical system resources before your memory is gone and before a garbage collector runs. Jim From ben.hutchings at roundpoint.com Tue May 22 16:38:03 2001 From: ben.hutchings at roundpoint.com (Ben Hutchings) Date: 22 May 2001 13:38:03 -0700 Subject: O(n^2) is bad - can it be fixed? References: <3B09FBF9.8691EBFE@accessone.com> <9ed4kr01877@enews1.newsguy.com> <7iheydfza5.fsf@enark.csis.hku.hk> Message-ID: Isaac To Kar Keung writes: > That means, when size is below 500, a list size will always be multiple of > 10. When size is larger, it is always multiple of 100. Of course, if the > object is already of the right size, the system resize() does nothing. > > Seems like magic to me... I run the following program and I didn't see *any* > slowdown, when each of the lists is as large as 8M, eating up 60M memory... > (Will it be the system realloc which actually do the geometric scaling, or > is it really that geometric scaling is unnecessary?) As the list buffer grows, realloc() will at some point find that the only place to put it is at the top of the heap. Once it's there, further realloc() calls will grow the heap and will not need to move the buffer. However, other systems - those with a shared memory space, or without a smart implementation of realloc() - are likely to behave differently. -- Any opinions expressed are my own and not necessarily those of Roundpoint. From see at my.signature Fri May 4 01:38:00 2001 From: see at my.signature (Greg Ewing) Date: Fri, 04 May 2001 17:38:00 +1200 Subject: Whither SmallScript? (was Re: Integer micro-benchmarks) References: <5bhG6.29435$qc2.7596549@typhoon.southeast.rr.com> <3AEE4061.860868AB@my.signature> <3AEF7EE5.6A5B78C3@my.signature> <3AEF8A5E.76BF7509@mail.com> Message-ID: <3AF24038.F106618E@my.signature> "James A. Robertson" wrote: > > MyClass addInstVarName: 'foo' > > MyClass removeInstVarName: 'foo' Presumably that implies recompiling all of MyClass's methods, and searching out and updating all of it's instances -- a much more heavyweight operation than the Python equivalent. It's not exactly the same thing, either -- Python instance variables are added on a per-instance basis, whereas that is adding one to all instances. That's not to say the Python way is necessarily better, just different. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From aleaxit at yahoo.com Wed May 16 17:22:54 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 16 May 2001 23:22:54 +0200 Subject: new.instancemethod References: Message-ID: <9dur3001sc@enews1.newsguy.com> wrote in message news:mailman.990039435.21839.python-list at python.org... ... > True. On the other hand, Python does support instance-specific methods. You mean bound-methods, right? > So what is a nice example usage of this capability and what is a good > practice for its implementation? What capability, exactly? Bound methods, unbound ones, the new module...? > In GUI code I often want to do something > like giving "instance-specific behavior" to each button on a panel. But in > practice, if I have two buttons, button1 and button2, lets say, I usually > assign two different handler methods, "handleButton1" and "handleButton2" > -- one to each button -- that are defined as part of some controller class. Why that, rather than bound methods directly? > So I'm using an instance-specific attribute (that references a bound method > -- which is extremely useful) but it's not an "instance-specific method" in > the sense that the "im_self" part of the bound method refers to the > controller object and not to the button object itself. So, what would be a > good example of an instance-specific method where the "im_self" of the > bound method object actually points back to the object of which it is an > instance-specific method (to describe the concept as poorly as possible ;-) > ). And then, how does one build such a method without using module "new"? I'm having something of a hard time understanding exactly what you are asking, but I'll give it a try. I guess you mean something like (it can be a bit more concise with nested scopes...): def makeBound(object, message): def emit(object, message=message): print "Hello and %s from %s"%( message, object.name) object.__class__._my_temp=emit result = object._my_temp del object.__class__._my_temp return result then obj.greet = makeBound(obj, "welcome") ...? The new module is better (no need to use a temporary _my_temp attribute of the class object, &c) but this works too. Now you may call obj.greet() or obj.greet("good luck"), etc. Maybe preferable (and maybe not) to: def makePseudoBound(obj, msg): def emit(msg=msg, obj=obj): print "Hello and %s from %s"%( msg, obj.name) return emit then obj.greet = makeBound(obj, "welcome") where the 'binding' is simulated through default arguments, or nested scopes, etc. > Any good examples from practice? Not that comes to mind. I have never had the need to store a bound method as an attribute of the object to which it was bound -- it seems more common, if stored it needs to be, to store it elsewhere. Nor have I ever actually needed this new-eschewing black magic, nor can I think why one would prefer that to module new. Alex From phd at phd.fep.ru Fri May 25 15:45:14 2001 From: phd at phd.fep.ru (Oleg Broytmann) Date: Fri, 25 May 2001 23:45:14 +0400 (MSD) Subject: Python 2.0 quick reference... In-Reply-To: <7itle9.q94.ln@news.onlinehome.de> Message-ID: On Fri, 25 May 2001, Andreas Dietrich wrote: > >As I admitted elsewhere in this thread, I'm a Microsoft > >victim^h^h^h^h^h^huser. Is Lynx available for Windows? I think not, but there was DOS port. > btw there is another textmode browser called links, which is in at least one > aspect better than lynx: links supports tables. And frames, and colors. But it doesn't support Basic Auth :( > Get it from > (win32 guys&gals could try cygwin) Oleg. ---- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From fredrik at pythonware.com Fri May 11 20:47:36 2001 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 May 2001 00:47:36 GMT Subject: Range Operation pre-PEP References: <98OK6.9793$sk3.2667317@newsb.telia.net> Message-ID: In the dumbest subthread in quite a while, someone wrote: > Perhaps you should treat people who disagree with you with more > respect. when you deserve it. > > if you're so experienced in Python as you say you are, maybe you can > > prove me wrong, by posting some code where you use lists and tuples > > the "wrong" way, and show that it won't work better if done the > > other way around. > > I don't have to post any code didn't expect you to. putting some weight behind your words isn't exactly your style. > I can just refer you to way Python itself works. Why do excess > parameters get put into a tuple rather than a list? yeah, why? is it because tuples are immutable (which was your main argument until you decided to tilt at another windmill)? if so, how come python's using *mutable* dictionaries for keyword args? or is it because excess arguments are more important than ordinary argument lists, and thus have influenced the whole design? do you really believe that? or is it because tuples are more efficient when the number of arguments is known at construction time (i.e when the function is called)? if so, you just proved my point. or maybe it's just an historical implementation artifact, and has nothing to do with the intended use of tuples vs. lists. > Excess parameters are not of a fixed length, and they are more > typically homogeneous than heterogeneous oh, you really do believe that. From max at alcyone.com Thu May 3 22:44:46 2001 From: max at alcyone.com (Erik Max Francis) Date: Thu, 03 May 2001 19:44:46 -0700 Subject: NNTP Post a file References: <3delu6mmg0.fsf@mems-exchange.org> Message-ID: <3AF2179E.8BA7ADA8@alcyone.com> Daniel wrote: > For all of you who want to share my experiences, here's the code + the > message: > > Python code: > import nntplib > > print "start" > s = nntplib.NNTP('news.skynet.be') > f=open('c:/temp/mymsg.txt') > s.post(f) > s.quit Note that you meant s.quit() here. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ The little I know, I owe to my ignorance. \__/ Sacha Guitry 7 sisters productions / http://www.7sisters.com/ Web design for the future. From richardd at pobox.com Fri May 25 08:29:10 2001 From: richardd at pobox.com (Richard Davies) Date: 25 May 2001 05:29:10 -0700 Subject: [FP] Rewriting name bindings as expressions References: <5078c6cc.0105240646.226c96ac@posting.google.com> <3B0DBC6E.CDB80197@my.signature> Message-ID: <5078c6cc.0105250429.6830c1eb@posting.google.com> > ans = [y+1 for x in range(10) for y in (x*x,)] For what it's worth, ans = [y+1 for x in range(10) for y in [x*x]] or ans = [y+1 for x in range(10) for y in x*x,] are a few characters shorter! Richard. From nperkins7 at home.com Tue May 8 18:46:04 2001 From: nperkins7 at home.com (Nick Perkins) Date: Tue, 08 May 2001 22:46:04 GMT Subject: .pyc crashes, .py doesn't References: <0IZJ6.6795$vg1.546865@www.newsranger.com> Message-ID: I'm sure this is not causing your problem, but.. It was recently discussed around here that floating-point numbers suffer a loss of precision when they are loaded from .pyc files. .. I wonder if there are other documented differences between the behaviour of .pyc code and .py code? ( your experience certainly suggests that there is, unless you are doing something strange with floats ) From mwh at python.net Tue May 8 02:27:45 2001 From: mwh at python.net (Michael Hudson) Date: 08 May 2001 07:27:45 +0100 Subject: ANNOUNCE: pyrepl 0.5.0 (was: ANNOUNCE: Readline Alternative 1.2) References: <001701c0d5a5$ebc12e00$a100000a@local> <20010507.153658.1983690368.27254@mead.troikanetworks.com> Message-ID: "Bruce Edge" writes: > > > > Mine's at: > > > > http://starship.python.net/crew/mwh/hacks/pyrepl.html > > > > Cheers, > > M. > > Hi, > Great news, I've had issues with readline for a while. Thanks for the interest! > Got a few questions. If the answer is "go read the code", that's > fine too, but I have to ask anyways. Well, reading the code isn't especially easy at the moment. It's evolved gradually over the course of some months (even though I've thrown everything out and started again at least twice), and this doesn't make for easy to read code. > First, there's a typo in completer.py: > > def complete(self, text): > if "." in text: > ruern self.attr_matches(text) <--- > else: > return self.global_matches(text) Eek! At least that's easy to fix. > Second, one of the issues I've had with readline is how to re-init > it to clear out old history. When I use pdb, I want to change my > history file name, and then reload my old history when I exit pdb, > and none of the existing history commands apply in pdb vs. python > shell. Can you do this with pyrepl? For sure! You'd just use different readers for pdb and the Python top-level. This isn't completely trivial as pdb.Pdb is written to use cmd.Cmd so you'd need to rewrite a bit (hmm, I wonder if one could write a class that you could inherit from a Cmd-using class with to get a pyrepl-using class...). In effect, this works already though: the top-level of pyrepl uses its history and pdb will use readline's. > Third, Key binding, what functions can you bind keys to? Whatever is in the reader's classdict attribute. What's in there depends on the make_classdict function of the reader you've instantiated... there are lots and lots of examples of commands in commands.py, and some more in historical_reader.py & completing_reader.py. > Lastly, Do you have any docs on the API, or had you intended it to > be an interactive python goodie only? Maybe. I wouldn't regard the API as fixed just yet; as I hinted above, I think bits of it are somewhat insane. Though attempting to document it might well help me spot which bits. Also, I need feddback so I can spot places where the API is a bit broken or insufficiently general (I have a few of these already). Thanks for the comments, M. -- This is not to say C++ = bad, Lisp = good. It's to say C++ = bad irrespective of everything else. -- Alain Picard, comp.lang.lisp From mwh at python.net Sat May 19 07:40:25 2001 From: mwh at python.net (Michael Hudson) Date: 19 May 2001 12:40:25 +0100 Subject: python 2.1 core dumping on redhat 6.2 References: <9e4hnk$dfp$1@news.service.uci.edu> Message-ID: strombrg at seki.acs.uci.edu (Dan Stromberg) writes: > Built smoothly, passed all tests. Make install appears to have > compiled everything. > > But when I run it interactively, I get: > > rh-strombrg> /dcs/packages/python-2.1/bin/python > Python 2.1 (#1, May 18 2001, 14:45:56) > [GCC 2.95.2 19991024 (release)] on linux2 > Type "copyright", "credits" or "license" for more information. > Segmentation fault (core dumped) Eek! [snip] > Any suggestions where I should start looking? Is it a known bug? Not to me. What readline version is it? > I suppose I could live without readline, but would rather not. Gratuitous plug: try pyrepl, my Python readline-a-like: http://starship.python.net/crew/mwh/hacks/pyrepl.html (I'll probably be packaging up a new version in the next few days). Cheers, M. -- All parts should go together without forcing. You must remember that the parts you are reassembling were disassembled by you. Therefore, if you can't get them together again, there must be a reason. By all means, do not use a hammer. -- IBM maintenance manual, 1925 From writeson at earthlink.net Sun May 27 19:38:57 2001 From: writeson at earthlink.net (Doug Farrell) Date: Sun, 27 May 2001 23:38:57 GMT Subject: GUI suggestions References: <_HTP6.34744$BN6.2065334@newsread1.prod.itd.earthlink.net> <9ep8p601h3k@enews2.newsguy.com> Message-ID: Alex, Thank you very much for the great feedback on GUI's with Pyton. I probably should have mentioned the utility program I write in C++ that is getting the GUI frontend run on Sun Solaris, so I'm not to concerned with cross platform development, at least for this application. I'm kind of baised towards using wxPython as I've done some reading and downloaded the system and tried the demos. I will look at Tkinker as well since I have no knowledge of that on which to base a decision, as of yet anyway. This last year I jumped ship from MS windows development and joined an online group doing CGI on the Sun platform. After getting up to speed a little bit on Unix/Linux I honestly can say I don't know why I waited so long!! Windows falls short in many areas that Unix has in spades. Though I liked developing VC6, I didn't like all of the holes and 'guru only' knowledge that was necessary to get a program to run well under Windows and MFC. Again, thanks for your response, Doug "Alex Martelli" wrote in message news:9ep8p601h3k at enews2.newsguy.com... > "Doug Farrell" wrote in message > news:_HTP6.34744$BN6.2065334 at newsread1.prod.itd.earthlink.net... > > Hi, > > > > I'm planning on doing some Python programming at work and the project I'm > > thinking about would be a GUI front end to a C++ command line utility. I > > know about wxPython and GTK+ (and I guess a few others), but does anyone > > have any suggestions or advice on which GUI tool I should invest time in > to > > learn? I'm a strong C++ programmer and pretty good at Windows MFC stuff, > so > > I do know the basics about GUI code. > > If the command-line utility you're using is Windows-only, so you don't > mind your GUI front-end also not being cross-platform, you may put > your MFC knowledge to good use (and thus presumably finish your > project faster) by using the Windows-only Pythonwin GUI framework, > as it's basically a Python wrapper over MFC. I don't think anybody will > argue for MFC being a "great" framework, but, if you already know it, > it may still be fastest for you to re-use that knowledge. > > wxPython is also a Python wrapper over a C++ framework, but the > framework is wxWindows, better-designed than MFC (IMHO) _and_ > cross-platform. If you invest time in studying wxPython, the > knowledge you gain will help you in cross-platform development, > even if one day you should unexpectedly find yourself having to > develop a _C++_ cross-platform application. > > Tkinter offers the advantage of being "the" classic GUI framework > used in scripting languages (not just Python -- Tk was born for > TCL, and is, AFAIK, the most-used GUI kit for Perl, too). If you > think one day you might find yourself having to code GUIs in TCL > or Perl, then some knowledge may "cross over" if you get familiar > with Tkinter. Tkinter is also cross-platform. > > wxPython and Tkinter are both free, with licenses similar to > Python's. I'm not so sure about other cross-platform GUI > frameworks -- depending on your situation, platform, etc, > you may find yourself having to pay money or abide by GPL > restrictions. If this is no problem for you, fine! -- if it may be > a problem, check out the licensing situation before you commit > time and effort to studying a framework. > > Some people swear by GUI-painters. wxPython has an "early > beta" one, called Boa Constructor, that is free. I think 'glade' > is similarly free for GTK++. Other GUI frameworks have > 'painter' programs that are commercial -- great if you can > afford to pay, of course, but maybe a stumbling block if > you can't. For Tkinter, the painter/layout manager is part > of Secretlabs' Python IDE, PythonWorks; for Qt, it's part of > another Python IDE called Blackadder (or you may get it as > part of a Qt license for a couple thousand dollars from Qt's > owners, Trolltech). If you have funding for SW purchase and > care about IDE's and GUI-painters, you will probably want to > try either or both of these commercial programs -- and their > quality may influence your GUI-toolkit choice. > > Tkinter has the edge in terms of documentation, IMHO. The > stuff that comes with wxPython is good, at least if you know > enough C++ to follow the wxWindows docs it's interleaved > with. But for Tkinter you can get /F's excellent manual AND > Grayson's book on Python and Tkinter, while there is no book > out on wxPython (nor, I believe, wxWindows either). > > > Me? When I need a GUI, I generally put together a bit of > HTML. On Windows, I can package my application up as > HTA (HTML Application), use Active/X controls, and get as > spiffy as I want. Cross-platform, my GUIs can't be very > fancy, but deployment flexibility is great -- the 'engine' > need not be running on the same box as the GUI... I like > that! Python comes with a simple but usable CGI capable > webserver that's easy to adapt to run your scripts behind > the HTML page 'GUI', without actually paying CGI per-hit > costs. Or you may choose Xitami (with LRWP), Apache > (with mod_python), whatever, for similar benefits. If your > GUI needs are reasonably simple, comparable to what can > reasonably put on a webpage, you may want to consider > the advantages of this unconventional architecture! > > At least you're spoiled for GUI painters, given the surfeit > of HTML editors, free and commercial, you can find...:-) > > > Alex > > > > From whisper at oz.nospamnet Mon May 14 20:28:41 2001 From: whisper at oz.nospamnet (David LeBlanc) Date: 15 May 2001 00:28:41 GMT Subject: What can you do in LISP that you can't do in Python References: <3AFFFB0E.70A8B5BF@wag.caltech.edu> Message-ID: <9dpt7p$eb5$0@216.39.170.247> In article <3AFFFB0E.70A8B5BF at wag.caltech.edu>, rpm at wag.caltech.edu says... > However, thus far I can't see anything that I could do in Scheme that I > couldn't do in Python. > Rick Wear out your paren keys. Try to keep ancient names for registers turned to function names straight: cadr caddr cadddr etc. etc. etc. Reinvent a lot of wheels far too often. From aleaxit at yahoo.com Sat May 12 07:30:33 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 12 May 2001 13:30:33 +0200 Subject: Need "sum" compatible checksum16 in Python References: <3AFCE8F7.6FE664B5@engineer.com> <3AFCF5EA.E181DCA1@engineer.com> Message-ID: <9dj6pf02n24@news1.newsguy.com> "B. Douglas Hilton" wrote in message news:3AFCF5EA.E181DCA1 at engineer.com... > Here is the relevent excerpt from sum.c from GNU textutils: > > while ((ch = getc (fp)) != EOF) > { > total_bytes++; > ROTATE_RIGHT (checksum); > checksum += ch; > checksum &= 0xffff; /* Keep it within bounds. */ > } > > This seems pretty trivial. In C there is no problem with > adding characters as integers, but I have found that it is > a big problem in Python. Maybe I need to make a c-lib > function from this and link with Python? For speed, you may choose to do that, but there's really no need in terms of pure functionality, even considering the definition of rotate_right you posted later as: #define ROTATE_RIGHT(c) if ((c) & 01) (c) = ((c) >>1) + 0x8000; else (c) >>= 1; The builtin array module helps -- something like the following untested code should work fine: import array def checksum(fileobj): filedata = array.array('B', fileobj.read()) totbytes = len(filedata) result = 0 def rotate_right(c): if c&1: return (c>>1)|0x8000 else: return c>>1 for ch in filedata: result = (rotate_right(result)+ch) & 0xFFFF return result but you don't HAVE to use array -- it should also work with something like: def checksum(fileobj): totbytes = 0 result = 0 def rotate_right(c): if c&1: return (c>>1)|0x8000 else: return c>>1 for ch in fileobj.read(): ch = ord(ch) & 0xFF result = (rotate_right(result)+ch) & 0xFFFF return result I'm not sure if ord() returns -128 to 127, or 0 to 255, whence the &0xFF. If the file is huge you may also read it in slices, of course, with either array or the direct loop on filedata approach. I believe your worry that Python "may be too high level for this computation" is misplaced. It's easy in Python to get down & dirty with the bits, if and when you want to -- array and struct help, but you may do without them if you want. It's all an issue of speed... low-level stuff often needs to be very speedy, so recoding it as a C coded extension may be worth the bother. But you can at least prototype it in Python without breaking a sweat:-). Alex From aleaxit at yahoo.com Thu May 10 07:29:01 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 10 May 2001 13:29:01 +0200 Subject: Unification Idea References: <3AF9B5BB.505746B4@javanet.com> Message-ID: <9ddu1r01ime@news1.newsguy.com> "Raymond Hettinger" wrote in message news:3AF9B5BB.505746B4 at javanet.com... > Complex numbers define: .real, .imag, and .conjugate(). > I think we ought to define them for floats, ints, and longs also. It WOULD ease polymorphic use of various number types as if they were complex, yes. I suspect the usage of complex numbers may be considered too rare to warrant adding attributes/methods to numeric types that now have none. > arr = [ 2,10L, 5.1, 3+2j ] > map( lambda z: z.conjugate(), arr ) # This is what I would like to do > > map( lambda z: type(z)==types.ComplexType and z.conjugate() or z, arr ) # vs. > what I have to do now I think a better "works now" solution might be: def conj(x): try: return x.conjugate() except AttributeError: return x map(conj, arr) This lets arr contain arbitrary user-types that implement the .conjugate() method, just like your "would like to do" case would, rather than constraining behaviour through a type-test. If you do this often, you only need write the simple functions conj(), real() and imag() once, of course, and you can stick them in your builtins or whatever... it's _almost_ as good as if they were "real" built-ins:-). Alex From vsbabu at erols.com Tue May 8 13:48:52 2001 From: vsbabu at erols.com (Satheesh Babu) Date: Tue, 8 May 2001 13:48:52 -0400 Subject: Absolute TO Relative URLs Message-ID: <9d9bf6$soo$1@bob.news.rcn.net> Hi, Let us say I've an HTML document. I would like to write a small Python script that reads this document, goes through the absolute URLS (A HREF, IMG SRC etc) and replaces them with relative URLs. I can pass a parameter which specifies the BASE HREF of the document. I'm not sure whether I should proceed with regex nightmare or are there any easy solutions? Any help/pointers will be greatly appreciated. Thanks -- v.s.babu vsbabu at erols.com http://vsbabu.csoft.net From aleaxit at yahoo.com Thu May 31 11:21:23 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 31 May 2001 17:21:23 +0200 Subject: I had a thought ... (I know, call the newspapers). References: Message-ID: <9f5nhn02816@enews2.newsguy.com> "Laura Creighton" wrote in message news:mailman.991316267.13430.python-list at python.org... > Lets give python a new type. We will call it money. And we will Visual Basic has that. It's called "Currency", I believe. They even CLAIM "Even though it's larger, the Currency data type is faster than the Single data type because the Currency data type doesn't use the floating-point processor" (quoted from "Microsoft Office 2000/Visual Basic Programmer's Guide"). I think they're talking though their hats. The denotation character, if I recall correctly, is @ in VB (@...?! I think that's because $ was already taken for strings), but $ in Visual FoxPro (which also has Currency; type Currency is also in the .NET minimal specifications -- any language must provide it to interoperate fully in .NET). I don't think anybody's really using it, though. I could be wrong, it's hard to get precise statistics, but for what I can judge from typical VB snippets seen around they seem to be using the convenient notation (which, I think, maps to floating-point) anyway. > In 20 years I have had 0 luck teaching people to not use floating > point for money. The fools carefully ignored me and went back to It appears to me MS isn't having much, even though they did put Currency and Decimal and all into their hodge podge of a language. The fact that just writing a plain simple 7.35 gives a float is apparently the killer. > I am almost convinced that I can teach them to use the type money, > a slower, more accurate type that accurately represents money and What if it's FASTER too, as MS is these days claiming for their Currency, see above? I believe the claim is unfounded, but that's another issue. It still seems to be little used even by the kind of people who take any MS claim as gospel:-). We can easily supply a Money or Currency or whatever type today, *APART* from convenience of literals. Maybe for experimental purposes we can supply that with a "preprocessor" at import time, ala PyHTML... (I'd use $ though, much as I love the Euro -- requiring Unicode source would not endear the concept to most users:-). Alex From julschae at t-online.de Sat May 26 07:31:30 2001 From: julschae at t-online.de (=?iso-8859-1?Q?Julian_Sch=E4fer-Jasinski?=) Date: Sat, 26 May 2001 13:31:30 +0200 Subject: Python FTP-Class w/ Resuming-Capabilities -- General Questions Message-ID: Hi List, My name is Julian and I have only coded a few snippets and small applications in python so far (about 1 year experience). Now I want to write an ftp-indexer (indexing files of special interest) and a server-side-download tool (later probably multi-threaded -> but that shall be a future headache ;-)). I have made myself familiar with the ftplib - but it doesn' t seem to support resuming. (Is that right?). Therefore I am trying to implement a small class myself using the socket-lib. I have the following questions: -> Is there already a neat tool for indexing / server-side download supporting resuming / multiple threads? -> How is the resuming implemented (didn't find the appropriate RFC). -> Is there some sample-code except for ftplib that I should have a look at (even other scripting-languages) / could use? -> Would it be easy to extend the ftplib with resuming-capabilities? Any other thoughts and suggestions are welcome as well... Thanks in advance, Juilan Schaefer-Jasinski ______________________________________________________________ Julian Schaefer-Jasinski julschae at usa.net Frankfurt, Germany - Student of CS From nessus at mit.edu Thu May 3 15:18:03 2001 From: nessus at mit.edu (Douglas Alan) Date: 03 May 2001 15:18:03 -0400 Subject: Ideas for a project? (a MSc project, sort of) References: Message-ID: scarblac at pino.selwerd.nl (Remco Gerlich) writes: > It would be interesting to have an overview of optimizations in CL > compilers, and how they could be applied to Python (or why they > can't). See the paper "Making Pure Object-Oriented Languages Practical" http://citeseer.nj.nec.com/chambers91making.html to find out how to make a compiler for Python that would generate very fast code. These techniques work on Self, which is even more orthogonal and flexible than Python, and I can't think of any reason why they wouldn't work on Python too. (I don't know how these techniques differ from those typically used in Lisp compilers.) |>oug From fdrake at acm.org Wed May 30 01:53:23 2001 From: fdrake at acm.org (Fred L. Drake, Jr.) Date: Wed, 30 May 2001 01:53:23 -0400 (EDT) Subject: [Python-Dev] RE: [Doc-SIG] [development doc updates] In-Reply-To: References: <20010530053101.4985F28A10@cj42289-a.reston1.va.home.com> Message-ID: <15124.35539.53551.52668@cj42289-a.reston1.va.home.com> Tim Peters writes: > Stumbled into one glitch: nonzerodigit doesn't resolve correctly; the > node24.html page it refers to doesn't seem to exist. That was the bug alluded to. The digit* grouped with the nonzerodigit also doesn't work, although the other two uses of digit on that page (floating.html) work properly. I'll investigate tomorrow; just too tired tonight. -Fred -- Fred L. Drake, Jr. PythonLabs at Digital Creations From see at my.signature Tue May 1 23:45:11 2001 From: see at my.signature (Greg Ewing) Date: Wed, 02 May 2001 15:45:11 +1200 Subject: Sockets: Sending/receiving arbitrary amounts of data References: <3AEE4D9C.B02403F8@my.signature> <87vgnlmopr.fsf@c0re.rc23.cx> Message-ID: <3AEF82C7.F4FAD345@my.signature> "Doobee R. Tzeck" wrote: > > Considering Python is a high level Language I ask myself > if there shouldend be a way in Python to optionally shield the > user (programmer) from the hassle of handling of short socket > reads. I think so, too. I once suggested that file.read(), socket.recv() and similar methods should have an optional two-argument form: recv(min, max) This would block until at least min bytes had arrived, and return at most max bytes. If EOF occurs before min bytes have arrived, an exception is raised. Putting min == 0 gives the current behaviour. Putting min == max gives you a fixed-length read. Perhaps I'll PEP this one day, too. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From kirschh at lionbioscience.com Tue May 8 07:13:55 2001 From: kirschh at lionbioscience.com (Harald Kirsch) Date: 08 May 2001 13:13:55 +0200 Subject: make module for Python? References: Message-ID: Roman Suzi writes: > Hello! > > I have not found it anywhere on the Web, but probably it > has different name, so it's better to ask. > > I want a make-utility functionality (maybe not all, but > basic) to be available from Python. (Similarly to the > grep.py which provides grep functionality). > > Is there anything for this? A year or two ago there was even a contest where people were asked to develop a python based build environment. One of the tasks was a make replacement. I would be interested what resulted from that. > I'd liked to have make dependence info not only for files, but for > arbitrary class instances. Isn't it cool? If you don't care to use Tcl rather than Python, have a look at http://wsd.iitb.fhg.de/~kir/brashome/ It would be great to have that functionality also in Python. Harald. -- ----------------+------------------------------------------------------ Harald Kirsch | kirschh at lionbioscience.com | "How old is the epsilon?" LION bioscience | +49 6221 4038 172 | -- Paul Erd?s *** Please do not send me copies of your posts. *** From amdescombes at diligo.fr Fri May 25 09:12:56 2001 From: amdescombes at diligo.fr (Andre M. Descombes) Date: Fri, 25 May 2001 15:12:56 +0200 Subject: Reinitializing the python interpreter form Java References: <9eg3fs$aaq$1@wanadoo.fr> <3B0C256D.4F33D28E@accessforall.nl> Message-ID: <9elln0$1d6$1@wanadoo.fr> Hi Ype, I tried your method, but when I have global variables, they don't seem to be changing their values after I do the setLocals, even with then copy() instruction. Any Idea what might be happening? Thanks, Andre M. Descombes > > I tried using getLocals and setLocals with no success. > > Did you make a copy of the dictionary returned by getLocals()? > > savedLocals = getLocals().copy() > > Each time you run your program you will have to pass it a fresh > copy of this copy, too: > > interpr.setLocals(savedLocals.copy()) > > The fresh copy will give the restore effect. > > Have fun, > Ype From bellman at lysator.liu.se Thu May 3 08:41:00 2001 From: bellman at lysator.liu.se (Thomas Bellman) Date: 3 May 2001 12:41:00 GMT Subject: PEP 234: Iterators References: Message-ID: <9crjks$9kn$1@newsy.ifm.liu.se> "Stephen Hansen" wrote: > I'd like to read 'iter(object)' as 'iterate(object)' and 'iter(func, > sequence)' as 'iterator(func, sequence)' since the latter is making an > iterator on the fly, and not iterating over it... But the former *doesn't* iterate over the sequence. It *also* instantiates (creates) an iterator. The *for* statement and the *map()* function iterates; the iter() function (whatever spelling) doesn't, so it shouldn't be called iterate(). > but that really doesn't > matter, i'd much rather just see 'iterate' for both of them. Perhaps it > would be better to 'traverse(iterator-object)' and then 'iterator(func, > sequence)'. In fact, that's my favorite option.. getting rid of the > excessive use of 'iter' and just calling it 'traverse'. Same problem with the name traverse(). -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "I don't think [that word] means what you ! bellman @ lysator.liu.se think it means." -- The Princess Bride ! Make Love -- Nicht Wahr! From cheong at msc.cornell.edu Sun May 27 09:10:34 2001 From: cheong at msc.cornell.edu (Siew-Ann Cheong) Date: 27 May 2001 13:10:34 GMT Subject: [Q]Python Classes References: <9epv95$9m8$1@news01.cit.cornell.edu> <5j0Q6.74410$eK2.15175666@news4.rdc1.on.home.com> Message-ID: <9equca$cil$1@news01.cit.cornell.edu> Nick Perkins (nperkins7 at home.com) wrote: : close!, you just have to remember to use self to refer to : class methods, like this: : : > class MyClass: : > def __init__(self, data): : > self.private_data = data : > self.MyInitialization() : ^^^^ : > def MyInitialization(self): : ... Thanks! That works! I think my problem was with reloading the class definitions when I was playing with this, but I have since found out how to reload modules properly. Cheong Siew Ann From MarkH at ActiveState.com Sun May 6 20:46:59 2001 From: MarkH at ActiveState.com (Mark Hammond) Date: Mon, 07 May 2001 00:46:59 GMT Subject: Help! Writing COM ActiveDocuments in Python References: Message-ID: <3AF5F0E2.7000208@ActiveState.com> Carlos Ribeiro wrote: > I need some help with Win32 and OLE/COM stuff. I'm trying to write an > ActiveX control in Python. The catch is that I want this control to be > embeddable, inplace editable, and persistent (able to write itself to a > stream). Please understand that I'm trying to write it using only Python > (i.e., I dont want to encapsulate a C++ component). If it ends up being > impossible for any reason, I'll be happy to do everything in C++ or > Delphi anyway. I did some searches, but I could not find any example of > this stuff. Do someone have a pointer for this specific kind of > application? Python's COM support does not support fully-fledged controls. The win32comext/axcontrol directory is the start of work in this direction, and supports many of the interfaces needed. If you would be happy to help, and to donate a trivial sample control I would be happy to help and guide you to getting this module up to scratch. As you say you are willing to use C++, hacking on some of the Python extensions should not scare you too much. Mail me if you think this sounds good... Mark. From kdart at kdart.com Mon May 14 03:08:20 2001 From: kdart at kdart.com (Keith Dart) Date: Mon, 14 May 2001 00:08:20 -0700 (PDT) Subject: Bug in Python large negative literal assignment? In-Reply-To: Message-ID: On Mon, 14 May 2001, Roman Suzi wrote: > On Sun, 13 May 2001, Keith Dart wrote: > > That is because 2147483648 can not be represented by > 32 bits ;-) Thanks, but I know 2147483648 cannot be, but -2147483648 can be. I think Python aught to allow it. You're right, it is probably doing a negation on the positive literal, but I have to do some ugly work-arounds on my project because of this. But, I managed it by simply assigning it as a hexadecimal number. > Python constructs numbers by operations: > > -2147483648 - is the result of "-" operation > on 2147483648 number. > > > I seem to have found a bug in how Python assigns the largest negative > > literal: > > > > Python 2.1 (#1, Apr 23 2001, 15:49:36) > > [GCC 2.95.1 19990816/Linux (release)] on linux2 > > Type "copyright", "credits" or "license" for more information. > > Sourcing .pythonrc... > > Python> # I cannot assign the following: > > .more.. i = -2147483648 > > OverflowError: integer literal too large > > Python> # however, I can do it the following ways: > > .more.. i = -sys.maxint-1 > > Python> i > > -2147483648 > > Python> i = 0x80000000 > > Python> i > > -2147483648 > > Python> i = -2147483647 ; i = i - 1 > > Python> i > > -2147483648 > > Python> i = -2147483647-1 > > Python> i > > -2147483648 > > Python> i = -2147483648 > > OverflowError: integer literal too large > > > > But, no, can't assign a max negative number as decimal literal. > > > > > > > > \\|// > > (O O) > > -- --------------------oOOo~(_)~oOOo---------------------------------------- > > Keith Dart > > > > > > ---------------------------------------------------------------------------- > > Ever since my brain transplant I ... > > ============================================================================ > > > > > > Sincerely yours, Roman A.Suzi > \\|// (O O) -- --------------------oOOo~(_)~oOOo---------------------------------------- Keith Dart ---------------------------------------------------------------------------- Ever since my brain transplant I ... ============================================================================ From ralf.claus_spam_ at t-online.de Sat May 12 09:04:46 2001 From: ralf.claus_spam_ at t-online.de (Ralf Claus) Date: Sat, 12 May 2001 15:04:46 +0200 Subject: ordinal not in range(128) References: <3AFBA4BA.B0DDD7B4@teleatlas.com> Message-ID: <9djcf4$ivn$06$1@news.t-online.com> I could answer the question. But i do not point why it functioned. Normally, this is the way to capture text from a TextWidget. (I type ?????? in the TextWidget) text = self.c.get(1.0,END) print text Traceback (most recent call last): File "e:\python20\lib\lib-tk\Tkinter.py", line 1287, in __call__ return apply(self.func, args) File "I:\EXAMPLE\ascii.py", line 16, in druck print text UnicodeError: ASCII encoding error: ordinal not in range(128) This way functioned: text = string.join(map(chr,map(ord,self.c.get(1.0,END))),'') print text ?????? What happens here exactly? "Ralf Claus" schrieb im Newsbeitrag news:3AFBA4BA.B0DDD7B4 at teleatlas.com... > Hello, > can you tell me something about this error ? > With py 1.5.2 and Tcl/Tk 8.05 there are no problems! > With py 2.0 and Tcl/Tk 8.3 this error occurs if i try to > work with german "Umlaute" >???< in a Text Widget. > To type s='?' in the idle is not possible. > How can i solve this problem ? > > Gru? > Ralf From kc5tja at dolphin.openprojects.net Mon May 21 19:18:20 2001 From: kc5tja at dolphin.openprojects.net (Samuel A. Falvo II) Date: Mon, 21 May 2001 23:18:20 GMT Subject: _winreg troubles! HELP! References: <3B09942F.6030706@ActiveState.com> Message-ID: On Mon, 21 May 2001 22:16:13 GMT, Mark Hammond wrote: >the problem may be your string. As it stands non-ascii characters are >being used. \b == 0x08. That's not the issue. I mis-wrote it in my newsreader, I do use \\ for path separators. As another pointed out, the bug is reproducable. I firmly believe it is a bug, though, as I am administrator of this NT box, and yet, it fails. -- KC5TJA/6, DM13, QRP-L #1447 Samuel A. Falvo II Oceanside, CA From mss at transas.com Sun May 13 14:38:47 2001 From: mss at transas.com (Mikhail Sobolev) Date: 13 May 2001 18:38:47 GMT Subject: urllib's performance References: <9dbmuo$978$1@harvester.transas.com> Message-ID: <9dmkbn$gm2$1@harvester.transas.com> In article <9dbmuo$978$1 at harvester.transas.com>, Michael Sobolev wrote: >Two days ago I tried to create a small script that should help me to estimate a >performance of a web system we created. But I found that using the python >script does not allow to get as many requests as I was able to with plain shell >with wget. It was a little bit surprising as I thought that python's >performance is rather good. Maybe I am just missing something. I am using >python 1.5.2 and the urllib that comes with it. Just to give a little bit more background. I have a server program that can create a number of working threads. What I tried to look at is how the number of working threads and the number of concurrent clients correlate. So my script looked like: for thread_no in range (1, 21): # as 20 seems to be a reasonable limit as # each working thread on server uses a # significant amount of memory for client_no in range (1, 21): # maybe 20 is not sufficient, but let's # have a look on that many concurrent # clients for client in range (1, client_no+1): thread.start_new (client_proc, args) wait_for_threads_to_finish () And the problem is that the request rate of each client_proc is not sufficient. Thank you in advance, -- Misha From costas at malamas.com Wed May 9 13:52:20 2001 From: costas at malamas.com (Costas Malamas) Date: Wed, 9 May 2001 20:52:20 +0300 Subject: Python in Windows Tray? References: <3AF935BA.20672.38FF9C1@localhost> Message-ID: <000a01c0d8b0$ce587040$6501010a@retek.com> Doesn't quite cut it; it leaves a console window behind... Thanks for the input though, Costas > > "Costas Malamas" wrote, in part: > > Does anyone know of a python interpreter than can sit in the Windows > > tray? > > > > I would like (no, I would *love*) to be able to launch some python > > scripts ... > > Costas, how does what is available as > C:\Python21\win32\Demos\win32gui_taskbar.py in the ActiveState > distribution of Python compare with what you want? - Bill > > > From piet at cs.uu.nl Sun May 27 11:22:56 2001 From: piet at cs.uu.nl (Piet van Oostrum) Date: 27 May 2001 17:22:56 +0200 Subject: Change dbhash values in place using next() loop? References: <3B10F2C5.624F87FC@schlund.de> Message-ID: >>>>> Carsten Gaebler (CG) writes: CG> Hi there! CG> I have a DBM file with values formatted like "a:b" where a and b are CG> strings. Every once in a while I'd like to set a=b for every item of the CG> file. I tried the following: CG> import dbhash CG> db = dbhash.open("my.db", "w") CG> while 1: CG> (k, v) = db.next() CG> (a, b) = v.split(":") CG> v = "%s:%s" % (b, b) CG> db[k] = v CG> This works for about half of the items, but the others remain unchanged. CG> Does changing the values change the ordering of the file? It could. dbhash uses a form of extensible hashing, which means that buckets may be reorganised when a value no longer fits in it. In that case the order will change. CG> Any ideas besides looping over db.keys() (which at the moment is 16 MB in CG> size) or creating a temporary file and then os.system("cp -f temp.db CG> my.db")? I would not copy, but rename the temporary file. And I think this might be the most efficient solution. Ny the way, you don't need os.system to rename. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From James_Althoff at i2.com Fri May 18 17:48:30 2001 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Fri, 18 May 2001 14:48:30 -0700 Subject: new.instancemethod Message-ID: Alex Martelli wrote: >...then class 'Tweak' will have ONE base class, rather than the variety >of specific base classes it will need for this use: which is ok if the instances that we want to tweak are all instances of the same class -- which is a bad assumption in general, so I agree with you: the class statement needs to be in the def body (which, to me, decreases the attractiveness of that approach compared to the first approach). >"Judiciously" is a keyword >here I think -- it's great for experimental interactive specialized >programming frameworks, but I can't think of a case I would WANT >to use such black magic in _production_ code. Presumably when you say black magic you are referring to the second approach (changing the __class__ attribute of an instance) and not the first approach (using "new.instancemethod")? Because if both, then I'm back to my original interest of looking for a good example of (needing) and practice for (implementing) "instance-specific behavior" that would be reasonable to use -- even in production code. I believe you are saying that approach 1 is a reasonable way to go in your experience (if the need arises such as in your bridge game example). > > >Alex Jim From cmg at uab.edu Fri May 25 09:49:47 2001 From: cmg at uab.edu (Chris Green) Date: 25 May 2001 08:49:47 -0500 Subject: speeding up string.split() References: Message-ID: duncan at NOSPAMrcp.co.uk (Duncan Booth) writes: > Chris Green wrote in > news:m2n182cs9c.fsf at phosphorus.tucc.uab.edu: > > > Is there any way to speed up the following code? > You haven't given much to go on here. Any real speedups are likely to > depend very much on what you want to do with the data after you have split > it. Sorry about that. I had factored out the portion that I thought was slowing me down. For all possibilities to be considered, let me state the nature of the data. Using ipaudit (http://ipaudit.sourceforge.net), I get gzip'd files containing details on internet traffic. Each hour on my connection yields roughly 330,000 lines of the format below. I have done the same set of things with a gzip'd file and the speed opt for it was to do readlines() rather than line by line. I wish to be able to define searchs on each of the 13 data fields breaking it up into a dict for each part of the field seemed like the cleanest way ( not fasted ). I'm willing to rely on ``good'' input data from the backend. Disappointed by the speed of splitting and then creating a dict, I got rid of the dict step since I knew it was positional in nature and then discovered that the split was a bottleneck. I might be able to use split and map to do my bidding and will try that but I'm not very hopeful. The string concatentation operation is purely artificial to make posting on usenet fit in 72 cols. > > #!/usr/bin/python > > from string import split > > > > for i in range(300000): > > array = split('xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy 6' + > > '1064 80 54 54 1 1 14:00:00.8094 14:00:00.8908 1 2') > > [ only applies to my 3 line example and not the real problem ] > > Alternatively: > 3. Put the code inside a function. I will try. My first example was function('xxx ....') but you are suggesting that the operation is bottlenecked by not being able to be optimized inside a def. I moved the entire function to a def speed_test(): and then called speed_test() from main. Looking at just the user times, it seems like a small speedup in my unscientific testings. inside function: ./speed.py 9.04s user 0.07s system 99% cpu 9.155 total ./speed.py 9.22s user 0.03s system 98% cpu 9.414 total outside function: ./speed.py 9.30s user 0.02s system 100% cpu 9.312 total ./speed.py 9.29s user 0.03s system 100% cpu 9.312 total > 4. Use the split method on the string instead of the split function This did give a noticable improvement but limits me to python 2.0+ AFAICT. > 5. Use string concatenation instead of '+' > 3, 4 and 5 together knock about 25% off the running time. > > 6. If whatever you intend to do with the data involves filtering it on the > first field or two, then using "xxx...".split(' ', 1) is very much faster > than splitting up all the fields. This can reduce the time by two thirds > easily. Yes this will work too and is how the author of the program that produces the data (uses zgrep to filter out based on ip). It's proven to be very useful data to be able to mine for traffic patterns ( esp on more than just src/dest ip ) and I've got a perl implementation already that is at the limits of acceptable for interactive use ( CGI ). > > 7. Use Perl, or C, or whatever else takes your fancy if speed is that > critical. I probably will have to use C to do the speed filterings and python to build an abstraction off that take the orignal approach.\ Thanks for your speedup tips. -- Chris Green "Yeah, but you're taking the universe out of context." From fredrik at pythonware.com Tue May 1 20:10:15 2001 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 02 May 2001 00:10:15 GMT Subject: Formatting numbers References: Message-ID: Daniel Klein wrote: > Given an integer, 12345, how to format this to 123.45 ? > Ok, this is what I've come up with so far > > x = 12345 > print '%.2f' % (x,) you don't have to "tuplify" a single value, but tuple or not, it doesn't really work as specified: >>> print "%.2f" % (x,) 12345.00 >>> print "%.2f" % x 12345.00 Cheers /F From fredrik at pythonware.com Wed May 2 11:49:45 2001 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 02 May 2001 15:49:45 GMT Subject: doctest or pyunit? References: <20010502.065745.2001229904.9225@mead.troikanetworks.com> Message-ID: Bruce Edge wrote: > Is doctest going to be updated to use 2.1's method attributes rather than > the doc string? given that doctest is designed to make sure your *documentation* is correct, that sounds like a really lousy idea ;-) but it works well for unit-testing too: write a test program that exercises relevant parts of your module, and use doctest to make sure *that* program works as expected. in my experience (having tried pyunit, several homebrewn frameworks, including ports of the original smalltalk framework, greg's unittest, and doctest), using doctest on test scripts beats all other approaches. less code, less work, easier to debug the tests. ymmv, as usual. Cheers /F From aahz at panix.com Thu May 31 19:37:54 2001 From: aahz at panix.com (Aahz Maruch) Date: 31 May 2001 16:37:54 -0700 Subject: Iteration index References: <9f63lo$rb0$1@zeus.polsl.gliwice.pl> <3B169FEC.7AACB50E@yahoo.com> Message-ID: <9f6kki$c48$1@panix6.panix.com> In article <3B169FEC.7AACB50E at yahoo.com>, Paul Winkler wrote: > >I guess you could do it without the variable like this: > >!! WARNING -- this only works if you use a list instead of a tuple >AND you know that the list contains no duplicate items!! > >s = ['a', 'b', 'ala', 'a'] >for el in s: > print s.index(el), el It's also extremely inefficient for large lists, because that's an O(N^2) algorithm -- it has to scan the list to get the index. -- --- Aahz <*> (Copyright 2001 by aahz at pobox.com) Androgynous poly kinky vanilla queer het Pythonista http://www.rahul.net/aahz/ Hugs and backrubs -- I break Rule 6 "Characters exist to suffer, you know. An author needs a little sadism in her makeup." --Brenda Clough From ransen_spam_me_not at nemo.it Mon May 14 12:24:57 2001 From: ransen_spam_me_not at nemo.it (Owen F. Ransen) Date: Mon, 14 May 2001 16:24:57 GMT Subject: FileExists() in Python? References: <3afeb5b7.1138522@news.newsguy.com> <9dmglm01ehn@news2.newsguy.com> Message-ID: <3b006801.695304@news.newsguy.com> On Sun, 13 May 2001 19:37:00 +0200, "Alex Martelli" wrote: >"Owen F. Ransen" wrote in message >news:3afeb5b7.1138522 at news.newsguy.com... >> What is the best style for writing a platform >> independent FileExists function? Using exceptions? > >How do you want your FileExists to differ from the >existing os.path.exists function? Ooops...that looks like the function I am looking for. -- Owen F. Ransen http://www.ransen.com/ Home of Gliftic & Repligator Image Generators From whisper at oz.nospamnet Sat May 12 17:54:29 2001 From: whisper at oz.nospamnet (David LeBlanc) Date: 12 May 2001 21:54:29 GMT Subject: doxygen for Python? References: <9db3qt$mm7$1@newsreaderm1.core.theplanet.net> <3AF962B7.21AF9361@alcyone.com> Message-ID: <9dkbel$qvj$1@216.39.170.247> In article <3AF962B7.21AF9361 at alcyone.com>, max at alcyone.com says... > Franz GEIGER wrote: > > > Does anyone know of a tool for Python like the awesome doxygen, which > > is for > > source doc'ing Java and C++ sources? > > I use HappyDoc. > > http://happydoc.sourceforge.net/ > > There is also autoduck, which seems to be part of PythonWin, and with some digging can be found in source form on the web. Dave LeBlanc From syver at NOSPAMcyberwatcher.com Tue May 29 17:44:53 2001 From: syver at NOSPAMcyberwatcher.com (Syver Enstad) Date: Tue, 29 May 2001 23:44:53 +0200 Subject: HTTP 1.1 client in Python. References: <9f0nvg$qgc$1@troll.powertech.no> <3b13fed8$1_5@news5.uncensored-news.com> Message-ID: <9f47r7$r7h$1@troll.powertech.no> Thanks very much Doug. I this solution looks a bit more general. "Doug Fort" wrote in message news:3b13fed8$1_5 at news5.uncensored-news.com... > Here's how I did it. > > while 1: > response = self._client.getresponse() > if response.status != 100: > break > # 2000-12-30 djf -- drop bogus 100 response > # by kludging httplib > self._client._HTTPConnection__state = httplib._CS_REQ_SENT > self._client._HTTPConnection__response = None > > I submitted this as bug #227361 on SourceForge. From aleaxit at yahoo.com Mon May 7 04:55:45 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 7 May 2001 10:55:45 +0200 Subject: Choosing a programming language as a competitive tool References: <9d3t3901nlq@news1.newsguy.com> <9d55e1$qel$1@slb1.atl.mindspring.net> <7iitjdren1.fsf@enark.csis.hku.hk> Message-ID: <9d5nug045j@news2.newsguy.com> "Isaac To Kar Keung" wrote in message news:7iitjdren1.fsf at enark.csis.hku.hk... ... > Right, vector really has its mathematical meaning. If you can understand > that vectors are not meant to be just 2D or 3D vector, you can understand > why vector means an array. But of course, I don't quite understand how a > mathematical vector can be "resized". Presumably by projecting it onto a space of lower dimensionality, or embedding it into a space of higher dimensionality. E.g., say that originally you know that a vector is (2, 4) -- in 2 dimensions, of course, as it has 2 components. Now, you learn that the 2-D space where that original vector lie is the plane Z=0 in 3-D space. Ok, so, to perform further operations using that vector in 3-D space, you "resize" it to (2, 4, 0). Of course, in maths, you don't "change" an entity -- entities are pretty much unchangeable there; rather, you define an injective function which gives you the new entities corresponding to the previous ones. But in programming (excepting most FP:-) it's quite normal to deal with "mutable entities", so I would hope that _vectors_ in particular being mutable would be no more of a problem than other kinds of entities being mutable. > Why don't just call it an array, I don't really know. Perhaps its because > the name comes from STL targeting C++, and for C++ arrays already means > something else. For Python too -- see standard module array, which defines _homogeneous_ "vectors". > But so what? Every language has its own terms. Who else use "tuple" and SQL was the first widespread programming language using the term "tuple" in this way, I believe -- but it's really a widespread word and concept in computer science and math, used in such languages as Haskell, Linda in all its variants, ML, ... > "dictionary" as used in Python? I'm not aware of any programming language predating Python that calls its mappings "dictionaries" -- however, I don't believe that "dictionary" was used to describe different data structures in any widespread pre-existing language, either. I believe Microsoft's "Scripting.Dictionary" is relatively recent ('94?), and it's close enough to a Python dictionary in functionality and approach that one might wonder about common roots... were those not obviously evident in the English language meaning:-). > Why call it a "field" or "method"? What is Rather widespread terms, these... I suspect they come from Simula 67 and Smalltalk respectively, but am not sure. > a "variable"? Ditto, and in this case the root is quite clear -- Fortran (later called Fortran I), 1954. Fortran stood for FORmula TRANslator, and its "variables" were meant to be what you would use for what were originally variables (in the normal mathematical sense of the word) in the formula you were "translating" (transcribing, transliterating, ...). > You really have to get used to it anyway. Sure, but that doesn't mean there aren't nomenclature choices that are more or less appropriate -- by making the "getting used" easier, and reminding one of just the right underlying concepts, or vice versa. Much will depend on a person's cultural background, of course -- e.g., calling a dictionary "a hash" may be OK if the average user is familiar with hash-tables and gets reminded of various characteristics (O(1) access, no intrinsic order), but it may make a hash of things when talking to somebody who thinks a hash is "#" and is reasonably perplex about that character having nothing to do with the case:-). I opine that most of Python's lexical choices are just fine, "list" being the only one to which I raise mild objections... Alex From scarblac at pino.selwerd.nl Tue May 1 13:37:48 2001 From: scarblac at pino.selwerd.nl (Remco Gerlich) Date: 1 May 2001 17:37:48 GMT Subject: function to check whether a variable already exists? References: Message-ID: Graham Guttocks wrote in comp.lang.python: > Can anyone tell me how to wrap the following in a function as to > avoid typing this try, except sequence for every variable whose > existence I want to check? > > For example, > > try: > if NEWSRC:pass > except NameError: > NEWSRC = os.path.expanduser("~/.newsrc") > > It seems tricky, because you can't just pass a function NEWSRC because > if it doesn't first exist NameError will immediately be raised. I don't think it can be done, in general, without invoking a load of black magic. And it looks like a weird construct - *why* do you need this?! Surely you have control over where your variables are initialized? And is that a global? Can't you at least set it to None at the top of the program and test for that? If the variable is in some module, you can test for hasattr(module,"NEWSRC"). Or store globals like this in some dictionary, and use dict.has_key("NEWSRC"). -- Remco Gerlich From ruediger.maehl at dzsh.de Thu May 3 07:24:18 2001 From: ruediger.maehl at dzsh.de (Ruediger Maehl) Date: Thu, 3 May 2001 13:24:18 +0200 Subject: mxDateTime: does strptime not exist? References: Message-ID: Thanks a lot! R?diger From Philippe.Bocquillon at trasys.be Thu May 17 04:21:36 2001 From: Philippe.Bocquillon at trasys.be (Bocquillon Philippe) Date: Thu, 17 May 2001 10:21:36 +0200 Subject: Winsock error Message-ID: Hello, I am using the httplib.py module on Windows NT from the Zope environment. I get the following error when trying to get files from URLs "on the other side" of the company proxy server: "Error Value: (10060, 'winsock error')" Note: Error 10060 means Connection timed out error. Is there any other lib than httplib.py that takes proxy servers into account and that I could use to replace httplib.py? Is it possible to tell Zope you are running it behind a proxy server? Many thanks in advance, Philippe Bocquillon Trasys 7 av. Ariane 1200 Bruxelles T?l : 32 - 2 - 773 88 14 Fax : 32 - 2 - 773 79 40 From ctavares at develop.com Tue May 22 02:44:22 2001 From: ctavares at develop.com (Chris Tavares) Date: Tue, 22 May 2001 06:44:22 GMT Subject: O(n^2) is bad - can it be fixed? References: <3B09FBF9.8691EBFE@accessone.com> Message-ID: "Helen Dawson" wrote in message news:3B09FBF9.8691EBFE at accessone.com... > The following script tests appending to a list and to a string. > [... snipped offending code ...] > > So, why can't string do that? > > When we could only go string = string + " " then fixing this problem > was probably impossible, but with += it seems like it should be quite > possible - maybe even easy! > You're forgetting one thing - strings are IMMUTABLE. Doing s += " " doesn't add anything to s, it creates a NEW string who's contents just happens to be a space concatenated to the old s. And please don't ask for mutable strings - immutability is the right answer here (just look at all the complexities that the C++ std lib people went through to make std::basic_string mutable, and it still doesn't work correctly in many cases.) > Right now if I am producing a text file a character at a time I have > to do it to a list and then use string.join() to convert at the end. > That works, but seems clunky. > This is one correct solution. Strings are not buffers, and should not be used as such. Another solution would be to use something that IS expected to act like a buffer - the cStringIO module. The interface is a little different - this one works like a file: import cStringIO def AppendTest2( io ): for i in range(100): for j in range(2000): io.write( " " ) print i This is visible faster on my box (Win2k, Python 2.1) than either the list or string versions shown above. -- Chris Tavares From pj at sgi.com Mon May 28 21:38:46 2001 From: pj at sgi.com (Paul Jackson) Date: 29 May 2001 01:38:46 GMT Subject: mod_python and MoinMoin ?? References: <9eugqg$bvu20$1@fido.engr.sgi.com> <3b12f61e.40576455@news.telus.net> Message-ID: <9euuj6$c085b$1@fido.engr.sgi.com> |> Please also check out thttpd. Ok - thanks for the pointer. Surprisingly enough, at this point in my web servers life, switching to other server software actually is an option. I will consider it. -- I won't rest till it's the best ... Manager, Linux System Software Paul Jackson 1.650.933.1373 From nomad*** at ***freemail.absa.co.za Wed May 9 04:53:47 2001 From: nomad*** at ***freemail.absa.co.za (nomad) Date: Wed, 09 May 2001 10:53:47 +0200 Subject: Module Browsing? References: Message-ID: On Tue, 08 May 2001 22:30:16 GMT, "Nick Perkins" wrote: >I often find myself doing the following: > >1) hear about a cool module >2) install it, or (more often), > find that i already have it (but didn't know about it) >3) >>>import cool >4) >>>dir(cool) >5) >>>cool.something( >(..see if IDLE shows an informative tool tip) >5) if it does, it's a function, i try it out >6) if not, it's a value, i see what it is >7) if the value is an object, i dir() it.... > >What I want to know is: > >Is there an easier way to 'browse' a module from the command line? >I would like to able to (quickly) see module values and their type, >module functions and their parameters and doc strings, etc. > >Is there a way to get a list of modules that i have installed? >If i wrote a script to do this, how would it work? >e.g.( walk sys.path, list all .py files, etc..) > >( but i'm sure it has been done, i just don't understand > how modules work well enough ) > >...here's another thing: >can i import a module that is not on the sys.path >by giving it's full path? > I don't know about browing from the command line, but the 'path browser' option in IDLE, or the 'browser' option in Pythonwin both work nicely for me, although the Pythonwin browser will probably give you more satisfaction. (I'm guessing by your usinging outlook express that you use Python on a Win32 platform?) Both of the above options will also show you which modules are installed on you file system. HTH From loewis at informatik.hu-berlin.de Wed May 16 13:14:59 2001 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 16 May 2001 19:14:59 +0200 Subject: speedup up dictionary access References: Message-ID: Roy Smith writes: > One of the big time consumers in an application I'm writing is a cache > lookup in the inner loop of the program. Right now, it looks something > like this: > > if (self.cache.has_key (name) and self.cache[name]) or self.check (name): > do stuff > > check() returns 0 or 1 based on the value of name, and also inserts this > value into the cache. > > I know that my cache hit ratio is going to be very high (almost 100%). > Would I do better writing it as: I'd write if self.cache.get(name) or self.check(name): do stuff .get returns None if name is not in the dict, or the value otherwise. Regards, Martin From sdm7g at Virginia.EDU Sat May 12 18:12:44 2001 From: sdm7g at Virginia.EDU (Steven D. Majewski) Date: Sat, 12 May 2001 18:12:44 -0400 (EDT) Subject: Asteroids... [was: Unix [was: do...until wisdom needed...] In-Reply-To: <9dk66p$u26$1@slb0.atl.mindspring.net> Message-ID: As we range ever further off topic from Python, Andrew Dalke wrote: > Steven D. Majewski asked: > > I think the problem is: If planet-devastating asteroid collisions > >are rare events, how would asteroid resistance evolve? > > There's a sf book I read about 9 years ago. I forgot the name > but it was about a civilization on a planet where astrophysical > catastrophies were frequent - once every thousand years. The > life on the planet evolved to become very compatible with each > other, so that new "orgnanisms" could arise as they were really > aggregates of different species working in a non-Darwinian fashion. > > As a result, the civilization was based more on biology than > physics, because it was easier to breed new useful species than > to build technology from minerals. Have you read Vernor Vinge's "A Deepness in the Sky" ? There are humans in it, but half of the story line is about a race that's evolved on an unstable star system, where everything hibernates through a 30 year winter so deep that the atmosphere condenses and rains out of the sky. (It's the prequel to his earlier book "A Fire Upon the Deep") -- Steve Majewski From phd at phd.fep.ru Thu May 17 10:23:36 2001 From: phd at phd.fep.ru (Oleg Broytmann) Date: Thu, 17 May 2001 18:23:36 +0400 (MSD) Subject: Simple yet powerful template library In-Reply-To: Message-ID: On Thu, 17 May 2001, Michele Beltrame wrote: > I need a simple but powerful template library (such as what HTML::Template > is for Perl), with some good usage examples. Suggestions? Zope DTML (DocumentTemplates)? Oleg. ---- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From tim.one at home.com Sun May 6 22:24:21 2001 From: tim.one at home.com (Tim Peters) Date: Sun, 6 May 2001 22:24:21 -0400 Subject: COM and currency conversion In-Reply-To: <3AF5F3A9.90607@ActiveState.com> Message-ID: [John] > I've run into another issue with using ADO/SQL Server with Python. > It has to do with how money fields come across in Python. Python > converts the money field into a 2 value tuple. Anyone know the way > to get a meaningful dollar about back out? Here are some examples > of dollar amounts and their representation in Python: $1,234,567.01 > == (2, -539231788) $1,000,000.00 == (2, 1410065408) $2,000,000.00 > == (4, -1474836480) Based on what Mark said later, here's a function that should do the trick: TWO32 = 2L ** 32 def tuple_to_100x_pennies((hi, lo)): if lo < 0: lo += TWO32 return (long(hi) << 32) + lo Using your examples, print map(tuple_to_100x_pennies, ((2, -539231788), (2, 1410065408), (4, -1474836480))) prints [12345670100L, 10000000000L, 20000000000L] Divide by 100 to get pennies; by 10000 to get dollars. [Mark Hammond] > This is a little sad. Python has no support at all for these. The > basic problem is that there is no Python type to convert it to. > It you dig on MSDN, you will find this represents a fixed decimal > point number. > In the interests of being correct when Tim may be watching it > is exactly: Way to cover your ass, Mark! I would have torn you to shreds . > "A currency number stored as an 8-byte, two's complement > integer, scaled by 10,000 to give a fixed-point number with 15 > digits to the left of the decimal point and 4 digits to the right. > This representation provides a range of 922337203685477.5807 to > -922337203685477.5808" > > I have discussed this with Tim, and he agrees in general that > conversion to float would be evil, and there is no better type. He > has suggested I rip out his "FixedPoint.py" > (ftp://ftp.python.org/pub/python/contrib-09-Dec-1999/DataStructures/ > FixedPoint.py) > and use that. I still do -- this particular format is just a special case of FixedPoint with 4 digits after the decimal point, so should be easy to supply via exposing a subclass of FixedPoint. > However, there is also implication that Python will grow something > like this as a core datatype, so I don't want to lock everyone > into FixedPoint when something more natural may be just around > the corner. One person said they were going to look into this and was never heard from again. I'd like to implement IBM's proposed standard for decimal arithmetic (http://www2.hursley.ibm.com/decimal/) but have no time for it (and never thought I would ). Marc-Andre Lemburg started down some sort of related path, but appeared to get distracted by wrapping the entire GNU multiprecision library instead (which is way cool for its own sake, but doesn't actually supply the decimal currency type he was looking for at the start). So don't hold your breath -- or at least don't hold mine . From thomas at xs4all.net Fri May 4 05:37:32 2001 From: thomas at xs4all.net (Thomas Wouters) Date: Fri, 4 May 2001 11:37:32 +0200 Subject: Design-by-Committee In-Reply-To: <9crbvk01cuu@news2.newsguy.com>; from aleaxit@yahoo.com on Thu, May 03, 2001 at 12:30:11PM +0200 References: <3aef2dbc.28491648@news.telus.net> <3af054a9.17396995@news.telus.net> <3dg0enpn5s.fsf@crystal.cnri.reston.va.us> <9crbvk01cuu@news2.newsguy.com> Message-ID: <20010504113732.W16486@xs4all.nl> On Thu, May 03, 2001 at 12:30:11PM +0200, Alex Martelli wrote: > Most changes since 1.5.2 seem to me to be quite good ones, > making Python even better for its job[s], at modest (if any) > cost in simplicity -- I can think of only one blatant > counter-example, and a few cases where I am not going to > be able to decide whether I like or dislike the change > until and unless I get more practical experience using > it, teaching it, etc. The net effect seems OK to me... Being one of the people who changed stuff since 1.5.2, I'm probably biased, but I have to agree with this. I'm worried too, but not about the same things as AMK. For instance iterators, augmented assignment, import-as, distutils-setup, healing the type/class dichotomy all are good things to me. The only thing I really dislike in the changes since 1.5.2 is oddly enough unicode support, which AMK in a later posting declared the most important feature since 1.5.2 . I doubt I will ever need to use unicode, so *to me*, it's a waste of resources. -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! From mertz at gnosis.cx Tue May 1 14:42:20 2001 From: mertz at gnosis.cx (Dr. David Mertz) Date: Tue, 01 May 2001 14:42:20 -0400 Subject: PEP 234: Iterators (fwd) Message-ID: - There is still discussion about whether for x in dict: ... should assign x the successive keys, values, or items of the dictionary. ...for sequences, "if x in y" iterates over y comparing the iterated values to x. If we adopt both of the above proposals, this will also hold for dictionaries. This proposal seems to introduce rather *contradictory* semantics for lists and dictionaries. I would argue against it on those grounds. For example, the construct: for x in collection: print collection[x] will fail if 'collection' is a list (or sequence, in general). But in the proposal this succeeds for dictionaries. The converse construct: for x in collection: print collection.index(x) will fail for dictionaries, but because of the missing '.index()' method. But conceptually, dictionaries could easily have an '.index()' method to implement the following code: def index(dct, val): for k,v in dct.items(): if v==val: return k Lists are easily thought of as dictionaries whose keys are an initial subsequence of the non-negative integers. The 'in' keyword applied to lists asks a question about a lists "values" not its "keys"... for both 'if' and 'for'. From jkraska1 at san.rr.com Wed May 23 20:37:06 2001 From: jkraska1 at san.rr.com (Courageous) Date: Thu, 24 May 2001 00:37:06 GMT Subject: How can we obtain a repository system similar to Vaults of Parnassus? References: <2e8c61fb.0105230635.166f421c@posting.google.com> Message-ID: >Is there any open source or commercial product with similar or the same >features? http://www.sourceforge.net will allow you to host most any truly open source project you like on their computers, with the restriction that you can't change your mind (can't "unopen" the source). C// From jmarshal at mathworks.com Tue May 1 16:55:13 2001 From: jmarshal at mathworks.com (Joshua Marshall) Date: 1 May 2001 20:55:13 GMT Subject: Tabs and spaces (style) References: Message-ID: <9cn7rh$mkh$1@news.mathworks.com> Marcin 'Qrczak' Kowalczyk wrote: > Tue, 01 May 2001 19:27:03 +0000, Kenneth Loafman pisze: >> I'm just the opposite... why would anyone use tabs? All a tab does is >> screw up the alignment for anyone that has a different tab size set and >> makes it very difficult to print, etc. > Why would anyone use a different tab size than 8? > (Except programming in Clean which stupidly defines the tab size to 4?) Although there are those who think a tab-width of 8 is "correct", it seems a width of 4 is more flexible. Also, some word-processors define tab-width to be something like one half inch. Tabs are whatever you use them as; don't expect them to be portable. From mwh21 at cam.ac.uk Tue May 1 13:34:45 2001 From: mwh21 at cam.ac.uk (Michael Hudson) Date: 01 May 2001 18:34:45 +0100 Subject: Using Python on a Mac References: <20010501124631.18325.00001968@ng-fj1.aol.com> Message-ID: twl4274979 at aol.com (TwL4274979) writes: > Can I use Python on a Mac Yes. Cheers, M. -- I saw `cout' being shifted "Hello world" times to the left and stopped right there. -- Steve Gonedes From transpicio at yahoo.com.au Mon May 7 04:38:32 2001 From: transpicio at yahoo.com.au (John Flynn) Date: Mon, 7 May 2001 18:38:32 +1000 Subject: xrange question References: Message-ID: "Paul Prescod" wrote in message news:mailman.989221390.12767.python-list at python.org... [...] > I wouldn't usually think twice to spend a third of a second getting > ready to process a million lines of text or a million patient records or > whatever... I guess that puts it into perspective ;-) > Here's a program you can use to get a feeling for the behavior of range > and xrange: [...] Thanks for that. I'll give it a run. From sill at optonline.net Mon May 14 11:50:59 2001 From: sill at optonline.net (Rainy) Date: Mon, 14 May 2001 15:50:59 GMT Subject: problem writing to file References: <3AFFF263.A9923451@netz.klinik.uni-mainz.de> Message-ID: On Mon, 14 May 2001 16:57:39 +0200, Christian Maus wrote: > Hi, > > I have a strange problem when I try to write to a file. I created a list > named named new_ldapentries. I create a file object in write mode: > testfile = open('/tmp/testfile', 'w') > then I go through the elements of my list and try to write them to the > file: > for i in range(len(new_ldapentries)): > testfile.write(new_ldapentries[i]) > testfile.close() > When I run the script I get the following error: > Exception in Tkinter callback > Traceback (innermost last): > File "/usr/lib/python1.5/lib-tk/Tkinter.py", line 764, in __call__ > return apply(self.func, args) > File "python/emailmanager.py", line 333, in writeLDAPentry > testfile.write(new_ldapentries[line]) > TypeError: read-only buffer, instance > > The strange thing is when I replace the new_ldapentries[line] with any > String like 'hello' everything works fine. > > Has anybody a idea where I made a mistake? > Thanks in advance, christian Did you do from os import *? os has a function called open.. Morale: do not use import *. -- I'll give you anything, everything if you want things - Syd From charlie at begeistert.org Thu May 31 09:48:34 2001 From: charlie at begeistert.org (Charlie Clark) Date: Thu, 31 May 2001 15:48:34 +0200 Subject: Writing an end of string character in Python Message-ID: I have a slight bug with the python module for writing attributes in BeOS. String values need to be terminated with a "\O" in order for them to be correctly read by some applications but I read in PP2E that "\0" does not terminate the string in Python. Is there anyway I can force it to? Thanx it advance. Charlie From rusha at data-tech.com Mon May 28 09:14:47 2001 From: rusha at data-tech.com (Rush) Date: 28 May 2001 06:14:47 -0700 Subject: Capturing COM object events Message-ID: <9c4a6c75.0105280514.7c1a4c59@posting.google.com> Newbie here, I'm using PythonWin to instantiate an instance of an ActiveX DLL. It works GREAT!! Very simple and straightforward. I can create an instance of the object, set its Properties, and invoke its Methods. Now, this COM object also returns events, and I have no clue as to how to code Python to capture these events. I've scoured the NET but cannot find sample code that illustrates capturing events returned by an ActiveX control. Can somebody help me out? Here's how I instantiate the control:: from Tkinter import * import win32com.client myJR = win32com.client.Dispatch("FaxJr.FaxJr.1") myFF = win32com.client.Dispatch("FaxFinder.FaxFinder.1") myDD = win32com.client.Dispatch("DeviceDesc.DeviceDesc.1") All of the above works great! Thanks.. From dima at xenon.spb.ru Thu May 10 03:47:15 2001 From: dima at xenon.spb.ru (Dmitry Rozmanov) Date: Thu, 10 May 2001 11:47:15 +0400 Subject: Python and LabVIEW Message-ID: <9ddh23$73r$1@shadow.xenon.spb.ru> Has anyone connected Python and LabVIEW? I would like to use Python as a scripting language with LabVIEW for the task that may be done simplier in Python. I have some ideas about connecting via TCP/IP. But may be someone has already done this? Regards, ---Dmitry. From nhodgson at bigpond.net.au Wed May 9 20:56:02 2001 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Thu, 10 May 2001 00:56:02 GMT Subject: How can I work with pointers? References: <3glK6.64836$r3.12810072@typhoon.nyroc.rr.com> Message-ID: Darrell: > My problem is how to recover the struct pointer cds. > How do I follow the pointer? > The struct module doesn't seem to provide this. The calldll module available from http://www.nightmare.com/software.html can be used for this sort of thing although it will lead to some low level coding. Another approach would to write a small extension in C to handle this and return the string being sent within the message. The struct module is designed to be safe and allowing pointer following could lead to crashes. My personal belief is that there should be low level pointer access for both data and calls in the standard Python library. WM_COPYDATA support would also be a reasonable addition to the Win32 extension library - just looked and doesn't appear to be there currently. Neil From machin_john_888 at hotmail.com Mon May 21 00:07:13 2001 From: machin_john_888 at hotmail.com (John Machin) Date: 20 May 2001 21:07:13 -0700 Subject: round probleme under python 2.0 References: <3B0694EE.FD76D2DF@noos.fr> <9e680b$l4a$1@panix3.panix.com> <3B06AECF.107984A0@noos.fr> Message-ID: <92ae279c.0105202007.5b36487e@posting.google.com> William Famy wrote in message news:<3B06AECF.107984A0 at noos.fr>... > Ok and thanks for the solution but i can't print in a file 0.20000000000000001 > instead of 0.2 !! > I will try FixedPoint.py. I am ready to test your decimal.py but i am a python > newbe and i do not a very fluent english. so tell me how help you for the > decimal.py and i will do my best. > Yeah well i do not a very fluent french either, but here goes: Si vous ne voulez pas "0.20000000000000001", essayez ceci: print "%.4f" % foo Ce donne "0.2000" ... A propos de votre ".sig", est-ce possible que "FW" == "Fils de Warlord"? > > -- > \\\|/// > \\ - - // > ( @ @ ) > +-----------------------oOOo-(_)-oOOo--------------------+ > |Famy William 36 avenue des barattes 74000 Annecy France| > |email:william.famy at noos.fr | > | william.famy at mail-enseignant.com | > +--------------------------------Oooo--------------------+ > oooO ( ) > ( ) ) / > \ ( (_/ > \_) From jim.vickroy at noaa.gov Wed May 9 09:42:38 2001 From: jim.vickroy at noaa.gov (jim.vickroy) Date: Wed, 09 May 2001 07:42:38 -0600 Subject: Problem with popen with win98 (python 2.0) References: Message-ID: <3AF9494E.DD1D1B47@noaa.gov> Hello Mike, import os os.popen ('notepad') # works on my win2k system I did note that "notepad" is in a "system32" folder. Do either of the commands, you tried, work from a DOS command line? Mike Callahan wrote: > What am I doing wrong? > > import os > >>> os.popen('notepad') > Traceback (innermost last): > File "", line 1, in ? > WindowsError: [Errno 2] The system cannot find the file specified > >>> os.popen('c:\\windows\\notepad.exe') > Traceback (innermost last): > File "", line 1, in ? > WindowsError: [Errno 2] The system cannot find the file specified > >>> > > Thanks for any help, > > Mike From mwh at python.net Mon May 7 03:36:28 2001 From: mwh at python.net (Michael Hudson) Date: 07 May 2001 08:36:28 +0100 Subject: xrange question References: Message-ID: "John Flynn" writes: > Again, this is not a big deal - but since Python removes just about > every other need to explicitly specify data types, it would also > make sense (to me at this stage) to implicitly convert integral > types based on what's being done with them. (But perhaps this is > more trouble than it's worth?) I think eroding the differences between Python ints and longs is a long term goal. It's not entirely simple, though. Cheers, M. -- Darned confusing, unless you have that magic ingredient coffee, of which I can pay you Tuesday for a couple pounds of extra-special grind today. -- John Mitchell, 11 Jan 1999 From grumble at usa.net Tue May 29 01:08:47 2001 From: grumble at usa.net (jcm) Date: 29 May 2001 05:08:47 GMT Subject: parse-time optimizations References: <9ervav$qu9$1@news.mathworks.com> Message-ID: <9evasv$9u8$1@news.mathworks.com> Remco Gerlich wrote: > jcm wrote in comp.lang.python: >> It'd be Nice if the Python parser (or bytecode-compiler or whatever >> non-runtime thing is most appropriate) would translate the addition of >> two string literals into a single string. Or maybe it does this >> already? I haven't tried. > Python does *no* magic optimizations. It's completely WYSIWYG in that > respect. You tell it to add the two strings, Python does that, at runtime > like every other addition. Yea, I guess it's just wishful thinking. Something about string-literal juxtaposition doesn't sit right with me. I guess I'm used to optimizing compilers, which would transform "a" + "b" into "ab" (and 1 + 2 into 3, etc). Having a different syntax specifically for string-literal concatenation seems odd (it seems less odd in C only because strings are so klunky). This set of optimizations, which are very easy to identify at parse-time, would be nice to see added to Python. There are some things to pay attention to (like arithmetic overflow), but still fairly simple to implement, as far as optimizations go. And yes, I have. Yeah I know: "so go implement it yourself in Python too". Wishful thinking is about as far as I expect I'll get. If I ever stuck my hands in the Python parser, there are a couple of things I'd want to change (like not generating the full concrete syntax tree--parser module be damned!). I should stop now or I might actually convince myself to go look at the Python source. From new_name at mit.edu Fri May 18 15:23:05 2001 From: new_name at mit.edu (Alex) Date: 18 May 2001 15:23:05 -0400 Subject: command parsing and interpreter interaction References: Message-ID: > I want to build a set of commands in the same way that the Cmd module > allows one to do, but I want all lines entered at the prompt that are > not defined by my interpreter to be handled by python as if it had > been entered at the python interactive interpreter prompt. Check out the pdb module, which does this. Alex. From dkuhlman at rexx.com Sun May 20 15:10:28 2001 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 20 May 2001 19:10:28 -0000 Subject: client side scripting References: <3B0587D3.8388C737@student.kuleuven.ac.be> <9e43db01kah@enews1.newsguy.com> Message-ID: <990385835.895842@rexx.com> Alex Martelli wrote: > [snip] > > It's possible with reasonably recent versions of IE *IF* the client > machine has Python installed (with ActivePython or win32all) as > ActiveScript. AFAIK, Netscape, differently from Microsoft, doesn't > support multiple alternative clientside script languages -- Javascript > is all you get (I hope this isn't so any more in Mozilla, but I think > it still is). In any case, ARE you willing to rely on the end-user > having properly installed whatever add-ons or plug-ins they need? > > >> scripting). Users should be able to use their own webbrowsers and > > Oh, they can, IF those web-browser have a halfway-decent architecture > (including "of course" the ability to specify multiple scripting languages). > > It's a pity that, so far, generally-maligned Microsoft seems to be the > only one to have designed their browser halfway-decently in this sense. > Looking to the future (and this is something that makes me bite my tongue each time I have something bad to say about Microsoft), the MS .Net strategy for Web services and all supports multiple languages. My understanding is that in that strategy, if it goes somewhere, you will be able to write .Net apps and services in a variety of languages in addition to C#. Python will be one of those languages and Python will even be usable within Visual Studio 7.0, due to the work by ActiveState. That is in sharp contrast to the "one language only" attitude in the Java camp. This is relevant for server-side stuff of course. [snip] > > Alex > > > -- Dave Kuhlman dkuhlman at rexx.com From sav at ulmen.mv.ru Tue May 15 16:02:11 2001 From: sav at ulmen.mv.ru (Alexander Semenov) Date: Wed, 16 May 2001 00:02:11 +0400 Subject: Python COM and distribution issues References: Message-ID: <9ds2mt$17dd$1@news1.simtel.ru> > The original GUID scheme included the 6-byte MAC ID of the generating > machine, a 4-byte date and time, and an 6-byte random number. Assuming JFYI, recently I've seen cheap NIC with tool for changing its MAC. WBR Alexander Semenov From toby.angell at usa.net Mon May 21 13:24:46 2001 From: toby.angell at usa.net (Toby Angell) Date: 21 May 2001 10:24:46 -0700 Subject: Netscape crashes M2Crypto/ZServerSSL Message-ID: <83ef2d59.0105210924.64cf3e4b@posting.google.com> I'm having a problem with ZServerSSL from M2Crypto 0.6 Snap 4. >From IE it works great. From Netscape 4.7 and Netscape 6, Zope crashes with: File "/usr/local/mindy/z2s.py", line 817, in ? File "/usr/local/Zope-2.3.0-src-2/ZServer/medusa/asyncore.py", line 146, in loop poll_fun (timeout, map) File "/usr/local/Zope-2.3.0-src-2/ZServer/medusa/asyncore.py", line 70, in poll try: r,w,e = select.select (r,w,e, timeout) select.error: (9, 'Bad file descriptor') Zope/Zope 2.3.0 (source release, python 1.5.2, linux2) ZServerSSL/0.06 It happens mostly when going from an https to an http page. I can download Snap 5 if you think it will help this, although I'm on Zope 2.3.0. I'm on Redhat 7.0, it has OpenSSL 0.9.5a instead of 0.9.6. Upgrading it looked to be quite a pain because of RPM dependencies. Could that be the problem? Thanks, Toby From sholden at holdenweb.com Thu May 10 01:25:54 2001 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 10 May 2001 01:25:54 -0400 Subject: Reading & Writing Python OK, Now I need to Speak It References: <3AFA1ABA.C1911B82@home.com> Message-ID: "Don O'Donnell" wrote in message news:3AFA1ABA.C1911B82 at home.com... > Hi All, > > I have a question I've never seen mentioned on this newsgroup. A google > search turned up nothing. > > How do you say (pronounce) "__init__", for example. Having to say > "double-underscore-double-underscore-init-double-underscore-double-underscor e" > gets awfully tedious after a while. > Not a phonetic, but my suggestion would be "magic init". regards Steve From cce at clarkevans.com Thu May 31 00:43:08 2001 From: cce at clarkevans.com (Clark C . Evans) Date: Wed, 30 May 2001 23:43:08 -0500 Subject: Against PEP 240 In-Reply-To: <9f155606df@enews2.newsguy.com>; from aleaxit@yahoo.com on Tue, May 29, 2001 at 11:44:38PM +0200 References: <9f155606df@enews2.newsguy.com> Message-ID: <20010530234308.B1199@doublegemini.com> On Tue, May 29, 2001 at 11:44:38PM +0200, Alex Martelli wrote: | | > If we're forced to use 'f' or 'F' I don't mind. We can | > do double precision in the same way ie use 'D'. | | 7.35F, or whatever, can specify floating-point with its little | tasteful decoration. Just leave plain 7.35 to the masses who | don't WANT it to actually mean 7.3499999999999996, or whatever, | but 7.35 exactly... +1 Please implement this change. I can't tell you how many times I'd had to fix financial reports that used doubles. On Wed, May 30, 2001 at 11:57:04AM +0400, Oleg Broytmann wrote: | On Tue, 29 May 2001, Alex Martelli wrote: | > OK, but gmpy doesn't come with Python and no doubt never will | > (as it relies on GMP, which is LGPL'd at least). | | There is no problem including gmpy into standard | distribution. There is already mpz that relies on the | same GMP. No problem. You cannot distribute GPL'd binaries | without source code. There is no problem distributing | Python source code that relies on GPL'd code. | >From what I understand, this is only true if the author explicitly states so; the cygwin distribution has this property beacuse the copyright owner has made an exception. Best, Clark From modman at altavista.com Tue May 29 15:12:04 2001 From: modman at altavista.com (Modman) Date: 29 May 2001 12:12:04 -0700 Subject: Location of the Pythin bin file? Message-ID: Hello, I am trying to setup a python script to execute automaticly, however I can not find the location of my Python bin file. I use Mandrake 8.0 I have looked in /usr/local/bin, /bin, /sbin, and any other place I could think of. Is it there and I just wrote the command out incorectly at the top of my source? please help TIA J. From andrew_dot_henshaw_at_earthling_dot_net Mon May 14 21:36:39 2001 From: andrew_dot_henshaw_at_earthling_dot_net (Andrew Henshaw) Date: Mon, 14 May 2001 21:36:39 -0400 Subject: Python and Ruby , object oriented questions References: <3AFDFC02.29C58D14@earthlink.net> <87y9s0fvyo.fsf@litterbox.meowing.net> Message-ID: "A Meowbot" wrote in message news:87y9s0fvyo.fsf at litterbox.meowing.net... > > I am looking for reasons to avoid learning Ruby. > > Okay, this kind of thing has bugged me for the longest time. What is > the source of this meme, that there can be One and Only One Real True > Language, and all others must be banished to the hinterlands? I'll answer your next though first. > > I've found all along that the more languages I play with, the easier > it becomes to play with yet more of them. Do others find it works out > differently for them, that carrying more than one language around just > makes a mental mishmash of the others? I'm sure that it works well for others. In my case, if the language is expressive and powerful enough, I prefer to immerse myself in that one language for a while. That way, my retention is better. As to the first question, I believe that not everything one learns while becoming an expert in a language will pay off for future work in other languages. There is a significant amount of time and effort involved in discovering the nuances of Python's standard library, for example. If I continue to program in Python, then that effort pays off everytime I do a project. If I never touch Python again, then perhaps that effort would have been better used elsewhere. Well, then why wouldn't I continue to use Python? I believe this is the crux of the issue - if a language doesn't attract a significant following, it can lose momentum and two things **might** happen: 1) new tools and libraries centered around the language aren't developed by the programming community 2) the opportunity to use the language on customer-driven projects begins to disappear If I had to use Perl on a new project, right now - I'd be at least 20% less productive - not just because of Python's advantages, but because of the choices I've made in learning as much as I can about Python. But if Python didn't have such favorable buzz around it, I might find it hard to convince companies that I contract with to let me use it. This would mean less profit for me, or I could even completely miss out on the contract. In other words, protectiveness for a favorite language may be a way of self-conservation of one's own effort and energy. From thomas at xs4all.net Wed May 30 10:20:46 2001 From: thomas at xs4all.net (Thomas Wouters) Date: Wed, 30 May 2001 16:20:46 +0200 Subject: parse-time optimizations In-Reply-To: <9f2u23$dsp$1@news.mathworks.com>; from grumble@usa.net on Wed, May 30, 2001 at 01:54:11PM +0000 References: <9f2u23$dsp$1@news.mathworks.com> Message-ID: <20010530162046.B690@xs4all.nl> On Wed, May 30, 2001 at 01:54:11PM +0000, jcm wrote: > This is an unambiguous situation. Don't just think of the program > text--these transformations would be done on the parse-tree. In > Python '+' is left-associative. We're talking about simple, > well-understood optimizations. The reason I am advocating these in > particular is because they can be done without heavyweight semantic > analysis. Read back in this thread. Michael Hudson already reported that his bytecodehacks packages already has a module to do constant-folding optimizations. He also says it isn't worth much :) Have you tried it out, yet ? -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! From Gerald.Osmann at sap.com Fri May 4 07:36:54 2001 From: Gerald.Osmann at sap.com (Gerald Osmann) Date: Fri, 4 May 2001 13:36:54 +0200 Subject: Bug or not ? References: <3AF28F44.EF9318FE@nd.edu> Message-ID: <9cu48l$3u4$1@news1.wdf.sap-ag.de> "Changsen Xu" wrote in message news:3AF28F44.EF9318FE at nd.edu... > Hi all, > > I met a problem, not sure it's bug or not, same > for Python version through1.5.2 to 2.0: > > >>> x= [ [0,0], [0,0] ] > >>> x > [[0, 0], [0, 0]] > >>> x[0][0] = 1 > >>> x > [[1, 0], [0, 0]] ## This is exactly what I expect, same as > C/C++ > > > >>> x = [ [0]*2 ] * 2 > >>> x > [[0, 0], [0, 0]] > >>> x[0][0] =1 > >>> x > [[1, 0], [1, 0]] ## This result differ from above > > > Anybody can give me an explanation ? Thanks in advance. > I was driven crazy to check my how-can-it-be-wrong > tiny program dozens of times until I finally found the above > difference! > > Hi Changsen, in the second example the two sublists refer to the same object. For list L L*2 is different vom [L]*2. Look into the data structure chapter of "Learning Python" for just this problem. Best wishes, Gerald From boltong at europem01.nt.com Wed May 30 10:57:41 2001 From: boltong at europem01.nt.com (Bolton, Gawain [ADC:4808:EXCH]) Date: Wed, 30 May 2001 16:57:41 +0200 Subject: No swap function in Python? Message-ID: <3B150A65.5D4986FC@europem01.nt.com> There doesn't seem to be a "swap" function in Python two swap the values of two variables. I was wondering why this is. Unfortunately writing a generic swap function swap(a,b) with no return type in Python doesn't work with immutable arguments (like strings) of course. Which made me think that a swap could be done like this: (a,b) = (b,a) But I'm not completely convinced doing this is safe. In tests I've done it works, but I'm not sure whether this works in all cases with all types... Finally, if the behaviour is guaranteed, is this an efficient way of doing a swap? Thanx in advance, Gawain -- ------------------------------------------------------------------------------- Gawain Bolton | E-mail: boltong at nortelnetworks.com Section 4808 | Internal mail stop: BA54 UMTS Development | Nortel Networks | Voice: ESN 579-3763 +33 1.39.44.37.63 Guyancourt, France | FAX: ESN 579-3009 +33 1.39.44.30.09 ------------------------------------------------------------------------------- From dan at www.cgsoftware.com Tue May 1 23:05:19 2001 From: dan at www.cgsoftware.com (Daniel Berlin) Date: Tue, 1 May 2001 23:05:19 -0400 (EDT) Subject: Surprising (for me) benchmark results... In-Reply-To: Message-ID: On Wed, 2 May 2001, Rainer Deyke wrote: > "Daniel Berlin" wrote in message > news:mailman.988762570.8591.python-list at python.org... > > Actually, the sort is probably not the bottleneck. > > As the file gets larger, the bottleneck becomes disk time, not sort time. > > Disk access is O(N); Out of where did you pull this? It's non-determinstic, practically, because it depends on way too many factors (where the disk is, your memory subsystem, your processor usage, your DMA capabilities, etc). It also depends where on the disk the file is, if it's entirely contiguous, etc. > sorting is typically O(N log N). > Therefore as the > number of entries in the file size increases, the time taken by the sort > becomes more significant and the time taken by disk access becomes less > significant. Bullshit. Please back this up with facts, not hand waving. Disk transfers are 7-16 meg per second, sustained, plus seek time. (Obviously the internal disk transfer rate is *much* higher) When the total program time is 600-1400ms, and you are including the disk i/o time, it's fair to assume a large portion of it could be disk I/O time. > This is assuming that the file fits into memory (as was the > case here). You still have to read it in. What really needs to be done is to time the *sort*, not the entire program. > > > -- > Rainer Deyke (root at rainerdeyke.com) > Shareware computer games - http://rainerdeyke.com > "In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor > > > -- > http://mail.python.org/mailman/listinfo/python-list > From meyer at diku.dk Thu May 24 11:06:30 2001 From: meyer at diku.dk (Jonas Meyer Rasmussen) Date: Thu, 24 May 2001 17:06:30 +0200 Subject: Making a dict from two lists/tuples In-Reply-To: References: <87u22bw197.fsf@womble.dur.ac.uk> <9eiljf$jg1$1@eising.k-net.dk> Message-ID: On Thu, 24 May 2001, Duncan Booth wrote: > "Jonas Meyer Rasmussen" wrote in > news:9eiljf$jg1$1 at eising.k-net.dk: > > > for key,value in keys,values > > dict[key] = value > > Bzzzt! Wrong answer. Why is it wrong?? it worked fine on my machine(2.1, win32). And what is zip supposed to do, i'm trying it here on another machine, which gives me a NameError(1.6 Linux) Jonas Meyer Rasmussen meyer at diku.dk From hannah at schlund.de Wed May 16 09:49:45 2001 From: hannah at schlund.de (Hannah Schroeter) Date: 16 May 2001 15:49:45 +0200 Subject: Why aren't we all speaking LISP now? References: <3B00AF25.8A903DA@my.signature> <2ph1gt82hc2jpn7s98l3ruhbv651ja4pag@4ax.com> <3B021985.DBBB7E7F@my.signature> Message-ID: <9du0hp$b3j$1@c3po.schlund.de> [Crossposting + F'up to c.l.lisp, as it isn't really Python related any more.] Hello! In article <3B021985.DBBB7E7F at my.signature>, Greg Ewing wrote: >Courageous wrote: >> One variant of loop has you doing: >> (loop while (condition) >> ) >I also seem to remember using a (while condition ...) >construct. I can't remember whether it was built-in >or whether I made my own using a macro. Either way, >it was much easier to use than (do ...), even if I >had to spell things out more verbosely inside it. Common Lisp has a very flexible loop macro, allowing expressions such as (loop while (some-condition) do (some-action)) (loop for i from 1 to 10 do (something-with-i)) (loop for i being the hash-keys of (some-hash-table) do ... finally ...) etc. See the HyperSpec for a zillion of more possibilities :-) Kind regards, Hannah. From sagracoi at larural.es Sun May 13 15:15:39 2001 From: sagracoi at larural.es (José María y Sagrario) Date: Sun, 13 May 2001 21:15:39 +0200 Subject: getting the output from os.system() Message-ID: <9dmlv6$8q3$1@talia.mad.ttd.net> Hi everyone, When I execute something using os.system(), I cant get the output that is produces into a variable, it just goes to the standar output, the screen. What I am actually trying to do is making a python script to execute another one, and getting the output that it produces... Exactly, the error mesages that python generates when something goes wrong... Lets see: ------ #! /usr/bin/python import os os.system("im_a_python_script.py") ---------- Well, if there is an error while evaluating "im_a_python_script.py" I would like to make it into a variable so the first program can handle the error, thats the whole point. Thanks a lot. James Gonzalez From m.hadfield at niwa.cri.nz Wed May 9 01:01:22 2001 From: m.hadfield at niwa.cri.nz (Mark Hadfield) Date: Wed, 9 May 2001 05:01:22 +0000 (UTC) Subject: which distro and Gui ? References: <3af8c42b.30001795@news.vif.com> Message-ID: <001801c0d845$13732470$d938a8c0@Hadfield> From: "Yvon Boulianne" > > Hello everybody, i'm starting to use python but before investing some > times in it i like to have a suggestion. > which version of python is the more (standard), i know there is > activestate version, beopen, and twistedmatrix and maybe more ? which > one better to run (on win95) ? I suggest either "standard Python" http://www.python.org/ftp/python/2.1/Python-2.1.exe plus the Windows extensions http://downloads.activestate.com/ActivePython/windows/win32all/win32all-139. exe OR ActivePython 2.1 http://aspn.activestate.com/ASPN/Downloads/ActivePython/index/ There's not much to distinguish between them at present. > also for the Gui, which one is the better one ? (faster execution, run > on many platforms, stable etc..) i know there is Tkinter and wxpython > and some other. I like WxPython: http://wxpython.org/ Tkinter's pretty cool too. Take a look at both (but try the WxPython demo first, and you'll be blown away.) > my purpose is to be able to learn OO and do some application (mainly > networking apps) so any suggestion will be verry cool :) Then you couldn't do better than Python > p.s. is it possible that some version of python are not compatible > with Tkinter (i think i read that somewhere, if i remember well it was > the active state who have a problem with it) ? The latest ActivePython includes Tkinter. And, above all, don't agonize about distributions, just get into it! --- Mark Hadfield m.hadfield at niwa.cri.nz http://katipo.niwa.cri.nz/~hadfield National Institute for Water and Atmospheric Research -- Posted from clam.niwa.cri.nz [202.36.29.1] via Mailgate.ORG Server - http://www.Mailgate.ORG From fredrik at pythonware.com Sat May 12 12:14:49 2001 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 May 2001 16:14:49 GMT Subject: Need suggestion to speed up code... References: Message-ID: Brad Bollenbach wrote: > Is there a reason that noone mentioned the tuple function? > > >>> x = (1, "hey", "how's it goin, dude?") > >>> y = tuple(x) > >>> y[1] > 'hey' > > That should do what you require. doesn't quite work if the data is in a string, though: >>> x = """(1, "hey", "how's it goin, dude?")""" >>> y = tuple(x) >>> y ('(', '1', ',', ' ', '"', 'h', 'e', 'y', '"', ',', ' ', '"', 'h', 'o', 'w', "'", 's', ' ', 'i', 't', ' ', 'g', 'o', 'i', 'n', ',', ' ', 'd', 'u', 'd', 'e', '?', '"', ')') Cheers /F From atodd at spam.free.email.com Wed May 2 20:07:29 2001 From: atodd at spam.free.email.com (Andy Todd) Date: Thu, 03 May 2001 00:07:29 GMT Subject: Inheritance Confusion References: <9cq56e$i6r$1@nntp9.atl.mindspring.net> Message-ID: "Andrew Dalke" wrote in <9cq56e$i6r$1 at nntp9.atl.mindspring.net>: > >>class B(A): >> def _init__(self): > ^^^ This should be __init__ > >Does any know if any the Python linting tools check for suspect >names like this? > > Andrew > dalke at acm.org Andrew, thanks for pointing out my (now) glaring error. I will consider myself suitably syntactically challenged and promise to check before I post next time! Regards, Andy -- Content free posts a speciality From cwebster at nevada.edu Sun May 27 18:01:45 2001 From: cwebster at nevada.edu (Corran Webster) Date: Sun, 27 May 2001 15:01:45 -0700 Subject: Powersets of a list? References: <9els3j$2kap$1@ID-11957.news.dfncis.de> <270520011028579603%cwebster@nevada.edu> <3b1148b5.183134130@news.okstate.edu> Message-ID: <270520011501451699%cwebster@nevada.edu> In article <3b1148b5.183134130 at news.okstate.edu>, David C. Url^H^Hllrich wrote: [snip] > [timings of various power sets snipped] > > Thanks (I _hate_ to install new software, even > new versions of Python - now I can put off 2.x > a little longer...) > > Two questions: Why did you omit the bitshifting ones > from the range(18) test, Impatience, basically. For MacPython, the numbers are: range(18): bitshifting1 233.366666667 bitshifting2 263.916666667 and were significantly higher when run from within the IDE. I killed the program when I was first testing it after about 3 minutes, since I expected it to take at most a minute. The values for Unix Python on OS X were much more reasonable: range(18): bitshifting1 39.32 bitshifting2 70.92 I'm not sure why it took so long in MacPython. I wonder if there's something weird with bitwise operations in MacPython? > and who's this David Urlich > guy? His code looks vaguely familiar but I can't place > the name. Urg. My abject apologies! Corran From lac at cd.chalmers.se Sun May 27 11:08:43 2001 From: lac at cd.chalmers.se (Laura Creighton) Date: Sun, 27 May 2001 17:08:43 +0200 (MET DST) Subject: Change dbhash values in place using next() loop? Message-ID: <200105271508.RAA13174@boris.cd.chalmers.se> You've already got a dictionary {'a':'b', 'a1':'b1', 'a2':'b2'} right? So just use apply with that dictionary as the third argument, no? Or am I totally misunderstanding something? Laura From jmarshal at mathworks.com Tue May 15 10:28:37 2001 From: jmarshal at mathworks.com (Joshua Marshall) Date: 15 May 2001 14:28:37 GMT Subject: Whrandom References: <9dp9md$bc0$1@newsreaderg1.core.theplanet.net> <9dpvgb$lfd$1@news8.svr.pol.co.uk> <3B01351C.E64BA7F3@stud.cs.uit.no> Message-ID: <9dreel$fap$1@news.mathworks.com> Ole Martin Bjorndalen wrote: > Duncan Smith wrote: >> >> I would do the following. >> >> >>> import whrandom >> >>> dict = {} >> >>> while len(dict.keys()) != 5: >> ... dict[whrandom.randint(1, 1000)] = None >> ... >> >>> dict.keys() >> [247, 844, 578, 892, 244] > Neat. A slightly faster version is: >>>> import random >>>> dict = {} >>>> while len(dict) != 5: > ... dict[random.randint(1, 1001)] = None > ... >>>> dict.keys() > [535, 859, 786, 17, 147] > (I've also replaced the depreciated whrandom with > random and bumped up randint() arguments as suggested > by others in this thread.) Note that random.randint is also deprecated in favor of randrange. In this case randint(1, 1000) was correct, and corresponds to randrange(1, 1001). The deprecation of randint was a good idea, in my opinion. I'd often forget the randint range includes its second argument. From aleaxit at yahoo.com Wed May 23 12:19:31 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 23 May 2001 18:19:31 +0200 Subject: Operator overloading for part of an object References: <2C79DE2B4809FFC1.69C331B478CA7679.C3649C0080E44646@lp.airnews.net> Message-ID: <9egnu2080o@enews1.newsguy.com> "David Humphrey" wrote in message news:2C79DE2B4809FFC1.69C331B478CA7679.C3649C0080E44646 at lp.airnews.net... ... > OK, I understand why it behaves this way, but I don't see how to preserve > c.name while updating c.data with the computed value. I konw I need to > overload the '=' operator, but don't see facilities in python to do that. There is no way in Python to change the meaning of '=', which is not an operator, but rather a separator (in various contexts including plain assignment). When you use plain assignment to re-bind a local or global variable (as opposed to re-binding an attribute or item or slice of some object), the re-binding will happen -- period. The object previously bound to that variable name is NEVER affected in any way (save that it disappears if/when there are no references to it any more, by garbage-collection). There is no way you can change this. c = a + b will ALWAYS rebind variable c, NEVER affect whatever c was previously bound to. So, you need to use different syntax sugar for the functionality you desire. There is an abundance of forms -- for example, if all the references in question were attributes on some supervising object rather than local or global variables, __setattr__ of the supervising object would give you the chance to do the dark deed you desire. But you can't use plain assignment's syntax-sugar on variables for other purposes than plain assignment - i.e., to bind or re-bind those variables. Alex From runyaga at thisbox.com Wed May 30 23:12:09 2001 From: runyaga at thisbox.com (alan runyan) Date: Thu, 31 May 2001 03:12:09 GMT Subject: Newbie: ZODB or mysql? References: Message-ID: > I am not sure which is a better choice for an application I am writing. > I have much more experisnce with relation databases than object databases. > > The application is attemping to submit charges to VISA and then at the end > of the day do a settlement on successful ones. do you need the data to be accessible to nonPython applications? > I am going to need the ability to search by date on these records for > settlement and reporting. I am not sure that ZODB is designed for that task. > I know it is an object database... but I am stuck in the mindset of needing > rows. not at all, you can traverse the objects and pick n' choose on attributes (dates) of objects stored in ZODB. I dont think ZCatalog is easily used outside of the ZOPE framework, i.e. the Standalone distrbution of ZODB. > Does anyone have an idea which would be more suitable for the task? if your data lends itself to being heirarchical and lots of your data objects need persistenance (not only a few attributes, but the entire object -- especially complex objects) then ZODB sounds like you get alot of functionality for free. you didnt provide enough info, but if you are dealing with financial data - which is usually tabular and need to be accessed by a variety of applications then RDBMS is definetly the way to go. cheers, ~runyaga From jason-dated-990212323.9f935b at mastaler.com Thu May 10 14:58:42 2001 From: jason-dated-990212323.9f935b at mastaler.com (Jason R. Mastaler) Date: 10 May 2001 12:58:42 -0600 Subject: os.popen hangs mutt In-Reply-To: <9deliv$n1u$1@nntp6.u.washington.edu> (Donn Cave's message of "10 May 2001 18:10:39 GMT") References: <9deliv$n1u$1@nntp6.u.washington.edu> Message-ID: Donn Cave writes: > My guess is that it will be blocking in wait(), called from > pclose(). If its qmail-inject child hasn't exited, that would even > be correct. popen2() doesn't tie close() to wait(). Another oddity is that this os.popen problem only happens on certain BSDs (FreeBSD and OpenBSD, but not IRIX, BSD/OS or Linux for example). > I imagine something must have fallen out of your examples, but the > first omits what I think would be an important write('\n'). It's not an omission actually. The write('\n') is not necessary in the os.popen example. -- (TMDA - http://tmda.sourceforge.net) (Python-based SPAM reduction system) From bsass at freenet.edmonton.ab.ca Wed May 23 19:22:56 2001 From: bsass at freenet.edmonton.ab.ca (Bruce Sass) Date: Wed, 23 May 2001 17:22:56 -0600 (MDT) Subject: Why isn't Python king of the hill? In-Reply-To: Message-ID: "Samuel A. Falvo II" wrote: <...> > Also, consider that Java and Python are designed to serve two different > markets. Python is a host scripting language, while Java is a platform > independent binary representation Like .pyc|o's, ya. What is a "host scripting language"? More generally (and directed towards those who would say, "Python is a scripting language"), why is Python even called a "scripting" language? Python is way too verbose to be a scripting language. i.e., Runs `farther' from the OS than a scripting language should. Compare: cat name.pt{1a,2a,3b} > name vs. ??? well, I'd probably do os.system("the-sh-script-line"); and a file with that, an import, and a #! line in it would be silly, IMO. - Bruce From grante at visi.com Wed May 9 22:47:15 2001 From: grante at visi.com (Grant Edwards) Date: Thu, 10 May 2001 02:47:15 GMT Subject: Unix [was: do...until wisdom needed...] References: <010601c0d8f0$945a2420$d938a8c0@Hadfield> Message-ID: On Thu, 10 May 2001 01:28:59 +0000 (UTC), Mark Hadfield wrote: >> A free and popular Unix would have only had to be compatible with >> itself. DOS, which was the competition at the time, not Windoze 3.1, >> was certainly no more compatible with human beings than Unix was. > >Well, DOS did have a "help" command. Not that I remember. IIRC, I was running PC-DOS 3.01 (3.10?) when I gave up and switched to Coherent (a v7 clone from Mark Williams Company). That was on an 8MHz 286 w/ 512K of RAM, and I had to port a few things like RCS and screen (after writing a pty driver), but it was a wonderful system compared to the horrible kludge that was DOS. I even got the MGR windowing system running on my Hercules Mono graphics board. Linux pretty much killed Coherent when it showed up with working TCP/IP and X and MWC never caught up. -- Grant Edwards grante Yow! I'd like TRAINED at SEALS and a CONVERTIBLE on visi.com my doorstep by NOON!! From transpicio at yahoo.com.au Wed May 9 02:30:07 2001 From: transpicio at yahoo.com.au (John Flynn) Date: Wed, 9 May 2001 16:30:07 +1000 Subject: do...until wisdom needed... References: <9be84s0q12@news1.newsguy.com> <9bfjoc0cjh@news2.newsguy.com> <9bfq560noo@news2.newsguy.com> <87n19fvdzo.fsf_-_@elbereth.ccraig.org> <9biukr$lu8$1@nntp9.atl.mindspring.net> <9cqpq9$dvm$1@nntp9.atl.mindspring.net> <9d53ku$o9j$1@slb6.atl.mindspring.net> <9d5rc6$l5q$1@nntp9.atl.mindspring.net> <9d61os0i05@news2.newsguy.com> <9d92fo01thk@news2.newsguy.com> Message-ID: "Alex Martelli" wrote: > I'm not sure there ARE real-world lessons to be > learned from [Lisp's unpopularity etc], but, I still wonder... Maybe technology trends are chaotic systems, as unpredicatable as the stock market or the weather? Not a very satisfying answer though, is it? (Nah, I don't buy it either). I too would like to know what drives language choices. I do this stuff mostly for fun, so I can't contribute much insight into the social, economic, political (or even technical) forces behind trends in language choice. I do find it psychologically interesting though ... Having only just started learning Common Lisp (and Python too for that matter), my first impression is: wow! Why is this thing languishing in obscurity? On complexity: Yes, Common Lisp is large and certainly complicated - relative to Scheme - which I guess is the context in which you meant it. (I'd wager that you know more about CL than I do, so perhaps you have better reasons for disliking the complexity). The only other comparably complex language I know is C++ and, relative to C++, CL seems quite simple. My early impression is that the core of Common Lisp is very clean and very potent. The complexity flowers out from a simple central motif, like a rich mandala. I love it. By contrast, Scheme feels - to me - exactly what its provenance suggests: a nice, simple algorithmic teaching language - somewhat uncomfortably spartan in furnishings. (Python, I know, has similar provenance, but I find Python _very_ comfortable. Nice and simple, yet it does not feel at all 'bare' in the way that Scheme does. Far from it). It's all hypothetical to me, but if I were starting a commercial project tomorrow, had unlimited freedom in my choice of tools, was in charge of hiring and firing, and wanted to have something up and running this year, I believe I _would_ use Common Lisp (or at least try to). Actually, I'd consider Python first, but Lisp would seem to be ideal for situations in which the cost of Python's interpreter is too high, especially if the speed-sensitive components were too large (and tedious) to write in C. What alternatives would I have for my 'startup'? Well ... again bearing in mind that I'm no expert, and that it's all hypothetical, and that all the circumstances are ideal, and that I only know a few languages, my personal choices would be: C++? Great for super-efficient 'finalisation' code, but far too painful to design in. Haskell, Miranda, other FP? Theoretically interesting, but I don't know 'em well enough to do much of practical value. Eiffel? I like it a lot, but for the same reason that you - Alex - wouldn't use Lisp/Scheme, I wouldn't use Eiffel these days. That is to say, I have no idea why I wouldn't use it ;-) [*] Java? Clean, shiny, new, comfortable, consistent, uniform, elegant, easily recyclable, component oriented evolution of C++ without the knotty outgrowths and sharp edges? No... when I hear this crap I want to shout: Plastic! Formica! Polystyrene! Rubber! Linoleum! Call me an aesthete, but after several attempts to like Java, I still can't - and have given up trying. I find it hard to imagine that any hacker would use it by choice. (Actually I'm no aesthete. Give me the gristle and fangs, warts and hair of C++ any day). Strangely enough, in spite of its alleged similarities to Java, C# does NOT strike me the same way. Not at all. I find it simple, elegant, quite powerful, and fun to use. (Surprisingly efficient too!) So, I dunno. Either I don't think the way most programmers do (and I certainly don't claim to be any better than most), or there are compelling (technical and/or other) reasons to use the more popular alternatives that I just can't see. Since nobody else seems to know these reasons, I might as well hazard a few guesses: * Safety in numbers: The desire to back a winner, and ride the bandwagon. Failure of many 'AI' companies in the '80s contributing to bad press for Lisp, coinciding with the rise of C++. Emergence of hot (huh!) new languages during the web era. There must have been a point where, psychologically - in the minds of investors and developers, Lisp became a thing of the past, associated with a few widely publicised failures, while Java et al were being touted as 'the future'. Novelty and hype generates its own momentum (as we're all sick to death of finding out). * Moving with the times: Maybe Lisp (as an environment, not as a language) didn't adapt to the industry but remained (perhaps a little disdainfully?) aloof. Eg. AFAIK, there's still no high quality open source bindings that would allow CL to take advantage of good stuff like GTK+ or Qt, though I can't see any technical reason why it couldn't be done, and done well. (Not that I'm anywhere near skilled enough to volunteer, mind you!). I think Lisp would also have been a great choice for filling the client-side web niche that Java (and now Curl) tried to fill. It would also be an excellent language for server side web programming (and, as far as I can tell, offers facilities for doing everything that XML tries to do - and more). But, for whatever reason, it didn't happen that way. The energy flowed elsewhere ... [*] Alex: since you can't quite finger your personal reasons for not wanting to use Lisp/Scheme - even though they were strong early influences, I wonder whether, rather than being permanent, early influences (like old clothes and old loves) become something that one "grows out of". Maybe there's a "moving on" factor at work. Eiffel was the first language I _really_ liked. The thought of using it today leaves me cold, but I still think it's an excellent language, and I can't see good technical reasons for my attitude. The fact that you chose a _completely_ unfamiliar language - Modula-2 - tends to support the hypothesis... From gardner at sounddomain.com Tue May 22 18:09:51 2001 From: gardner at sounddomain.com (Jonathan Gardner) Date: Tue, 22 May 2001 15:09:51 -0700 Subject: Python vs. Perl Message-ID: <01052215095105.01539@avatar.cardomain.com> I am interested in Python, not because it looks cool - but precisely the opposite. My first impressions of Python were that it was going to be something like MatLab (horrors!) or BASIC (GASP!) So I thought to myself, "If this looks so bad from the outside, there must be something good on the inside. Otherwise, no one would be using it." I've examined superficially all the constructs in Python. It looks very well designed. It looks robust and easy to read. (It looks painfully easy to read for a perl guy! Aren't computer languages supposed to be more like hieroglyphics and ASCII art?) I like the object-oriented aspects of it. I like the documentation aspects. I like the simplicity of everything - the way almost anyone can understand it. (Is this a feature or a bug?) It doesn't seem good enough to convince me to get knee deep, however. I am going to miss a lot of the C features that I live and die by (while (a = getc())), and I am going to miss the "do this or die unless that" aspect of Perl. What does Python have that makes it so great? Why should I spend time to become intimate with it? I am looking for comments from people that actually have used Perl or C/C++ extensively, and I am looking for comments that go beyond the FAQ. -- Jonathan Gardner Software Engineer, CarDomain Networks (425) 820-2244 x123 gardner at sounddomain.com From DanielK at jBASE.com Tue May 1 19:13:30 2001 From: DanielK at jBASE.com (Daniel Klein) Date: Tue, 1 May 2001 16:13:30 -0700 Subject: Formatting numbers Message-ID: This is almost embarrasing to have to ask this but I can't seem to find this information. Given an integer, 12345, how to format this to 123.45 ? Thanks, Dan Klein From aleaxit at yahoo.com Fri May 4 12:22:09 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 4 May 2001 18:22:09 +0200 Subject: Design-by-Committee References: <3aef2dbc.28491648@news.telus.net> <3af054a9.17396995@news.telus.net> <3dg0enpn5s.fsf@crystal.cnri.reston.va.us> <9crbvk01cuu@news2.newsguy.com> <9cu2o201ih6@news2.newsguy.com> Message-ID: <9cukvl0l63@news1.newsguy.com> "Michael Hudson" wrote in message news:m34rv16u4t.fsf at atrus.jesus.cam.ac.uk... ... > > > feature since 1.5.2 . I doubt I will ever need to use unicode, so > > > *to me*, it's a waste of resources. ... > > ISO-8859-1 does not suffice? Never need to drive a COM server or > > implement one? And I think XPCOM uses Unicode like COM (not sure). > > I'm not Thomas (obviously) but I can easily think of places you might > use Python where you don't need unicode. Scientific computing and > sysadmin-style duct tape are just two that spring to mind almost "sysadmin-style duct tape" on Windows systems is likely to include some COM calls and thus benefit from good-quality, centralized Unicode support. If XPCOM takes roots (as I hope it will), the same will happen cross-platform -- it's a very good thing that we have Unicode in place already against that eventuality. Scientific computing may easily need to exchange data files with other scientific-computing sites, and XML is emerging as a likely format for such exchanges in certain fields. Again, I'm quite happy we have the Unicode support needed for standard XML support -- in ONE centralized place in the language & core library. That you may not need to use Unicode _right now_ is quite likely. But I'm surprised at predictions that one likely "will never need to use Unicode", except perhaps if they come from somebody very close to retirement age:-). > immediately. I don't *think* Thomas was suggesting that adding > Unicode was a mistake. In any case, I'm seconding AMK's opinion about it having been an excellent strategic move:-). Alex From gerhard.nospam at bigfoot.de Tue May 1 18:47:35 2001 From: gerhard.nospam at bigfoot.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Wed, 02 May 2001 00:47:35 +0200 Subject: Is There a CGI Expert In the House?? Good Grief!! References: Message-ID: <3AEF3D07.CD8DF259@bigfoot.de> Ben Ocean wrote: > > Hi; > I have been trying DESPERATELY to get the answer to this question. I was > under the impression that Python was an ideal language for CGI scripting. > Now, would SOMEONE PLEASE answer this question: > > Scenario: > My client, BladeChevy.com, frames around Kelley Blue Book (KBB.com). The > visitor fills out a form on KBB.com's page and submits it. The info is sent > back to BladeChevy.com to a page I specify (in the cgi-bin directory). The > data is sent back via the *data buffer* > > Question: > What the &*()$)*_% is a data buffer and how the &*(&*% do I get the data > out of it? I don't know about a "data buffer". The data is sent via HTTP POST. The Python cgi module transparently manages the CGI methods GET and POST. Just use the cgi module with cgi.FieldStorage() and friends, there is really no magic to it. If in trouble, use this simple script to see what's going on: #!/usr/bin/env python import cgi cgi.test() Gerhard -- Sorry for the fake email, please use the real one below to reply. contact: g e r h a r d @ b i g f o o t . d e web: http://highqualdev.com From akuchlin at mems-exchange.org Sat May 12 12:47:56 2001 From: akuchlin at mems-exchange.org (Andrew Kuchling) Date: 12 May 2001 12:47:56 -0400 Subject: Why aren't we all speaking LISP now? References: <989424635.15477.0.nnrp-12.c1c3e154@news.demon.co.uk> Message-ID: <3dzocibjk3.fsf@ludwig.cnri.reston.va.us> grante at visi.com (Grant Edwards) writes: > Why do people think Python is so Lisp-like? I just don't get I'm reading Paul Graham's book _ANSI Common Lisp_ right now (*excellent* book, BTW, at least so far), and can think of a few parallels: * Uncluttered syntax, depending on your definition of uncluttered. * Treatment of references and assignment is quite similar. * High-level data structures included, so you don't have to reinvent them. * A large standard library, though Lisp's seems to focus more on data structures than on OS or network interfaces. >From newsgroup discussion, it seems fairly clear that while Lisp is sometimes used to teach functional programming, it's not really a functional language because real Lisp programs aren't usually purely functional; instead, it's a multiparadigm language where you can program in your choice of imperative style, OO style, or functional style. You have similar freedom in Python; the other day I was looking at some code written by another developer here, and it was essentially functional style. I don't think tail recursion, or even frequent use of recursion, is necessarily a hallmark of Lisp; you could do everything in iterative style if you preferred. (Here's hoping they get the QuickTime video of that panel on the Web soon.) --amk From dsh8290 at rit.edu Fri May 25 12:10:03 2001 From: dsh8290 at rit.edu (D-Man) Date: Fri, 25 May 2001 12:10:03 -0400 Subject: pointer address In-Reply-To: <9elspf$h6a$1@info1.fnal.gov>; from ng@fnmail.com on Fri, May 25, 2001 at 10:12:24AM -0500 References: <9elspf$h6a$1@info1.fnal.gov> Message-ID: <20010525121003.A341@harmony.cs.rit.edu> On Fri, May 25, 2001 at 10:12:24AM -0500, Enrico Ng wrote: | I want to pass by reference a variable to a function. | how to I pass the address of a variable. | & doesnt work. & works just fine -- except it doesn't mean "address of" as in C. ;-) In Python functions, classes and modules are all first-class objects. What this means is that a function is an object just like the string "Hello World". Passing a reference to the function is exactly like passing a reference to a string. Here is an example: def func( arg1 , arg2 ) : print "func was called with arguments '%s' and '%s'" % ( arg1 , arg2 ) def call_a_function( function ) : # the argument 'function' should be a reference to a function # (or any other callable) object. It will be called with 2 # arguments function( "Hello World" , "In Python simple things are still simple!" ) # here is the "main", where we pass a reference to a function to # another function call_a_function( func ) In Python _all_ lines are executable statements. Even "def" and "class". The "def" statement creates a new name in the current scope and binds it to the function object that is defined by the body of the function. Thus functions are quite orthogonal because they behave as all other objects. This is in contrast to C, C++, and Java where function/method definitions are special -- the compiler creates a space in memory for the resulting code to lie, but the function "object" exists only during the compilation phase. A tag is put in the "object file" (.o or .class) to the function so the linker knows where to jump to when the function is called, but at runtime the functions (and classes) aren't actual objects. In Java you can do introspection on classes, etc, but it isn't pretty -- nowhere near as simple and concise and understandable as Python's introspection. HTH, -D From pknews at kirks.net Mon May 21 11:38:09 2001 From: pknews at kirks.net (Patrick Kirk) Date: Mon, 21 May 2001 16:38:09 +0100 Subject: How hard can this be? References: <9ebb9d$p43$1@newsg2.svr.pol.co.uk> Message-ID: <9ebcp1$j55$1@newsg3.svr.pol.co.uk> Thanks all. I've subscribed to the python tutor mailing list so I hope whatever my next posting to this ng will be, it will be a bit meatier than these very basic questions! From aleaxit at yahoo.com Tue May 29 18:03:01 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 30 May 2001 00:03:01 +0200 Subject: Against PEP 240 References: <9f03m401qcu@enews2.newsguy.com> <9f0ha4029t6@enews2.newsguy.com> Message-ID: <9f16bs07h2@enews2.newsguy.com> "Robin Becker" wrote in message news:WrYUdKAGE$E7EwEI at jessikat.fsnet.co.uk... ... > >> My main objection is that this is likely to bust just about any > >> extension that uses floating point. > > If I have made a really fast vector multiplier for floats I might use > myfastmult((1.0,2.0),(3.0,4.0)); if I was being really speed conscious I > would always assume that this function was being used with floats. It > would go wrong if I used the same call. I now have to either force the > conversion internally (which slows things down) or locate and change > every call of the function. Exactly! The extension isn't disturbed one bit: when it calls its PyFloat_AsDouble's, exactly like today, there may be some conversion (nb->nb_float(op) is called, where nb is the PyNumberMethods* obtained by op->ob_type->tp_as_number) if needed (if it uses PyFloat_AS_DOUBLE instead, it's arguably broken already...:-). The *Python sources* using the extension will be a bit slowed down until and unless you find the time to run a script on them all to change your \d+\.\d+'s by appending an F to them. Is that your definition of "bust"...? > >Can't you do interval arithmetic today, btw? Quite apart from > >the issue of what a literal 7.35 means? > ... > I can do interval type arithmetic with a class definition no problem. If > we're allowing new literals and the like I might want to have an > interval literal like (1,2)I :) And would that improve your quality of life noticeably when compared to the I(1,2) notation for the same thing that you can already use today...? Alex From gerrie at trispen.com Tue May 29 05:53:18 2001 From: gerrie at trispen.com (Gerrie Roos) Date: Tue, 29 May 2001 11:53:18 +0200 Subject: Check for existence? Message-ID: <3B13718D.557CDBE3@trispen.com> I'm very new to Python and got a very basic question: How do I check to see if a variable exists/is available in the current namespace? I need to do this since I'm writing a script that gets called from Zope and I'm not sure the vars I need are in the namespace...I might misunderstand the whole issue, though, in which case I'll seek assistance from the Zope list. I've been through 'Diving into Python', the lang and lib refs, FAQ etc... From aleaxit at yahoo.com Wed May 16 17:38:20 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 16 May 2001 23:38:20 +0200 Subject: modifying vars() dictionary? References: Message-ID: <9durvq03uu@enews1.newsguy.com> "Lance E Sloan" wrote in message news:mailman.990033564.4299.python-list at python.org... > > In the documentation, it says about vars(): > > The returned dictionary should not be modified: the effects on > the corresponding symbol table are undefined. > > Why are the effects undefined? Why doesn't it always work to set > a value for variable 'x' by assigning that value to the 'x' element > of the dictionary from vars()? Because the variables themselves may not be in a dictionary, and surely not in the artificial 'vars()'-created dictionary... if vars() must merge some locals and some globals to create it (when it's called from a function that has locals). Rebinding an entry in a dictionary only affects that dictionary, because Python always works that way -- no "side effects" on other items/references. But sometimes it may be most efficient for vars() to give you the actual dictionary (when there are no locals to be 'merged'...). So don't rely on rebiding items in vars() to NOT affect variables -- do an explicit copy if you need one. > I've noticed that sometimes it works and sometimes it doesn't. In my > small example it worked, but a colleague who asked me about this > couldn't get it to work in a larger program. I assume that I'm just > lucky mine worked and that his problem may have something to do with > the size of the symbol table or the kinds of objects in it. Probably an issue of where vars() was called from, but that depends on version-specific optimization issues. A future version may well do other optimizations... Alex From not.this at seebelow.org Thu May 3 01:03:40 2001 From: not.this at seebelow.org (Grant Griffin) Date: Thu, 03 May 2001 00:03:40 -0500 Subject: Ideas for a project? (a MSc project, sort of) References: Message-ID: <3AF0E6AC.1C05FE74@seebelow.org> eloy wrote: > > Dear friends, > > I have entered the world of Python about two months ago. I really > fell in love with the language inmediately (don't tell my girlfriend). > > I teach at the University of C?rdoba (Spain) and would like to > guide one of my students in a project related to Python. In Spain, after > three years (the equivalent of a MsC, I believe) our students must > develop a project to obtain the diplomma. The estimated duration is > around 4-6 months, sometimes part-time, sometimes full-time. Darn. Python's productivity is going to work against that . I started doing a web search engine, and after two weeks, spare-time, it's nearly done. (Of course, I still need to write the documentation, so I guess I'm only half done.) > > So, as I am new to the Python community, I would like to ask > if there is any idea about projects that could fit that description. Of > course the results would be available to everybody. Here's one I thought of earlier today. Python 1.5.2 was the standard for a long time, until somewhat recently (I forget exactly when.) Newever versions (1.6, 2.0, 2.1) have added several useful features, my personal favorites of which are "augmented assignment" (the "+=" operator and friends) and string methods (which were previously handled by the "string" module.) I wrote my search engine using these features, but, as I thought about it, I realized that it would be nice to change these things to the old-fashioned way, to be compatible with 1.5.2 (which is still widely used--for example, on my web site.) The features I mention can be automatically "translated" to/from 1.5.2 fairly easily using regular expressions. (For example, by itself the augmented assignment thing could probably be put together in an hour or so.) One could carry this a step further by creating some kind of generalized translation engine. Of course, translating certain other features would be harder (e.g. list comprehensions). But that's the sort of thing that makes for 4-6 month project (if you get really carried away .) Something like this would be not just an interesting project (for MsC types, at least ), it would also be useful to the community. Note that, ideally, the translations could be done in _both_ directions: the newer constructs, if available, are more efficient in some cases, so one would like to translate both old code into New Python and new code into Old Python. please-scratch-my-itch-for-me-ly y'rs, =g2 -- _____________________________________________________________________ Grant R. Griffin g2 at dspguru.com Publisher of dspGuru http://www.dspguru.com Iowegian International Corporation http://www.iowegian.com From b.e.n. at .r.e.h.a.m.e...c.o.m Thu May 17 02:19:48 2001 From: b.e.n. at .r.e.h.a.m.e...c.o.m (Ben) Date: Thu, 17 May 2001 16:19:48 +1000 Subject: Touching Files On Windows References: Message-ID: Thanks ... changing the access time of a file is exactly what I wanted to do ... I do apologise if my post was obfuscated. On Wed, 16 May 2001 17:57:49 +1000, Ben wrote: >Hi, > >Is there a way to touch files under windows using python? I can return >the values as a tuple ... but it is immutable > >Any suggestions greatly appreciated. > >Ben From tyler at tylereaves.com Sun May 13 21:28:59 2001 From: tyler at tylereaves.com (Tyler Eaves) Date: Mon, 14 May 2001 01:28:59 GMT Subject: Komodo (Short Rant) References: <3sGL6.742$Rp4.4139@newsfeed.slurp.net> Message-ID: On Sun, 13 May 2001 19:25:37 -0600, "bowman" wrote: >"Tyler Eaves" wrote in message >news:lafuftoegd12m0n2lmb6d60dmqnr9sltg0 at 4ax.com... >> They want me to pay $249 without even giving me a *HINT* of >> functionality?!?!?!?!?!!!!!! > >http://aspn.activestate.com/ASPN/Downloads/Komodo/KomodoBeta > >If you register for ASPN, which is free for non-commercial uses, the Komodo >beta may be downloaded, again for free. There is also on-line documentation, >screen shots, and so forth. What more did you want?!?!? > Perhaps I will be using it in a commercial environment where a beta release would not be the smartest thing to use? From pbrian at demon.net Wed May 9 12:14:54 2001 From: pbrian at demon.net (Paul Brian) Date: Wed, 9 May 2001 17:14:54 +0100 Subject: Why aren't we all speaking LISP now? References: Message-ID: <989424635.15477.0.nnrp-12.c1c3e154@news.demon.co.uk> I suspect I am taking this a bit more off topic.... I agree with what Laura wrote, (my most involving course (in the late 80's) was on History of Science! - a full course credit for 2 hours a week explains why I took it, but I loved it.) however an interesting question would be : What should be taught as Computer Science? When should it be taught? My university days seemed to be based around teach a little theory, supported by a low level language, then teach a bit more theory supported by a new language that supports those constructs (From Basic to Pascal to Fortran to C++, by way of SQL). >From the Paul Graham article recently I got the feeling that unless you were already using the "best" language (LISP), you could not understand what you were missing (The Blub paradox?). This seems to advocate that we should teach the "best" language first and the theory could follow on from there. so... If my ideal course was just teaching programming, when would it be necessary to teach me theories, and which ones, so that I would progress? What about macros and lexical closures and the other advantages of LISP. Are they important because of theory or practise? If the course was teaching just theory, when would it be necessary to let me program something? What would that be? And in which language? Does teaching bubblesort algorthims help when most high level languages have highly efficent sorting routines available? And if we never taught bubblesorts, how would we arrange it so that someone who needed to write a better sorting routine could find out. It would be interesting to hear from someone with experience of modern CS teaching though. I could be ranting about nothing. "Laura Creighton" wrote in message news:mailman.989409253.7945.python-list at python.org... > Datapoint: > Most people in the late 1970s and early 1980s at the University > of Toronto were not in the computer science program because they wanted > to become academics, computer scientists, but rather because they wanted > to become programmers. They were in there for the same reason that > people studied Dentistry, or Law -- they wanted a Profession, not to be From spamers at must.die Sat May 5 11:50:22 2001 From: spamers at must.die (Fernando Rodríguez) Date: Sat, 05 May 2001 17:50:22 +0200 Subject: Choosing a programming language as a competitive tool References: <3dlmoflsjv.fsf@ute.cnri.reston.va.us> Message-ID: On Wed, 02 May 2001 14:48:42 GMT, Courageous wrote: >On 02 May 2001 10:44:04 -0400, Andrew Kuchling wrote: > > >Not really, no. Not only is it difficult to find Lisp programmers, it's hard >to train them, and even harder to make them good Lisp programmers. >Add to this mix that there's little out there in terms of third party (pay or >free) library support, and you have a really sour recipe. In my experience, >if you're going the Lisp route, you need mavericks. > >Python, however, is different. Nonsense. Python and lisp are quite similar, and Pyhton owes most of it's "coolness" to lisp. The only thing remotely difficult in both languages is optimization (since so much happens under the hood). This happens to any high level language. At least, you don't struggle for months (or years) to get your app working, only a few days to optimize it. In my experience, using a good lisp compiler you can have a running app (with a performance equivalent to C++) when the C++ programmer is still declaring variables. Common Lisp is a useful tool for the Python programmer when you need more power or speed. I use both. //----------------------------------------------- // Fernando Rodriguez Romero // // frr at mindless dot com //------------------------------------------------ From aahz at panix.com Fri May 25 12:23:38 2001 From: aahz at panix.com (Aahz Maruch) Date: 25 May 2001 09:23:38 -0700 Subject: floor() function and mathematical integers References: <3b0e0ca4.254456579@wa.news.verio.net> <3b0e6e65.279481372@wa.news.verio.net> Message-ID: <9em0ua$8ad$1@panix6.panix.com> In article <3b0e6e65.279481372 at wa.news.verio.net>, Bengt Richter wrote: > >Decided to add fractional float bit printing. Just started playing >with Python, as you can probably tell. No warranty. For comparison, take a look at this routine from Tim Peters to convert floats to strings (yes, Tim, I modified it to work with 1.5.2): def _floatToString(x): """Return float x as exact decimal string. The string is of the form: "-", if and only if x is < 0. One or more decimal digits. The last digit is not 0 unless x is 0. "e" The exponent, a (possibly signed) integer """ import math # XXX ignoring infinities and NaNs for now. if x == 0: return "0e0" sign = "" if x < 0: sign = "-" x = -x f, e = math.frexp(x) assert 0.5 <= f < 1.0 # x = f * 2**e exactly # Suck up CHUNK bits at a time; 28 is enough so that we suck # up all bits in 2 iterations for all known binary double- # precision formats, and small enough to fit in an int. CHUNK = 28 top = 0L # invariant: x = (top + f) * 2**e exactly while f: f = math.ldexp(f, CHUNK) digit = int(f) assert digit >> CHUNK == 0 top = (top << CHUNK) | digit f = f - digit assert 0.0 <= f < 1.0 e = e - CHUNK assert top > 0 # Now x = top * 2**e exactly. Get rid of trailing 0 bits if e < 0 # (purely to increase efficiency a little later -- this loop can # be removed without changing the result). while e < 0 and top & 1 == 0: top = top >> 1 e = e + 1 # Transform this into an equal value top' * 10**e'. if e > 0: top = top << e e = 0 elif e < 0: # Exact is top/2**-e. Multiply top and bottom by 5**-e to # get top*5**-e/10**-e = top*5**-e * 10**e top = top * 5L**-e # Nuke trailing (decimal) zeroes. while 1: assert top > 0 newtop, rem = divmod(top, 10L) if rem: break top = newtop e = e + 1 return "%s%de%d" % (sign, top, e) From thomas at xs4all.net Sun May 27 18:40:56 2001 From: thomas at xs4all.net (Thomas Wouters) Date: Mon, 28 May 2001 00:40:56 +0200 Subject: Long names are doom ? In-Reply-To: ; from tim.one@home.com on Sun, May 27, 2001 at 05:41:08PM -0400 References: <20010527150003.Z690@xs4all.nl> Message-ID: <20010528004056.G690@xs4all.nl> On Sun, May 27, 2001 at 05:41:08PM -0400, Tim Peters wrote: > [Thomas Wouters] > > There are basically two choices wrt. allowing reserved words as > > vrbl names: > > 1) allow them everywhere, in any situation. ... > > ... > > 2) Allow them in certain locations only, like calling functions > > with keyword arguments, attribute-referencing/assignment and 'def' > > statements inside classes (but not outside.) ... > > ... > > Guido agreed with #2 already (pending implementation). I'm > > not sure what his opinion of #1 is, > I'll channel him, then: no way. Pity, but understandble. I have to admit that the 'other parsers' argument has been nagging in the back of my mind every time the subject of a more advanced parser comes up. > As a first cut, you might, e.g., try replacing > dotted_name: NAME ('.' NAME)* > with > dotted_name: NAME ('.' anyname)* > anyname: NAME | 'and' | 'assert' | 'break' | ... | 'while' Been there, done that. It's somewhere in the python-dev archives, *I believe* right before 2.0 was released (but I'm not sure.) One of the few threads that all of Mark, Guido and me posted, if that's any help in searching ;) > Then see what breaks and fix it . Unfortunately, doing it that way breaks a whole lot. Almost every place in compile.c that handles NAME's just does a 'STR(n)', and tracking them is a serious pain in the tooshie. I went the even-easier-way , and replaced e.g. dotted_name: NAME ('.' NAME)* with dotted_name: NAME ('.' NAME | 'and' | 'assert' | 'break' | ... | 'while')* That worked fine, for the limited testing I did with it. That's why my earlier posting talked about a pre-processor. Or did it ? Maybe that posting was stillborn -- I'm tired, I might have taken the easy way out :) If-only-the-ellipsis-in-the-keyword-list-actually-worked-ly y'rs, -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! From kca17 at dial.pipex.com Sat May 19 16:01:31 2001 From: kca17 at dial.pipex.com (Eddie and Babs) Date: Sat, 19 May 2001 21:01:31 +0100 Subject: Python time class References: <3b0584d0$0$12249$cc9e4d1f@news.dial.pipex.com> Message-ID: <3b06d135$0$12250$cc9e4d1f@news.dial.pipex.com> What I mean by a good "model" of time is a good PROGRAMMING model. I realise that metrologists already have a rigorously defined time unit in the Second (and even binary prefixes, unpleasantly named kibi = 1024, mebi = 1048576, etc, analogous to kilo, mega, etc; horrible names, yes, but they do exist). As programmers, we have to do calculations with values that represent points in time. I was not referring to relativistic physical calculations, but rather to simple things like time and date intervals, etc. Although a well elaborated and complete system for expressing and calculating with these values may exist, I have never seen it (not that I am any kind of expert). However inconvenient it may be for programmers, we obviously can't expect users to input times into a diary application as 32-bit numbers of seconds since 1970. So, we provide for hours, minutes and seconds, etc. If we want to tell the user what will be happening two and a half hours from now, we could calculate something like:- currentTime += (2 * 3600) + (30 * 60) # Time as seconds but something along the lines of:- currentTime += Hour(2) + Minute(30) ...is surely more legible and no less precise. And time intervals are prone to "endpoint paranoia" (ie, the interval from 1st July to 7th July; does this include the 7th July or stop just before it? Answer: it depends what the programmer had in mind at the time - there is no standard model generally expected by programmers.) And when someone specifies that something happened "yesterday" they will generally mean sometime between 0:00 and 23:59, not the exact point in time specified by currentTime - 86400. Need I go on? This is what I mean by a good model of time. A consistent set of routines, classes and, most importantly, semantics to support the kinds of calculations that programmers actually USE day to day. But it will take a new language I think (Python3K, perhaps?) before such a model becomes transparent and we can write things like:- currentTime += 23h27m ...without even noticing. &. PS - you are not at all dense. It's me - nobody seems to understand a word I write on this newsgroup <(500000000L - 8j) / (1000000000L + 9j) wink> ---------- In article , Eugene.Leitl at lrz.uni-muenchen.de wrote: > Eddie and Babs wrote: >> >> I have always thought that the computing world lacks a mature and >> "standard", yet powerful model of time. I find it amazing that modern > > What do you mean? There is this nifty SI unit called second. And > a set of prefixes, unfortunately not based on binary orders of magnitude. > >> high-level languages like Python don't have time literals and built-in >> support for time calculations (we do, after all, have built-in support for >> complex number calculations, which are surely far less common than time >> calculations). > > Huh? What's wrong with > 10002354235341341223412452353234253450000L * > 20342345235435335235323452353452352345545235345435L > for instance? > >> The operative words here are "model of time". Any particular > > Do you mean Newtonian time, or General Relativity? As an interpreted > language, I don't think Python needs corrections for travel and spacetime > curvature... > >> Once a good time model exists, it will be largely independent of language > > Perhaps I'm a bit dense, but I honestly fail to see your point. > You don't happen to refer to this completely arbitrary, > comonnly deprecated 24/7/12/365 chunking scheme? > >> and platform (and it would be typically Pythonic to have a Python version >> and also a C version for those who value the extra speed; if the model is >> sufficiently satisfying, then people will love to implement it in as many >> ways as possible). >> >> A good time class would be another first for Python, but I suspect we will >> have to wait for another language to come along to do for time what Python >> did for subscripts. > From steffen.ries at sympatico.ca Wed May 2 07:12:08 2001 From: steffen.ries at sympatico.ca (Steffen Ries) Date: Wed, 02 May 2001 11:12:08 GMT Subject: CGI Redirect References: <5.0.2.1.0.20010501094910.00a21b30@thewebsons.com> <5.0.2.1.0.20010501080840.00a01c50@thewebsons.com> <5.0.2.1.0.20010501080840.00a01c50@thewebsons.com> <5.0.2.1.0.20010501094910.00a21b30@thewebsons.com> Message-ID: Ben Ocean writes: > >Uuuh? Normally Content type and location headers shouldn't be mixed as > >the first one will disable all the others... For me, Location alone > >works (Apache 1.3.19). > > Here's my code. Can you tell me where I'm going wrong? (Everything > gets replaced like it should, it's just the aforementioned error.) I did not follow the whole thread, so I may miss something... > >>> > #!/usr/bin/python > > import os, sys, cgi, string > > FormData = cgi.FieldStorage() > print "Content-type: text/html\n\n" The two "\n\n" produce two empty lines, where the first one separates the HTTP header from the body. > Disallowed = ['\nTo:', '\nCc:', '\nBcc:'] > > FormData = open("/apache/vhosts/bladechevy/New/test.html", "r") > formstuff = "" > while FormData.readline(): > safe = string.maketrans("`|~!@#$%^&*()_+=:;{}[]", "----------------------") > line = > string.replace(string.replace(string.replace(string.translate(FormData.readline(), > safe), " "\">", ".") > formstuff = string.join([formstuff,line]) > FormData.close() # close the file > import smtplib > server = smtplib.SMTP("localhost") > server.sendmail("beno at thewebsons.com", "beno at thewebsons.com", formstuff) > server.quit() > > print "Location:http://bladechevy.com/" This goes into the body of the HTTP get-response. IOW the line is interpreted as regular HTML text and has no special meaning for the browser. What you want is: --8<-- print "Content-type: text/html" # this line does not do anything, but is harmless ... print "Location: http://bladechevy.com/" --8<-- hth, /steffen -- steffen.ries at sympatico.ca <> Gravity is a myth -- the Earth sucks! From see at my.signature Fri May 11 00:25:18 2001 From: see at my.signature (Greg Ewing) Date: Fri, 11 May 2001 16:25:18 +1200 Subject: os independent temp dir? References: Message-ID: <3AFB69AE.2FDBB822@my.signature> "Mike C. Fletcher" wrote: > > No idea if the Mac even has environmental variables, It doesn't. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From tjenkins at devis.com Wed May 16 16:27:10 2001 From: tjenkins at devis.com (Tom Jenkins) Date: Wed, 16 May 2001 16:27:10 -0400 Subject: Preferred way of determining type References: <9dueq7$4slq$1@ID-11957.news.dfncis.de> Message-ID: <3B02E29E.70202@devis.com> Emile van Sebille wrote: > More frequently lately it seems that isinstance(obj, types.Type) or simply > if type(obj) == types.Type is recommended over what I regularly use, eg: if > type(obj) == type([]). > > Anyone care to explain why or in what circumstances there's a difference? > At the recent Python conference in Long Beach I overheard Guido say that isinstance should be the way you check for type equality. Example: if isinstance(obj, type([])): #do whatever here The reason is that isinstance will continue to work once the type/class split is mended, but he did not think that type(obj) == type([]) would not. I distinctly remember this because I made a note to myself to tell my folks here to stop doing it the way you (and I) regularly used. But again this was overheard, I have not code to explain why. -- Tom Jenkins devIS - Development Infostructure http://www.devis.com From rcameszREMOVETHIS at dds.removethistoo.nl Sat May 5 09:46:16 2001 From: rcameszREMOVETHIS at dds.removethistoo.nl (Robert Amesz) Date: Sat, 05 May 2001 13:46:16 GMT Subject: The joys and jilts of non-blocking sockets Message-ID: I've recently been doing a little work with sockets, more in particular non-blocking sockets, and I'm sorry to say the standard Python documentation isn't really too helpful here. I feel this is a mistake: without documentation people like me will experiment to find out how things work, and we may end up relying on features which are either different for different platforms, or not guaranteed to work with different versions of Python, or both. This is not good. I've documented my experiments in the hope that will be useful to others and also to elicit some comments, in particular where other platforms or versions of Python are concerned. I've also studied timeoutsocket.py for some hints and pointers about socket behaviour, and this is a good source of information about some of the quirks of non-blocking sockets, so I'd like to thank Timothy O'Malley for that. Even so I'd like to take the opportunity to point out a few bugs and a design flaw in version 1.15 (the latest version I was able to find). One of the bugs is/are a set of missing commas in lines 142, 143, 144 and 147: without those commas tuples aren't tuples, I'm afraid. (My guess is those were lists originally.) The other, slightly larger bug is that error code 10022 (in TimeoutSocket.connect()) is taken as an indication that the connection has been made, while in fact the connection has been refused (see below for more details about that). The design flaw is that the module makes non-blocking sockets behave like blocking ones: this just doesn't make sense to me. Arguably, using both types of sockets in a single application shouldn't be too common, but as it - very cleverly - replaces the normal socket-module once imported, it really should handle the non-blocking case too. Not that it's hard: in fact, it's almost trivial, but it should be done. But let's concentrate on socket behaviour itself. The observations below have been done on an Windows 98 machine, they might be different on other Windows versions, and they certainly *will* de different on a different OS, like UNIX or MAC-OS. I'm using Python version: Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 Exceptions are shown on an indented line as they are displayed by 'print' or the stack trace, and on the next line you'll find the symbolic name(s) for that code, as defined in module 'errno'. The codes starting with 'WSA' are from the Windows sockets .dll. CONNECTING THE SOCKET --------------------- If the host exists and can be reached, connecting to it using a non- blocking call *always* leads to this exception: (10035, 'The socket operation could not complete without blocking') 10035 = EWOULDBLOCK WSAEWOULDBLOCK This message does not give you *any* information about the status of the connection: the machine may be busy connecting, the connection may have been made, or the connection may have been refused. If the connection is refused (i.e. there's either no service listening to the port you're trying to connect to, or no new connections are being accepted on that port), trying to receive (or send) data through that socket will, once again, produce the same exception (10035), so that won't really help you to find out what your connection status is. Using getpeername() is more helpful: (10057, 'Socket is not connected') 10057 = ENOTCONN WSAENOTCONN Unfortunately, the manual says this function doesn't exist on all platforms, so portable code should try to avoid it. But don't despair: if a connection is refused trying to connect again to the same host using the same socket will yield the following surprising exception: (10022, 'Invalid argument') 10022 = WSAEINVAL Well, it accepted the parameter(s) before, so what's that all about? Furthermore, it doesn't make any difference if you change the port number, you'll get the same result. Using a different hostname which points to the same IP-address doesn't change anything either, but using a different hostname *does*, strangely enough. As sockets can't be re-used anyway this isn't something to look into too deeply. After a close() all further operations on that socket are are expressly forbidden, and in fact impossible. Yes, I just had to try! Although the exception you get when you try to reconnect is pretty puzzling: AttributeError: 'int' object has no attribute 'connect' What happens here is that the internal socket object has been replaced by the int 0. But please don't rely on behaviour like that. Ok, back to connecting. Because I did my testing on a single machine I wasn't able to catch the socket system in the middle of the connection handshake, so I can't tell if trying to connect at that time will yield another exception, but trying it after establishing the connection will result in this very predictable exception. (10056, 'Socket is already connected') 10056 = EISCONN WSAEISCONN Hurrah, we're connected! Or are we? Well, not neccesarily: the connection may have been broken already. The system doesn't seem to be able to tell an idle connection from a broken one (this may be part of the nature of TCP/IP), and you need to do something with the stream to find that out, as you'll see below. On the other hand, if you try to connect to a non-existent IP-address you'll see this exception: (10065, 'No route to host') 10065 = EHOSTUNREACH WSAEHOSTUNREACH If the hostname couldn't be resolved, this is what you get: ('host not found',) What, no error code? That's right, and this could be an issue if you expect a number in the first position of this tuple-like exception, or anything at all in the second position. SENDING DATA ------------ Pretty straightforward, really. Just do MySocket.send(data), and if there's nothing wrong with the connection it will either work, or raise: (10035, 'The socket operation could not complete without blocking') 10035 = EWOULDBLOCK WSAEWOULDBLOCK In the documentation it states that the function returns the number of bytes actually sent, but I've never observed this number to be different from the amount you're trying to send, even when it's a big chunk of data. When trying to flood a connection with data with small bits of data (I didn't read the data on the receiving end) it would raise the above exception after about 18K of data was 'sent', but if you try to send() larger (even much larger) chunks of data the first call always works, and only subsequent calls raise the exception. This behaviour might not be portable, though. If you try to send data when the connection has been broken the following exception is raised: (10054, 'Connection reset by peer') 10054 = ECONNRESET WSAECONNRESET RECEIVING DATA -------------- Doing a MySocket.recv(max_length) can certainly result in some unexpected behaviour: if the connection is good, and there's some data waiting, the data will be returned. That's not the surprising bit. When the connection is good, and there's no data waiting, you'll get the ubiquitous (10035, 'The socket operation could not complete without blocking') 10035 = EWOULDBLOCK WSAEWOULDBLOCK exception. That, too, isn't surprising. What *is* surprising, however, is that when the connection has been broken on the other end, no exception is raised whatsoever, but the recv() function will keep returning zero- length strings. I wonder if that behaviour is intentional? Or portable, for that matter. As this is the only way that I know of telling a dead connection from a live one when receiving data, we're forced to rely on this strange behaviour, but I'd prefer the ECONNRESET-exception to would be raised. SOCKET EXCEPTIONS ----------------- Sockets raise exceptions of type socket.error, and like any other exception that's a class. But you might be forgiven for thinking that it's a tuple because for all intents and purposes it behaves like one. (I presume this is for historic reasons, to make sure older code will keep working as expected.) It looks that way in the traceback, and if e is the exception you've caught you can look at e[0] (the number of the error) and e[1] (the associated message). This rule has one exception, however, and that is the ('host not found',) exception, which has the error message in the first position, and doesn't have a second position. Strange beasts, those sockets. Under Windows, anyway. Robert Amesz -- APPENDIX - socket error codes from the 'errno' module 10004 = WSAEINTR 10009 = WSAEBADF 10013 = WSAEACCES 10014 = WSAEFAULT 10022 = WSAEINVAL 10024 = WSAEMFILE 10035 = EWOULDBLOCK WSAEWOULDBLOCK 10036 = EINPROGRESS WSAEINPROGRESS 10037 = EALREADY WSAEALREADY 10038 = ENOTSOCK WSAENOTSOCK 10039 = EDESTADDRREQ WSAEDESTADDRREQ 10040 = EMSGSIZE WSAEMSGSIZE 10041 = EPROTOTYPE WSAEPROTOTYPE 10042 = ENOPROTOOPT WSAENOPROTOOPT 10043 = EPROTONOSUPPORT WSAEPROTONOSUPPORT 10044 = ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT 10045 = EOPNOTSUPP WSAEOPNOTSUPP 10046 = EPFNOSUPPORT WSAEPFNOSUPPORT 10047 = EAFNOSUPPORT WSAEAFNOSUPPORT 10048 = EADDRINUSE WSAEADDRINUSE 10049 = EADDRNOTAVAIL WSAEADDRNOTAVAIL 10050 = ENETDOWN WSAENETDOWN 10051 = ENETUNREACH WSAENETUNREACH 10052 = ENETRESET WSAENETRESET 10053 = ECONNABORTED WSAECONNABORTED 10054 = ECONNRESET WSAECONNRESET 10055 = ENOBUFS WSAENOBUFS 10056 = EISCONN WSAEISCONN 10057 = ENOTCONN WSAENOTCONN 10058 = ESHUTDOWN WSAESHUTDOWN 10059 = ETOOMANYREFS WSAETOOMANYREFS 10060 = ETIMEDOUT WSAETIMEDOUT 10061 = ECONNREFUSED WSAECONNREFUSED 10062 = ELOOP WSAELOOP 10063 = WSAENAMETOOLONG 10064 = EHOSTDOWN WSAEHOSTDOWN 10065 = EHOSTUNREACH WSAEHOSTUNREACH 10066 = WSAENOTEMPTY 10067 = WSAEPROCLIM 10068 = EUSERS WSAEUSERS 10069 = EDQUOT WSAEDQUOT 10070 = ESTALE WSAESTALE 10071 = EREMOTE WSAEREMOTE 10091 = WSASYSNOTREADY 10092 = WSAVERNOTSUPPORTED 10093 = WSANOTINITIALISED 10101 = WSAEDISCON From Steven_Shaw at adc.com Wed May 2 05:50:47 2001 From: Steven_Shaw at adc.com (Steven_Shaw at adc.com) Date: Wed, 2 May 2001 09:50:47 +0000 (UTC) Subject: pygrep Message-ID: <4A256A40.0036180F.00@ssxrgw01.savillemailbr.com> Hi there, I have converted an old Perl4 script to Python2.1. It is a simple tool to replace grep. My new Python script currently runs about twice as slow as the old Perl version. I've tried afew things from the Python FAQ, but nothing seems to improve things much. Can anyone suggest performance improvements for this code? Here's the original Perl source code (pgrep): (See attached file: pgrep) Here's the Python source code (pygrep): (See attached file: pygrep) cheers, Steve. -------------- next part -------------- A non-text attachment was scrubbed... Name: pgrep Type: application/octet-stream Size: 125 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: pygrep Type: application/octet-stream Size: 667 bytes Desc: not available URL: From aleaxit at yahoo.com Mon May 14 04:48:45 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 14 May 2001 10:48:45 +0200 Subject: Search in textfiles? References: <_gML6.10366$sk3.2783263@newsb.telia.net> Message-ID: <9do65a0e3j@news2.newsguy.com> "Martin Johansson" <045521104 at telia.com> wrote in message news:_gML6.10366$sk3.2783263 at newsb.telia.net... > import string > > word = raw_input("Write a word ") > c=open('10 Maj 08_580,2183,106_nyheter_1022,00.html.txt', 'r') > textstring = c.read() > index = string.find(textstring, word) > if index > 0: > print "yes the word exists in the textfile" > else: > print "it doesn?t exist" > > this code I rote, but what can be done if big letters should not be threated > different than small letters? > > (Martin should be the same as martin) Simplest is to lowercase both the string you're looking for and the one into which you're looking, changing the 2nd and 3rd lines of this snippet as follows: textstring = c.read().lower() index = textstring.find(word.lower()) If for some reason you're still using a very old Python and so can't use methods of string objects, you may equivalently call string.lower() on the string of which you want to get the lowercased equivalent. There are alternatives, such as using regular expressions and the case-insensitive-search flag you can pass when you compile a regular expression, but just lowercasing the strings before the search is simpler in most use-cases. Alex From michael at stroeder.com Thu May 31 10:12:32 2001 From: michael at stroeder.com (Michael =?iso-8859-1?Q?Str=F6der?=) Date: Thu, 31 May 2001 16:12:32 +0200 Subject: Problem using SocketServer.ThreadingTCPServer on Windows? References: <3b15725e.157061953@news.supernews.com> Message-ID: <3B165150.B92A406E@stroeder.com> Robert Amesz wrote: > > Xtian wrote: > > > AttributeError: 'int' object has no attribute 'send' > > > > It seems that after the second print, for no (obvious to me) > > reason, the conn object (which has reported it is a socket twice) > > is suddenly an int. > > Using a closed socket will raise that cryptic exception. As I've not > used SocketServer before it's hard for me to tell *why* the socket > has been closed. If it's Python 2.1 it could be this one: http://sourceforge.net/tracker/index.php?func=detail&aid=417845&group_id=5470&atid=105470 Ciao, Michael. From jcopella at cfl.rr.com Sat May 5 02:56:52 2001 From: jcopella at cfl.rr.com (John Copella) Date: Sat, 05 May 2001 06:56:52 GMT Subject: Problems importing a module (as a shared lib) from the current working directory Message-ID: I'm using Python 2.1 on AIX 4.2, and I'm having some trouble with the import statement. If I attempt to import a module (implemented as a shared lib) that resides in the same directory where I am running the interpreter, I get an ImportError exception. However, if I then change directories (doesn't matter where), I can import the module fine, as long as sys.path is set correctly. Alternatively, I can move the .so to some other location in sys.path, and things are fine. Consider the following transcript: [269] > setenv PYTHONPATH `pwd` [270] > ls -l *.so -rwxrwxr-x 1 xxxxxxxx usr 17587 May 05 01:09 examplecmodule.so [271] > python -c 'import examplec' Traceback (most recent call last): File "", line 1, in ? ImportError: from module examplecmodule.so No such file or directory [272] > cd .. [273] > python -c 'import examplec' [274] > #note no error occurs It's not really a show-stopper, but it's one of those things that makes me feel uneasy, because I thought I had a good handle on import semantics. Any ideas as to what's going on here? JC From see at my.signature Thu May 10 01:42:48 2001 From: see at my.signature (Greg Ewing) Date: Thu, 10 May 2001 17:42:48 +1200 Subject: Why aren't we all speaking LISP now? References: <989424635.15477.0.nnrp-12.c1c3e154@news.demon.co.uk> Message-ID: <3AFA2A58.FBB931A5@my.signature> Paul Brian wrote: > > Does teaching bubblesort algorthims help when most high level languages have > highly efficent sorting routines available? The point of teaching bubblesort isn't so that you know how to write a bubblesort. Studying it, together with other sorting algorithms such as minselect and quicksort, teaches you how to analyse algorithms and compare the performance of different algorithms for solving the same problem. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From rnd at onego.ru Thu May 10 01:31:31 2001 From: rnd at onego.ru (Roman Suzi) Date: Thu, 10 May 2001 09:31:31 +0400 (MSD) Subject: Range Operation pre-PEP Message-ID: On Wed, 9 May 2001, Fredrik Lundh wrote: > Roman Suzi wrote: > > Please, recall the main reason for the new feature: > > > > - to allow beginners learn loops BEFORE they learn > > lists and functions (which are needed now to explain > > for-loop). > > > > Even recursion could be explained without lists in Python, > > why for-loops need this prerequisite? > > done much python training lately, or are you just making Yes. I taught programming classes a year ago. That is where I had some trouble with for-loops. > things up as you go? > > (in my experience, you don't have to understand much > about functions and lists to learn how to *use* range in > simple for-in loops...) > > Cheers /F Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From rjroy at takingcontrol.com Tue May 15 21:46:57 2001 From: rjroy at takingcontrol.com (Robert Roy) Date: Wed, 16 May 2001 01:46:57 GMT Subject: Solaris Weirdness with 2.1 References: <200105151505.LAA18242@smtp3.andrew.cmu.edu> Message-ID: <3b01d8e0.616294859@news1.on.sympatico.ca> On Tue, 15 May 2001 11:05:37 -0400, Michael P Collins wrote: > >I've been trying to install Python 2.1 on a Solaris box and have run >into the following error messages during the make, any thoughts? > >skipping 'timing' extension (up-to-date) >skipping 'audioop' extension (up-to-date) >skipping 'imageop' extension (up-to-date) >skipping 'rgbimg' extension (up-to-date) >building 'readline' extension >skipping /usr2/mcollins_dev/Python-2.1/Modules/readline.c >(build/temp.solaris-2.7-sun4u-2.1/readline.o up-to-date) >gcc -shared build/temp.solaris-2.7-sun4u-2.1/readline.o >-L/usr/lib/termcap -L/usr/local/lib -lreadline -ltermcap -o >build/lib.solaris-2.7-sun4u-2.1/readline.so >Text relocation remains referenced > against symbol offset in file > 0x38 >/usr/local/lib/libreadline.a(xmalloc.o) > 0x3c >/usr/local/lib/libreadline.a(xmalloc.o) > 0xe0 >/usr/local/lib/libreadline.a(xmalloc.o) > > >It goes on (and on, and on) from there - I've never seen this kind of >compile error before, and it specifically only happening on our >solaris boxes. Any sugestions? > >Here's the Uname: SunOS nan.ndim.edrc.cmu.edu 5.7 Generic_106541-04 sun4u sparc SUNW,Ultra-2 > > I had similar problems. I ended up modifying Modules/Setup to link readline (and a couple of other modules) statically. Since I did not have write access to the system dirs, this also let me link against more recent versions of these libraries than were available in the usual places (/usr/local .... etc). For some of the extension modules I built, I had to add the flag -mimpure-text to the compile string. Bob From bokr at accessone.com Sun May 27 11:03:22 2001 From: bokr at accessone.com (Bengt Richter) Date: Sun, 27 May 2001 15:03:22 GMT Subject: floor() function and mathematical integers References: <3b0e0ca4.254456579@wa.news.verio.net> <3b0e6e65.279481372@wa.news.verio.net> <9em0ua$8ad$1@panix6.panix.com> Message-ID: <3b110e06.451418064@wa.news.verio.net> On 25 May 2001 09:23:38 -0700, aahz at panix.com (Aahz Maruch) wrote: >In article <3b0e6e65.279481372 at wa.news.verio.net>, >Bengt Richter wrote: >> >>Decided to add fractional float bit printing. Just started playing >>with Python, as you can probably tell. No warranty. > >For comparison, take a look at this routine from Tim Peters to convert >floats to strings (yes, Tim, I modified it to work with 1.5.2): > >def _floatToString(x): > """Return float x as exact decimal string. > [...] > # Now x = top * 2**e exactly. Get rid of trailing 0 bits if e < 0 > # (purely to increase efficiency a little later -- this loop can > # be removed without changing the result). > while e < 0 and top & 1 == 0: > top = top >> 1 > e = e + 1 > UIAM, since digit has the last non-zero chunk, you could let the FPU count the trailing bits instead of using a while loop: trailing_bits = math.frexp(float(digit^(digit-1)))[1]-1 top >>= trailing_bits e += trailing_bits FWIW, I think you could speed up the decimal trailing zero trim too. What's the biggest number of possible trailing decimal zeroes? 22? Of course, this would slow things down when there's no or few zeroes. Adjust kzlog2 to taste. BTW, what's the preferred style for avoiding "magic numbers" in python code, with no #define SOME_CONSTANT? I have in mind replacing > # Nuke trailing (decimal) zeroes. > while 1: > assert top > 0 > newtop, rem = divmod(top, 10L) > if rem: > break > top = newtop > e = e + 1 > with something like: # Nuke trailing (decimal) zeroes. kzlog2 = 4 zlog2 = kzlog2 #log2 of zeroes possibly removed in curr loop while zlog2 >=0: assert top > 0 newtop, rem = divmod( top, 10L**(1< <5bhG6.29435$qc2.7596549@typhoon.southeast.rr.com> <3AEE4061.860868AB@my.signature> <3AEF7EE5.6A5B78C3@my.signature> <3AEF8A5E.76BF7509@mail.com> Message-ID: <3AF032C6.2F81D489@san.rr.com> James A. Robertson wrote: > > were wondering. And add or remove instance variables > > dynamically, too (I don't think that one is so easy in > > Smalltalk). > > Sure it is. > MyClass addInstVarName: 'foo' > MyClass removeInstVarName: 'foo' This is a little different from Python, tho. In smalltalk, addInstVarName adds the instance variable to the *class* and then updates all instances to now have that variable in them. (A relatively high-overhead operation, yes.) IIRC, it might also have to recompile some or all of the class code? In Python, you add instance variables to individual instances. Not all instances of the same class must have the same set of instance variables. (In one sense, all instances of a class have the same instance variables, but one of those instance variables is a dictionary mapping instance variable names to values, and the syntax makes this mostly invisible.) I think if you want to add an instance variable to all instances of a class, you need to write a loop to iterate over all those instances. I'm not sure whether you could find them. -- Darren New / Senior MTS & Free Radical / Invisible Worlds Inc. San Diego, CA, USA (PST). Cryptokeys on demand. Invasion in chinese restaurant: ALL YOUR RICE ARE BELONG TO US! From mwh at python.net Tue May 29 15:01:14 2001 From: mwh at python.net (Michael Hudson) Date: 29 May 2001 20:01:14 +0100 Subject: parse-time optimizations References: <9ervav$qu9$1@news.mathworks.com> <9evasv$9u8$1@news.mathworks.com> <9f0op4$6b5$1@news.mathworks.com> Message-ID: jcm writes: > Michael Hudson wrote: > > > Thing is, if you're writing code that benefits from constant folding - > > WHY? If your code contains things like: > > > "a" + "b" > > > then you have bigger problems than Python's lack of optimizations... > > The example "a" + "b" was, of course, an example. Something like > > "some really long string (probably longer than this one) that I " + > "can't quite fit onto one line in good conscience" > > would be more realistic. Well, there are other ways round that one; literal conatenation or backslashing the newline. > There's also the case where code is generated by another tool. > Somewhat relatedly, I've seen C macros that generate expressions > like > > 1 + 1 + 1 + 1 + 1 + 1 + 0 > > so there are instances where this sort of thing comes up. True - but Python has no preprocessor so this is still fairly unlikely. I don't think that many people machine generate Python - but I could be wrong. I don't want to discourage anyone from implementing these optimizations for Python - but the benefit/effort ratio is rather small. Cheers, M. -- Academic politics is the most vicious and bitter form of politics, because the stakes are so low. -- Wallace Sayre From dsh8290 at rit.edu Fri May 18 11:41:41 2001 From: dsh8290 at rit.edu (D-Man) Date: Fri, 18 May 2001 11:41:41 -0400 Subject: wxPython or TKinter? In-Reply-To: <3B0541C7.AFE8DBEF@bioreason.com>; from kelley@bioreason.com on Fri, May 18, 2001 at 04:37:43PM +0100 References: <990102611.252860@nntp01.uskonet.com> <9e0ogt$lti$1@nntp6.u.washington.edu> <9e0qif02on3@enews1.newsguy.com> <9e11cs$jhc$1@nntp6.u.washington.edu> <3B0541C7.AFE8DBEF@bioreason.com> Message-ID: <20010518114141.A6748@harmony.cs.rit.edu> On Fri, May 18, 2001 at 04:37:43PM +0100, Brian Kelley wrote: | | Glade has been ported to windows. Unfortunately the windows version of pygtk | doesn't seem to support libglade yet. This should be a minor fix. I'm Does libglade itself build/run on windows? It might be a bigger problem than it seems. Even so, there are tools to generate python code from the Glade description thus eliminating the need for libglade. Libglade is really cool, though. -D From opengeometry at yahoo.ca Thu May 17 15:19:42 2001 From: opengeometry at yahoo.ca (William Park) Date: Thu, 17 May 2001 15:19:42 -0400 Subject: Evaluating python - a question In-Reply-To: <9e100t$8e1$1@news.netmar.com>; from alan.prescott@nospam.jarrold.com on Thu, May 17, 2001 at 04:59:09PM +0000 References: <9e100t$8e1$1@news.netmar.com> Message-ID: <20010517151942.A5755@node0.opengeometry.ca> On Thu, May 17, 2001 at 04:59:09PM +0000, alan.prescott at nospam.jarrold.com wrote: > me = person() > me.forename = 'Alan' > > is Ok but a simple typo (especially with my keyboard skills) of > > me.froname = 'Fred' > > will go undetected and I'll have to spend ages digging around to find a bug > which languages like C/C++/Pascal would throw out at compile time. Well, let see in C... int forename, froname; forename = 1 froname = 2 So, what's the difference? A typo in Python is also typo in C. Solution: get a decent editor! In Vim, you can do word completion ^p/^n (going up and down, respectively). -- William Park, Open Geometry Consulting, 8 CPU cluster, (Slackware) Linux, Python, LaTeX, Vim, Mutt, Sc From rnd at onego.ru Sun May 27 13:13:28 2001 From: rnd at onego.ru (Roman Suzi) Date: Sun, 27 May 2001 21:13:28 +0400 (MSD) Subject: Python -> C++ compilation In-Reply-To: Message-ID: On 27 May 2001, Martin von Loewis wrote: Thanks a lot, Martin! I've not thought there are 3 possible solutions to this. However: >The basic question is why you'd want to have such a thing. To make a >stand-alone executable? Use freeze, or the installer. To gain >execution speed? In your typical Python program, much execution speed >can be gained with small modifications - although those modifications >are often hard to find. Because it's cool? That certain was the >primary motivation for the two IPC authors. Because you could sell it >for a lot of money? Dunno, you may ask Andreas Otto about that. Let me explain. Python programming is too easy to consider C++ for doing most work. However, if one is _forced_ to use C++ because the project is being developed with it, there are 5 options: 0. Convince management on using Python (see #3 also) 1. Write in Python then automatically compile into C++ using some tool 2. Write Python program for C++ code generation 3. Embed Python (not easy even though Python is Free!) and have fun 4. Give up Python My question was theoretical (at my current job we use Python with pleasure). But what-if... always remains. It's too easy to get accustomed to good and elegant things, you know. I myself have pulled trick #2 for markup-languages four times already. No doubt, it will work for C++ too ;-) >Regards, >Martin Thanks for your input! Sincerely yours, Roman Su zi From garry at sage.att.com Mon May 14 14:27:27 2001 From: garry at sage.att.com (Garry Hodgson) Date: Mon, 14 May 2001 18:27:27 GMT Subject: Why aren't we all speaking LISP now? (Andy Todd) References: Message-ID: <3B00238F.3E144258@sage.att.com> Courageous wrote: > Well, just don't forget, Canada is kind of like Puerto Rico... practically > a State. i always thought of it as a colony. -- Garry Hodgson sometimes we ride on your horses Senior Hacker sometimes we walk alone Software Innovation Services sometimes the songs that we hear AT&T Labs are just songs of our own garry at sage.att.com From zope at thewebsons.com Thu May 3 21:21:23 2001 From: zope at thewebsons.com (Ben Ocean) Date: Thu, 03 May 2001 18:21:23 -0700 Subject: Last Problem, I Think, In CGI Script: Please Help Message-ID: <5.0.2.1.0.20010503181124.00a657b0@thewebsons.com> Hi; I frame around a Web page from Kelley Blue Book on my car dealer's site. KBB has the visitor fill out a form. The data is then posted back to my car dealer's site via STDIN. I capture the data via cgi.FieldStorage(). I test to see if a certain variable of my own making is valid. If it is not, I raise a NameError exception and print to screen the data the visitor filled out in the form. Then I offer the visitor the opportunity to have this data sent back to the dealership or, conversely, printed to screen in a printer-friendly format. I do this by writing the data to a separate file at the same time as I originally post the data to the screen. The problem comes in when I try and retrieve the data from the file. When the visitor selects one of the aforementioned options, the variable of my own making for which I test (which the first time around threw the NameError exception) is set in STDIN in the URL and the same script is called. The page is printed to screen and the data is supposed to be read from the file I'd written, but for some reason it isn't! The data's in there, so what gives? Here's the part that's not working: >>> file = open("outfile.txt", "r") print file <<< Should work, right? Your help is appreciated. The entire file follows if you care to look for errors, although I've tested the rest and it appears to be in good, working order. TIA, BenO SCRIPT FOLLOWS... #!/usr/bin/python import cgi, os import string print "Content-type: text/html\n\n" form = cgi.FieldStorage() save = [] for i in form.keys(): v = form[i].value save.append(i + ": " + v + "\n") if form.has_key("token"): token = 1 data = string.join(save,"") data = string.replace(data, "%%", "
") data = string.replace(data, "PrintablePageHeading: ", "") data = string.replace(data, "
", "") data = string.replace(data, "\"Kelley", "") data = string.replace(data, "
", "") data = string.replace(data, "", "") array = string.split(data, "QueryWindowStatus") table = string.maketrans("`~@#$^&*+{}\|[]?", "----------------") _saver = string.translate(array[0], table) try: if token == 1: print " \n" print "\n" print "\n" print "\n" print "\n" print "\n" print "\n" print "\n" #print "\n" print "\n" print "\n" print " Your Vehicle \n" print "\n" print "\n" print "\"Blade\n" print "\"Home\"\n" print "\"Pre-Owned\n" print "\"Commercial\n" print "\"New\n" print "\n" print "\"New\n" print "\"New\n" print "\n" print "\"RV's\"\n" print "\"Service\"\n" print "\"Parts\"\n" print "\"Auto\n" print "\"Staff\"\n" print "\"Directions\"\n" print "\"Our\n" print "\"E-Mail\n" print "E-Mail Us!\n" print "Here's Your Vehicle!\n" print "\n" #print "

If you would like us to help you purchase this car, click here!
\n" #print "For a printable version, click here!

 
\n" print "\n" file = open("outfile.txt", "r") print file print "\n" print "\n" print "\n" except NameError: file = open("outfile.txt", "w") file.write(_saver) file.close() print " \n" print "\n" print "\n" print "\n" print "\n" print "\n" print "\n" print "\n" #print "\n" print "\n" print "\n" print " Your Vehicle \n" print "\n" print "\n" print "\"Blade\n" print "\"Home\"\n" print "\"Pre-Owned\n" print "\"Commercial\n" print "\"New\n" print "\n" print "\"New\n" print "\"New\n" print "\n" print "\"RV's\"\n" print "\"Service\"\n" print "\"Parts\"\n" print "\"Auto\n" print "\"Staff\"\n" print "\"Directions\"\n" print "\"Our\n" print "\"E-Mail\n" print "E-Mail Us!\n" print "Here's Your Vehicle!\n" print "\n" print "
If you would like us to help you purchase this car, click here!

\n" #print "
For a printable version, click here!

 
\n" print "\n" print _saver print "
\n" print "\n" print "\n" From aahz at panix.com Sat May 12 17:33:38 2001 From: aahz at panix.com (Aahz Maruch) Date: 12 May 2001 14:33:38 -0700 Subject: speedup up dictionary access References: Message-ID: <9dka7i$7vj$1@panix3.panix.com> In article , Roy Smith wrote: > >One of the big time consumers in an application I'm writing is a cache >lookup in the inner loop of the program. How do you know that? >I know that my cache hit ratio is going to be very high (almost 100%). >Would I do better writing it as: > > try: > if self.cache[name]: > do stuff > except KeyError: > if self.check (name): > do stuff That will be a tiny bit faster than the 'if', but not enough to make a difference if the cache lookup is really the problem. You should probably spend some time thinking about the work you're actually trying to accomplish and whether you're going about it the right way. -- --- Aahz <*> (Copyright 2001 by aahz at pobox.com) Androgynous poly kinky vanilla queer het Pythonista http://www.rahul.net/aahz/ Hugs and backrubs -- I break Rule 6 "I am not a helpless chained naked virgin who is going to be eaten by the dragon; I am a sexually mature feline-type-dragon who has chosen to live with the dragon." --SJM From tim.one at home.com Sun May 27 16:09:26 2001 From: tim.one at home.com (Tim Peters) Date: Sun, 27 May 2001 16:09:26 -0400 Subject: Compiling python extensions on Windows In-Reply-To: <3B115E7C.C70E4A8D@wag.caltech.edu> Message-ID: [Richard P. Muller, on Cygwin] > ... > (2) If not, I have access to several other build environments > (Codewarrior, Microsoft VisualStudios). Does anyone know which > environment was used to build Python2.1 on windows? You didn't say where you got Python2.1 from. Python 2.1 now ships with Cygwin (thanks to Jason Tishler); here from a straight recent Cygwin install: $ type python python is /usr/bin/python $ python Python 2.1 (#1, Apr 17 2001, 09:45:01) [GCC 2.95.3-2 (cygwin special)] on cygwin_nt-4.01 Type "copyright", "credits" or "license" for more information. >>> Try using that one. > Are there easy to follow instructions anywhere for the build > (I assume that "./configure" doesn't work on windows)? It does if you're building Python on Cygwin (but since they already do that for you, I'm not sure why you'd want to). If you're talking about the stock Windows Python distribution, you need to download the source distribution and read PCBuild/readme.txt: it comes with an MSVC project file for building Python under MSVC 6. I suspect your problems are due to mixing builds. If you're going to do Windows work under Cygwin, stick with the Cygwin stuff. If you're going to do Windows work under Windows, avoid the Cygwin stuff. From phd at phd.fep.ru Mon May 14 10:58:03 2001 From: phd at phd.fep.ru (Oleg Broytmann) Date: Mon, 14 May 2001 18:58:03 +0400 (MSD) Subject: Making a "deep" copy In-Reply-To: <3AFFEE8A.1DAF14D2@pad.zuken.de> Message-ID: On Mon, 14 May 2001 alex at pad.zuken.de wrote: > I've got a dictionary which contains lists and other dictionaries. > I want to create a real copy, but dict.copy() only copies the first > "layer". Is there a (fast) way to do this? You already mentioned "deep" copy! Just do copy.deepcopy(dict) :) Oleg. ---- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From maug at kopnet.gliwice.pl Thu May 31 14:48:12 2001 From: maug at kopnet.gliwice.pl (Marek Augustyn) Date: Thu, 31 May 2001 20:48:12 +0200 Subject: Iteration index Message-ID: <9f63lo$rb0$1@zeus.polsl.gliwice.pl> Hello! 1. Do I have to use additional variable when I want to know iteration index? Example: s = ('a', 'b', 'ala', 'a') i = 0 # additional variable for el in s: print i, el i += 1 2. Are there block comments in Python? (like /* */ in C) Regards, August From zope at thewebsons.com Tue May 1 13:01:50 2001 From: zope at thewebsons.com (Ben Ocean) Date: Tue, 01 May 2001 10:01:50 -0700 Subject: CGI Redirect In-Reply-To: <98442382882.20010501190033@buz.ch> References: <5.0.2.1.0.20010501094910.00a21b30@thewebsons.com> <5.0.2.1.0.20010501080840.00a01c50@thewebsons.com> <5.0.2.1.0.20010501080840.00a01c50@thewebsons.com> <5.0.2.1.0.20010501094910.00a21b30@thewebsons.com> Message-ID: <5.0.2.1.0.20010501095931.009ff360@thewebsons.com> At 07:00 PM 5/1/2001 +0200, you wrote: >-----BEGIN PGP SIGNED MESSAGE----- > >Hello Ben, > >Tuesday, May 01, 2001, 6:50:35 PM, you wrote: > >>This should work without the trailing semicolon in Python (assuming > >>that > >>nothing outputs any other headers before, of course!). > > Ah, yes, but in order to get the form to not toss up an HTTP 500 >server > > error I have to put in the following: > > > print "Content-type: text/html\n\n" > >Uuuh? Normally Content type and location headers shouldn't be mixed as >the first one will disable all the others... For me, Location alone >works (Apache 1.3.19). Here's my code. Can you tell me where I'm going wrong? (Everything gets replaced like it should, it's just the aforementioned error.) >>> #!/usr/bin/python import os, sys, cgi, string FormData = cgi.FieldStorage() print "Content-type: text/html\n\n" Disallowed = ['\nTo:', '\nCc:', '\nBcc:'] FormData = open("/apache/vhosts/bladechevy/New/test.html", "r") formstuff = "" while FormData.readline(): safe = string.maketrans("`|~!@#$%^&*()_+=:;{}[]", "----------------------") line = string.replace(string.replace(string.replace(string.translate(FormData.readline(), safe), "", ".") formstuff = string.join([formstuff,line]) FormData.close() # close the file import smtplib server = smtplib.SMTP("localhost") server.sendmail("beno at thewebsons.com", "beno at thewebsons.com", formstuff) server.quit() print "Location:http://bladechevy.com/" <<< TIA, BenO From othello at javanet.com Wed May 9 17:25:15 2001 From: othello at javanet.com (Raymond Hettinger) Date: Wed, 09 May 2001 17:25:15 -0400 Subject: Unification Idea Message-ID: <3AF9B5BB.505746B4@javanet.com> Complex numbers define: .real, .imag, and .conjugate(). I think we ought to define them for floats, ints, and longs also. arr = [ 2,10L, 5.1, 3+2j ] map( lambda z: z.conjugate(), arr ) # This is what I would like to do map( lambda z: type(z)==types.ComplexType and z.conjugate() or z, arr ) # vs. what I have to do now Raymond Hettinger ''' the more polymorphism, the better ''' From grumble at usa.net Tue May 29 14:11:48 2001 From: grumble at usa.net (jcm) Date: 29 May 2001 18:11:48 GMT Subject: parse-time optimizations References: <9ervav$qu9$1@news.mathworks.com> <9evasv$9u8$1@news.mathworks.com> Message-ID: <9f0op4$6b5$1@news.mathworks.com> Michael Hudson wrote: > Thing is, if you're writing code that benefits from constant folding - > WHY? If your code contains things like: > "a" + "b" > then you have bigger problems than Python's lack of optimizations... The example "a" + "b" was, of course, an example. Something like "some really long string (probably longer than this one) that I " + "can't quite fit onto one line in good conscience" would be more realistic. There's also the case where code is generated by another tool. Somewhat relatedly, I've seen C macros that generate expressions like 1 + 1 + 1 + 1 + 1 + 1 + 0 so there are instances where this sort of thing comes up. From scarblac at pino.selwerd.nl Wed May 30 09:40:27 2001 From: scarblac at pino.selwerd.nl (Remco Gerlich) Date: 30 May 2001 13:40:27 GMT Subject: Python Tutorial 4 Newbies? References: Message-ID: Peg Leg wrote in comp.lang.python: > I am absolutely brand new to programming and it was suggested to me that > Python would be the one to learn because of it's ease of use and power. Does > anyone know of any online tutorial or book that may be purchased that is > geared towards the village idiot? Any help is greatly appreciated. http://www.crosswinds.net/~agauld/ (now also available as a book) There's also the open book "How to think like a computer scientist" at http://www.ibiblio.org/obp/ Join the Python Tutor list for asking newbie questions, at http://www.python.org/mailman/listinfo/tutor/ -- Remco Gerlich From adjih at crepuscule.com Thu May 3 04:30:35 2001 From: adjih at crepuscule.com (Cedric Adjih) Date: 3 May 2001 08:30:35 GMT Subject: Surprising (for me) benchmark results... References: Message-ID: <9cr4vb$bk2$1@ites.inria.fr> I was ready to post an anwser to Daniel along the same lines, but you already did, so I've tried to found arguments for the opposite point of view :-) John J. Lee wrote: > On Wed, 2 May 2001, Daniel Berln wrote: > [...] >> Typically, an item is multiple bytes. Let's say the average english word >> is 5 characters ( I can't remember what the actual figure is). >> This would mean Disk accesses are O(n), Sorting is O(n/5 log n/5) where >> both n's are directly comparable. Once again, disk access clearly >> dominates. > > O(N/5 log N/5) = O(N log N) > > The constant factors etc. only affect the *point* at which disk access > becomes unimportant, not *whether* it does (assuming you can get to big > enough N without running out of memory). Very true. However the value of N necessary to compensate an fixed initial constant factor grows exponentially with this factor ; when comparing O(N) to O(N log N). For instance in order to compensate a factor 30, log N=30 would give N=10^13, which is somewhat big. Although a factor 10 is more likely to be offset (N ~= 20000). >> Until you are sorting a very large number of single byte items with >> quicksort, disk accesses will dominate. > > Yes, that may well be true. I don't know. > >> Now, this is even assuming disk accesses are O(n), which they aren't. > > They are O(N), but that doesn't mean that the time it takes is simply > proportional to N, does it? Or that there won't be some variation about > the O(N) behaiviour for small changes in N? > > I think we're just not using the same terminology. Rainer was just saying > that, for large enough N, disc access will not dominate (as long as > everything fits in memory). This is true. I think (correct me if I'm > wrong) you're saying that we won't get to that point before we run out of > memory. Or perhaps you're just saying that for some small N and small > change in N, the trend goes in the other direction, and in fact as N > increases disk access goes from being unimportant to being important. > These statements may or may not be true, I don't know. It seems unlikely > that O(N) could be too far wrong for if the storage required is close to > the amount of memory in your machine and N isn't too small, at least. Well actually file access is not necessary O(N). Linux for instance uses tree with depth=0, then tree with depth=1, then tree with depth=2, then tree with depth=3 to access the block number of a given block. Since IIRC you need a regular tree with depth = O(N) to access N elements, it could be argued file access is O(N log N). Of course since Linux and most implementations don't allow arbitrary deep trees, it becomes difficult to talk about O(N) or O(N log N) :-) And you could directly access the hard disk blocks. After all, it seems comparing O(1) and O(log N) is difficult in practice. -- Cedric From whisper at oz.nospamnet Sat May 5 14:17:52 2001 From: whisper at oz.nospamnet (David LeBlanc) Date: 5 May 2001 18:17:52 GMT Subject: PIL Gotcha maybe? References: <3AF02E83.844FA376@alcyone.com> <9gjuvwAJhE86EwUk@jessikat.demon.co.uk> Message-ID: <9d1g4g$708$1@216.39.170.247> I don't know if the square at the url given is still the one you're having trouble with, but on my 1280x1024x24bit "truecolor" display using IE 5.5, I see a plain green square surrounded by a thin white border - no appearance of mottling etc. Dave LeBlanc From fuess1 at home.com Sat May 19 10:05:10 2001 From: fuess1 at home.com (David Fuess) Date: Sat, 19 May 2001 14:05:10 GMT Subject: Python 2.0 quick reference... References: Message-ID: <2otcgt8u7km5ciff9b4jbj49kgmnvsl147@4ax.com> On 18 May 2001 20:58:41 GMT, kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) wrote: > I've encountered people who are hostile to it before (sometimes VERY >hostile, verging on religious jihad, as though the existence of a text >browser is somehow causing them direct physical harm), but this is the >first time I've seen someone who allegedly uses computers regularly who >didn't know what it was. --- RANT ALERT --- Now this is a point that has always confused me. Why on earth would anyone be hostile against something as benign as a piece of software? If you don't like it, don't use it. If something bad happens to your system when you use it then a) don't use it again, b) look at the developers, not the software for the cause. If I don't like a program, I give it no space on my system nor bandwidth in my thoughts. There are lots of things in this world to get religious about, but software just isn't one of them. And this includes the never ending OS wars! --- RANT OFF --- I do have fond memories of LYNX though. I remember wishing I could find a copy that would run on my DOS box because UNIX was too expensive to run at home. From ed_tsang at yahoo.com Fri May 4 17:21:39 2001 From: ed_tsang at yahoo.com (ed_tsang at yahoo.com) Date: Fri, 04 May 2001 21:21:39 -0000 Subject: Need suggestion on printing more meaningful traceback information ... Message-ID: <9cv6h3+tjgq@eGroups.com> hi: I am trying to execute a python function in file inc.py, from try.py. I also want this function execution can be turned on or off at try.py, without commenting any code or changing any code other than the ENABLE_ME flag. So I include a file pix.py that has a varable ENABLE_ME, which can be enabled or diabled, from file pix.py. Since the attached code is the simplified version, the opeation is not continuous and can't show the user to enable or diable some function execution at run time. My problem is I want to print the traceback information just in case something like: the function to be executed cannot be found in inc.py. Although I am able to print some info, it does not specify me the error is in inc.py instead it say from try.py during exec(cmd). This may mislead user that the try.py is the one in question. How can I point out the error is actually from inc.py??? Thanks Here is the attached code: file inc.py: def a(): print "A is executed\n" def b(): print "B is executed\n" file pix.py: from inc import * ENABLE_ME = 1 file try.py: try: import traceback, sys exec('import pix') exec('reload(pix)') if hasattr(pix,'ENABLE_ME') > 0: if pix.ENABLE_ME == 1: cmd = '%s.%s'%('pix','a()') exec(cmd) print "hihiht" cmd = '%s.%s'%('pix','b()') exec(cmd) cmd = '%s.%s'%('pix','c()') # deliberately call some nonexisting function to generate error exec(cmd) except SyntaxError: exc = sys.exc_info() traceback.print_exception(exc[0],exc[1],exc[2]) #traceback.print_exc() Results: A is executed B is executed Traceback (innermost last): File "try.py", line 15, in ? exec(cmd) File "", line 1, in ? AttributeError: c See the error is saying in exec(cmd) in try.py but the real problem is there is no function called c in inc.py .... :( I want to generalise this to include any type of error hapeend when executing functions in inc.py. Anyone? Thanks From zope at thewebsons.com Wed May 2 18:31:42 2001 From: zope at thewebsons.com (Ben Ocean) Date: Wed, 02 May 2001 15:31:42 -0700 Subject: Where O Where Did My Data Buffer Go? In-Reply-To: References: Message-ID: <5.0.2.1.0.20010502151843.00a41b30@thewebsons.com> 0At 09:54 PM 5/2/2001 +0000, you wrote: >"Ben Ocean" wrote in ... > > Hi, > > I'm trying (for several days now) to capture data in a data buffer and > > parse it. Someone suggested I use the *parse* functions in the cgi module > > (which include *parse_qs* and *parse_qsl*). Okay, great. Now, how do I get > > the freakin data buffer in there? In other words... > > parse_qsl(???) > > and I need to fill in the ??? It's not as easy as just tossing in *form* > > from this line: > > form = cgi.FieldStorage() > > So, what do I do? > > TIA, > > BenO > > >Ben: > >I should say the first thing you needed was a clue. I've responded to your >inquiries on the newsgroup and by email, without ever having any reply Really?? I thought I had gratefully responded to everyone that had helped me! Apologies. >, or >any indication that your insight into the problem had improved. >Are you simply stabbing around blindly, with no knowledge of the >architecture of the system you are trying to build a component for? What's >going on here? Asking the same question using five different wordings does >not enlighten the unenlightened :-) > >Where IS "the freaking data buffer"? We aren't mind readers (though some on >c.l.py do well at psychic debugging). Is the page you are framing from some >other site a form? I *have* made that fact perfectly clear in other posts, Steve. >If it is, then all it can send is CGI data, and the CGI >module will meet your needs. What else do you need to know? Um, maybe *how* to utilize the module? Try as I may, I haven't gotten it to spit out the data. That's why I asked above, what variable do I put into the parser to parse? And what kind of variable is it? A tuple? A dictionary? >We can't help you solve your problem until we understand it. Until *you* >understand it, that goal seems some distance off. Well, of course, that *is always* the problem with people who are new to programming. If you can remember back in the distant past when you were new to this, unless you were blessed to have someone there to teach you, well, it's a bitch, huh? You can be a little understanding, right? If you care to point out where this newbie's screwing up, here's the source code, such as it is. Your help (or anyone's!) is appreciated. TIA, BenO >>> #!/usr/bin/python import os, sys, cgi, string, htmllib, xdrlib print "Content-type: text/html\n\n" form = cgi.FieldStorage() Form = sys.stdin.read() formstuff = "" for i in range(len(Form)): FormData = sys.stdin.readline() safe = string.maketrans("`|~!@#$%^&*()_+=:;{}[]", "----------------------") line = string.replace(string.replace(string.replace(string.translate(FormData, safe), "",".") formstuff = string.join([formstuff,line]) FormData.close() # close the file import smtplib server = smtplib.SMTP("localhost") server.sendmail("beno at thewebsons.com", "beno at thewebsons.com", formstuff) server.quit() <<< From phd at phd.fep.ru Wed May 23 06:20:40 2001 From: phd at phd.fep.ru (Oleg Broytmann) Date: Wed, 23 May 2001 14:20:40 +0400 (MSD) Subject: problems using % in strings with %(var)s replacements In-Reply-To: Message-ID: On Wed, 23 May 2001, Thomas Weholt wrote: > I see the % in 50% is the problem but how can I use the %-char in strings > and still use %(...)s replacements?? %% Oleg. ---- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From aleaxit at yahoo.com Tue May 29 08:50:59 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 29 May 2001 14:50:59 +0200 Subject: Against PEP 240 References: Message-ID: <9f05tv01sca@enews2.newsguy.com> "Oleg Broytmann" wrote in message news:mailman.991135091.17843.python-list at python.org... > On Tue, 29 May 2001, Roman Suzi wrote: > > I wonder, why at all need such things? Are there any standard library for > > inf-precision in current Python version? If so, was it tested long > > enough? > > > > (If such standard library exists, please, remind me it's name. Thanks) > > mpz -- GNU arbitrary magnitude integers. This is a wrapper for GNU mp > (multiprecision) library. But what does it deliver (apart from speed -- maybe a few extra functions?) wrt Python's portable built-in "long"s? I wrapped GMP again (http://gmpy.sourceforge.net) to expose all functions, and the mpr (rationals) and mpf (floating point) as well as mpz (integer) unlimited-precision types. Alex From jmarshal at mathworks.com Tue May 8 17:37:29 2001 From: jmarshal at mathworks.com (Joshua Marshall) Date: 8 May 2001 21:37:29 GMT Subject: Three Minor Feature Requests for 2.2 References: <3AF85C2D.44AD7E8B@javanet.com> Message-ID: <9d9oup$irk$1@news.mathworks.com> Raymond Hettinger wrote: ... > 2. Amend the syntax for class definitions to optionally accept an empty > argument > list for superclasses. This comes up when adding and then later removing > mix-ins. In what way? Could you be more specific here? From ransen_spam_me_not at nemo.it Sun May 13 13:11:23 2001 From: ransen_spam_me_not at nemo.it (Owen F. Ransen) Date: Sun, 13 May 2001 17:11:23 GMT Subject: FileExists() in Python? Message-ID: <3afeb5b7.1138522@news.newsguy.com> What is the best style for writing a platform independent FileExists function? Using exceptions? -- Owen F. Ransen http://www.ransen.com/ Home of Gliftic & Repligator Image Generators From nospam at codegnome.org Wed May 16 04:54:56 2001 From: nospam at codegnome.org (Todd A. Jacobs) Date: Wed, 16 May 2001 01:54:56 -0700 (PDT) Subject: Stringify a list Message-ID: I have a list object that contains card values (i.e. 2-10, J, Q, K, A), but I can't seem to print the list in such a way that it doesn't appear as follows: [2, 6, 'A', 8, 'J'] I don't mind the commas, but how do I remove the quotes and brackets without going through contortions? -- Todd A. Jacobs CodeGnome Consulting, LTD From tim.one at home.com Sat May 19 01:34:30 2001 From: tim.one at home.com (Tim Peters) Date: Sat, 19 May 2001 01:34:30 -0400 Subject: Another dict method... In-Reply-To: <9e4uda$13fu0$1@ID-11957.news.dfncis.de> Message-ID: [Emile van Sebille, about the 2.2 dict.iteritems() iterator] > Yes. Can it retrieve them in sorted order? No. The order of retrieval is undefined. It's not magic, it's fast . The only sort gimmick of any kind in the language is list.sort(). > I also see a clear method. Is there an advantage in using it over simply > reassigning to a new {} ? dict.clear() clears the dict in-place, without creating a new object. Whether that's what you want depends on whether you want aliases (other ways of getting to the object besides via the name "dict") to see the effect of the clear too. From tim.one at home.com Mon May 7 22:44:12 2001 From: tim.one at home.com (Tim Peters) Date: Mon, 7 May 2001 22:44:12 -0400 Subject: Is this a bug? (__eq__, __lt__, etc.) In-Reply-To: Message-ID: [Edw88253] > The __eq__, __gt__, etc. methods seem to be called more often than > necessary when I compare two objects. Is this a bug or a feature? So long as you get the right answer, it's neither: it's an internal implementation detail. > (See transcript below) If it's a feature, what's it accomplishing? Sorry, but implementation details can be very tedious to explain. If you're curious enough, you can figure it out yourself from studying the source code. Generally speaking, A == B gives A.__eq__(B) a chance, then B.__eq__(A) a chance, then falls back to assorted ways of trying to deduce the correct result via legacy 3-way comparisons, incl. *simulating* 3-way comparisons via the __eq__ etc methods again. Since you define every relevant method but return NotImplemented from every one of them, you force Python to try every way to come up with a meaningful result it can think of, until it finally gives up and falls back to comparing by object address. > E.g., what are the semantics if __lt__(a,b) returns true the first > time and false the second time? This question didn't make sense, since the only __lt__ example you gave returned NotImplemented in every case. At a higher level, if you write comparison methods that return inconsistent results, you may get back inconsistent results -- but that shouldn't be surprising . Write a specific test case and observe what it does. > ... > I would appreciate it if you could cc responses to > edloper at gradient.cis.upenn.edu ... If that's what Edw88253 resolves to, you got it. From Bill.Scherer at VerizonWireless.com Wed May 23 10:07:29 2001 From: Bill.Scherer at VerizonWireless.com (Scherer, Bill) Date: Wed, 23 May 2001 10:07:29 -0400 (EDT) Subject: files via http In-Reply-To: <3B0BB901.594FB997@student.kuleuven.ac.be> Message-ID: Checkout websucker.py in Tools/webchecker in your Python tree. On Wed, 23 May 2001, Stijn Gunst wrote: > how can i download an entire website from a server via http. > those are ordinary sites which i can't telnet or ftp to. > i want to be able to specify a directory on a remote webserver into a > gui-frontend, push on a 'download'-button and get all the files and > subdirectories in that directory. > i don't know if it is possible, because this should be done over http > (no ftp- or telnet-access) > > anyone an idea? > > William K. Scherer Sr. Member of Applications Staff - Verizon Wireless Bill.Scherer_at_VerizonWireless.com From jepler at inetnebr.com Fri May 25 08:12:58 2001 From: jepler at inetnebr.com (Jeff Epler) Date: Fri, 25 May 2001 12:12:58 GMT Subject: automatically naming a global variable References: Message-ID: <900.3b0e4c4a.19bfc@localhost> On 22 May 2001 19:00:50 GMT, Remco Gerlich wrote: > Chad Everett wrote in comp.lang.python: >> If I have a string variable defined, how can I create a global >> variable with the same name as the string? >> >> For example: >> >> >>> x = "variable_name' >> >> Now I want to be able to use x to create a global variable whose >> name is 'variable_name' > > Can someone explain to me why this question comes up so often? > > (The answer is something like - this is a bad idea, use a dictionary). > > What use is a global variable that you don't know the name of, so you have > to use once more to get to its value? In some other languages, this is "how it's done". For instance, in TCL, there are "array" variables, which are names of the form array(key), and correspond roughly to Python dictionaries. To say "the value of ", you write "$name", where name is defined in the current scope. In tcl, arrays can only be passed by name .. For instance, one might write proc setitem { arrayname keyname value } { upvar $arrayname array set array(keyname) value } proc getitem { arrayname keyname } { upvar $arrayname array return $array(keyname) } setitem myarray 1 "hi there" puts $myarray(1) ;#prints "hi there" --- the "upvar" statement says "let me refer to the thing with the name of the first argument in the caller's scope when I use the name given in the second argument. Talk about gross! But, anyhow, I suspect it's for desire of something like "upvar" that people keep asking this question, although a similar idea probably exists in other languages. Jeff From lsloan at umich.edu Wed May 16 13:18:04 2001 From: lsloan at umich.edu (Lance E Sloan) Date: Wed, 16 May 2001 13:18:04 -0400 Subject: modifying vars() dictionary? Message-ID: <200105161718.NAA24640@birds.us.itd.umich.edu> In the documentation, it says about vars(): The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined. Why are the effects undefined? Why doesn't it always work to set a value for variable 'x' by assigning that value to the 'x' element of the dictionary from vars()? I've noticed that sometimes it works and sometimes it doesn't. In my small example it worked, but a colleague who asked me about this couldn't get it to work in a larger program. I assume that I'm just lucky mine worked and that his problem may have something to do with the size of the symbol table or the kinds of objects in it. -- Lance E Sloan Web Services, Univ. of Michigan: Full-service Web and database design, development, and hosting. Specializing in Perl & Python CGIs. http://websvcs.itd.umich.edu/ - "Putting U on the Web" From mwh at python.net Sun May 6 10:31:10 2001 From: mwh at python.net (Michael Hudson) Date: 06 May 2001 15:31:10 +0100 Subject: ANNOUNCE: pyrepl 0.5.0 (was: ANNOUNCE: Readline Alternative 1.2) References: <001701c0d5a5$ebc12e00$a100000a@local> Message-ID: writes: > Chris> Question: Is anyone interested in a port to Unix/Linux/BSD? That > Chris> is, are there many (indeed, any) users who hate the GPL badly > Chris> enough to rip out readline entirely? > > Yeah, I'm sure there are a few people. At least a few others will be > interested in something slightly smaller than readline. I think it's finally time to release my line reader I've been working on on and off for about a year now: pyrepl 0.5 (it used to be called pyrl, not that many people heard of it at all). I've been beating on it a bit in the last few weeks, and I think it's ready for a wider audience. Only tested on Linux; should work on unix in general (wherever termios and curses get built) and should be relatively easy to port to windows using /F's console library. It offers: * sane multi-line editing * history, with incremental search * completion, including displaying of available options * a fairly large subset of the readline emacs-mode keybindings (adding more is mostly just a matter of typing) * a new name (pyrepl) and a license (just the standard Python/MIT liberal one) * a new python top-level that I *really* like; possibly my favourite feature I've yet added is the ability to type ->> from __f and hit TAB to get ->> from __future__ then you type " import n" and hit tab again to get: ->> from __future__ import nested_scopes (this is very addictive!). * no global variables, so you should be able to run two independent readers without having their histories interfereing (haven't tested this too much, to be honest, but it should work). * Supports Python 2.0 and 2.1. There are still a few little bugs & misfeatures, but _I_ like, it and use it as my python top-level most of the time. > BTW, got a URL for your package? Mine's at: http://starship.python.net/crew/mwh/hacks/pyrepl.html Cheers, M. -- People think I'm a nice guy, and the fact is that I'm a scheming, conniving bastard who doesn't care for any hurt feelings or lost hours of work if it just results in what I consider to be a better system. -- Linus Torvalds From glen at enabledventures.com Wed May 23 13:13:06 2001 From: glen at enabledventures.com (Glen Starchman) Date: Wed, 23 May 2001 10:13:06 -0700 Subject: Python and Autoconf References: <3B0AACD0.654DE0A5@enabledventures.com> Message-ID: <3B0BEFA2.A284F44A@enabledventures.com> I am actually working on a whole suite of macros (listed below). None of them are terribly complex, but due to time constraints, I am only implementing them as a I actually *need* them. Any more idea? AC_CHECK_PYTHON -- returns path to the interpreter, sets PYTHON_PATH AC_PYTHON_LIB_PATH -- returns sys.path in a way sh can use it, sets PYTHON_LIB_PATH AC_PYTHON_VERSION -- sets PYTHON_VERSION to the, well, python version AC_PYTHON_CHECK_LIB -- given the name of a module (called lib to be in keeping with AC naming conventions), looks for it in PYTHON_LIB_PATH and cwd, sets PYTHON_HAVE_LIB_{MOD_NAME} AC_PYTHON_CHECK_BUILTIN -- given the name of a builtin, see if python was compiled with support for it, sets PYTHON_HAVE_BUILTIN_{BUILTIN} AC_PYTHON_CHECK_SHARED -- same as AC_PYTHON_CHECK_LIB but searches for shared libraries, sets PYTHON_HAVE_SHARED_{SHARED_MOD} AC_PYTHON_CHECK_ARG -- given a module name and a method, return the number of args a method expects. Sets PYTHON_ARGCOUNT_{METHOD}. Searches for module in PYTHON_LIB_PATH and cwd. AC_PYTHON_CHECK_METHOD -- given a module name and a method, checks if method is defined in module. Sets PYTHON_HAVE_{MODULE}_{METHOD} AC_PYTHON_CHECK_CLASS -- same as AC_PYTHON_CHECK_METHOD buts checks if a class named klass exists in module. Sets PYTHON_HAVE_{MODULE}_{KLASS} AC_PYTHON_CHECK_IMPORT -- checks if module1 imports module2. Sets PYTHON_{MODULE1}_IMPORTS_{MODULE2} AC_PYTHON_SOURCE -- searches for a Python source tree, and sets PYTHON_SOURCE_PATH AC_PYTHON_MOD_PATH -- given a module, return it's path. Sets PYTHON_{MOD_NAME}_PATH AC_PYTHON_TRY_COMPILE -- given a code block and a symbolic name, try to execute code block. Sets PYTHON_TEST_{SYMBOLIC_NAME} to true|false AC_PYTHON_EXT -- sets PYTHON_EXT to the extension python uses for files interpreted with the -O option. rs von Wedel wrote: > > Hi, > > Now, that's extremely useful. I'll give it a try during the next few > days. > > Lars > > > Anyway, hopefully someone finds these macros useful... I will > > (eventually) have them added to the autoconf repository. > Or to the Python distribution? > > > (for the uninitiated, you have to add these macros to a file called > > aclocal.m4 in the same directory as your configure.in script in order to > > use them in your configure.in) > Off-topic, but: can I add several .m4 files in a config subdirectory? > > A further idea might be to check the Python interpreter version and/or > to ensure some minimum version. Such as > > AC_PY_VERSION(2.0) > > Lars From MarkH at ActiveState.com Sun May 6 03:41:30 2001 From: MarkH at ActiveState.com (Mark Hammond) Date: Sun, 06 May 2001 07:41:30 GMT Subject: Small bug (assertion error) in PythonWin References: Message-ID: <3AF50083.6070901@ActiveState.com> Carlos Ribeiro wrote: > File "F:\Python21\Pythonwin\pywin\idle\PyParse.py", line 115, in set_str > assert len(str) == 0 or str[-1] == '\n' > AssertionError > > It was not a fatal error. Anyway, assertions are here to signal a > problem, isn't? My version information is: > > PythonWin 2.1 (#15, Apr 23 2001, 18:00:35) [MSC 32 bit (Intel)] on win32. > Portions Copyright 1994-2001 Mark Hammond (MarkH at ActiveState.com) - see > 'Help/About PythonWin' for further copyright information. Yeah - I occasionally get that too :( One of these days... :) Mark. From leodebeo at hotmail.com Thu May 10 18:15:19 2001 From: leodebeo at hotmail.com (LeoDeBeo) Date: Thu, 10 May 2001 22:15:19 GMT Subject: precompiled scripts? References: Message-ID: it is possible, actually in directories with python scripts you already have executed, the bytecodes of the python scripts will still be available. those are enough to run the application but the bytecodes are easy to disassemble, someone wilh a bit of python knowledge can easily turn the bytecodes into source code again. i figure that it's the same for tcl/tk and perl. it must be possible to disassemble them too. Ben wrote: > hi, > i need to write an applet but don't want the source to be visible. so i > need to know, wether it is possible to use a kind of precompiled binary of > a python script or not. i know, that it is possible with perl an tcl/tk, > but i'd better like to use python because of its graphical functions. > > thanx, > > ben > > p.s.: please reply also per pm to: > dietze at freepage.de > > From aleaxit at yahoo.com Mon May 21 04:37:03 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 21 May 2001 10:37:03 +0200 Subject: ease (was Re: Messaging in Py?) References: Message-ID: <9eak3d08ca@enews1.newsguy.com> "Kendall Clark" wrote in message news:aa03c0d9.0105201805.2bd5a19c at posting.google.com... ... > Seriously, while I agree that it's easy to write networking code > in Python, nothing's easier than finding out someone's already done > or started the project you need, and you can help out or adapt their Sometimes I wonder about this "apparently self-evident truth". Python makes certain kinds of tasks *SO* deucedly easy (this doesn't necessarily apply to the specific one being discussed here -- this is just a generic musing!-), that the temptation IS serious to just recode it and be done, rather than start looking for an already-almost-there solution out on the web. Which may be why we end up with so *MANY* modules solving the same (easy and not-so-easy) problems...:-). Alex From just at letterror.com Tue May 8 17:23:24 2001 From: just at letterror.com (Just van Rossum) Date: Tue, 08 May 2001 23:23:24 +0200 Subject: Absolute TO Relative URLs References: <9d9bf6$soo$1@bob.news.rcn.net> Message-ID: <3AF863CC.A2D90164@letterror.com> Satheesh Babu wrote: > Let us say I've an HTML document. I would like to write a small Python > script that reads this document, goes through the absolute URLS (A HREF, IMG > SRC etc) and replaces them with relative URLs. I can pass a parameter which > specifies the BASE HREF of the document. > > I'm not sure whether I should proceed with regex nightmare or are there any > easy solutions? > > Any help/pointers will be greatly appreciated. It's indeed pretty easy by deriving from SGMLParser. In case the absolute-to-relative url part of your question is still interesting: I was recently looking for exactly that functionality, couldn't find anything (apart from a sucky implementation in HTMLgen) so I wrote my own. See below. Just import string def abs2rel(src, dst): """Given two absolute paths, return the relative path from src to dst.""" src = string.split(src, "/") dst = string.split(dst, "/") for i in range(min(len(src), len(dst))): if src[i] <> dst[i]: break src = src[i:] dst = dst[i:] back = len(src) - 1 dst = back * [".."] + dst return string.join(dst, "/") if __name__ == "__main__": print abs2rel("/", "/sadfsdfd/foo.html") print abs2rel("/first/second/index.html", "/first/second/foo.html") print abs2rel("/first/second/index.html", "/first/second/third/foo.html") print abs2rel("/first/second/index.html", "/first/third/foo.html") print abs2rel("/first/second/index.html", "/bloo/blah/foo.html") print abs2rel("/first/second/index.html", "/first/second/index.html") From R.Brodie at rl.ac.uk Thu May 24 06:36:24 2001 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 24 May 2001 11:36:24 +0100 Subject: Making a dict from two lists/tuples References: <87u22bw197.fsf@womble.dur.ac.uk> <9eiljf$jg1$1@eising.k-net.dk> Message-ID: <9eio7a$vpm@newton.cc.rl.ac.uk> "Jonas Meyer Rasmussen" wrote in message news:9eiljf$jg1$1 at eising.k-net.dk... > for key,value in keys,values > dict[key] = value >>> dict {'foo': 'bar', 1: 2} How about: for key, value in map(None, keys, values): dict[key] = value From jflores at codeit.com Tue May 8 14:33:47 2001 From: jflores at codeit.com (Julio F. Schwarzbeck) Date: Tue, 08 May 2001 11:33:47 -0700 Subject: os independent temp dir? In-Reply-To: <3afa217e.5211036@news.newsguy.com> Message-ID: <5.1.0.14.2.20010508113105.00a27ad0@216.32.129.216> import tempfile tmpDir = tempfile.tempdir If TMPDIR os environment var is not set, None is return, works in Linux & Win afaik. At 05:06 PM 5/8/01 +0000, Owen F. Ransen wrote: >Hello All, > >Is there a Python way of finding the standard system >temporary directory ? I need to place a file there >with a specific file name. The function should work >in Mac and Windows... > >TIA > >Owen > >-- >Owen F. Ransen >http://www.ransen.com/ >Home of Gliftic & Repligator Image Generators >-- >http://mail.python.org/mailman/listinfo/python-list From bas.vangils at home.nl Wed May 30 03:59:22 2001 From: bas.vangils at home.nl (Bas van Gils) Date: Wed, 30 May 2001 09:59:22 +0200 Subject: random Message-ID: <20010530095922.A18313@cp68200-b> Good morning, For one of my classes (machine learning, actually) I'm going to do an experiment. One of the jobs that I should tackle is segmenting a dataset. The total set is 10000 items big. First I make a set of 1000 items, then 2000 etc etc.. Making this set is done by *randomly* extracting items from the big set. One of the things that I'm concerned about is this random-ness. My teacher (actually a nice guy :) explained to us that not all random-number-generators are "good", and that this selection process *must* *be* *random*. So, my question: how random is the random-number-generator that python uses? thank-you-in-advance-ly yours Bas -- Bas van Gils From costas at malamas.com Wed May 9 16:02:56 2001 From: costas at malamas.com (Costas Malamas) Date: Wed, 9 May 2001 23:02:56 +0300 Subject: Python in Windows Tray? References: <3AF935BA.20672.38FF9C1@localhost> <5.0.2.1.0.20010509154350.0245fa20@mail.inet.com.br> Message-ID: <001b01c0d8c3$0ee5fdf0$ef01010a@retek.com> Well, I'll be damned... didn't know that. Extremely cool. Thanks everybody, Costas > At 20:52 09/05/01 +0300, you wrote: > >Doesn't quite cut it; it leaves a console window behind... > > To close the console window just rename the script with the .pyw extension. > There are two versions of the intrpreter in the Windows distro; PYTHON.EXE > leaves the console window open, PYTHONW.EXE doesn't. And the extension .pyw > is bound to PYTHONW.EXE, so it's that easy. > > > Carlos Ribeiro > > > From m.hadfield at niwa.cri.nz Wed May 23 17:40:41 2001 From: m.hadfield at niwa.cri.nz (Mark Hadfield) Date: Wed, 23 May 2001 21:40:41 +0000 (UTC) Subject: python... References: <3B0CB69A.7DDB322@student.gu.edu.au> Message-ID: <00b901c0e3d1$0237b850$d938a8c0@Hadfield> From: > Main difference? One of the most friendly newsgroups on the web. >... Though a little smug at times. --- Mark Hadfield m.hadfield at niwa.cri.nz http://katipo.niwa.cri.nz/~hadfield National Institute for Water and Atmospheric Research -- Posted from clam.niwa.cri.nz [202.36.29.1] via Mailgate.ORG Server - http://www.Mailgate.ORG From hinsen at cnrs-orleans.fr Thu May 31 04:51:19 2001 From: hinsen at cnrs-orleans.fr (Konrad Hinsen) Date: 31 May 2001 10:51:19 +0200 Subject: Against PEP 240 References: Message-ID: "Tim Peters" writes: > That's "merely" a factor of 60 (5*24/2). WRT simulating decimal f.p., the > FAQ at http://www2.hursley.ibm.com/decimal/ claims: > > emulation is 100 to 1000 times slower than a hardware > implementation could be That should be much less in Python, as times for standard binary FP are dominated by the interpreter overhead. [coercion] > There's no problem of that nature that I know of for any builtin numeric > type. If you're talking about user-defined types, then a and b both get a > chance at doing coercion, left operand first; they're expected to follow the > builtin types in doing so consistently and predictably, but Python can't In practice, most user-defined types make sure they interact well with the built-in types, but they can't possibly cope with all other user-defined types out there in a reasonable way. And I am rather sure that many user-defined types would not behave appropriately when new built-in types appear. Moreover, with the proposed addition of a rational and/or arbitrary precision BCD type, it is not clear what the coercion rules between this and the standard float type should be. If the BCD types becomes "higher" and is the default for float constants, it will be almost impossible to do complex float calculations. If floats are declared higher-up in the coercion order, the the precision-conscious BCD people are in for bad surprises. -- ------------------------------------------------------------------------------- Konrad Hinsen | E-Mail: hinsen at cnrs-orleans.fr Centre de Biophysique Moleculaire (CNRS) | Tel.: +33-2.38.25.56.24 Rue Charles Sadron | Fax: +33-2.38.63.15.17 45071 Orleans Cedex 2 | Deutsch/Esperanto/English/ France | Nederlands/Francais ------------------------------------------------------------------------------- From aahz at panix.com Thu May 24 12:02:11 2001 From: aahz at panix.com (Aahz Maruch) Date: 24 May 2001 09:02:11 -0700 Subject: threads References: Message-ID: <9ejba3$ek5$1@panix6.panix.com> In article , lrobb wrote: > >I have a global timer thread that cycles an event every 20 minutes. >When I stop the program via (Ctrl-C), this thread doesn't die. >How can I stop him? David Bolen gave you some good responses. If you want the timer thread to clean up faster, it should check its event queue more frequently, perhaps once every ten seconds. (In the grand scheme of things, this will add a miniscule load to your program.) -- --- Aahz <*> (Copyright 2001 by aahz at pobox.com) Androgynous poly kinky vanilla queer het Pythonista http://www.rahul.net/aahz/ Hugs and backrubs -- I break Rule 6 "You do not make history; you can only hope to survive it." --G'kar From usenet.2001-05-08 at bagley.org Tue May 8 19:20:26 2001 From: usenet.2001-05-08 at bagley.org (Doug Bagley) Date: 08 May 2001 18:20:26 -0500 Subject: Language comparisons References: <3AF801A4.BE4562D1@philips.com> Message-ID: "Nick Perkins" writes: > It seems that these tests are a bit unfair. > The test specifies that each program must work > 'in the same way'. The tests are specified as > algorithms, and tests of specific little operations. Some are specified that way on purpose, as I explain on this page: http://www.bagley.org/~doug/shootout/method.shtml#sameway I feel that it is interesting to compare languages this way, you're certainly entitled to feel otherwise. > A true 'shootout' would specify a 'goal', > a correct output, and not specify an algorithm. And I do have some tests written this way too. If you want to propose a new test that you feel would be more fair, then by all means please do so. > Also, the tested source code is not published. It certainly is. Please click on the language name link in the table on each test index page. For example: http://www.bagley.org/~doug/shootout/bench/wordfreq/wordfreq.python > I bet that if the tested Python code were > posted on this ng, we could speed it up a bit > (or a lot) Please send your contribution! I'll happily include any improvements. Thanks. Cheers, Doug From phd at phd.fep.ru Thu May 24 12:30:45 2001 From: phd at phd.fep.ru (Oleg Broytmann) Date: Thu, 24 May 2001 20:30:45 +0400 (MSD) Subject: Spam handling (was Re: WWW.FNORB.COM) In-Reply-To: <9ejbo1$g05$1@panix6.panix.com> Message-ID: On 24 May 2001, Aahz Maruch wrote: > > SpamCop.net did a good job for me about this message. > > You can't be sure of that. If the original message used false headers, > the netnews spam will contain the false headers. It seems you've never tried SpamCop! It does amazing job digging real information from even false headers!!! Oleg. ---- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From jkraska1 at san.rr.com Sun May 13 23:41:20 2001 From: jkraska1 at san.rr.com (Courageous) Date: Mon, 14 May 2001 03:41:20 GMT Subject: Python and Ruby , object oriented questions References: <3AFDFC02.29C58D14@earthlink.net> <87y9s0fvyo.fsf@litterbox.meowing.net> Message-ID: >I've found all along that the more languages I play with, the easier >it becomes to play with yet more of them. Do others find it works out >differently for them, that carrying more than one language around just >makes a mental mishmash of the others? No, but on a daily basis switching from one language to the next I make _all kinds_ of syntax errors. For example, this doesn't work very well in Java or C++, and yet I do it all the time, danggonnit, Python! MyObject o = MyObject(); I generally adjust after a few minutes of cursing. :-) Python is the _One True_ of programming languages, I tell you! :-) C// From duncan at NOSPAMrcp.co.uk Wed May 2 10:42:46 2001 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 2 May 2001 14:42:46 +0000 (UTC) Subject: ZODB binary for Win32? References: <9cp20a$o0m$1@usenet.otenet.gr> Message-ID: "Costas Malamas" wrote in <9cp20a$o0m$1 at usenet.otenet.gr>: > Hi all, > > I am interested in playing with ZODB of Zope fame, but I donot have a > unix machine handy or a VC++ compiler on my NT laptop. Is there any > ready-made binaries for ZODB for Windows (NT/2k?) Couldn't find > anything on the ZODB pages or the web. I am also wondering if I could > 'extract' it from Zope. Any thoughts? > > Thanks, > > Costas Malamas > Install Zope from the normal windows binary distribution, no need to actually run it though. Set PYTHONPATH to point to the zope installation: e.g. set PYTHONPATH=\zopedir\lib\python run Python 1.5.2: \zopedir\bin\python.exe and import ZODB >>>import ZODB -- 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 BPettersen at NAREX.com Wed May 2 11:50:37 2001 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Wed, 2 May 2001 09:50:37 -0600 Subject: PEP 234: Iterators Message-ID: > From: Just van Rossum [mailto:just at letterror.com] > Roman Suzi wrote: > > > > On 2 May 2001, Michael Hudson wrote: > > > > >"Peter Caven" writes: > > > > > >> I really like the idea of returning different kinds of > iterators for > > >> dictionaries as described: > > >> > > >> > for key, value in dict.iteritems(): ... > > >> > for value in dict.itervalues(): ... > > >> > for key in dict.iterkeys(): ... > > > > > >Me too. > > > > What about xitems, xvalues, xkeys (as in xrange?) > > Please read the PEP: iterators largely make these redundant. > Eg. dict.iteritems() > doesn't return a list of items (we already have dict.items() > for that) but an > _iterator_, allowing you to iterate over the items _without_ > creating a list > containing them all... Perhaps it's only a matter of naming? How about itemIterator(), valueIterator(), etc (or itemiter() if you don't like camelcase) -- bjorn From rnd at onego.ru Thu May 10 07:38:38 2001 From: rnd at onego.ru (Roman Suzi) Date: Thu, 10 May 2001 15:38:38 +0400 (MSD) Subject: Range Operation pre-PEP In-Reply-To: Message-ID: On Thu, 10 May 2001, Fredrik Lundh wrote: > Roman Suzi wrote: > > > > > done much python training lately, or are you just making > > > > Yes. I taught programming classes a year ago. > > That is where I had some trouble with for-loops. > > and you don't think you can adjust the training material to cover > lists and functions briefly (from a use, don't create perspective) > before going into details about what for-in really does? > > adding inconsistencies to the language to work around a problem > someone once had when explaining the current situation doesn't > sound that appealing... There is no demand for syntactically supported ranges? > Cheers /F > > > Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From english at spiritone.com Wed May 30 02:04:29 2001 From: english at spiritone.com (Josh English) Date: Tue, 29 May 2001 23:04:29 -0700 Subject: Help with Tkinter and MacPython References: <3B140FA6.C16FFE33@spiritone.com> <9f1caf$eue$1@nntp6.u.washington.edu> Message-ID: <3B148D6D.37789E0E@spiritone.com> "Russell E. Owen" wrote: > Also, there are at least two standard gotchas, both well documented in > the ReadMe: > - All versions of MacPython require you to drop a script on > PythonInterpreter. Never try to run Tk scripts in Python IDE! I haven't found that in the Read Me files, but it works. Thanks. Josh English english at spiritone.com From nperkins7 at home.com Sat May 26 01:39:55 2001 From: nperkins7 at home.com (Nick Perkins) Date: Sat, 26 May 2001 05:39:55 GMT Subject: Long names are doom ? References: <3B0EEAE7.FAD87BD@aol.com> Message-ID: ThereMustBeABetterWayThanThis this_is_more_readable_but_harder_to_type thisistheworstofbothworlds hmm.. what if you wanted to name, say, a function with a string so that you could include spaces? fn={} def f(): blah.. blah.. fn['my special function']=f ... # call function fn['my special function']() ...just a silly idea. ok, i'll go to bed now. From tim at bladerman.com Tue May 29 15:50:28 2001 From: tim at bladerman.com (Tim Gahnström /Bladerman) Date: Tue, 29 May 2001 19:50:28 GMT Subject: Spatial Python, anyone? References: <9etvu4$1g1$1@tyfon.itea.ntnu.no> Message-ID: <84TQ6.5940$Yu6.1374589@newsc.telia.net> "Magnus Lie Hetland" > (For those who wonder: Spatial Access Methods are > about storing/retrieving multi-dimensional points > and/or regions. Can also be useful in indexing > other kinds of objects like sequences etc.) I see there is not a whole lot of answers to your message. I dont no nothing about Spatial but I have a little suggestion anyway. Since you didnt get much response here I think it might be better of asking this question in a Spatial group or in an advanced algorithms groop where the percentage of posters use these things. Another suggestion is that even if you will have to do the project yourself. Put it up on sourceforge anyway (if it is not to much work, i dont know that) then you might atrackt someone in a later stage or atleast get a few other users wich might generate a little ego boost :-) Tim From robin at jessikat.fsnet.co.uk Wed May 2 13:47:53 2001 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 2 May 2001 18:47:53 +0100 Subject: PIL Gotcha maybe? References: <3AF02E83.844FA376@alcyone.com> Message-ID: <9gjuvwAJhE86EwUk@jessikat.demon.co.uk> In article , Fredrik Lundh writes >Robin Becker wrote: >> >It looks dithered. I presume that by default the GIF PIL plugin uses >> >the Web palette; your color isn't exactly represented in that palette, >> >so it's dithering it in the output. >> > >> I thought so too, but dithering isn't done to BMP, TIFF etc and I've no >> idea how to turn it off. > >BMP, TIFF, etc support 24-bit truecolor images ("RGB"). >GIF doesn't, so it converts the image to "P" on the way >out. > >adding this line before im.save might work (untested): > > im = im.convert("P", dither=Image.NONE, palette=Image.ADAPTIVE) > >Cheers /F > > That seems much better and even my anti-aliased images are reasonable. I guess they'll use up my colours pretty quickly. Is there any docco for the various palette/dither controls? -- Robin Becker From lac at cd.chalmers.se Thu May 31 09:36:11 2001 From: lac at cd.chalmers.se (Laura Creighton) Date: Thu, 31 May 2001 15:36:11 +0200 (MET DST) Subject: I had a thought ... (I know, call the newspapers). Message-ID: <200105311336.PAA29932@boris.cd.chalmers.se> Lets give python a new type. We will call it money. And we will tell people to use that. And under float, we will suggest strongly that people are most likely to want to use the type money rather than float. And we will document the behaviour of float. And we will strongly suggest that people who do not know what to use, use money. Indeed we can say that `floating point is servere black magic used by people who really know exactly how to deal with the sort of errors caused by 1.999999996 not really being 2.0. If this does not sound like you, do not use floating point.' And we can use the ? (This is a Euro sign for those of you using the wrong font.) This will show off that we have Unicode, which is cool and remind the Americans that there are non-Americans on this planet, which is cool for another reason. And all of us that use real floats will not have to do a thing. In 20 years I have had 0 luck teaching people to not use floating point for money. The fools carefully ignored me and went back to their old vile ways most of the time. They can't tell the difference between floating point and fixed and they don't listen when you tell them and they don't remember what you said at lunch time. the good ones ask `which was the fixed point, again?' and the bad ones just say `fixed? floating? No I am sure you never mentioned those words this morning.' I wanted the default to change because I did not think that it was ever possible to teach most people about floating point because `nothing' is precisely how much they want to know about it with a near religious furvor. I wanted the default behaviour to change so that these people can't screw up their lives, my life, everybody's life too much. **********BUT*********** I am almost convinced that I can teach them to use the type money, a slower, more accurate type that accurately represents money and other valuable things that must not have floating point error in them. I'd like to run some tests first, and drat, the students are all writing exams or on vacation so I don't have a handy supply of victims. Is this a good idea? Or I am just deleriously happy because my friend Anders Hammarquist, the person who told us to use python and who has been using it since 1.4 has stopped being a full time physics grad student who can't come over to my house for dinner let alone write code with me and has gone back to being another founder of this company? Wow how the code gets fixed now, and he knows all the current coolest tricks in physics too. I'm happy enough to be crazy for sure. But is the idea any good? Laura From aleaxit at yahoo.com Wed May 30 03:19:52 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 30 May 2001 09:19:52 +0200 Subject: Against PEP 240 References: <9f03m401qcu@enews2.newsguy.com> <9f0ha4029t6@enews2.newsguy.com> <9f16bs07h2@enews2.newsguy.com> Message-ID: <9f273e41ar5@enews2.newsguy.com> "Robin Becker" wrote in message news:i2aJ6WAI3CF7Ew7I at jessikat.fsnet.co.uk... ... > >And would that improve your quality of life noticeably when > >compared to the I(1,2) notation for the same thing that you can > >already use today...? > ... > the same argument applies exactly to rationals. No it doesn't. You're comparing (1,2)I versus I(1,2) -- ALL that changes is the ordering of the SAME, IDENTICAL tokens. Having 7.35 MEAN 7.35 rather than 7.3499999999999996 is an issue of another conceptual order of magnitude, except to people who have already been "brainwashed" by experience. Having to write, e.g., 7.35r to mean 7.35, while unadorned 7.35 means 7.3499999999999996, is perverse, impossible to justify to newcomers except by such handwaving as "the computer being unable to deal with it" (utter hogwash, of course, and newbies aren't stupid -- they see through such cover-ups), and reminiscent of "hazing" in fraternities as far as the appeal to "tradition" goes. I'm not sure 7.35 should BE a _rational_, rather than a decimal (a la Cowlishaw) -- rational might be most useful to ME, but then, I should be among those experienced enough to see some decoration needs as quite acceptable. To a newcomer, decimal might be preferable. I'm quite willing to listen to pro's and con's of each possibility (not that it would do anybody much good -- _Guido_ has better be the one listening:-), and have not made up my mind (the ABC experience does suggest that rationals-by-default has some serious pitfalls, if I understand that correctly). But to have unadorned 7.35 mean 7.3499999999999996 forevermore, *THAT* is what I've come to see as unconscionable (after just a few attempts teaching to newbies...). Alex From tim.one at home.com Wed May 2 19:07:23 2001 From: tim.one at home.com (Tim Peters) Date: Wed, 2 May 2001 19:07:23 -0400 Subject: Threads problem: the limbo_lock is making me cry In-Reply-To: <9cq0nm$mhk$1@slb2.atl.mindspring.net> Message-ID: [posted & mailed] > Obligatory disclosure: I'm using Py2.0 on Win2K Try Python 2.1 and see whether it persists. > ... > MainThread: <_ServerThread(Thread-2, stopped)>.join(): thread stopped > Unhandled exception in thread: > Traceback (most recent call last): > File "c:\python20\lib\threading.py", line 392, in __bootstrap > self.__delete() > File "c:\python20\lib\threading.py", line 401, in __delete > _active_limbo_lock.acquire() > AttributeError: 'None' object has no attribute 'acquire' MainThread does a .join() on all other (non-daemon) threads when Python is shutting down. This is arranged via an exit handler: atexit.register(self.__exitfunc) in threading._MainThread.__init__. 2.1 fixed some race conditions here (both in atexit.py, and in Python's shutdown sequence). > This problem appears to go away if I include a time.sleep(1) after > the end of the GUI event loop (when this ends, the program stops). Says "race condition" to me -> try 2.1. > I figure that I must be doing something stupid to see problems with > _active_limbo_lock at all Probably not your fault: "it's impossible" for _active_limbo_lock to be None, as it's set to a non-None value during threading.py's initialization. Therefore, if you're seeing a None value at shutdown, it's most likely that Python has somehow managed to tear down the threading module before the exit handler has managed to run. It's also possible that some other component is your app is "illegally" calling into Python after Py_Finalize() was called. But that could be very difficult to track down, so, again, try 2.1 first. From nessus at mit.edu Thu May 10 18:17:36 2001 From: nessus at mit.edu (Douglas Alan) Date: 10 May 2001 18:17:36 -0400 Subject: Range Operation pre-PEP References: <3AF8D070.B0ECF09A@my.signature> <9db0u6018es@news2.newsguy.com> Message-ID: Ben Hutchings writes: > Lists also have count() and index() methods, which tuples do not. > Doesn't this suggest a difference in intended purpose to you? I also see that tuples support "in" and "+" and "*" and slicing and len() and min() and max(). In light of this, it seems that the fact that they are missing count() and index() should only been seen as an unfortunate oversight. >>> Tuples are like data structures or product types in other >>> languages, except that their types and fields are nameless. >>> Comprehensions work with a variable number of homogeneous values, >>> so they produce lists. > > filter() on a tuple returns a tuple. The length of the tuple cannot > > be known in advance. > Presumably filter() only requires its argument to be a sequence. Yes, if its sequence argument is a tuple, then it returns a tuple. If you were right, you should never want to run filter on a tuple, and if you were so foolish to use filter() on a tuple, it should return a list to show you the errors of your ways. Or actually, tuples shouldn't be sequences at all, since you should never treat a tuple as a sequence, rather than just as a record. |>oug From aahz at panix.com Fri May 11 01:55:57 2001 From: aahz at panix.com (Aahz Maruch) Date: 10 May 2001 22:55:57 -0700 Subject: Why aren't we all speaking LISP now? References: Message-ID: <9dfutd$hr1$1@panix6.panix.com> In article , Tim Roberts wrote: >"Delaney, Timothy" wrote: >> >>Indeed, the point of teaching bubblesort is to teach *not to use* >>bubblesort. > >I would have said "...to teach WHEN not to use bubblesort." There have >been many times I needed to sort a list in some throaway utility when I >knew the list was going to be limited in size. I KNOW I can write a >bubblesort or insertion sort and get it right. I'd have to look up and >debug a quicksort or a heapsort. Except now you use Python, right? -- --- Aahz <*> (Copyright 2001 by aahz at pobox.com) Androgynous poly kinky vanilla queer het Pythonista http://www.rahul.net/aahz/ Hugs and backrubs -- I break Rule 6 "Everyone is entitled to an *informed* opinion." --Harlan Ellison From rnd at onego.ru Mon May 21 07:05:59 2001 From: rnd at onego.ru (Roman Suzi) Date: Mon, 21 May 2001 15:05:59 +0400 (MSD) Subject: Nicier code for this? Message-ID: Hello! I know exec is not very nice, but I am not sure if something better exists for the following: fake, v = {}, {} exec """from mod_%s import func""" % modname in fake, v return v["func"](args) Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From fredrik at pythonware.com Thu May 3 03:29:32 2001 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 03 May 2001 07:29:32 GMT Subject: doctest or pyunit? References: Message-ID: Tim Peters wrote: > So for *simple* things, unittest puts a lot of artificial constructs between > what you're trying to test and getting it tested. OTOH, tests that require > repeated setup and teardown get real tedious real fast to write in doctest > format: since doctest is WYSIWYG, you have to show every step of every > test explicitly in the string. OTOH, creating a setup/teardown framework for your test scripts isn't that hard. here's a variant of the doctest-for- unit-testing driver I use: import doctest test = ["myfirsttest", "mysecondtest", ...] for mod in tests: try: mod = __import__(mod) except ImportError, v: print "***", "skipping", mod, "(%s)" % v continue if hasattr(mod, "setup"): mod.setup() doctest.testmod(mod, report=0) if hasattr(mod, "teardown"): mod.teardown() status = doctest.master.summarize() if status[0]: print "*** %s tests of %d failed." % status else: print "%s tests passed." % status[1] under this driver, an optional "setup" function can be used to initialize a test environment (in global variables), and "teardown" can be used to clean up after the test. Cheers /F From costas at meezon.com Mon May 21 18:12:38 2001 From: costas at meezon.com (Costas Menico) Date: Mon, 21 May 2001 22:12:38 GMT Subject: Python 2.0 quick reference... References: Message-ID: <3b099277.362532593@News.CIS.DFN.DE> On Wed, 16 May 2001 14:55:23 +0100, Simon Brunning wrote: >> On Wed, 16 May 2001, Simon Brunning wrote: >> > ... now available from >> > . >> > >> > Inaccuracies, omissions and any other comments should be reported to me >> at >> > . A version 2.1 quick reference is on its way... >> >> Very nice, thank you! But please, can you make it not so big? Split to >> pages? And/or put short description unto >> http://www.brunningonline.net/simon/python/ > >Splitting the quick reference into separate pages would be a good idea. I'll >probably do that while updating for Python 2.1. I'll also look at cleaning >up the format a bit. > >I will also be putting up an index page, but I only bought the domain a >couple of days ago, and I haven't had the time as yet. Please do not split. I would prefer not to have 20 pages to downoad and save on my system. Either way most people would agree that its not that huge. But if you do, can you also make a downloadable zip file? Thanks costas From paulp at ActiveState.com Tue May 29 12:00:44 2001 From: paulp at ActiveState.com (Paul Prescod) Date: Tue, 29 May 2001 09:00:44 -0700 Subject: Active State and the PSF References: Message-ID: <3B13C7AC.AC313839@ActiveState.com> Jim Abrams wrote: > > I faintly remember a friend of mine at Sapient extolling his woes as having > to use Tcl as an embedded language for some project of his. He was mostly > upset that he couldn't use Perl because of the GPL would require that some > portions of the project remain free? Perl comes under two licenses. One is the GPL. The other is very liberal. He could have used Perl under the other license. But you were still right to encourage him to use Python for other reasons. > This was where I pushed Python on him (of which he and other Sapient folk > have converted), but the question I am getting at is: > > Forgive my lazyiness in not deciphering the GPL, but does the GPL put some > legal restriction of the use of GPL'ed widgets in commerical widgets? Python is not licensed under the GPL or anything remotely like it. > Will the new Python license uphold the 'free to do just about anything' feel > is has now? Yes. http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/LICENSE -- Take a recipe. Leave a recipe. Python Cookbook! http://www.ActiveState.com/pythoncookbook From u42480468 at spawnkill.ip-mobilphone.net Thu May 3 06:06:30 2001 From: u42480468 at spawnkill.ip-mobilphone.net (u42480468 at spawnkill.ip-mobilphone.net) Date: Thu, 03 May 2001 10:06:30 GMT Subject: Debugging multithreaded Python application Message-ID: Hi, we are developing some CORBA application, and using Python to implement clients and thin servers (e.g. providing callbacks for the central server). Now, I'm stuck with some dead-locking problem. I'm not sure on which side is the problem? On the client side which uses omniORB and Python or on the server side uses VisiBroker and Java? I tried to check the thread states when Python client gets blocked but I can see only the main thread with pdb. Is there any way to check tracebacks for Python threads? I would like a tool like "jdb" for Java with a "threads" command! No fancy GUI is needed! Any help appreciated, Somogyi Balazs -- Sent by bikapocs from hotmail piece of com This is a spam protected message. Please answer with reference header. Posted via http://www.usenet-replayer.com/cgi/content/new From ron.l.johnson at home.com Fri May 11 13:48:30 2001 From: ron.l.johnson at home.com (Ron Johnson) Date: Fri, 11 May 2001 17:48:30 GMT Subject: Does "server" asyncore need to use asynchat?? Message-ID: Hello, All the examples that I've seen at www.nightmare.com and in the Medusa source code that use asyncore also use asynchat. Are there any examples of asyncore-without-asynchat? Sincerely, Ron -- Ron Johnson, Jr. Home: ron.l.johnson at home.com Jefferson, LA USA http://ronandheather.dhs.org "Is Python better or worse than Perl?" "Perl is worse than Python because people wanted it worse." -Larry Wall, 10/14/1998 From rob at jam.rr.com Wed May 30 07:22:55 2001 From: rob at jam.rr.com (Rob Andrews) Date: Wed, 30 May 2001 11:22:55 GMT Subject: Python Tutorial 4 Newbies? References: Message-ID: <3B14D721.922BDF8F@jam.rr.com> Peg Leg wrote: > > I am absolutely brand new to programming and it was suggested to me that > Python would be the one to learn because of it's ease of use and power. Does > anyone know of any online tutorial or book that may be purchased that is > geared towards the village idiot? Any help is greatly appreciated. > Peg Leg I try to make the list of tutorial links at Useless Python quite thorough. You should find quite a bit of brain candy there. http://www.lowerstandard.com/python/tutoriallinks.html Rob -- Useless Python! It's the right thing to do. http://www.lowerstandard.com/python/index.html From jason-dated-989633005.80347c at mastaler.com Thu May 3 22:03:25 2001 From: jason-dated-989633005.80347c at mastaler.com (Jason R. Mastaler) Date: Thu, 3 May 2001 20:03:25 -0600 Subject: Windows editor? In-Reply-To: ; from vanevery@3DProgrammer.com on Fri, May 04, 2001 at 01:21:48AM +0000 References: Message-ID: <20010503200325.A9156@mastaler.com> Brandon J. Van Every writes: > What's a good Python editor for programming under Windows, specifically > Windows 2000? XEmacs. The best editor on any platform. -- (TMDA - http://tmda.sourceforge.net) (Python-based SPAM reduction system) From thomas.heller at ion-tof.com Thu May 17 15:46:20 2001 From: thomas.heller at ion-tof.com (Thomas Heller) Date: Thu, 17 May 2001 21:46:20 +0200 Subject: win32com: gencache problem References: <3B0401EB.F00F4F6@web.de> <9e18u4$i935$1@ID-59885.news.dfncis.de> Message-ID: <9e19tg$jkcq$1@ID-59885.news.dfncis.de> I wrote: > ... Mark's testExplorer.py script (in win32com\test) builds out of > the box and without any special arrangements in the build process. > The first part using dynamic dispatch (the TestExplorer function) > works like a charm, the TestExplorerEvents function fails because it > needs the makepy generated support which is not automatically included > into the exe-file. I just checked in a fix for py2exe so that you can give a wildcard to the -i option (which specifies additional modules to include). With this fix you can add '-i win32com.gen_py.*' to the py2exe command line and include all the makepy generated modules into the executable. You better make sure that it does not contain too much... Thomas From emile at fenx.com Sun May 27 14:33:02 2001 From: emile at fenx.com (Emile van Sebille) Date: Sun, 27 May 2001 11:33:02 -0700 Subject: Powersets of a list? References: <9els3j$2kap$1@ID-11957.news.dfncis.de> <9em0l10kdt@enews1.newsguy.com> <3b0fabc2.5506652@nntp.sprynet.com> <9eorfa0kj1@enews2.newsguy.com> <3b11015c.2099508@nntp.sprynet.com> Message-ID: <9erhh8$stmj$1@ID-11957.news.dfncis.de> "David C. Ullrich" wrote in message news:3b11015c.2099508 at nntp.sprynet.com... > On Sat, 26 May 2001 20:09:20 +0200, "Alex Martelli" > There have been several power set routines posted. > I suspect that they're all O(N*2^N), but when I time > them (on Windows, starting with a list of length 15) > some of them are at least 10 time faster than > others. > Timing results for four of the powerset generators posted to this thread (format edited for usenet): SetSize: 5 enum recurs1 recurs2 lComp reps: 5 : 0.01 0.00 0.00 0.02 reps: 10 : 0.02 0.00 0.01 0.02 reps: 15 : 0.03 0.01 0.01 0.04 SetSize: 10 reps: 5 : 0.50 0.08 0.06 0.63 reps: 10 : 1.01 0.14 0.13 1.24 reps: 15 : 1.46 0.23 0.19 1.88 SetSize: 15 reps: 5 : 26.23 6.75 5.84 32.00 reps: 10 : 56.81 13.31 14.05 64.70 reps: 15 : 90.25 20.51 25.01 97.16 -- Emile van Sebille emile at fenx.com --------- #---powersetTimings.py def toggle(pattern): if pattern[-1] == 0: pattern[-1] = 1 else: pattern[-1] = 0 pattern[:-1] = toggle(pattern[:-1]) return pattern def genNibbles(qty): rslt = [[0]*qty] for i in xrange(2**qty - 1): rslt.append(toggle(rslt[-1][:])) return rslt def enum(set): incl = genNibbles(len(set)) sq = range(len(set)) rslt = [] for i in incl: sset = [] for j in sq: if i[j] == 1: sset.append(set[j]) rslt.append(sset) return rslt def recurs1(seq): """ To computer the powerset of seq, we need to know the powerset of seq[1:] and combine a copy of it with seq[0] (as well as keeping an unmodified copy). We stop the recursion when seq is a singleton -- the powerset of [a] is [[a], []]. """ # Trivial case if len(seq) == 1: return [seq, []] # Now do the recursion and combine the results subSet = recurs1(seq[1:]) resultSoFar = subSet[:] for set in subSet: resultSoFar.append([seq[0]] + set) return resultSoFar def AddTo(list, elt): return list + [elt] def recurs2(list): if list: ans = recurs2(list[:-1]) return ans + map(AddTo, ans, [list[-1]]*len(ans)) else: return [[]] def lComp(L): N = len(L) return [ [L[i] for i in range(N) if X&(1L< <9eldd9$qcf$00$1@news.t-online.com> Message-ID: <9elh35$6d3dj$1@hades.rz.uni-sb.de> Eduard Hiti wrote: | Have you run makepy for the ADO library? | This will generate wrappers for the ADO type library that I think are needed | for symbolic constant support in the constants module. | You can run makepy from the PythonWin environment by selecting 'COM makepy | utility' in the 'Tools' menu. Then choose 'Microsoft ActiveX Data Objects | Library 2.x' and let makepy do its work. Afterwards the constants module | should work. i did it... methods of the ADO object are known, but not the attributes/constants.... yours, uwe. -- Uwe.Schmitt at num.uni-sb.de Universit?t des Saarlandes phone: +49 (0)681/302-2468 Geb. 36.1, Zi. 4.17, PF 151150 D-66041 Saarbr?cken http://www.rocksport.de http://www.rocksport.de/first_ride.mp3 From aleaxit at yahoo.com Fri May 11 18:38:20 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 12 May 2001 00:38:20 +0200 Subject: Why aren't we all speaking LISP now? References: <5YRK6.68$5J2.1540@newsfeed.slurp.net> Message-ID: <9dhpqc02s0t@news1.newsguy.com> "bowman" wrote in message news:5YRK6.68$5J2.1540 at newsfeed.slurp.net... > > "Tim Roberts" wrote in message > news:tcumfto5unpji5u109b8bctegnji4po3ap at 4ax.com... > > > > knew the list was going to be limited in size. I KNOW I can write a > > bubblesort or insertion sort and get it right. I'd have to look up and > > debug a quicksort or a heapsort. > > at least in C, my lookup of sorting ends with 'man qsort'. While ANSI does So what happens when you have to sort a (linked) list -- you have to pour it into an array to call qsort on it, then back into linked form? Feels sort of expensive (sure, still O(N log N), but...). If one works with a lot of linked lists in C, mergesort is pretty nice, and the list variant of quicksort not bad either in certain cases. C++ does supply such niceties (in its standard library), but C per se doesn't... Alex From pbleyer at embedded.cl Tue May 29 13:17:24 2001 From: pbleyer at embedded.cl (Pablo Bleyer Kocik) Date: 29 May 2001 10:17:24 -0700 Subject: [ANN] xio, the cross platform serial IO python module Message-ID: [Sorry if this message is posted twice] Hi! I am releasing an early beta of a cross platform serial IO module for python, codenamed "xio". The idea is that the interface will remain very similar across platforms. It currently supports POSIX systems using the standard termios implementation, and Win32 systems through the native Windows API. Actually, the module borrows code from a library for embedded systems we are writing at my company ("ecl - embedded control library"); however the module is completely idependent from it. Currently, the module implements port creation, opening, closing, configuration, reading, writing & status peeking. It has been tested under Linux-x86 and Win-9X. It contains a na?ve implementation of flow control (and pretty untested -- so beware!). You can download the source files & binaries for Python-2.1 (Linux-x86, libc6-gcc-2.95.2 & Win32, mingw32-2.95.3) from http://ecl.embedded.cl/xio. Please, send comments, suggestions & bug reports to pbleyer at embedded.cl. [multi-platform-io-serialized-ly'yrs, PBK] -- Pablo Bleyer Kocik Design Engineer embedded^cl -- http://www.embedded.cl From whisper at oz.nospamnet Wed May 23 14:46:38 2001 From: whisper at oz.nospamnet (David LeBlanc) Date: 23 May 2001 18:46:38 GMT Subject: What can you do in LISP that you can't do in Python References: Message-ID: <9eh0ie$cac$4@216.39.170.247> In article , James_Althoff at i2.com says... > > o We (the Smalltalk-80 group at Xerox PARC) designed the syntax and > semantics of Smalltalk-80 from the very beginning to allow "nameless, > in-place" code blocks to serve a *very* prominent role in the language -- > namely, to implement *all* control structures. In fact, we designed the > syntax and semantics of Smalltalk-80 specifically so as to make it > unnecessary to define *any* builtin control structure into the language > proper (aside from method invocation). (The goal was to design the language > such that essentially every construct -- including every control structure > -- could be considered to be a "parameterized message sent to an object). > Python (like most languages), on the other hand, was designed to have > special syntax and semantics to support each of its builtin control > structures. In this sense, lambdas do not serve the same fundamental role > in Python that blocks do in Smalltalk. > > > Jim I think having smalltalk-style block closures in Python would be great! The only problem I can see, given the pythonic aversion to left/right (brackets, carets, braces), is how it would look. Dave LeBlanc From kens at sightreader.com Fri May 18 00:56:02 2001 From: kens at sightreader.com (Ken Seehof) Date: Thu, 17 May 2001 21:56:02 -0700 Subject: Check if variable is defined References: <3wMM6.2594$Yu6.664291@newsc.telia.net> Message-ID: <002301c0df56$d7bc3070$a325fea9@his> ---- Original Message ----- From: "Courageous" Newsgroups: comp.lang.python To: Sent: Thursday, May 17, 2001 5:37 PM Subject: Re: Check if variable is defined > > >> I once wondered if vars(), locals() or globals() have a time cost to > >> produce the dictionary in a usable format > > I'm too lazy to go over to my Python source tree at the moment, > but I believe that these already _are_ in Python dictionaries, right > inside Python. IOW, they aren't "producing" anything, they are > simply giving you a reference to an already-existing construct. > > C// Yup. You really don't need to look at the sources. In fact, at the interpreter all three functions give a reference to the same dictionary. >>> v1 = vars() >>> v2 = vars() >>> g1 = globals() >>> g2 = globals() >>> l1 = locals() >>> l2 = locals() >>> id(v1), id(v2) (3145180, 3145180) >>> id(g1), id(g2) (3145180, 3145180) >>> id(l1), id(l2) (3145180, 3145180) - Ken From chris.gonnerman at newcenturycomputers.net Wed May 9 21:27:57 2001 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Wed, 9 May 2001 20:27:57 -0500 Subject: GPL Revisited (Asbestos underwear activated) Message-ID: <00a901c0d8f0$81511820$0101010a@local> I just read a very informative article regarding the GPL in Open Magazine. It's on their website also, at: http://www.openmagazine.net/featured/01/04/18/1529243.shtml Briefly, the author is Lawrence Rosen, an attorney for the Open Source Initiative (opensource.org). While they are supporters of free software in general they are much more "centrist" than the FSF, hence I tend to trust his opinion in this matter. Many people who scream and yell that the GPL is pure evil repeatedly state that the GPL can "infect" other programmer's code bases against their will. Lawrence explains how this really works from a lawyer's view, in particular considering the explicit language of the Copyright Act. I recommend reading his article; I'm sure most of the anti-GPL people will still think it's evil, but perhaps there are some whose opinions aren't set in concrete. Interesting reading regardless of which side you are on (or if, like me, you've moved past taking "sides" on everything). One thing I find strange is that there seem to be many who are adamantly pro GPL, and many who are adamantly anti GPL, but there seem to be few like me who have no strong opinions either way. From not.this at seebelow.org Thu May 10 13:23:47 2001 From: not.this at seebelow.org (Grant Griffin) Date: 10 May 2001 10:23:47 -0700 Subject: Python Risk References: <3doft22t2w.fsf@mems-exchange.org> <9dc7kt$29l$1@panix6.panix.com> Message-ID: <9deir30202@drn.newsguy.com> In article <9dc7kt$29l$1 at panix6.panix.com>, roy at panix.com says... > >In article <3doft22t2w.fsf at mems-exchange.org>, >>* Strings may now be enclosed in double quotes as well as in single >>quotes. There is no difference in interpretation. >> >>I mean, really, who ordered *that*? > >Not to mention triple quotes. Sounds like we got invaded by spies >from the "There's more than one way to do it" camp :-) now_dont_get_me_started_on_that \ = [tmtowtdi for new_features in list_comprehensions] which-are-neither-single-nor-obvious-ly y'rs, =g2 _____________________________________________________________________ Grant R. Griffin g2 at dspguru.com Publisher of dspGuru http://www.dspguru.com Iowegian International Corporation http://www.iowegian.com From aleaxit at yahoo.com Tue May 8 07:48:00 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 8 May 2001 13:48:00 +0200 Subject: xrange question References: Message-ID: <9d8me701gd6@news2.newsguy.com> "Tim Peters" wrote in message news:mailman.989291471.16806.python-list at python.org... [snip] > historically varies across both n and platforms. So pick one by flipping a > coin, stick with it, and feel free to blame me if it turns out you picked the > wrong one. I always use range() -- and it's all Tim Peters' fault, darn it! Alex From kc5tja at dolphin.openprojects.net Thu May 24 01:18:10 2001 From: kc5tja at dolphin.openprojects.net (Samuel A. Falvo II) Date: Wed, 23 May 2001 22:18:10 -0700 Subject: WWW.FNORB.COM In-Reply-To: References: Message-ID: <200105240518.WAA12295@dolphin.openprojects.net> In comp.lang.python, on Thu, 24 May 2001 12:59:23 +0800, you (Christine Hall) wrote: > > > > This type of post on Usenet isn't welcome, in particular, in the comp.lang.python newsgroup. While Fnorb uses Python as its implementation language, it is not related to Python in any other way. Your advertisement would be better targeted if you contacted the appropriate parties directly, via e-mail. Unfortunately, I am not at liberty to disclose their e-mail addresses. You should be able to glean their addresses from their website. Thank you. -- KC5TJA/6, DM13, QRP-L #1447 Samuel A. Falvo II Oceanside, CA From jkrukoff at ltgc.com Thu May 17 19:10:35 2001 From: jkrukoff at ltgc.com (John Krukoff) Date: Thu, 17 May 2001 17:10:35 -0600 Subject: Objections to print >>file syntax from a complete newbie. (And question about raw strings and dos filenames) Message-ID: Hi everybody, I've just started my first programming project with python, and I was thinking about the print >>file syntax. As I've been learning python nothing else has stood out so much as being an odd, unusual, and inelegant syntax as this. Both the oddity of it being position and special character dependant, as well as it being part of the argument list to print. It feels like dealing with an overloaded function rather than dealing with the other python statements. After taking a look at the PEP documents, I was wondering why a syntax parallel to the other location specifying command, import (as in from modulename import name ) wasn't mentioned? Something like in stdout print name or something similar, so as to avoid the special characters and the need for adding it to the argument list. Also, not being able to have a backslash on the end of a raw string has been frustrating. I'm using a couple of hard coded DOS filenames and raw strings seemed like a good way save on typing, but by design they can't go at the end of the string. Does anybody have a better method than using strip? As in filename = r"c:\mydir\ ".strip() -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3014 bytes Desc: not available URL: From sholden at holdenweb.com Fri May 4 08:08:07 2001 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 04 May 2001 12:08:07 GMT Subject: Bug or not ? References: <3AF28F44.EF9318FE@nd.edu> Message-ID: "Changsen Xu" wrote in message news:3AF28F44.EF9318FE at nd.edu... > Hi all, > > I met a problem, not sure it's bug or not, same > for Python version through1.5.2 to 2.0: > > >>> x= [ [0,0], [0,0] ] > >>> x > [[0, 0], [0, 0]] > >>> x[0][0] = 1 > >>> x > [[1, 0], [0, 0]] ## This is exactly what I expect, same as > C/C++ > > > >>> x = [ [0]*2 ] * 2 > >>> x > [[0, 0], [0, 0]] > >>> x[0][0] =1 > >>> x > [[1, 0], [1, 0]] ## This result differ from above > > > Anybody can give me an explanation ? Thanks in advance. > I was driven crazy to check my how-can-it-be-wrong > tiny program dozens of times until I finally found the above > difference! > The puzzling aspect of this question comes about because x = [ [0]*2 ] * 2 gives you a list containing two references to the same [0]*2. This has been discussed before, but it's a common thing for Python starters to stumble over. The correct way to overcome the problem is to build your lists dynamically, rather than using the * operator. I should have thought there would be a FAQ entry about this, but I don't see one -- anyone? regards Steve From robin at jessikat.fsnet.co.uk Tue May 29 10:50:41 2001 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 29 May 2001 15:50:41 +0100 Subject: Against PEP 240 References: <9f03m401qcu@enews2.newsguy.com> <0E0E06297253FE1B.D13D6C3BAEE41AD8.4A273FCB042833CB@lp.airnews.net> Message-ID: In article <0E0E06297253FE1B.D13D6C3BAEE41AD8.4A273FCB042833CB at lp.airnew s.net>, Cameron Laird writes >Let's be precise: extensions that pass float- >ing point data will all be broken. I don't >regard broken extensions lightly; I know what >a cost it can be to reassemble all the parts >just to recreate what one had before. Do you >agree there'd be value in adding a coda to the >PEP about how to rewrite extensions? Shall >part of the PEP be a function on the C side >that helps ease the task? >> well thinking about this a bit it seems that direct arguments will have an f type argument flag and then the conversion should be supplied by the interface mechanisms. Indirect arguments will be the problem and therefore stuff that used to be fine eg myextension.func([1.4,2.3]) will very likely need to be looked at. If I had made the assumption that these were numbers then it's likely that some kind of conversion to float is already present. The problem is then whether that works when rationals are added to the mix. Since the above [f0,f1,....] kind of thing is fairly common some kind of support for converting this list to a vector of x would probably be most useful. We already have a tuple format indicator, but this requires explicit format indicators for everything inside. I guess we should really ask the Numpy authors to comment on things they would like to see in the C api. I know that a lot of extension writing is about getting the arguments in and out and they have a bunch of mechanisms for doing that. -- Robin Becker From tdelaney at avaya.com Fri May 11 02:14:40 2001 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 11 May 2001 16:14:40 +1000 Subject: Why aren't we all speaking LISP now? Message-ID: > >Indeed, the point of teaching bubblesort is to teach *not to use* > >bubblesort. > > I would have said "...to teach WHEN not to use bubblesort." > There have > been many times I needed to sort a list in some throaway > utility when I > knew the list was going to be limited in size. I KNOW I can write a > bubblesort or insertion sort and get it right. I'd have to > look up and debug a quicksort or a heapsort. You can always write an insertion sort and get it right. You can always write a bubble sort and get it right. The code is very similar in length. Conceptually, an insertion sort is more logical (despite this, *everyone* I've known, including myself, wrote a bubble sort as their first ever sort - I wonder why?). Given these facts, you still should *not* use a bubble sort, as a insertion sort is much more efficient. Nonetheless, I concede the point. *When* not to use a bubble sort, which is any time you remember that an insertion or better sort exists. Tim Delaney From scarblac at pino.selwerd.nl Mon May 21 08:44:11 2001 From: scarblac at pino.selwerd.nl (Remco Gerlich) Date: 21 May 2001 12:44:11 GMT Subject: Python time class References: Message-ID: Oleg Broytmann wrote in comp.lang.python: > Hello! > > On Fri, 18 May 2001, Werner Geuens wrote: > > You may have noticed that at least one function - strptime() - doesn't work > > on at least one platform. > > Yes, THAT platform. The parent post never got here, Andrew Markebo wrote a pure Python strptime.py, find it at http://www.fukt.hk-r.se/~flognat/hacks/ Locale support isn't there, but if you need only English or Swedish dates, it works fine. > Well, let us return to our muttons. You DO need strptime() > implementation? It is not our responsibility to bring it to you. Hey, in > the world of free software it is YOUR responsibility to bring it to us! But somebody else already did :) -- Remco Gerlich From fredrik at pythonware.com Fri May 11 10:50:58 2001 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 May 2001 14:50:58 GMT Subject: Interview with Mark Lutz on O'Reilly References: Message-ID: Lyle Johnson wrote: > I hadn't seen this mentioned here yet. Slashdot ran an article yesterday > pointing out this interview with Mark Lutz, author of "Programming Python" > (2nd ed.). you're late; the daily Python URL pointed to this two days ago ;-) http://www.pythonware.com/daily/ Cheers /F From nas at python.ca Wed May 16 19:54:39 2001 From: nas at python.ca (Neil Schemenauer) Date: Wed, 16 May 2001 16:54:39 -0700 Subject: Replacement for Py_Malloc? In-Reply-To: <3B030CB3.55A24994@spacenet.tn.cornell.edu>; from loredo@spacenet.tn.cornell.edu on Wed, May 16, 2001 at 07:26:43PM -0400 References: <3B030CB3.55A24994@spacenet.tn.cornell.edu> Message-ID: <20010516165439.A17494@glacier.fnational.com> Tom Loredo wrote: > > Hi- > > I'm installing Python 2.1, and in rebuilding an old 3d-party extension > that I used with 1.5.2, I'm getting errors because the extension > calls Py_Malloc. What should I do about these calls (about 10 of them)? > Is there a "drop in" replacement for Py_Malloc? You might want PyMem_Malloc. Make sure to use MyMem_Free to free the memory though. If the memory is freed with free() you may want to allocate it with malloc(). What is the memory used for? Neil From alf at leo.logilab.fr Fri May 18 04:30:14 2001 From: alf at leo.logilab.fr (Alexandre Fayolle) Date: Fri, 18 May 2001 08:30:14 +0000 (UTC) Subject: UML Case Tool for Python References: Message-ID: Nunez, Alex wrote: >Does anyone has any experience with OpenThorn? I tried it once, and it's not worth using right now if you need anything beyond class diagrams. The best open source UML tool for now is Argo UML. http://argouml.tigris.org/ Alexandre Fayolle -- http://www.logilab.com Narval is the first software agent available as free software (GPL). LOGILAB, Paris (France). From michael at stroeder.com Thu May 24 20:22:16 2001 From: michael at stroeder.com (Michael =?iso-8859-1?Q?Str=F6der?=) Date: Fri, 25 May 2001 02:22:16 +0200 Subject: problems with mod_python References: <9ek5kj$sro$1@eising.k-net.dk> Message-ID: <3B0DA5B8.50628336@stroeder.com> Jonas Meyer Rasmussen wrote: > > I am having alot of trouble getting mod_python to work... > [..] > I know its kinda OT, but this was the best place i could find to ask. The best place to ask about mod_python is its mailing list. You should find information how to subscribe on http://www.modpython.org. Ciao, Michael. From ullrich at math.okstate.edu Wed May 30 09:09:01 2001 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Wed, 30 May 2001 13:09:01 GMT Subject: Powersets of a list? References: <9els3j$2kap$1@ID-11957.news.dfncis.de> <9em0l10kdt@enews1.newsguy.com> <3b0fabc2.5506652@nntp.sprynet.com> <9eorfa0kj1@enews2.newsguy.com> <3b11015c.2099508@nntp.sprynet.com> <9erchj012m5@enews1.newsguy.com> <3b125c53.441935@nntp.sprynet.com> <9etq8k0f49@enews1.newsguy.com> <3b13a688.315231@nntp.sprynet.com> <9f0d47025ir@enews2.newsguy.com> Message-ID: <3b14f04d.538210@nntp.sprynet.com> On Tue, 29 May 2001 16:53:47 +0200, "Alex Martelli" wrote: >"David C. Ullrich" wrote in message >news:3b13a688.315231 at nntp.sprynet.com... > ... [...] > >The basic idea would be something like: > [...] Ah. That's more or less the NxN array I figured you must be talking about - I didn't see the point to it, but when you actually spell it out the point's clear - thanks. Duh. David C. Ullrich ********************* "Sometimes you can have access violations all the time and the program still works." (Michael Caracena, comp.lang.pascal.delphi.misc 5/1/01) From wa at net-federation.de Tue May 22 11:21:50 2001 From: wa at net-federation.de (Wendelin Auer) Date: Tue, 22 May 2001 17:21:50 +0200 Subject: newbie problem with urllib.urlopen Message-ID: <9ee03d$8v4$02$1@news.t-online.com> Hello, I'm no python programmer, but I have to fix a python problem in a search engine. I want to fetch two urls and write the content in the header and footer part of a html-file. It nearly works, but theres one problem left. Don't worry about the strange output mode, this is a part of one of many html-templates with scripted python: .......... &$data; ............. I hope this is not ridicolous ;-) My Problem: This returns something like: <td nowrap bgcolor="#e5edf0"><img src="images/pix.gif" width="1" height="1"></td> </tr> </table> </body> </html> This is what was fetched: All linebreaks are gone, too. What I need is a way to decode, or even better, to get exactly the content of the fetched url into the data-variable. Please do not only explain, an example would be nice, i'm an absolute beginner. Thanks in advance, Wendelin Auer From robin at jessikat.fsnet.co.uk Tue May 29 04:58:49 2001 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 29 May 2001 09:58:49 +0100 Subject: string repr in 2.1 In-Reply-To: <20010529102414.P690@xs4all.nl> References: <20010529102414.P690@xs4all.nl> Message-ID: In message <20010529102414.P690 at xs4all.nl>, Thomas Wouters writes >On Tue, May 29, 2001 at 12:47:39AM +0100, Robin Becker wrote: >> In article , Remco Gerlich >> writes > >> >Since 2.1, string repr uses heximal escapes instead of octal ones. > >> yes I guess all those *nix tools that like octal should be whipped and >> made to obey the malevolent dictator. > >Do you have tools you use to parse quoted (repr'd) Python strings that >handle octal correctly, but don't handle \x and \n\r escape codes ? Which >ones ? And were you aware that they were going to break sooner or later, >just because someone can prefer 'readable' escape codes and feed it that >instead ? :) > Yes I have such tools. One is called Acrobat Reader, another is traditional sed and awk. My dos grep doesn't seem to like hex, I suppose I must update it and all other tools. My C compiler understands octal and the newer ones do hex as well. I can read octal and do arithmetic in it probably easier than hex. I don't defend the octal representation it's just very widespread in the older tools. Our usage of repr was probably stupid as clearly repr can change. How I long for my 18-bit PDP-15 :) what happened to my 15 octal digit cdc! Oh woe is me! Where are the duo-decimal calculators of yore? -- Robin Becker From phd at phd.fep.ru Fri May 25 04:07:41 2001 From: phd at phd.fep.ru (Oleg Broytmann) Date: Fri, 25 May 2001 12:07:41 +0400 (MSD) Subject: Spam handling (was Re: WWW.FNORB.COM) In-Reply-To: <9ejsej$dve$1@panix3.panix.com> Message-ID: On 24 May 2001, Aahz Maruch wrote: > >>> SpamCop.net did a good job for me about this message. > >> > >> You can't be sure of that. If the original message used false headers, > >> the netnews spam will contain the false headers. > > > > It seems you've never tried SpamCop! It does amazing job digging real > >information from even false headers!!! > > That's only true if the true headers don't get stripped. I just > checked, and Mailman does preserve the original Received: headers -- but > only on the mailing list. The mail->news gateway definitely strips Yes, I read this newsgroup by mail (e.i. I subscribed to Mailman list, not newsgroup). > those Received: headers, and that's what SpamCop uses to figure out > where the spam came from. That is, SpamCop relies on the fact that > people forwarding e-mail haven't munged the headers, and therefore the > last connection listed in the Received: headers *has* to be valid. There is a worse problem, though - some spam appeared here because it was posted to the newsgroup, not mailed to the maillist. Then even SpamCop has problems (though sometimes it does its job anyway). Oleg. ---- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From phd at phd.fep.ru Thu May 31 04:17:36 2001 From: phd at phd.fep.ru (Oleg Broytmann) Date: Thu, 31 May 2001 12:17:36 +0400 (MSD) Subject: Python celebrities photos In-Reply-To: Message-ID: On Thu, 31 May 2001, Robin Dunn wrote: > Here's a different Tim Peters: > > http://www.dynapower.com/Employees/Tim%20Peters.htm > Will that do? No. Too much difference :))) Oleg. ---- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From ruediger.maehl at dzsh.de Wed May 30 10:28:08 2001 From: ruediger.maehl at dzsh.de (Ruediger Maehl) Date: Wed, 30 May 2001 16:28:08 +0200 Subject: Small, Local Web/CGI Server Advice References: <67abb823.0105300435.260f47d2@posting.google.com> Message-ID: Sloth wrote <67abb823.0105300435.260f47d2 at posting.google.com>... > [snip] >laptop computers. Basically, the salesperson would run a local Web >server that allows for basic CGI scripts to be run. The customer is > [snip] Hi Sloth, I can recommend Xitami (http://www.xitami.com) as a webserver, which is free of charge and available for different platforms. You can start Python scripts thru CGI (Python interpreter is started for each script, though). HTH R?diger From nospam at nospam.de Sun May 27 06:30:01 2001 From: nospam at nospam.de (Uwe Hoffmann) Date: Sun, 27 May 2001 12:30:01 +0200 Subject: a sub process problem. References: <9eq5pf$l1u3$1@ID-82539.news.dfncis.de> Message-ID: <3B10D729.7701F1D@nospam.de> Rajarshi Guha wrote: > > i, > I was writing a script to search my mail archives. After doing the search > I'd like to start Pine from the script and view the results. In addition > after the > exit of Pine I want the script to carry on - ie the script should wait until > the pine process finishes. I've tried using the popen2 class but I get the > following error: > > Traceback (most recent call last): > File "/home/rajarshi/src/misc/py/ptest.py", line 153, in ? > print p.poll() > AttributeError: 'tuple' object has no attribute 'poll' > > ,where p = os.popen4("pine") instead use p=popen2.Popen4("pine") http://www.python.org/doc/current/lib/module-popen2.html the Popen4 objects created by popen4 (maybe the term factory function is misleading here, i'm not sure) are used internally only. from popen2.py library module ... def popen4(cmd, bufsize=-1, mode='t'): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout_stderr, child_stdin) are returned.""" inst = Popen4(cmd, bufsize) return inst.fromchild, inst.tochild ... > > But the docs say that instances of popen2 and peopn4 have the methods poll() > and wait(). I also tried os.spawn(os.P_WAIT,"pine") but then the the > program just carries on and no pine comes up. > > Could somebody please tell me where I'm going wrong and how I could solve > this problem. > > PS. I'm doing all this under Linux and Python 2.1 > TIA, > > -- > ------------------------------------------------------------- > Rajarshi Guha > > email: rajarshi at presidency.com > web: http:/www.psynet.net/jijog From pete at visionart.com Thu May 3 14:58:04 2001 From: pete at visionart.com (Pete Shinners) Date: Thu, 3 May 2001 11:58:04 -0700 Subject: ANNOUNCE: SolarWolf 1.0 Message-ID: <9cs912$64u$1@news.unitel.co.kr> Announcing SolarWolf 1.0 by Pete 'ShredWheat' Shinners http://shredwheat.zopesite.com/solarwolf SolarWolf is an action/arcade game written entirely in Python. It is opensource and is released under the LGPL license. There is a full source package and a precompiled windows installation available. The source is dependent on pygame, which in turn depends on Python2, SDL, SDL_mixer, SDL_image, and SDL_ttf. It features quick and smooth fullscreen 800x600 graphics. There is alpha transparent blitting, colorkeying, animated sprites, scrolling starfield background, antialiased font rendering, and more. The sound system supports multiple sound channel playback, along with streaming music support. It also supports input from keyboard or joystick. The game and its dependencies are extremely cross platform, allowing gameplay on just about all platforms; Windows, Linux, BeOS, IRIX, Solaris, NT4, and more. SolarWolf is built with Pygame 1.0. This library is a great set of modules for game development in python, with a growing community of users. It provides a "pythonic" object oriented interface for the fantastic SDL media library. The game is originally based of one of my childhood favorites, SolarFox on the Atari 2600. All this, yet the best feature of all is; It is a hecka lotta fun! The point of the game is to scramble through 48 levels of patterns, collecting all the boxes. The part that makes it tricky is avoiding the relentless hailstorm of fire coming at you from all directions. Find out more about the dependencies with these URLs; http://pygame.seul.org http://www.python.org http://www.libsdl.org From sholden at holdenweb.com Tue May 8 22:01:10 2001 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 8 May 2001 22:01:10 -0400 Subject: How to convert binary file data? References: Message-ID: <#xcVkwC2AHA.289@cpmsnbbsa09> Take a look at the struct module, which was good enough for reading Outlook Express files. Otherwise you'll need to use the ord() function to get the character's numeric value, but that way madness lies when you already have struct available. regards Steve "DOC" wrote ... > I must be missing something here. I am reading a file that has > binary data and want to be able to handle/convert it... > > But I can't seem to figure out how to do it. > > >>># read in 1 byte: > ...buf=x.read (1) > > >>># this is what's in buf > ... buf > '\xe0' > > >>># try the eval > ...eval (buf) > Traceback... > ... > SyntaxError: unexpected EOF while parsing > > >>># OK try string.atoi! > ...string.atoi (buf) > Traceback... > ... > ValueError: invalid literal for int(): > > ********* > > An odd char is shown for both of the above. Likely unicode for \xe0. > > So can someone tell me the right way to handle this? > > Thanks, > DOC > > > From cribeiro at mail.inet.com.br Sun May 6 20:30:41 2001 From: cribeiro at mail.inet.com.br (Carlos Ribeiro) Date: Sun, 06 May 2001 21:30:41 -0300 Subject: Problem with wxPython: wxDialog crashes inside PythonWin In-Reply-To: References: Message-ID: <5.0.2.1.0.20010506212839.023baec0@mail.inet.com.br> At 21:19 06/05/01 +0000, Nick Perkins wrote: >i have experienced similar things with PythonWin on NT >i have noticed that after shutting down PythonWin, >there is sometimes a process still running, >which can been seen from the 'task manager' I think there are two different issues here. One is the problem with wxPython; the other is the ghost process. Everytime I get a lockup on PythonWin (which happens sometimes) the Python icon remains on the system tray, until I move the mouse over it - then it disappears. This has never caused me any problem, though, but it is a problem nonetheless. Carlos Ribeiro From ask at me.com Mon May 21 19:42:05 2001 From: ask at me.com (erudite) Date: Mon, 21 May 2001 17:42:05 -0600 Subject: nesting 'if' statements? Message-ID: <%ShO6.1153$LT4.90852@e420r-sjo2.usenetserver.com> Hey guys, Just a quick question: Is it possible to nest 'if' statements in python? If so how is it accomplished? Can you provide sample code? eg. if expression: statements if expression: statements elif expression: statements else: elif expression: statements if expression: statements else: statements --EOF-- thanks, ~Eruditus~ "You can't talk to a psycho like a normal human being." -- Poe 'Trigger Happy Jack' From montagne at boora.com Fri May 11 20:41:54 2001 From: montagne at boora.com (michael montagne) Date: Sat, 12 May 2001 00:41:54 GMT Subject: PythonWin Outlook connection References: Message-ID: More info for the interested: If I do a dir on the folder object on my machine: >>> dir(folder) ['_builtMethods_', '_enum_', '_lazydata_', '_mapCachedItems_', '_oleobj_', '_olerepr_', '_unicode_to_string_', '_username_'] If I do a dir on the folder object on the bad machine: >>> dir(folder) ['_oleobj_'] -mjm "michael montagne" wrote in message news:mp_K6.47333$FS3.505691 at sjc-read.news.verio.net... > The following sequence works on my machine during development but when I > install on another computer(the actual user) I am greeted with the error at > the bottom. I ran the COM MakePy Utility for Outlook. We both have the > same version of MSOffice. > > >>> import win32com.client > >>> objOut = win32com.client.dynamic.Dispatch("Outlook.Application.9") > >>> objNamespace=objOut.GetNamespace("Mapi") > >>> objNamespace.Logon() > >>> folder=objNamespace.Folders.Item("Public Folders").Folders.Item("All > Public folders").Folders.Item("Proj").Folders.Item("98011 UC > Davis").Folders.Item("UCD RFI's") > >>> objemail=folder.Items(1) > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: _Items instance has no __call__ method > > > > From sill at optonline.net Sat May 19 11:53:23 2001 From: sill at optonline.net (Rainy) Date: Sat, 19 May 2001 15:53:23 GMT Subject: ANN: Pymp3 Message-ID: Pymp3 - console python front-end for mpg123 http://silmarill.org/pymp3 The Idea I used mpg123 and was happy with it except for lack of three things: recursive loading, ability to easily switch to the next directory, and searching. For instance, in pymp3 you can type dn and the first mp3 in next directory in list will play, or hit 'f', type in a search pattern and the first song matching that pattern will play. Requirements You will need mpg123 and optional aumix for volume control. I tested it with python2.1 on linux, but 2.0 will probably work, on windows it may work. Example session Pymp3 v0.2: 4 directories, 46 files loaded [type dl..] Pymp3> directory list Directories: 1) family/anyway 3) family/fearless 2) family/family entertainment 4) family/music in a doll's house [type s] Pymp3> start family/anyway Playing: 1) Family - Good News Bad News [type dn] Pymp3> directory next family/family entertainment Playing: 1) Family - Hung Up Down [type mr] Pymp3> mode Random Random mode: [on] Playing: 7) Family - Normans It's my first relatively big script, so some of the code is fairly ugly. If you have any advice on how to improve the design, please follow-up. In particular, most functions in Pymp3 class don't return any values and instead modify self.something variables - is this considered bad design? Also, I have main() function inside of class, but usually it goes into top level. -- Jupiter and Saturn Oberon Miranda And Titania Neptune Titan Stars can frighten - Syd From reedy37 at home.com Sat May 19 01:19:46 2001 From: reedy37 at home.com (Terry Reedy) Date: Sat, 19 May 2001 05:19:46 GMT Subject: GNU/Linux vs. Windows as Python platform References: Message-ID: > This thread could be endless and belongs to *.advocacy usenet groups. As to the second, no. I asked for and has received (some privately) non-preachy Python-specific and Python-relevant information that will help me make a decision sometime in the next year. (I am now leaning more towards adding Linux than I was a week ago.) This is quit different from advocacy. As to the first, when those with relevant dual-system experience who care to share have done so, this thread will be over as far as I am concerned. Terry J. Reedy From aahz at panix.com Tue May 8 09:57:35 2001 From: aahz at panix.com (Aahz Maruch) Date: 8 May 2001 06:57:35 -0700 Subject: Maintenance release? (Was RE: Variables different between .py and .pyc) References: Message-ID: <9d8u0f$s48$1@panix6.panix.com> In article , Tim Peters wrote: >[Aahz Maruch, on a proposed change to make .pyc/.pyo files store > repr(float) instead of str(float)] > >> Ouch. This is the kind of situation where I was thinking that a >> distinction between "bugfix release" and "maintenance release" might >> be useful. OTOH, it's hard to imagine a case where fixing this >> would make things worse.... I mean, really, what could this break? > >Perhaps you have no experience with floating-point code <2/3 wink>? >Over the years I've spent a good (distributed) half year of my life >tracking down gross problems in numerically naive algorithms triggered >by measly 1-bit differences. This is a much bigger change than that. >Even a good algorithm will return *different* results, and of course >some people will scream "different" == "broken". You can't fix *any* >bug that changes a result without somebody feeling abused. Yes; I'm not going to get into arguments with *you* about floating point. ;-) I guess my sarcasm was a little too subtle: I think you'd agree that anyone who's writing code based on Python's current behavior has code that's already broken. Their code will overall be no more broken with this fix (remember, every time they modify their .py, they'll get wrong results for one run), and at least they'll finally get consistent results. My opinion on whether this "can" go into a bugfix release depends on whether you and Guido think this needs a .pyc magic number upgrade. If the magic number changes, this has to be dropped. Period. Otherwise, I don't have a strong opinion about which way this goes. An amusing side effect of fixing this particular bug is that someone who generates a .pyc in 2.1.1 (and 2.0.1 if we fix it there, too) who gives that .pyc to someone running 2.1 will automatically "fix" the problem for that person, too. That behavior may in fact make this bugfix a Bad Idea. -- --- Aahz <*> (Copyright 2001 by aahz at pobox.com) Androgynous poly kinky vanilla queer het Pythonista http://www.rahul.net/aahz/ Hugs and backrubs -- I break Rule 6 "Don't be so humble -- you are not that great." --Golda Meir From kkto at csis.hku.hk Wed May 23 11:32:30 2001 From: kkto at csis.hku.hk (Isaac To Kar Keung) Date: 23 May 2001 23:32:30 +0800 Subject: Tkinter problems References: <9egarb$rv5$1@bambi.zdv.Uni-Mainz.DE> Message-ID: <7i66esf5dd.fsf@enark.csis.hku.hk> >>>>> "Christian" == Christian Maus writes: Christian> In one of these childwindows I put a button which calls a Christian> method to create a new frame in the childwindow. Instead of Christian> creating a new frame in this childwindow, containing a label Christian> and an entry, it is created in my mainwindow. When I insert a Christian> label directly into the window, instead of a new frame the Christian> label is created in the childwindow just as I intended. Probably because you didn't tell Tkinter that you want to create the subwindow with the window as the parent. Remember that Tkinter has no idea about *your* class hierarchy. It has *its own* idea about the parent-child relationships among the widgets. So be sure to create a widget like self.mylabel = Label(self.mytoplevel, option1=value1, ...) Regards, Isaac. From pkalliok at cc.helsinki.fi Thu May 31 05:53:22 2001 From: pkalliok at cc.helsinki.fi (Panu A Kalliokoski) Date: 31 May 2001 09:53:22 GMT Subject: asyncore: suggested patch References: Message-ID: <9f54ai$m1k$5@oravannahka.helsinki.fi> Robert Amesz wrote: > careful look at your patch *and* at asyncore.py I'm sorry to have to > say that your patch really totally goes against the asyncore design > principle of having a single poll-loop drive the system. I took the time to watch at the original connect() of dispather at asyncore. The issue is basically dealt with correctly, returning to the select() loop when the socket is not yet connected, but if it is true, as Jonathan reports, that connecting to a non-existent port on an existing host loops forever, the problem is the unneeded use of non-blocking sockets and incorrect parsing of error values. What we need to know is what the error value is in a situation like this and how it could be known different from the legitimate ones (EINPROGRESS, EWOULDBLOCK ...). > If the only thing you want to do is abort the connection attempt after > a certain amount of time it would be better just to simply check if the > connection is actually established at or after a certain point in time. > That should be straightforward enough, if you clone the loop() function > in asyncore and put the timeout-check in the 'while map:' loop. This is also one part of functionality which is missing in asyncore: scheduled events (such as explicit connect() timeouts). > (It might be better still if asyncore would be extended to handle > timeouts by calling two more callback-functions, say > handle_connect_timeout() and handle_io_timeout().) Better still to move to my Selecting. (http://sange.fi/~atehwa-u/selecting-0.8/) Panu Kalliokoski From dsh8290 at rit.edu Sat May 26 10:37:00 2001 From: dsh8290 at rit.edu (D-Man) Date: Sat, 26 May 2001 10:37:00 -0400 Subject: Anybody use variables/names longer than 31 characters? In-Reply-To: <200105260900.LAA29200@boris.cd.chalmers.se>; from lac@cd.chalmers.se on Sat, May 26, 2001 at 11:00:57AM +0200 References: <200105260900.LAA29200@boris.cd.chalmers.se> Message-ID: <20010526103700.A3430@harmony.cs.rit.edu> On Sat, May 26, 2001 at 11:00:57AM +0200, Laura Creighton wrote: | UglyBitmapMaskBecauseSignExtensionIsBroken Why would you need such a long name when you have namespaces/modules? I often see really long names in C because of the lack of (top-level) namespaces (such as the GTK+ API). -D From jkraska1 at san.rr.com Thu May 10 11:04:58 2001 From: jkraska1 at san.rr.com (Courageous) Date: Thu, 10 May 2001 15:04:58 GMT Subject: Why aren't we all speaking LISP now? References: <9dc2d8$tck$1@slb6.atl.mindspring.net> Message-ID: <2rblftohfsp1kce03n1v4t2e98gcra3jg1@4ax.com> >>> Computer Science is a science. > >I would have to disagree. CS is much more closely related to >math than to Science. Most of the CS faculty I had when I was >in school had Math degrees. The CS dept and the Math dept >offices were adjacent and shared facilities -- There's an old joke amongst acamicians which says "any discipline which has the word science in it isn't." This is somewhat amusing with regards to computer science, in which most of the "science" is mathematics. :-) C// From phd at phd.fep.ru Thu May 24 11:18:22 2001 From: phd at phd.fep.ru (Oleg Broytmann) Date: Thu, 24 May 2001 19:18:22 +0400 (MSD) Subject: OT - Limiting freedom In-Reply-To: Message-ID: http://lwn.net/daily/guardians.php3 "It is fundamentally about why this movement is about free software, not open source. FreeDevelopers is about being the guardians of the world's freedoms, not just the freedoms of developers. And certainly not about just efficient and better software. If you don't understand that, then you do not understand what Richard has been saying for 17 years. And if you have not understood it after 17 years, it becomes doubtful that you will ever understand it." "With the connectivity of the Internet and cyberspace, software is the functional equivalent to law in real space, because it controls people, just like law does. But while law uses a human police force to enforce its rules, software uses a digital police force to enforce its rules. That actually makes the digital police force much more obedient and therefore dangerous in the wrong hands." "The world has fought a lot of wars to make regular law open, democratic and available to the governed. We shouldn't let technology take us backwards to a time when a few people have the arbitrary power to create whatever law they please and have everyone else just subject to it. I found that technologists discount these ideas more than they should. You should seriously think about them." Oleg. ---- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From carlca at dircon.co.uk Tue May 22 08:19:58 2001 From: carlca at dircon.co.uk (Carl Caulkett) Date: Tue, 22 May 2001 13:19:58 +0100 Subject: Interbase + Gemini ODBC + Python References: Message-ID: In article , carlca at dircon.co.uk says... > > Has anyone used the Gemini ODBC driver to connect to an Interbase 6.0 > dialect 3 database from Python? If so, what connection string did you > use? This is using the odbc module that comes with PythonWin, BTW. Never mind. I found a precompiled build of gvib that works by going going direct to the Interbase API. http://home.t-online.de/home/err666/ -- Carl From paulp at ActiveState.com Tue May 29 18:05:25 2001 From: paulp at ActiveState.com (Paul Prescod) Date: Tue, 29 May 2001 15:05:25 -0700 Subject: XML Parser Trouble in Python 2.1 References: <3B13FC0E.81FAC10B@raqia.com> Message-ID: <3B141D25.2DC9FC31@ActiveState.com> David Lees wrote: > >... > > However, when I try executing it on my RedHat Linux 7.1 system I get the > following error stack, which puzzles me. I do not understand why some > of the error messages even refer to 'sax' parser, since I am using dom. > And I am puzzled why I get any errors in the first place. I have a feeling you are missing the expat library. Try this: >>> import xml.parsers.expat >>> parser = xml.parsers.expat.ParserCreate() -- Take a recipe. Leave a recipe. Python Cookbook! http://www.ActiveState.com/pythoncookbook From Gareth.McCaughan at pobox.com Sun May 20 17:57:23 2001 From: Gareth.McCaughan at pobox.com (Gareth McCaughan) Date: Sun, 20 May 2001 22:57:23 +0100 Subject: Python is also a Lisp compiler name? References: <9dpq3p$o31$1@panix3.panix.com> Message-ID: Aahz Maruch wrote: [I said:] >> When there have been discussions about the difficulties of compiling >> Python to decent native code, I have been tempted to post an article >> saying "I have on my machine a Python compiler, which does a fine job >> of type inference and such stuff despite the dynamism of the language, >> and produces code within a factor of 2 of optimized C"... :-) > > Thank you, Pierre. ?Que? -- Gareth McCaughan Gareth.McCaughan at pobox.com .sig under construc From aleaxit at yahoo.com Tue May 22 17:13:31 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 22 May 2001 23:13:31 +0200 Subject: automatically naming a global variable References: <9ee2nl02at8@enews1.newsguy.com> Message-ID: <9eekrb0238@enews1.newsguy.com> "Chad Everett" wrote in message news:slrn9gl8fv.5j4.chat at linuxsupreme.homeip.net... ... > I have sets that are described by a list of attributes and > properties that are implemented using python dictionaries. > One of a set's attributes is its name. I need to provide > the user with a mechanism for referring to a dictionary that > represents a set, by using the set's name. The user does > not want to have to reference the set via something like: > > sets['set_name'] So far, so good. > They need to have a variable that references to the dictionary > for the set by simply using set_name. Naah! What they need is to have an object that groups all sets, and use set.name rather than set_name for their references. > I need to be able do this: > > set_name = sets['set_name'], so that: > > >>> set_name > > and > > >>> sets['set_name'] > > reference exactly the same thing. class SetOfSets: def __init__(self, refdict): self.__ref = refdict def __getattr__(self, name): return self.__ref[name] set = SetOfSets(sets) That's it. Now, sets['name'] and set.name reference exactly the same thing forevermore. If you INSIST on the 'set_' prefix for the key in dictionary sets, just change the last line of the SetOfSets classbody to: return self.__ref['set_'+name] though I'm not sure what this buys you. This way you avoid all kinds of problems typical of the overuse of globals -- such as the user not religiously using the set_ stropping-prefix and accidentally hiding builtins such as 'len()' by naming a set that way... If you INSIST on creating such horrible problems for your users, as I said, then setattr(sys.modules[__name__], 'set_name', sets['set_name']) lets you do that for one name at a time, or even sys.modules[__name__].__dict__.update(sets) for faster, mass-slaughter kind of suicide:-). (PS, if the 'user code' in question is something you are handling with eval, or exec, or execfile, etc, you can pass arbitrary dictionaries to it -- then, preparing an artificial dictionary of "globals" which includes your 'dictionary of sets' is a far more sensible approach than damaging the actual dict of globals... similarly, you can use new.function or other techniques to tweak the globals for user functions that you get as function-objects, etc...). Alex From com-nospam at ccraig.org Thu May 17 13:53:21 2001 From: com-nospam at ccraig.org (Christopher A. Craig) Date: 17 May 2001 13:53:21 -0400 Subject: PHP feelings? References: <3B03E083.C075B1BB@saiph.com> Message-ID: <87lmnveub2.fsf@elbereth.ccraig.org> Imbaud Pierre writes: > Do I have a (python driven, for instance) alternative to PHP? I would suggest Python. Take a look at the Web topic guide http://www.python.org/topics/web/ I started writing a PHP replacement for Python, but I've pretty much abandoned as of late because I did a fairly large project in PHP and found that for any reasonably large project the model of embedding programming in your content rather than the other way around was not all that useful. Zope is far more than a mere content management tool. I used Zope a bit and found that I really like just writing pages in straight Python more, but it can certainly do what you want. There are also several little projects like PyHP, or PMZ that try to imitate PHP with Python. They are all incomplete and each have their own (usually major) drawbacks. -- Christopher A. Craig The use of COBOL cripples the mind; its teaching should, therefore, be regarded as a criminal offense -- Edsger Dijkstra From thomas.heller at ion-tof.com Thu May 3 03:18:36 2001 From: thomas.heller at ion-tof.com (Thomas Heller) Date: Thu, 3 May 2001 09:18:36 +0200 Subject: py2exe - new version Message-ID: <019d01c0d3a1$457d2a40$e000a8c0@thomasnotebook> I've released py2exe version 0.2.6. Some smaller changes, as well as support for Python 2.1. Thomas http://starship.python.net/crew/theller/py2exe/ From robert at roebling.de Fri May 25 17:05:16 2001 From: robert at roebling.de (Robert Roebling) Date: Fri, 25 May 2001 23:05:16 +0200 Subject: ANN: wxDesigner commercial RAD tool Message-ID: Hi, A new version of wxDesigner has seen the light of the day, version 2.5 to be exact. wxDesigner is a commercial RAD tool for the Open Source cross-platform C++ library wxWindows (and its Python and Perl bindings). It lets you create dialogs, application skeletons, event, getters and classes quickly and includes a syntax-highlighting text editor, a bitmap editor and some other goodies. New in version 2.5 is support for menus and menu events as well as many dozens of smaller enhancements and bug fixes. wxDesigner is now also available for IRIX, in addition to Windows, Linux, Solaris and FreeBSD with work being done to get wxDesigner working on the Mac as well. wxDesigner 2.5 is available from http://www.roebling.de Regards, Robert -- Robert Roebling, MD From fredrik at pythonware.com Sat May 12 12:46:57 2001 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 May 2001 16:46:57 GMT Subject: Testing for version to use from __future__ in 2.1 References: <9djlcu$icnnm$1@ID-11957.news.dfncis.de> Message-ID: <5OdL6.1704$Yu6.423593@newsc.telia.net> Emile van Sebille wrote: > I think the point is that nested scopes can (potentially) break existing > code. Existing applications should be tested to see if they break. To do > so, you add from __future__ import nested_scopes to your code base. no, all you have to do is to run the code under 2.1 as is. if it might break, the 2.1 compiler will warn you. consider this code: bar = "global" def spam(): bar = "local" def egg(): return bar return egg() print spam() under Python 2.0, this prints "global" under Python 2.1, it says "SyntaxWarning: local name 'bar' in 'spam' shadows use of 'bar' as global in nested scope 'egg'" and then prints "global" under Python 2.2, and under 2.1 with a future statement, it prints "local" Cheers /F From ilya at glas.net Wed May 16 10:57:01 2001 From: ilya at glas.net (ilya at glas.net) Date: Wed, 16 May 2001 14:57:01 +0000 (UTC) Subject: Implementing SSL server? Message-ID: <9du4ft$j11$1@news.sovam.com> Greetings, Is there a way to implement server capable of accepting SSL connections based on the socket module? It looks that socket module misses server side functionality of openssl (stuff like SSL_accept() etc). Also, it looks like there is no provision in socket module for using SSL over a non-blocking file descriptor. Is there a solution on this? Thanks, ilya From roy at panix.com Thu May 10 22:22:28 2001 From: roy at panix.com (Roy Smith) Date: Thu, 10 May 2001 22:22:28 -0400 Subject: Need suggestion to speed up code... Message-ID: I need to split up a string into a list of fields. The strings are value lists from SQL statements, and look something like this: (1, 'foo', 'bar', 34, 3.14159, 'an imbedded comma, this sting has', 'this one isn''t so easy either') If it wasn't for the fact that I need to handle commas and quotes imbedded in quoted strings, it would be trivial -- just a call to string.split. But, as it is, the best I can figure out is to walk the string, character by character, keeping track of what state I'm in (parsing an integer, parsing a floating point, or parsing a quoted string). It works, but profiling shows it's the bottleneck in my whole program. Anybody have any idea for a better way to do this? If I really had to, I suppose I could write this bit in C as an extension module, but I'd rather do a pure python implementation to keep it portable. From kapblp at bellsouth.n0t Wed May 9 15:23:58 2001 From: kapblp at bellsouth.n0t (KEVIN) Date: Wed, 9 May 2001 15:23:58 -0400 Subject: I'm new and need some help!!!!! References: Message-ID: > a "Python Programmer" just with this? and where can i > find some REAL basic tutorials. I'm doing same -- first language. have you poked around at python.org where you can download the program and some howtos From vze2nbmq at verizon.net Tue May 15 18:18:22 2001 From: vze2nbmq at verizon.net (Bernd Prager) Date: Tue, 15 May 2001 22:18:22 GMT Subject: newbie trouble with #! Message-ID: Hi, I start completely new with python and have a very simple question: I'm havin trouble with the shebang line in python. -- snip ----------- [root:/etc/ipcheck]# type python python is hashed (/usr/bin/python) [root:/etc/ipcheck]# head ipcheck.py #! /usr/bin/python import base64, getopt, urllib, httplib, os, re, sys, stat, string, time, telnetlib, socket try: import syslog except: # for platforms without syslog that try to use --syslog option class fake_syslog: def openlog(self,foo): raise Exception("Syslog not supported on this platform") [root:/etc/ipcheck]# ./ipcheck.py bash: ./ipcheck.py: No such file or directory -- snip ----------- When I type /usr/bin/python ipcheck.py everything works fine. I'm using Python 1.5.2. Does anybody have an idea what that could be. (I was already checking if I got some weird character within the first line: I didn't!) Thanks for your help, -- Bernd From andrew_dot_henshaw_at_earthling_dot_net Wed May 2 00:55:01 2001 From: andrew_dot_henshaw_at_earthling_dot_net (Andrew Henshaw) Date: Wed, 2 May 2001 00:55:01 -0400 Subject: Formatting numbers References: <%4KH6.58717$qc2.15144507@typhoon.southeast.rr.com> Message-ID: "Steve Holden" wrote in message news:%4KH6.58717$qc2.15144507 at typhoon.southeast.rr.com... ...snip... > > so this won't be useful in the general case. One way might be: > > >>> def fmt(i): > ... bits = divmod(i, 100) > ... return "%d.%02d" % bits > ... > >>> fmt(12345) > '123.45' > >>> fmt(12340) > '123.40' > >>> fmt(12300) > '123.00' > ...snip... This approach won't work correctly for negative values. >>> fmt(-12345) '-124.55' Andy Henshaw From rgruet at intraware.com Mon May 21 13:01:12 2001 From: rgruet at intraware.com (Richard Gruet) Date: Mon, 21 May 2001 17:01:12 GMT Subject: Python 2.0 quick reference... References: Message-ID: <3B0949D8.4F4B9A8D@intraware.com> Very nice job, Dan. How did you convert html to pdf ? Richard Gruet "Rolander, Dan" wrote: > I've created a PDF version of the Python 2.0 Quick Reference, with bookmarks > and thumbnails. You can get it from > http://rolander.com/python/python_2_0_quickref.pdf. > > I've sent this to Simon and expect him to eventually host it, but it's > already the weekend back there in the UK. ;-) > > Comments welcome. > > Dan > > > -----Original Message----- > > From: Bo Vandenberg [mailto:bosahv at netscapenospam.net] > > Sent: Wednesday, May 16, 2001 11:11 PM > > To: python-list at python.org > > Subject: Re: Python 2.0 quick reference... > > > > > > Great work, makes me wonder at what python has achieved. > > > > Could anyone format it as a PDF file with working index????? > > > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- A non-text attachment was scrubbed... Name: rgruet.vcf Type: text/x-vcard Size: 370 bytes Desc: Card for Richard Gruet URL: From john_hopkins at bigfoot.com Fri May 11 22:25:09 2001 From: john_hopkins at bigfoot.com (John Hopkins) Date: Fri, 11 May 2001 19:25:09 -0700 Subject: Is this a bug? References: <3af2b89d.338629833@News.CIS.DFN.DE> Message-ID: This just came up in one of the mailing lists I track. Python apparently requires that last '\' to be escaped, even though you're using "Raw". So myPath = r'c:\Windows\\' *should* work, though I haven't tried it. -- John Hopkins john_hopkins at bigfoot.com wrote in message news:3af2b89d.338629833 at News.CIS.DFN.DE... > The following example gives me an error in PythonWin 2.0. > > myPath = r'c:\Windows\' > > It does not like the last BS. > > However > > myPath = r'c:\Windows' > > works fine. > > Any ideas? > > Costas From nospam at codegnome.org Thu May 17 03:50:57 2001 From: nospam at codegnome.org (Todd A. Jacobs) Date: Thu, 17 May 2001 00:50:57 -0700 (PDT) Subject: Check if variable is defined Message-ID: I'm having a lot of trouble doing something that was simple in Perl: specifically, I want to create if/else clauses that take action only if a particular variable is undefined. How do I check to see if a variable or object has already been defined? If there's no better way, I suppose I could try to catch the exception, but that seems like a bit of a kludge, especially if I have to create the exception in order to find out what exception the interpreter throws first. -- Todd A. Jacobs CodeGnome Consulting, LTD From robin at jessikat.fsnet.co.uk Fri May 4 08:38:36 2001 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 4 May 2001 13:38:36 +0100 Subject: use of import of PIL incorrectly documented, or is it just me ? References: <7kzyibx5.fsf@atosorigin.com> Message-ID: In article <7kzyibx5.fsf at atosorigin.com>, Paul Moore writes >Max M?ller Rasmussen writes: > >> Well what I have is: >> >> C:\Python20\Lib\site-packages\PIL.pth >> C:\Python20\Lib\site-packages\PIL\ >> C:\Python20\DLLs\_imaging.pyd >> C:\Python20\DLLs\_imagingtk.pyd > >site-packages isn't supported on Win32. Hopefully, it will be soon - >see PEP 250. > >Paul Moore > I'm using PIL as a package to avoid clashes with other Image(s) and find that it doesn't save PNG format files unless I do a from PIL import PngImagePlugin is the behaviour different when the PIL files aren't on the path? -- Robin Becker From grante at visi.com Wed May 9 13:09:36 2001 From: grante at visi.com (Grant Edwards) Date: Wed, 09 May 2001 17:09:36 GMT Subject: Sockets... References: Message-ID: In article , Vincent A. Primavera wrote: > I have been experimenting with a variant of the program listed below from >the Python Library Reference... I'm getting the error below very frequently. >How can I prevent this from happening? And when it does happen is there a >way that I can 'manually' free up the 'socket'? >Traceback (innermost last): > File "./server.py", line 37, in ? > auth() > File "./server.py", line 17, in auth > sck.bind((host, port)) >socket.error: (98, 'Address already in use') A particular port can't be reused for X seconds after it's closed (for security reasons). X varies from stack to stack. If you want to be able to re-use it right away, set the SO_REUSEADDR option: s = socket(AF_INET, SOCK_STREAM) s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) s.bind(host,port) s.listen(1) -- Grant Edwards grante Yow! Yow! Are we wet yet? at visi.com From costas at meezon.com Thu May 24 16:51:02 2001 From: costas at meezon.com (Costas Menico) Date: Thu, 24 May 2001 20:51:02 GMT Subject: A new metaclass pattern, class methods References: <3B0BE4D2.3B38E410@python.net> <3b0d5845.4074548@News.CIS.DFN.DE> Message-ID: <3b0d742a.3996972@news.cis.dfn.de> P.S. it would be much cleaner, if anyone can figure out how to use the __del__ methods to destroy instance objects. I tried different ways but could not figure how to get it to work. That's why I have the destroy() method. costas From mt_horeb at yahoo.com Sat May 26 23:48:19 2001 From: mt_horeb at yahoo.com (Sloth) Date: 26 May 2001 20:48:19 -0700 Subject: Windows ME, CGIHTTPServer & pain... Message-ID: <67abb823.0105261948.76eac84a@posting.google.com> I'm putting a little app together that (in theory) will run a simple CGI capable server on Windows 98 and Windows ME laptops. The server, which conveniently uses CGIHTTPServer, looks like this: from CGIHTTPServer import CGIHTTPRequestHandler import BaseHTTPServer httpd = BaseHTTPServer.HTTPServer(("", 8001), CGIHTTPRequestHandler) print "Serving at port 8001" httpd.serve_forever() Below the working directory is a '/cgi-bin' directory. When I ran this script on a WinNT Workstation, everything worked as one would expect, and the server allowed me to link to and call CGI scripts (*.py) from cgi-bin. But, alas, there is now a major problem... While testing the above server on a Windows ME laptop, the server (or Windows) does not allow CGI scripts to run. The server allows HTML to be served up quite nicely. However, linking to a CGI script causes Windows to beep at me and causes the browser to basically hang. The page stays where it is, the IE logo spins around, but I never go to my CGI script! The console shows that Windows has called C:\Python20\Python.exe on my script, but it won't go anywhere!!! Even more ridiculous is the fact that the script really clobbers the rest of the laptop, usually leading to the death of Explorer. Does anyone know how to get Win98/ME to play nicely with the *HTTPServer modules? I realize that I could download Apache/mod_python, but I would rather use the built-in modules, since this app will never be networked. To summarize: WindowsNT + CGIHTTPServer = CGI is served up! WindowsME + CGIHTTPServer = BOOM Thanks in advance! Sloth From thomas at cintra.no Thu May 31 12:53:47 2001 From: thomas at cintra.no (Thomas Weholt) Date: Thu, 31 May 2001 18:53:47 +0200 Subject: Urgent: User authentication problems using ODBC thru Mod_python/Apache Message-ID: I've defined a System DSN/ODBC-resource using the ODBC Data Source Administrator, gat_reg. When using the PythonWin ODBC-module thru PythonWin it works great. I've also installed Apache and mod_python and when the same objects using the odbc-code is called in pages served by Apache I get a error like : [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'domainname\username$'. in LOGIN ( Where domainname and username is replaced with actual data ). Why? What's so different when I'm using ODBC in Apache than in plain python? How can I fix this? Thomas From tim.one at home.com Mon May 28 13:56:39 2001 From: tim.one at home.com (Tim Peters) Date: Mon, 28 May 2001 13:56:39 -0400 Subject: Powersets of a list? In-Reply-To: <3b1203da.514350967@wa.news.verio.net> Message-ID: [Bengt Richter] > What about the effect of garbage collection? To be fair, shouldn't all > timings be started after a fresh garbage collection, at least on an > algorithm basis, if not each invocation? The bulk of garbage collection in CPython is done by reference counting, and objects normally go away as soon as their last reference goes away. That's "fair" across algorithms, in the sense that they'll pay for the amount of trash they create while they're running. There's another scheme, though, for cleaning up trash with cycles, which reference counting alone can't discover. This is triggered by "excess" allocations: if, since the last time this pass ran, the number of allocations is greater than the number of destructions by a certain amount, this other scheme kicks in, and searches *everything* for the possibility of trash cycles. So when you're, say, creating oodles and oodles of lists, but not destroying them, the cycle-detection system gets triggered often. That's also fair (in some sense ), but much subtler. To see the effect on a particular algorithm, it's easiest to disable that form of gc for the duration: import gc gc.disable() # run the algorithm; report times gc.enable() It *usually* doesn't make much difference (a few percent). From scarblac at pino.selwerd.nl Thu May 17 04:27:59 2001 From: scarblac at pino.selwerd.nl (Remco Gerlich) Date: 17 May 2001 08:27:59 GMT Subject: floor() function definition References: <7616gt4d8n7041gcfknjbvuo4gj4ku8our@4ax.com> Message-ID: Dev_NuLL wrote in comp.lang.python: > >Try it and see! > > Seems to strip everythin off the right of the decimal point in a > positive number. > > After looking at the negative numbers it gives the closet integer less > than x. Or equal. Highest integer that isn't bigger. > Thanks to you and the others who ANSWERED the question, and 'up your > ass' to the jerk off who's answer was 'go take a course in math'. The > answer cannot even be found on 'Ask Dr. Math's' site because this is a > programer's function, not a common math function because it cannot be > explained by a simple formula. Please restrain yourself, this is comp.lang.python. Even if his post was a bit uncalled for, flames don't belong here. -- Remco Gerlich From grante at visi.com Thu May 10 10:23:26 2001 From: grante at visi.com (Grant Edwards) Date: Thu, 10 May 2001 14:23:26 GMT Subject: Unix [was: do...until wisdom needed...] References: <014401c0d8ff$3b3038d0$d938a8c0@Hadfield> Message-ID: In article <014401c0d8ff$3b3038d0$d938a8c0 at Hadfield>, Mark Hadfield wrote: >> >> A free and popular Unix would have only had to be compatible with >> >> itself. DOS, which was the competition at the time, not Windoze 3.1, >> >> was certainly no more compatible with human beings than Unix was. >> > >> >Well, DOS did have a "help" command. >> >> Not that I remember.... > >Oops. It has also been pointed out to me that "at the time" >(i.e. when the 386 came out) DOS did not have "edit" either. There was "edlin" which was a rather lame attempt at a line-oriented editor. It was pretty much useless compared to the Unix line editor "ed". -- Grant Edwards grante Yow! Spreading peanut at butter reminds me of visi.com opera!! I wonder why? From tim.one at home.com Tue May 29 20:14:38 2001 From: tim.one at home.com (Tim Peters) Date: Tue, 29 May 2001 20:14:38 -0400 Subject: Against PEP 240 In-Reply-To: <9f03m401qcu@enews2.newsguy.com> Message-ID: [Alex Martelli] > ... > Rexx is also based on 7.35 meaning exactly 7.35, neither more > nor less; it was the premier scripting language for both IBM > mainframes and (I'm told) Amiga computers. This is a convenient point to draw a distinction: Rexx (and almost all of the others) still use floating-point in this case, but with a decimal (rather than binary) base. So, yes, 7.35 is WYSIWYG, and 7.35/7 is exactly 1.05, but 7.35/17 is again just an approximation. PEP 240 wants much more than that: it wants unbounded rationals, not just a decimal base. Note that Aahz is making good progress behind the scenes implementing a Python module for IBM's decimal arithmetic proposal (driven by Mike Cowlishaw -- Rexx's dad): http://www2.hursley.ibm.com/decimal/ > I'm not sure what various dialects of Lisp, Scheme, Prolog, Erlang, > Haskell, and other non-classic languages do, but I'd bet that > SOME of them take 7.35 as meaning 7.35 (aka 147/20, an exact > rational number). I even suspect other scripting languages > behave similarly, though I don't recall precisely. ABC (Python's predecessor) took 7.35 as an exact rational. But it went way beyond PEP 240: it took, e.g., 6.02e23 and 1.9187e-219 as meaning exact rationals too. Guido deliberately didn't do that in Python, and as a fellow victim of ABC's unpredictable time and space requirements I agreed with him at the time (before Python 1.0 was released). But then you can blame both of us for Python's integer division too . The Scheme std says any undecorated numeric literal with a decimal point or exponent is inexact. But #i and #e qualifiers can be attached, so that, e.g., #e6.02e23 is exact despite that 6.02e23 is not, and #i42 is inexact despite that 42 is exact. "#i" is nicely ambiguous: it can mean "inexact" or "incorrect" <#e0.9107 wink>. But I expect rationals are very unusual in commercial number crunching, while variants of decimal fixed- and floating-point are extremely common. That makes the IBM proposal (above) worth taking seriously (and Guido is predisposed to do so -- after his first reading, he remarked that this proposal appeared to achieve what they were *trying* to do with ABC numerics). > ... > Oh, read ALL Kahan has written, and if you emerge still > thinking you KNOW what you're doing when floating point > is involved, you're either Tim Peters, or the world champ > of hubris. I find it's possible to be both . But *nothing* about fp comes easily to anyone, and even Kahan works his butt off to come up with the amazing things that he does. As Knuth observed in TAoCP (vol 2, ed 3, pg 229): Many serious mathematicians have attempted to analyze a sequence of floating point operations rigorously, but found the task so formidable that they have tried to be content with plausibility arguments instead. It's a bitch. The great thing about the Rexx approach is that if you have a reason to suspect your results, you can just run the same program again asking for 2 (or 3, or 4, or ...) times the amount of precision. And that's the *only* practical way I've ever seen for non-experts to get a handle on either the existence or cause of numeric surprises. The 754 committee was hoping to get a more modest version of the same thing by recommending single-extended and double-extended formats, but while Intel implemented double-extended in the Pentium line, terrible language support rendered it worse than useless (you can never predict, e.g., when MSVC will or won't use double-extended, so instead of a great safety net it turned into just another source of unpredictable numeric surprise). From matthias at my.gnus.org Tue May 29 22:38:08 2001 From: matthias at my.gnus.org (Matthias Wiehl) Date: 30 May 2001 04:38:08 +0200 Subject: Location of the Pythin bin file? References: Message-ID: <87ae3vwohb.fsf@fulmine.dhs.org> Anonymous Coward writes: > I am trying to setup a python script to execute automaticly, however > I can not find the location of my Python bin file. How exactly are you trying to do that? What does `which python' say? From parkw at better.net Tue May 1 17:35:44 2001 From: parkw at better.net (William Park) Date: Tue, 1 May 2001 17:35:44 -0400 Subject: Differences between Ruby and Python. In-Reply-To: ; from ddublanc@free.fr on Tue, May 01, 2001 at 09:08:24PM +0000 References: Message-ID: <20010501173544.A1588@better.net> On Tue, May 01, 2001 at 09:08:24PM +0000, Dublanc, David wrote: > Hello, > I am looking for the differences between Ruby and Python. > In which case Ruby is most powerful than Python ? It really comes down to syntax style. Ruby has Perl flavour, although much better. Another difference is that Python has better documentation. --William Park, Open Geometry Consulting, Mississauga, Ontario, Canada. 8 CPUs, Linux, python, LaTeX, vim, mutt From rob at ZOOstation.cc Wed May 23 18:17:14 2001 From: rob at ZOOstation.cc (Rob Brown-Bayliss) Date: 24 May 2001 10:17:14 +1200 Subject: sequence integrity insite begin-commit? In-Reply-To: <988808414.28339.0.camel@ZOOstation.cc> References: <988808414.28339.0.camel@ZOOstation.cc> Message-ID: <990656235.1454.0.camel@ZOOstation.cc> On 03 May 2001 01:00:14 +1200, Rob Brown-Bayliss wrote: > Hi. I am develeoping an app with python that uses postgresql. > I have hit a snag in that I need to know the value of a sequence from an > insert just performed, but the interface from python to postgres (called > PoPy) does not return the oid from the insert as psql does. > > So what I am doing is begining a transaction, inserting the data, > selecting the last_value from the sequence and then commiting the > transaction. > > I ma not sure if this will work in the real world as what happens if > between one user inserting their data if another insets data as well? > will the last_value from the sewuence (inside the transaction) be > correct, or will it show the valu for the second user? > > Am I being clear? try this > > USER ONE | USER TWO > =========================== > Begin | Begin > Insert | Insert > Select | Select > Commit | Commit > > If these two are happening at the same time (or as near as is possible > can I rely on the selected last_value being the sequence value that was > inserted by the user? (the sequence is the default falue for a column > and user does not enter it) > > > Thanks > > -- > > Rob Brown-Bayliss > ---======o======--- > www.ZOOstation.cc -- Rob Brown-Bayliss ---======o======--- www.ZOOstation.cc From phd at phd.fep.ru Fri May 25 06:26:31 2001 From: phd at phd.fep.ru (Oleg Broytmann) Date: Fri, 25 May 2001 14:26:31 +0400 (MSD) Subject: seg fault on asscessing undefined attr in __getattr__ In-Reply-To: <20010525.055604.1597322404.21285@home.com> Message-ID: On Fri, 25 May 2001, Kong-Jei Kuan wrote: > hi, i am still using python 1.52, and don't know if this happens to other > versions, can some verify this? > > Python 1.5.2 (#0, Dec 27 2000, 13:59:38) [GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2 > Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam > >>> class A: > ... def __getattr__(self, name): > ... self.x > ... > >>> a=A() > >>> a > Segmentation fault Do you understand you've put your Python into infinite recursion? Oleg. ---- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From boudewijn at tryllian.com Wed May 9 04:12:58 2001 From: boudewijn at tryllian.com (Boudewijn Rempt) Date: Wed, 9 May 2001 10:12:58 +0200 Subject: which distro and Gui ? References: <3af8c42b.30001795@news.vif.com> Message-ID: <3af8fcb8$0$55460$e4fe514c@newszilla.xs4all.nl> Yvon Boulianne wrote: > Hello everybody, i'm starting to use python but before investing some > times in it i like to have a suggestion. > which version of python is the more (standard), i know there is > activestate version, beopen, and twistedmatrix and maybe more ? which > one better to run (on win95) ? > also for the Gui, which one is the better one ? (faster execution, run > on many platforms, stable etc..) i know there is Tkinter and wxpython > and some other. > > my purpose is to be able to learn OO and do some application (mainly > networking apps) so any suggestion will be verry cool :) > > p.s. is it possible that some version of python are not compatible > with Tkinter (i think i read that somewhere, if i remember well it was > the active state who have a problem with it) ? > Take a look at http://starbase.neosoft.com/~claird/comp.lang.python/python_GUI.html to acqaint yourself with the variety there is in GUI toolkits. There are three or four serious contenders: Tkinter, PyQt, wxPython and PyGTK, I think. There's an excellent book on Tkinter, by Grayson, and I'm writing a book on PyQt - but using PyQt on Windows entails buying BlackAdder. -- Boudewijn | http://www.valdyas.org From aahz at panix.com Tue May 8 11:42:30 2001 From: aahz at panix.com (Aahz Maruch) Date: 8 May 2001 08:42:30 -0700 Subject: Maintenance release? (Was RE: Variables different between .py and .pyc) References: <9d82e3$i0a$1@panix6.panix.com> Message-ID: <9d9456$6i3$1@panix2.panix.com> In article , Thomas Wouters wrote: > >Hmmm.... But 'i' would be 1 or 2 depending on whether the interpreter >had loaded a .pyc file or compiled a fresh one ? Ewwww :) I'm tempted >to say this is a bugfix, but since it's a bugfix that changes things >silently, I'll say that even then it's not supposed to go into >2.1.x. People have been living with it for 10 years, they can live with >it for a few more months ;) You're the boss. BTW, feel free to update PEP 6 to list yourself as the 2.1.1 owner; it wasn't official as of the last update, and I haven't felt like bugging Barry to do it. -- --- Aahz <*> (Copyright 2001 by aahz at pobox.com) Androgynous poly kinky vanilla queer het Pythonista http://www.rahul.net/aahz/ Hugs and backrubs -- I break Rule 6 "Don't be so humble -- you are not that great." --Golda Meir From samschul at pacbell.net Tue May 22 23:31:11 2001 From: samschul at pacbell.net (samschul at pacbell.net) Date: 23 May 2001 03:31:11 GMT Subject: hello, its me again :-) References: Message-ID: <9efatv$rkv$1@news.netmar.com> Try this: evaluate(list) needs to return answer fix_Expresion(list) needs to return result from evaluate(list) def evaluate(list): num1 = int(list[0]) num2 = int(list[2]) operator = list[1] if operator == '+': answer = num1 + num2 elif operator == '-': answer = num1 - num2 elif operator == 'X': answer = num1 * num2 elif operator == 'x': answer = num1 * num2 elif operator == '*': answer = num1 * num2 elif operator == '/': answer = num1 / num2 else: print 'invalid operator' return answer def fix_expression(list): word = list l = [] n1 = word[0] n2 = word[1] n3 = word[2] l.append(n1) l.append(n2) l.append(n3) return evaluate(l) Sam Schulenburg In article , the_2nd_coming writes: >thanks to all who have helped me with this simple little program. > >I have finally gotten rid of all the errors, however, now I am getting a >value of none returned. > >the source is : >--------------------------------------------------------- > >def evaluate(list): > num1 = int(list[0]) > num2 = int(list[2]) > operator = list[1] > > if operator == '+': > answer = num1 + num2 > elif operator == '-': > answer = num1 - num2 > elif operator == 'X': > answer = num1 * num2 > elif operator == 'x': > answer = num1 * num2 > elif operator == '*': > answer = num1 * num2 > elif operator == '/': > answer = num1 / num2 > else: > print 'invalid operator' > >def fix_expression(list): > word = list > l = [] > n1 = word[0] > n2 = word[1] > n3 = word[2] > l.append(n1) > l.append(n2) > l.append(n3) > evaluate(l) > ># - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - >- - - - - - - - - - - - - - - - - - - - - >import string >expression = raw_input('please enter your singel operator expression') >string.strip(expression) # get rid of all leading and trailing white space# >list = string.split(expression) > >if len(list) >1: > print evaluate(list) >elif len(list) == 1: > print fix_expression(list[0]) > >else: > import sys > sys.exit >=================================================================== > >now what have I missed?!! > >I really appreciate every thing that you-all have done. >this community is really a helpful one > >thanks > >J ----- Posted via NewsOne.Net: Free (anonymous) Usenet News via the Web ----- http://newsone.net/ -- Free reading and anonymous posting to 60,000+ groups NewsOne.Net prohibits users from posting spam. If this or other posts made through NewsOne.Net violate posting guidelines, email abuse at newsone.net From chris.gonnerman at newcenturycomputers.net Sun May 6 01:30:04 2001 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Sun, 6 May 2001 00:30:04 -0500 Subject: ANNOUNCE: Readline Alternative 1.2 References: <001701c0d5a5$ebc12e00$a100000a@local> <15092.46930.497064.223022@beluga.mojam.com> Message-ID: <002001c0d5ed$9fde8620$a100000a@local> ----- Original Message ----- From: Subject: Re: ANNOUNCE: Readline Alternative 1.2 > Yeah, I'm sure there are a few people. At least a few others will be > interested in something slightly smaller than readline. > > BTW, got a URL for your package? Whups, forgot again... http://newcenturycomputers.net/projects/readline.html Summary (which was requested by others): My alternative readline provides command history and inline editing in Python under Win32. Completion is not supported, but certainly not impossible to implement. This software is in two parts: _rlsetup, a C extension based heavily on code by Fredrik Lundh (from his _wincon module). _rlsetup is covered by the effbot's copyright and is under BSD-style license from Secret Labs. The second part is a pure Python readline.py module, which implements the line input, editing, and history functionality. The license is BSD-style under my copyright. Binaries are only included for 2.0; I don't yet have a 2.1 install to build against. The code should also build cleanly for 1.5.2. From gerhard.nospam at bigfoot.de Thu May 31 10:17:07 2001 From: gerhard.nospam at bigfoot.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Thu, 31 May 2001 16:17:07 +0200 Subject: Python OCR form scanner success! References: <3B15B4CD.D64554EA@engineer.com> Message-ID: On Wed, 30 May 2001 23:04:45 -0400, B. Douglas Hilton wrote: >[...] > Following up on a recent post, I am commiting to develop >mainly in Python and Ada where possible from now on, and >reverting to C or C++ only where necessary. >[...] For connecting Python and Ada code, I have started the pyAda project (http://pyada.sf.net). Have you already used it? Do you have any comments? Unfortunately, I wont' have much time in the next months to invest in pyAda. But if you have something specific that you'd like to see there, just drop me a note and I'll do this first. Else, the next goals are 1) more and better docs and 2) going to Python 2.1. Gerhard PS: I am not too much convinced any more wether this project makes much sense (Python's extension capabilities are a little too much tied to C for my tastes, especially they need C's variable number of arguments madness and they are tied to ugly, distasteful C #defines). -- mail: gerhard bigfoot de registered Linux user #64239 web: http://highqualdev.com public key at homepage public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From dougfort at downright.com Sat May 26 12:53:50 2001 From: dougfort at downright.com (Doug Fort) Date: 26 May 2001 17:53:50 +0100 Subject: Distributed computing in Python - Callback howto ? References: Message-ID: <3b0fdf94$1_1@news5.uncensored-news.com> Sasa Zivkov wrote: > Hi, > > What options one have for distributed computing in Python ? > Check out Frederik Lund's implementation of xmlrpc -- http://www.pythonware.com/products/xmlrpc/index.htm If you want to see some sample code, we use it in our agent infrastructure http://pyagent.sourceforge.net -- Doug Fort Senior Meat Manager Downright Software LLC http://www.downright.com ______________________________________________________________________ Posted Via Uncensored-News.Com - Still Only $9.95 - http://www.uncensored-news.com With Seven Servers In California And Texas - The Worlds Uncensored News Source From BPettersen at NAREX.com Thu May 17 12:21:44 2001 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 17 May 2001 10:21:44 -0600 Subject: floor() function definition Message-ID: <6957F6A694B49A4096F7CFD0D900042F27DB60@admin56.narex.com> > From: Dev_NuLL [mailto:dev_null at email.com] > > >I think you should post an apology. > > No, I think the person I replied to should appologize TO ME and I > think you should mind your own damn business before these types of > threads get out of control and completely off topic. When someone > responds to a legitimate question with a smart ass remark like "Go > take a math course" then I will NIP IT IN THE BUD. Don't like it? > Don't read any of my posts. Actually, I think you should apologize to _me_. Using the F-word is just as offensive as using the N-word. If you can't understand this and why it requires an apology, I feel sorry for you. I guess it explains why you don't want anyone to know your real name though... As for not reading your posts, I can hear people adding you to their killfiles allready. Good luck getting help on any future issues. -- bjorn From BPettersen at NAREX.com Mon May 14 11:56:49 2001 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Mon, 14 May 2001 09:56:49 -0600 Subject: Find your sole mate here!! Message-ID: <6957F6A694B49A4096F7CFD0D900042F27D3BD@admin56.narex.com> > From: aahz at panix.com [mailto:aahz at panix.com] > > In article , > Delaney, Timothy wrote: > > > >No - it just assumes a monogamous and monoandrous (sp?) > culture. You may > >only have *one* mate. > > "Monoamorous" And here I thought I could find a fish to live out my days with... *sigh* -- bjorn From dougfort at downright.com Wed May 2 07:22:50 2001 From: dougfort at downright.com (Doug Fort) Date: Wed, 02 May 2001 07:22:50 -0400 Subject: curry and compose -- functional language constructs References: Message-ID: <3AEFEE0A.9040809@downright.com> Dr. David Mertz has written a couple of good articles on functional programming in Python. The latest one is up on the IBM Developerworks site. http://www-106.ibm.com/developerworks/linux/ You probably know all this stuff already, but it's new to me. I've started studying Haskell: I find that some of the good things happening to Python are coming from functional programming. Doug Fort Senior Meat Manager Downright Software LLC ______________________________________________________________________ Posted Via Uncensored-News.Com - Still Only $9.95 - http://www.uncensored-news.com With Seven Servers In California And Texas - The Worlds Uncensored News Source From Pekka.Pessi at nokia.com Tue May 29 16:05:31 2001 From: Pekka.Pessi at nokia.com (Pekka Pessi) Date: Tue, 29 May 2001 20:05:31 GMT Subject: Coddling Emacs References: Message-ID: In message Laura Creighton writes: >Emacs keeps making wretched FILES all over my system. I know >all about auto-save-default and make-backup-files now and I have made >emacs politely keep its backups out of the current directory >(this is not v6 unix. We don't crash all the time here. We do, >however, run out of disk space.) What I can't figure out is how to >make emacs stop making symbolic links like this: >lrwxrwxrwx 1 lac lac 44 May 29 08:19 .#CapsBasicWidgets.pyc > -> lac at ratthing-b246.strakt.com.24677:990877909 >every time I modify a file and then go visit a different file without >writing out the changes. This made my package loader very ill. >Changing my package loader was faster (and easier) than figuring out emacs, >but now I am mortally offended. Does anybody know what emacs calls these >things internally so I can find out how to tell emacs to do it someplace else? Nope. But you can keep backup files somewhere else: (setq auto-save-directory (expand-file-name "~/.backup/") delete-auto-save-files t auto-save-default t auto-save-hash-p (equal system-type 'windows-nt)) Setting auto-save-hash-p to 'emacs-me-gently-with-a-chainsaw can help your package loader, too. Pekka From parkw at better.net Mon May 21 03:03:08 2001 From: parkw at better.net (William Park) Date: Mon, 21 May 2001 03:03:08 -0400 Subject: shell command output In-Reply-To: ; from s_gherman@yahoo.com on Sun, May 20, 2001 at 10:06:58PM -0700 References: Message-ID: <20010521030308.B591@node0.opengeometry.ca> On Sun, May 20, 2001 at 10:06:58PM -0700, Sorin Gherman wrote: > The only solution I can think of is to use a temp file: > > os.system("diff f1 f2 > tmp") > tmpfile = open("tmp") > tmpcontent = tmpfile.readlines() > for line in tmpcontent: > print line > > Is there any solution to avoid the temp file? popen() in 'os' module. -- William Park, Open Geometry Consulting, . 8 CPU, (Slackware) Linux, Python, LaTeX, Vim, Mutt, Sc. From JamesL at Lugoj.Com Tue May 1 18:42:26 2001 From: JamesL at Lugoj.Com (James Logajan) Date: Tue, 01 May 2001 15:42:26 -0700 Subject: Tabs and spaces (style) References: Message-ID: <3AEF3BD2.143688D@Lugoj.Com> Kenneth Loafman wrote: > > Nick Perkins wrote: > > > > Absolutely! > > ..that drives me nuts! > > Why would anyone not use tabs exclusively? > > I'm just the opposite... why would anyone use tabs? All a tab does is > screw up the alignment for anyone that has a different tab size set and > makes it very difficult to print, etc. Well, you can torture me by putting me in the _comfy chair_, but I will still insist on using tabs only with a tabsetting of 4! And I'll do it using vi! (Yes, I am evil!) Just don't threaten me with the soft pillows! From kosh at aesaeion.com Tue May 8 23:17:05 2001 From: kosh at aesaeion.com (kosh) Date: Tue, 8 May 2001 21:17:05 -0600 Subject: How do you set up a stack? References: <3y1K6.28593$q7.286847@typhoon.mw.mediaone.net> <9qehft8gspqhtpb50d3men0j12r7mnkp7i@4ax.com> Message-ID: <9dad3g$83t$1@apollo.csd.net> Umm. While this solution will work I think there are some things that need to be dealt with. Mainly you need to check f for items that should not be in there. eval will evaulatuate any valid piece of python code so the other things that can be done are large. This is a fairly large security risk at this point I think. At the very least I would check if it has any letter characters and if so not run then. Tyler Eaves wrote: > On Wed, 09 May 2001 02:01:35 GMT, the_2nd_coming > wrote: > > > try this code: > > f=raw_input('>') > print eval(f) > > >>hello, >>I am a python/programming newbie (Python is my first language), >>and I am writing a program that will be able to take a mathematical >>function, that, as of right now, is restricted to Multiply and Divide with >>one operator, (2/4 or 3*7). I want to be able for the end-user to be able >>to type the function at the python prompt and to have the program create a >>list of the characters in the list, I am using raw_input and I think I >>need >>to implement a stack in order to pass each character to the list as I pop >>them off the stack. this is good and all, however, I do not know how to >>implement this. >> >>this is what the layout is at this point: >> >> >> >> >> function = raw_input("put your function hear") >> . >> . #this is where the stack will be implemented and >> the . # charactors will be placed in the list. >> operator = function_list[1] # item 1 will be the position of the >> operator >> #in the list after any whitespace is >> #striped. >> >> if operator == "*": #the operator is the astrik >> multiplication(function_list[0], Function_list[2]) >> >> else: >> Division(Function_list[0], Function_list[2]) >> >> # the rest of the program >> >>so, how do I implement a stack, and, is there any other way I could >>acomplish this task? >> >>thank-you in advance >> >>Jeremy Petzold > > From carmstro at twistedmatrix.com Sun May 13 21:52:43 2001 From: carmstro at twistedmatrix.com (Chris Armstrong) Date: Sun, 13 May 2001 21:52:43 -0400 Subject: Input-Output to web pages, Jython? Zope? Tkinter? JavaScript? Advice??? References: <3AFDB80B.430612A2@earthlink.net> Message-ID: In article <3AFDB80B.430612A2 at earthlink.net>, "Ron Stephens" wrote: > 3. Is there a simpler Python web server program that will allow me to do > what I discuss in (2) above in a simpler, easier way? I do not need much > functionality at all from such a web server, and expect very low volume. Check out Twisted Python at http://twistedmatrix.com and look at the part on twisted.web. I view twisted.web as in Zope's domain, but somewhat of an anti-zope. (ie, simple and functional). It's really a kick to write web resources and work with Twisted Python in general. It's a very neat research project, but with practical goals. Anyway, I think twisted.web is the perfect solution to what you talk about in #2 above. Try it out. But don't get mad when you get sucked into a whole other Twisted Universe. -- Chris Armstrong carmstro at twistedmatrix.com http://twistedmatrix.com/~carmstro carmstro at dynup.net From phd at phd.fep.ru Tue May 22 04:32:30 2001 From: phd at phd.fep.ru (Oleg Broytmann) Date: Tue, 22 May 2001 12:32:30 +0400 (MSD) Subject: Variable inheritance In-Reply-To: Message-ID: On Tue, 22 May 2001, Roman Suzi wrote: > I was always very irritated when somebody proposed something like > > class Line(Point): > ... > > just because line could be made of two points. Of course. Now THIS is bad design. Line IS NOT a point, hence, no inheritance should occur. Line CONSISTS of two point, so class Line: def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 But grey mouse DOES NOT "contains" grey color. The mouse IS really grey thing, hence I used inheritance. This is difference between "thing IS a thing of the class" and "thing CONTAINS things". Oleg. ---- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From greg at pdxperts.com Thu May 24 03:12:49 2001 From: greg at pdxperts.com (Greg Jorgensen) Date: Thu, 24 May 2001 07:12:49 GMT Subject: How to Read/Write RTF and Word Files? In-Reply-To: <9egtfi$cac$2@216.39.170.247> References: <3b06b81e_3@news4.newsfeeds.com> <3B09AF45.B2D3AA2@yahoo.com> <9egtfi$cac$2@216.39.170.247> Message-ID: On 23 May 2001, David LeBlanc wrote: > Microsoft calls it "embrace and extend" - I call it "bait and switch". Further off-topic: The practice used to be called platform lock-in; IBM perfected it back in the heyday of mainframes. Every hardware and software company wants to lock their customers in. I don't see anything evil in it as long as they don't try to crush their competitors (which perhaps they have done or tried to do). In the case of RTF, the standard started with Microsoft and it's always been a published standard. It suffers from inconsistent implementation, but overall it works well enough. On the other hand the word .doc format has never been open or published. Microsoft's implementations of HTML and the JavaScript DOM are no less standard than Netscape's (and a good bit more useful, in my opinion). For a while Microsoft's Java VM on Windows was the best Java VM anywhere, certainly better than Sun's. I only half-fault Microsoft for picking up Java and running with it; Sun's pace of development is too slow, and Sun is only committed to open source as long as they can make money from it. I work with Oracle and PL/SQL at my day job, and I sure wish Oracle had exercised some restraint with their non-standard implementation of SQL--talk about platform lock-in! By comparison Microsoft's T-SQL conforms very closely to the SQL standard. I'm not defending everything Microsoft does and I don't use their software unless I have to, but not everything they do is evil, and some of their whiniest critics are guilty of the same bad behavior. -- Greg Jorgensen PDXperts LLC Portland, Oregon USA gregj at pobox.com From jkraska1 at san.rr.com Sat May 12 14:07:27 2001 From: jkraska1 at san.rr.com (Courageous) Date: Sat, 12 May 2001 18:07:27 GMT Subject: Why aren't we all speaking LISP now? References: <989424635.15477.0.nnrp-12.c1c3e154@news.demon.co.uk> Message-ID: >> Even simple things like iterating over a sequence of objects is done >> in a completely different way: in Lisp you do something to the first >> item then recurse. In Python, you use "for x in list". I missed this comment earlier. It's incorrect. Amongst professional Common Lisp programmers, there are two common forms used for iterating over items in a list. They are (dolist), which is identical in function to Python's for: form, and (map) which is identical in function to Python's map/lambda (which was borrowed directly from Lisp) and very similar in function to Python's list comprehension. (dolist) is used to iterate over a list, (map) is often used to transmogrify one sequence into another, although isn't limited to this (i.e., map can do what dolist does, albeit a bit less efficiently, I think). thinks-whoever-wrote-that-comment-doesn't-know-much-about-lisp ly-yrs C From mcfletch at home.com Fri May 25 15:44:08 2001 From: mcfletch at home.com (Mike C. Fletcher) Date: Fri, 25 May 2001 15:44:08 -0400 Subject: Flatten..with less recursion In-Reply-To: Message-ID: <000801c0e553$10e4f2e0$010010ac@cr706570a> Oh, let's pull out this hoary old nugget anyway... def collapse(inlist, type=type, ltype=types.ListType, maxint= sys.maxint): ''' Destructively flatten a list hierarchy to a single level. Non-recursive, and (as far as I can see, doesn't have any glaring loopholes). Further speedups and obfuscations by Tim Peters :) ''' try: # for every possible index for ind in xrange( maxint): # while that index currently holds a list while type(inlist[ind]) is ltype: # expand that list into the index (and subsequent indicies) inlist[ind:ind+1] = inlist[ind] #ind = ind+1 except IndexError: pass return inlist Who knows, maybe there's even ways to make it faster these days. Enjoy, Mike -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org]On Behalf Of Nick Perkins Sent: May 25, 2001 14:14 To: python-list at python.org Subject: Re: Flatten..with less recursion > > def flatten(L): > if type(L) != type([]): return [L] > if L == []: return L > return flatten(L[0]) + flatten(L[1:]) ...hmm this might make a good Scheme program, but I would consider this excessive and unnecessary recursion in any language that does not do proper tail recursion. Python performance on any long list would probably be very bad. (hmm...Stackless?...i wonder...) ..what about: def flatten(L): if type(L) != type([]): return [L] if L == []: return L return reduce(lambda L1,L2:L1+L2,map(flatten,L)) ...maybe someone knows how to avoid the lambda, but I think this should be much faster. -- http://mail.python.org/mailman/listinfo/python-list From qrczak at knm.org.pl Fri May 18 04:16:38 2001 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: 18 May 2001 08:16:38 GMT Subject: What can you do in LISP that you can't do in Python References: <9dqneu02c2o@news2.newsguy.com> Message-ID: Tue, 15 May 2001 09:56:17 +0200, Alex Martelli pisze: > This "normal order evaluation" more colloquially and expressively > "lazy evaluation", has an extreme elegance, and does away with the > need to distinguish functions from special-forms, code-blocks from > other values, finite sequences from infinite ones, and so on. Let me add that the main reason why many Lisp macros are expressible as Haskell functions is not lazy evaluation but the distinction between building a statement and executing it. Most macro examples in this thread were involved in specifying when a statement is executed; not in delaying evaluation of pure expressions until their result is demanded. In Python, as in most languages, providing arguments to a function is combined with executing it. For parameterless functions parens do the execution; for functions with parameters parens do two things: specify arguments and execute. In Haskell a statement is an expression which describes an action. Execution of a statement doesn't happen implicitly when it's formed, but by composing smaller statements into larger statements using functions, operators and syntactic sugar. Parameterization is a separate concept. For example by applying a function to arguments you may get as a result a statement to execute. The only purpose of applying a function is parametrization: a function can't execute statements itself, it only transforms values to other values. OTOH execution of a statement doesn't take arguments, only produces a result. These two concepts are used together to express actions depending on parameters. -- __("< Marcin Kowalczyk * qrczak at knm.org.pl http://qrczak.ids.net.pl/ \__/ ^^ SYGNATURA ZAST?PCZA QRCZAK From aleaxit at yahoo.com Thu May 24 04:38:07 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 24 May 2001 10:38:07 +0200 Subject: Convert long integer to string References: <3B0CAC7C.DCF2B091@seznam.cz> Message-ID: <9eih8p0f05@enews1.newsguy.com> "erik" wrote in message news:3B0CAC7C.DCF2B091 at seznam.cz... > Hi, > how convert long integer ( >2147483647 ) to string whithout "L" on end? D:\Python21>python Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> x=99999999999999999L >>> print x 99999999999999999 >>> str(x) '99999999999999999' >>> repr(x) '99999999999999999L' >>> Alex From just at letterror.com Sat May 5 14:55:31 2001 From: just at letterror.com (Just van Rossum) Date: Sat, 05 May 2001 20:55:31 +0200 Subject: PEP 234: Iterators References: <3AF1E830.A71AD2CA@letterror.com> <6qwv7v67ao.fsf@abnoba.intevation.de> Message-ID: <3AF44CA0.C5E69B72@letterror.com> Bernhard Herzog wrote: > > Just van Rossum writes: > > > the xrange object supports random access, whereas an iterator does > > not. > > Well, I see no reason why an iterator object couldn't provide random > access in addition to the iterator interface. There's no reason it couldn't, but why would you? Iterators have state, so generally shouldn't be shared (eg. across threads). If xrange objects were iterators, you couldn't do this (or at least it would have a different effect than it has now ;-), even if they *also* provided random access: r = xrange(10) for x in r: for y in r: ... Just From mike at pdc.kth.se Thu May 10 15:51:52 2001 From: mike at pdc.kth.se (Mike Hammill) Date: Thu, 10 May 2001 21:51:52 +0200 Subject: codecs, Swedish characters, and XML...don't mix? Message-ID: <200105101951.f4AJpX8188246@ratatosk.pdc.kth.se> Hi, A Web searched shows that there used to be some problems with python, Swedish characters (two with umlauts ?, ?, one with a circle ? all are part of ISO8859-1), and XML. I'm still having the problem with Python 2.1. Does anyone know what's wrong? Brief description of the problem: (1) read an XML file containing Swedish characters in using Python's LATIN1 codec. (2) write the same file out using Python's UTF-8 codec (3) read file with xml.minidom, but get error when writing using dom.toxml(): "UnicodeError: ASCII encoding error: ordinal not in range(128)" More detailed: (1) Python version: Python 2.1 (#1, Apr 17 2001, 20:20:54) [GCC 2.96 20000731 (Red Hat Linux 7.0)] on linux2 (2) Code: #!/usr/bin/python2.1 import codecs import xml.dom.minidom import string try = 'doc.swedish.xml' out = 'doc.utf8.xml' out2= 'del.me' outout = 'doc.utf8.after.xml' def main(): (LATIN1_encode, LATIN1_decode, LATIN1_streamreader, LATIN1_streamwriter) = codecs.lookup('ISO8859-1') (UTF8_encode, UTF8_decode, UTF8_streamreader, UTF8_streamwriter) = codecs.lookup('UTF-8') input = LATIN1_streamreader(open(try, 'r')) s = input.read() input.close() output = UTF8_streamwriter( open(out, 'w') ) output.write(s) output.close() f = open(out, 'r') g = open(out2, 'w') f_list = f.readlines() f.close() del f_list[0] f_list.insert(0,'') g.writelines(f_list) g.close() ff = open(out2, 'r') dom = xml.dom.minidom.parse(ff) gg = open(outout, 'w') gg.write(dom.toxml()) if __name__ == '__main__': main() (3) File "doc.swedish.xml": Demo slidesh?w (4) Traceback: Traceback (most recent call last): File "./q_mini4.py", line 49, in ? main() File "./q_mini4.py", line 46, in main gg.write(dom.toxml()) UnicodeError: ASCII encoding error: ordinal not in range(128) lxl01:/public/www/snac/Spring_2001/adm/crontab> (5) Observations: (a) The characters look fine in the input file. A simple in and out decoding of them using LATIN1 codec for both in and out produces the same file as the original. (b) The output UTF8 file does change the umlauted o to a different looking couple of characters (c) If the Swedish character is replaced by a regular "o" in the input file, everything works fine. (d) Yikes! This shouldn't be that hard! From scarblac at pino.selwerd.nl Mon May 21 17:59:02 2001 From: scarblac at pino.selwerd.nl (Remco Gerlich) Date: 21 May 2001 21:59:02 GMT Subject: bracing for a firestorm References: <93d9a839.0105210833.6da56b58@posting.google.com> <3d1ypi4n8x.fsf@mems-exchange.org> Message-ID: Andrew Kuchling wrote in comp.lang.python: > rzantow at usa.net (- RZ) writes: > > Can anyone tell me what would be involved in creating a version of > > Python that used {braces} as its indent/dedent delimiters? What > > modules would have to be changed? > > Probably just hacking the tokenizer so that '{' returns INDENT and '}' > returns DEDENT. While probably not completely trivial, I can't see > this taking more than an evening's work to get an initial hack > running. But then, dictionaries also use { }... -- Remco Gerlich From aleaxit at yahoo.com Mon May 28 05:14:35 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 28 May 2001 11:14:35 +0200 Subject: writing extension -- custom type validation References: Message-ID: <9et4se02sfp@enews1.newsguy.com> "Eric Hagemann" wrote in message news:TniQ6.31542$G5.6615112 at news1.rdc1.md.home.com... > I am making a new data type in an extension module. > > Is there as way to detect / check for a custom type (of the type I am > creating) from a PyObject ? Of course. You normally define an appropriate macro: #define PyPloppy_Check(v) (((PyObject*)v)->ob_type == &PyPloppy_Type) Alex From see at my.signature Wed May 9 22:50:23 2001 From: see at my.signature (Greg Ewing) Date: Thu, 10 May 2001 14:50:23 +1200 Subject: Baffling extension module compile problem Message-ID: <3AFA01EF.CE6CC0F9@my.signature> I have a REALLY screwy problem. I'm working on a C extension module. If I issue my 'make' command from the shell, everything is fine. But if I use the 'make' command in Emacs, the resulting module causes a seg fault when I import it! Exactly the same compile/link commands are being executed in both cases, and proceed without error. My LD_LIBRARY_PATH is the same in both environments as far as I can tell. Examining the core file after the crash reveals that somehow Py_InitModule4 is being called with junk for the first argument (i.e. the module name). This is the only part of the code that is executed on import: static PyMethodDef LSInter_methods[] = { {"fit", LSInter_fit, METH_VARARGS}, {NULL, NULL} }; DL_EXPORT(void) initLSInter() { PyObject *m, *d; m = Py_InitModule("LSInter", LSInter_methods); d = PyModule_GetDict(m); } Does anyone have any idea what sort of weird juju is going on? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From s713221 at student.gu.edu.au Sat May 19 12:08:57 2001 From: s713221 at student.gu.edu.au (s713221 at student.gu.edu.au) Date: Sat, 19 May 2001 16:08:57 +0000 Subject: Playing with Dict - Can anyone see a way around this? Message-ID: <3B069A99.18AF2522@student.gu.edu.au> Somebody mentioned in this group a couple of months ago, the posibility of making [].keys, [].items and [].values directly scriptable, so you could iterate over them either by calling them, or by treating them as lists. I've taken their suggestion as far as I can go as an exercise in curiosity, but have run into a little bit of a problem. I took their suggestion of making keys, values and items, classes rather than functions. class MyDict: def __init__(self): self.dict = {} self.keys = self.__keys(self.dict) self.items = self.__items(self.dict) self.values = self.__values(self.dict) def __getitem__(self,item): return self.dict[item] def __setitem__(self,item,value): self.dict[item] = value def __getattr__(self,key): if key in ['keys','items','values']: return self.__dict__[key] else: return self.dict[key] def __repr__(self): return str(self.dict) def __delitem__(self,item): del self.dict[item] class __keys: def __init__(self,dict): self.dict = dict def __repr__(self): return str(self.dict.keys()) def __call__(self): return self.dict.keys() def __getitem__(self,item): return self.dict.keys()[item] class __items: def __init__(self,dict): self.dict = dict def __repr__(self): return str(self.dict.items()) def __call__(self): return self.dict.items() def __getitem__(self,item): return self.dict.items()[item] class __values: def __init__(self,dict): self.dict = dict def __repr__(self): return str(self.dict.values()) def __call__(self): return self.dict.values() def __getitem__(self,item): return self.dict.values()[item] Now this mostly works >>> a = MyDict() >>> for i in range(10): a[i] = i >>> a {9: 9, 8: 8, 7: 7, 6: 6, 5: 5, 4: 4, 3: 3, 2: 2, 1: 1, 0: 0} >>> a.keys [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> a.values [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> a.items [(9, 9), (8, 8), (7, 7), (6, 6), (5, 5), (4, 4), (3, 3), (2, 2), (1, 1), (0, 0)] And it's possible to iterate over a.items in the following ways: >>> for i in a.keys: print i, 9 8 7 6 5 4 3 2 1 0 >>> for i in a.keys(): print i, 9 8 7 6 5 4 3 2 1 0 >>> for i in a.items(): print i, (9, 9) (8, 8) (7, 7) (6, 6) (5, 5) (4, 4) (3, 3) (2, 2) (1, 1) (0, 0) However, I've hit a rather interesting hiccup, due to i.keys returning the class __keys, rather than a list of keys. Umm, it's explained better in the example. Now everything looks okay at first glance, due to some hacking on __keys.__repr__ >>> b = a.keys >>> b [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] But watch what happens when I iterate over a.keys and change the dictionary in place. >>> for i in a.keys: print i del a[i] 9 7 5 3 1 >>> a {8: 8, 6: 6, 4: 4, 2: 2, 0: 0} Whoops. Not what I wanted. And this invalidates my aim of having a.keys and a.keys() acting the same way. >>> for i in a.keys(): print i del a[i] 9 8 7 6 5 4 3 2 1 0 >>> Anycase, can anyone see a way around this? This is mostly for curiosity, but I'm damned curious at the moment. Joal Heagney/AncientHart From qrczak at knm.org.pl Wed May 2 04:34:09 2001 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: 2 May 2001 08:34:09 GMT Subject: Formatting numbers References: <7oquetg5hvmt7mijn9jkutemo6e6uotroa@4ax.com> Message-ID: Tue, 01 May 2001 19:04:37 -0700, Daniel Klein pisze: > Thanks Matt. This works fine for some numbers but not all. :-( > Try it with 123456 to see what I mean. "%.2f" % (123456 / 100.0) works fine. -- __("< Marcin Kowalczyk * qrczak at knm.org.pl http://qrczak.ids.net.pl/ \__/ ^^ SYGNATURA ZAST?PCZA QRCZAK From dalke at acm.org Sun May 13 14:17:50 2001 From: dalke at acm.org (Andrew Dalke) Date: Sun, 13 May 2001 12:17:50 -0600 Subject: Advice on optimium data structure for billion long list? References: <3AFD60E6.4090805@herts.ac.uk> Message-ID: <9dmjn7$uu1$1@nntp9.atl.mindspring.net> [CC'ed response to Blobby as well] Mark blobby Robinson: > [asked about storing a large number of 15-mer substrings for > some pattern match work he's doing against DNA data] Here's a few ideas. Don't store your keys as a full string. Encode them. You're already assuming ATCG are enough, so you can use 2 bits instead of 8. This can be done with a C extension. If all strings are 15 bases then you only need 30 bits. You say there are ~1.4 billion possible entries, which is 4**15 + 4**14 + 4**13 + 4**12 + ... 4**1 + 4 ** 0 and implies you also have strings of length less than 15. This means you also need to encode the length since 4 bits doesn't encode a termination character. A simple length encoding needs at least 4 bits (2**4 = 16), which puts each key as 34 bits. HOWEVER, suppose you encode the first few bits to mean 00 - 15 bases encoded (plus 30 for the bases = 32 bits total) 01 - 14 bases encoded (plus 28 for the bases = 30 bits total) 11101 - 13 bases encoded (plus 26 for the bases = 31 bits total) 11100 - 12 bases encoded (plus 24 for the bases = 29 bits total) 11011 - 11 bases encoded (plus 22 for the bases = 27 bits total) 11010 - ... so this is a way (amoung many) to fit all of your fragments in a 32 bit word. This encoding can be done with a simple C extension. The 32 bits works nicely as the hash for the entry. You haven't said how you store the values for each entry. Most likely it will be a list of record identifiers. I know there are fewer than 2**32 sequence records - GenBank has O(11M) records so they can be stored in 24 bits. It's likely even less since there are ways to encode lists of integers of this sort. Get a copy of "Managing Gigabytes" which describes several ways to do this encoding. There are 12G bases in GenBank. Assuming you have every 15 base substring in GenBank, that's 180G. Only 1.4G are unique, so there are on average (in the worst case) 130 entries per key, or about 0.5KBytes per value. You haven't mentioned the memory contraints on your machine. You really, really want everything to be in memory. One way to do this is read everything into memory as much as possible. When memory fills, write the intermediate data structure to disk, reset the data structure and process the next input block. Repeat until done. After the data is read, sort and merge the written blocks to produce on on-disk data structure for the whole input data. Again, Managing Gigabytes describes some ways to do this. You'll likely want all of this as a C extension in order to manipulate all of the bits directly. This option (multiple writes followed by merge) can be easily parallized. (As Alexandre Fayolle and others suggested.) Most likely you will not have all 1.4G possible combinations. There are lots of tradeoffs you can do depending on how much memory you have, the amount of data and what you want to do with the result. Still, this should be enough to point out a few possibilities or enable you to better evaluate other possibilities. Eg, consider Dave LeBlanc's suggestion to use bsddb (I assume bsddb3). It implements a key-value data structure which is persistent on disk and as I recall uses an in-memory cache. If there is a distribution of 15mers or your data size is small then you should be able to get good cache coherency and use it to store the the 32 bit encoded key and <~0.5KByte encoded values. It's only when you have these really large data sets that that might begin to yield problems. It all depends on what resources and limitation you have. Andrew dalke at acm.org P.S. You could also try this question on one of the biopython.org mailing lists. From meowbot at meowing.net Tue May 22 21:37:23 2001 From: meowbot at meowing.net (A Meowbot) Date: 22 May 2001 21:37:23 -0400 Subject: rfc822.Message mapping interface In-Reply-To: barry@digicool.com's message of "Tue, 22 May 2001 10:06:49 -0400" References: <87elthg2bb.fsf@ppp31-44.gis.net> <15114.29305.612107.66787@anthem.wooz.org> Message-ID: <87n184voa4.fsf@litterbox.meowing.net> [Hm, this made it to python-list but not the newsgroup. Odd.] barry at digicool.com (Barry A. Warsaw) wrote: > I think it's just that the docs need updating. *whew* > If you're doing MIME, please check out http://sf.net/projects/mimelib > for a candidate of a next generation replacement for mimetools, > rfc822, MIMEWriter, etc. I've got a small backlog of updates to the > code there that I'll try to check in shortly. Oo, shiny, and items() does the Right Thing this time around! Only had a couple hours to play with this as yet, but it sure looks like it does a nice job of avenging the sins of the current message handlers. FWIW, this is a message filter embedded in a C program and I'm trying to make it easy for the user to take advantage of Python's stock Message-like objects. It looks like since the rfc822 and mimelib Message objects do both parse file-like objects and return compatible items() lists, the user can work from either module family and have everything Just Work. I like. Thanks Barry and Fred for the clarification and new toy. From loewis at informatik.hu-berlin.de Thu May 24 11:05:32 2001 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 24 May 2001 17:05:32 +0200 Subject: Python and Autoconf References: <3B0AACD0.654DE0A5@enabledventures.com> Message-ID: Glen Starchman writes: > Anyone have any more Python-specific autoconf macros? While I believe that you can solve your problems with autoconf, you may consider using distutils for the Python parts. That has a convenient procedure for building and installing Python libraries, both for Python and C modules. Also, much of the compile-time configuration stuff is often done at runtime. E.g. you don't check at installation time whether a certain module is available (unless you plan to install it if it is not). Instead, if you have fallback code, you perform a runtime check by importing the module, and falling back on ImportError. You can still integrate distutils nicely into a make(1) driven build procedure, see Python 2.1 for an example. Regards, Martin From aleaxit at yahoo.com Fri May 25 12:08:35 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 25 May 2001 18:08:35 +0200 Subject: Flatten... or How to determine sequenceability? References: Message-ID: <9em0160j7s@enews1.newsguy.com> "Noel Rappin" wrote in message news:mailman.990802119.12058.python-list at python.org... > I'm writing code that needs to flatten a multi-dimension list or tuple into > a single dimension list. > > [1, [2, 3], 4] => [1, 2, 3, 4] > > As part of the algorithm, I need to determine whether each object in the > list is itself a sequence or whether it is an atom. Using the types module > would cause me to miss any sequence-like object that isn't actually the > basic type. So, what's the best (easiest, most foolproof) way to determine > whether a Python object is a sequence? Hmmm -- good question. Checking whether x[:] raises an exception is reasonable, but a mapping that accepts slice objects would fool this test. I _suspect_ the most-foolproof test today might be: def is_sequence(x): try: for _ in x: return 1 else: return 1 # empty sequences are sequences too except: return 0 However, if I understand correctly, this would break in 2.2, since mappings then also become usable in a for statement, not just sequences. This would then incorrectly identify _any_ mapping as "a sequence", too. What *IS* there that you can do ONLY to a sequence, ANY sequence, but NOT to any mapping...? zip(), which seems like it could serve, apparently does NOT test its arguments for "sequencehood" (well, depending how you define that, I guess...): it does a PySequence_GetItem, and fails iff that fails with other than an IndexError. >>> class x: ... def __getitem__(self, k): return k ... >>> a=x() >>> zip(a,'x') [(0, 'x')] map() and friends would be slow on long sequences, AND do require a sequence to have a length to accept it, too. I'm almost tempted to propose a tiny extension module, since the C-API level *DOES* expose an "is-a-sequence" test...: #include "Python.h" static PyObject *is_seq(PyObject* self, PyObject* args) { int i, rc; PyObject *arg; if(!PyArg_ParseTuple(args, "O", &arg)) return 0; return Py_BuildValue("i",PySequence_Check(arg)); } static PyMethodDef sq_module_functions[] = {{ "is_seq", (PyCFunction)is_seq, METH_VARARGS }, { 0, 0 }}; voidinitsq(void) { PyObject* sq_module = Py_InitModule("sq", sq_module_functions); } and of course the setup.py to go with it: from distutils.core import setup, Extension sq_ext=Extension('sq', sources=['sq.c']) setup(name="sq", ext_modules=[sq_ext]) but that doesn't seem fair... ...plus, it ALSO gets thrown by above-exemplified object a from class x...! So, maybe zip IS best after all, something like: def is_sequence(x): try: zip(x,'') except: return 0 else: return 1 Oh BTW -- all of these methods will see a string or unicode object as a 'sequence', because it IS one by Python's rules (you can index and slice it, loop on it with for, &c). Most often in such tasks one wants to consider strings as atoms, but that will require some further special-casing, anyway. Alex From thomas at xs4all.net Sat May 26 05:12:55 2001 From: thomas at xs4all.net (Thomas Wouters) Date: Sat, 26 May 2001 11:12:55 +0200 Subject: Python vs. Perl In-Reply-To: ; from gisle@ActiveState.com on Sat, May 26, 2001 at 04:22:47AM +0000 References: <20010525203358.S690@xs4all.nl> Message-ID: <20010526111255.U690@xs4all.nl> On Sat, May 26, 2001 at 04:22:47AM +0000, Gisle Aas wrote: > Thomas Wouters writes: > > God, yes. That was in the top-2 of my Perl hash annoyances :) The top-1 is, > > of course, that you have to go through oddball magic just to see what a hash > > contains. I prefer 'print dict' . > I would not really call invocation of a function "oddball magic": > print Dumper($hash); It is if you have never heard of 'Dumper' once in 4 years of programming Perl, while sitting across the room from a Perl guru who started programming in Perl 3 ;) -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! From see at my.signature Thu May 10 00:11:38 2001 From: see at my.signature (Greg Ewing) Date: Thu, 10 May 2001 16:11:38 +1200 Subject: Range Operation pre-PEP References: <3AF8D070.B0ECF09A@my.signature> <9db0u6018es@news2.newsguy.com> Message-ID: <3AFA14FA.B604683A@my.signature> Douglas Alan wrote: > > Speaking of creeping-featurism, how come we have list comprehension, > but not tuple comprehension? Who says we don't? tuple([2*i for i in [1,2,3]]) :-) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From Darren.Watson3 at ntlworld.com Fri May 18 19:35:41 2001 From: Darren.Watson3 at ntlworld.com (Darren Watson) Date: Sat, 19 May 2001 00:35:41 +0100 Subject: Determining an Image Size? Message-ID: Hi I know very little about image formats, but I am very interested in finding out if it is possible to determine the dimensions (in pixels) of a JPEG or GIF file from a Python script. I would be grateful for any ideas Many Thanks Darren Watson From helend at accessone.com Wed May 30 02:54:01 2001 From: helend at accessone.com (Helen Dawson) Date: Wed, 30 May 2001 06:54:01 GMT Subject: O(n^2) is bad - can it be fixed? References: Message-ID: <3B1499A7.446F1FD4@accessone.com> Tim Peters wrote: > [Tim] > In the meantime, I did check in a change (for 2.2) that continues to do mild > over-allocation, but on a sliding scale that doesn't think the world ends at > 500 elements. This speeds real-life appends, but mostly because it gets rid > of the current integer multiplication and division in favor of simple bit > shifts. For what it's worth - this might actually be one point in MS's favour. If I remember correctly the divides in the roundup() routine are all dividing by integer constants. VC++ deals with those very nicely. In optimized builds (optimized for speed anyway) it is impossible to get it to emit a divide instruction - it always replaces it with bit shifts. It does a particularly efficient job if the number you are dividing is unsigned. It doesn't matter what number you divide by - it knows how to simulate dividing by every integer I've ever tested with. So, you may have improved on a Win32-only problem, and also improved on a non-Win32-only problem also. The symmetry appeals to me. Bruce/Helen Dawson From tjg at hyperlinq.net Thu May 10 13:05:05 2001 From: tjg at hyperlinq.net (Timothy Grant) Date: Thu, 10 May 2001 10:05:05 -0700 Subject: Reading & Writing Python OK, Now I need to Speak It In-Reply-To: ; from ljohnson@resgen.com on Thu, May 10, 2001 at 08:19:49AM -0500 References: <3AFA1ABA.C1911B82@home.com> Message-ID: <20010510100505.Q2224@trufflehunter.avalongroup.net> On Thu, May 10, 2001 at 08:19:49AM -0500, Lyle Johnson wrote: > > How do you say (pronounce) "__init__", for example. Having to say > > > "double-underscore-double-underscore-init-double-underscore-double-underscor > e" > > gets awfully tedious after a while. > > I think the underscores are silent and you can just say "init". > I concur. Around here we just talk about a the "init method" -- Stand Fast, tjg. Timothy Grant www.hyperlinq.net Chief Technology Officer tjg at hyperlinq.net HyperLINq Technologies, Inc. <>< (503) 246-3630 >>>>>>>>>>>>>Linux, because rebooting is *NOT* normal<<<<<<<<< >>>>This machine was last rebooted: 43 days 19:17 hours ago<< From dsh8290 at rit.edu Fri May 18 11:07:22 2001 From: dsh8290 at rit.edu (D-Man) Date: Fri, 18 May 2001 11:07:22 -0400 Subject: GNU/Linux vs. Windows as Python platform In-Reply-To: ; from reedy37@home.com on Fri, May 18, 2001 at 07:19:21AM +0000 References: <97WM6.478$uk2.228879@news1.rdc2.pa.home.com> Message-ID: <20010518110722.D6585@harmony.cs.rit.edu> On Fri, May 18, 2001 at 07:19:21AM +0000, Terry Reedy wrote: | | and wonder if there might be good enough reasons to add Linux to this or my | next machine, perhaps within the next year. Sure -- Linux is stabler, faster, and more useable (all IMO) than Windows. :-) | By binaries, I was thinking of extension modules like PIL, wxPython, etc | for which the developers have often made Windows binaries but not | everything else. # for PIL $ apt-get install python-imaging # for wxPython $ apt-get install libwxgtk2.2-python Check out Debian's package list at http://packages.debian.org Debian has a lot (>4000 I think) packages. There are a lot of prebuilt python extensions neatly bundled up into packages. Installation is as simple as the above commands. -D From theservo at bellsouth.net Sat May 19 23:29:35 2001 From: theservo at bellsouth.net (Servo) Date: Sat, 19 May 2001 22:29:35 -0500 Subject: web page programs References: Message-ID: Yeah the main window for the program will display the webpage, and from there you'll enter information into the database. I just have to figure out how to get the information from the web page fields to the database w/o using a server. "Nick Perkins" wrote in message news:REGN6.15813$eK2.2813326 at news4.rdc1.on.home.com... > ...so you mean not an internet app, but just an app that displays an html > page in it's window? > if so, i think that most gui toolkits have a simple control that will do it. > (eg. wxHtmlWindow in wxWindows, ..something else in Tkinter, etc..) > > > From aleaxit at yahoo.com Wed May 2 10:50:17 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 2 May 2001 16:50:17 +0200 Subject: glob and os.path.walk (was Re: pygrep) References: Message-ID: <9cp6rl01oqb@news2.newsguy.com> "Mike Brenner" wrote in message news:mailman.988808473.19351.python-list at python.org... [snip] > Therefore, it would be nice if Python had a way of expanding > the second argument, both the stars and question marks, and Check out module glob in the standard Python library. > also the ability to iterate through all files at all levels. Also check out function walk() in module os.path, also in the standard Python library. > This would be WITHIN python, not depending on the operating > system to do it. They delegate appropriately to the operating system (how else would they find out about what files live in what directory, if not by appropriately asking the os...?). Alex From sholden at holdenweb.com Tue May 8 22:08:42 2001 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 8 May 2001 22:08:42 -0400 Subject: socket.recvfrom() & sendto() References: Message-ID: "Ron Johnson" wrote ... > Steve Holden wrote: > > > "Ron Johnson" wrote in ... > > [ ... ] > >> > >> It seems like the server *and* the client both must use asyncore. > >> But does asyncore, underneath it all, sit at select.select() waiting > >> on the next readable socket? So if the client is also using asyncore, > >> does it need a thread for network IO and a thread for user interaction, > >> and the 2 threads talk to each other? > >> > > Nope. The advantage of asyncore, and Medusa, is that you don't *need* > > separate threads. You create a separate object for each dialog > > (connection), which holds the stat information for that connection, and > > the whole program just becomes one big select() loop, where each > > connection object is told when there is data to be read, when it can > > write, and so on. > > > > So it's a single thread, processing multiple objects asynchronously, > > depending on events which are detected by the use of select(). > > > > When you start, it's about as weird as your first GUI-based program -- > > event-driven programs are held together by string! > > Interesting. > > Since the server can send messages to the client at random and > irregular interevals, how can the client accept input from the > user at the same time that it is "stalled" at a select() ? > Under Unix I *believe* that select() can treat a tty channel like a socket, but under Windows I understand that select() only works on sockets. One possibilty (not perhaps the best one) would be to make your client module receive input from a separate user interface module over a local (loopback) socket, which would put user input on a par with network input at the expense of some structural inconvenience. > The server side I think I understand, at least from the perspective > of *my* needs: the server sits at a select() until it detects (an) > incoming message(s) from client(s); it then processes the message, > sends messages back to the sending client(s) and also possibly other > clients, then goes back to the select(). > That's the ticket. regards Steve From dnew at san.rr.com Tue May 15 17:35:20 2001 From: dnew at san.rr.com (Darren New) Date: Tue, 15 May 2001 21:35:20 GMT Subject: What can you do in LISP that you can't do in Python References: <3AFFFB0E.70A8B5BF@wag.caltech.edu> <9dpqra$5gl$1@newsy.ifm.liu.se> <9dreda$oao$1@saltmine.radix.net> <9dro3r$rnp$1@newsy.ifm.liu.se> Message-ID: <3B01A118.F461FFFB@san.rr.com> Thomas Bellman wrote: > Assume that you have a bunch of things to do. Before each > operation, you want to call spam(), and after the operation, you > want to call eggs(). I.e the equivalent of > > def spam_and_eggs(code): > spam() > exec code > eggs() > > In LISP: > > (defmacro spam-and-eggs (&rest code) > `(progn > (spam) > , at code > (eggs))) > > Now, you have fifty different things that you want to do, each > thing "protected" with spam-and-eggs, and they should be done in > a row: In Tcl, something like proc spam_and_eggs {thinglist} { foreach code $thinglist { spam uplevel -1 exec $code eggs } } # Note that "uplevel" is there to keep the things in thinglist # from seeing "code" as a local variable. I might have the syntax # on the uplevel call wrong. spam_and_eggs { {this thing that thing} {The second thing second half} } This would run spam this thing that thing eggs spam The second thing second half eggs If you want to parse Tcl code, it's very easy. There are routines to parse strings into individual commands. Other fun Tcl stuff: proc xxx {name parms body} { origproc $name $parms "start $name\n$body\nend $name" } rename proc origproc ; rename xxx proc Now everything after that calls "start" at the start of each body and "end" at the end (assuming no "return" in there). You can also do things like iterating thru all the functions that start with "impl_*" and parsing the argument lists to generate a usage message automatically. You can iterate through a namespace to find all the functions declared there and delegate from your namespace to that other namespace, which is handy when doing layered network protocol design. Etc. Not noticably harder in Tcl than Lisp. > In LISP, the macro basically gets passed a parse tree of the > code. Since Tcl is linear, there's no need to pass a parse tree. I.e., since code and data are the same thing, you don't need to pre-parse it. It's all strings. > (Or of whatever kind of data you give it as an argument; > LISP doesn't distinguish between code and data the way many other > languages do.) Neither does Tcl, often to the surprise of people expecting comments to still be comments inside of strings that look like code. -- Darren New / Senior MTS & Free Radical / Invisible Worlds Inc. San Diego, CA, USA (PST). Cryptokeys on demand. This is top-quality raw fish, the Rolls-Rice of Sushi! From greg at pdxperts.com Sun May 20 22:37:22 2001 From: greg at pdxperts.com (Greg Jorgensen) Date: Mon, 21 May 2001 02:37:22 GMT Subject: How to Read/Write RTF and Word Files? In-Reply-To: <3b06b81e_3@news4.newsfeeds.com> References: <3b06b81e_3@news4.newsfeeds.com> Message-ID: On Sat, 19 May 2001, Dry Ice wrote: > How to Read/Write RTF and Word Files? > > Any suggestions on modules or code which > will allow reading and writing of the above? RTF is a published format. The standard isn't as rigourously followed as one would like, but it is more consistently implemented than HTML. Microsoft defined RTF and you can find the documentation on their site. Start at the knowledge base article: http://support.microsoft.com/support/kb/articles/Q86/9/99.ASP Microsoft Word uses a proprietary and undocumented format for .doc files. The Word file format has changed significantly across versions of Word. Whether by reverse-engineering or licensing the spec from Microsoft, quite a few companies have implemented at least some Word import/export capabilities. Microsoft also gives away Word document reader. I don't believe they have a Linux version, though. But you don't need Word to view Word documents if you have Windows or Mac OS running. The free Word reader may work under Wine; it certainly works under VMWare. Greg Jorgensen PDXperts LLC Portland, Oregon, USA From stephen_purcell at yahoo.com Mon May 14 23:23:19 2001 From: stephen_purcell at yahoo.com (Steve Purcell) Date: Tue, 15 May 2001 11:23:19 +0800 Subject: Python programmers at Shanghai Linux Expo? Message-ID: <20010515112319.A26386@freedom.puma-ag.com> Are any Python programmers on this list planning to be at the Shanghai Linux Expo this week? http://www.linuxexposhanghai.com/ If anybody is interested in meeting up there, send me a mail. Having traded programming Python for eating it this month in China, I'd like to find out how the language is doing here. -Steve -- Steve Purcell, Pythangelist Get testing at http://pyunit.sourceforge.net/ Any opinions expressed herein are my own and not necessarily those of Yahoo From meh9 at cornell.edu Thu May 17 10:55:13 2001 From: meh9 at cornell.edu (Matthew Hirsch) Date: Thu, 17 May 2001 10:55:13 -0400 Subject: $PYTHONHOME Message-ID: <3B03E650.6D33B050@cornell.edu> Hi, I'm using Python on a hp-unix machine. This is what I get when I type python at the prompt (I added it to my path already). $python Could not find platform dependent libraries Consider setting $PYTHONHOME to [:] Python 1.5.2 (#1, Jan 3 2000, 15:54:36) [GCC 2.95.2 19991024 (release)] on hp-uxB Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> The python directory is under /usr/local/. I found a directory /usr/local/python-1.5.2/lib/python1.5/plat-hp-uxB. I'm guessing that this is the directory for the platform dependent libraries. I tried adding $PYTHONHOME=/usr/local to my .profile but it didn't make a difference. Is there a root profile that I need to change? Thanks for your help, Matt From kzaragoza at mediaone.net Thu May 10 14:17:55 2001 From: kzaragoza at mediaone.net (Kris J. Zaragoza) Date: Thu, 10 May 2001 18:17:55 GMT Subject: Why aren't we all speaking LISP now? References: <9dc2d8$tck$1@slb6.atl.mindspring.net> <3AFAD323.986CDA55@san.rr.com> Message-ID: On Thu, 10 May 2001 17:42:59 GMT, Darren New wrote: >Grant Edwards wrote: >> I would have to disagree. CS is much more closely related to >> math than to Science. > >It's actually a combination of math and engineering and science, IMHO. > >It's math with a limit on the size of sets and numbers of alphabets you >can have. The truly "theoretical computer science" falls under "what can >we do with an infinite-size infinite-speed computer." That nobody has >built such a beast is what adds the engineering to the comp sci. > >The other point to note is that computer science has a lot to do with >people as well as math. So studying how people interact with computers, >for example, in order to improve your GUI, is quite a lot like science. >We'd all be programming turing machines if there wasn't any real-world >science going on. I mean, what's the mathematical basis of preferring >object-oriented programming over procedural? Absolutely. I would say that the human element and application on deterministic, physical machines are what set Computer Science apart from pure mathematics. These are things that can be measured, modified, and measured again, applying proper scientific methods of experimentation. Without these aspects of CS, I would have to agree with the earlier poster about CS simply being math. > >And of course there's the whole field of "AI", whatever's included there >this year. Much of the linguistics going on there is done as science >rather than math. > Actually, sometimes I wonder whether AI and it's related fields qualify CS as some sort of black magic. ;-) -Kris -- Kris J. Zaragoza | "Unfortunately, most people can't out-think a kzaragoza at mediaone.net | grapefruit." --Jon Bodner From bedge at troikanetworks.com Wed May 2 09:50:20 2001 From: bedge at troikanetworks.com (Bruce Edge) Date: Wed, 02 May 2001 06:50:20 -0700 Subject: Tabs and spaces (style) - the only real issue References: Message-ID: <20010502.065020.588219756.9225@mead.troikanetworks.com> There is only one issue I can see with using tabs. When used in conjunction with the readline completer, pasting code from you editor yields garbage as readline tries to complete each tab. I'd love to know of a way around this, like maybe preventing tab completion of there is nothing on the line at a secondary prompt. Pasting: def cexec(args): """Provide a conveniant access point for running CLI type commands from a python shell """ # Run entered command g.ctree.execute( args ) yields: >>> def cexec(args): ... ArithmeticError """Provide a conveniant access point for running CLI type commands IndentationError: expected an indented block (line 2) >>> ArithmeticError from a python shell File "", line 1 ArithmeticError from a python shell ^ SyntaxError: invalid syntax >>> ArithmeticError """ ... ArithmeticError # Run entered command ... ArithmeticError g.ctree.execute( args ) In article , "Cantanker" wrote: > What is the consensus about mixing tabs and spaces in a Python script? > > Don't people find it plain annoying to come across a bunch of scripts > where the author has obviously used a tabsize of 8 characters, and > alternated expanded tabs (4-spaces) and real tab characters (not wanting > to name names here *cough*Mailman*cough*). It makes for a real PITA when > you set your editor to display tab characters with a width of 2, or 4 > spaces, and the code doesn't line up properly. > > It imposes one author's choice of tabsize onto everyone else. > > Thoughts? > > From andrew at one.net.au Wed May 2 18:23:16 2001 From: andrew at one.net.au (Andrew Maizels) Date: Thu, 03 May 2001 08:23:16 +1000 Subject: Using Lisp to beat your Competition References: <3AF01D77.27AC4D3@one.net.au> <00B986A155D4FA7E.A6A6D7993AFAAF7A.82977DA072669707@lp.airnews.net> Message-ID: <3AF088D4.379C28B8@one.net.au> Cameron Laird wrote: > > In article <3AF01D77.27AC4D3 at one.net.au>, > Andrew Maizels wrote: > . > . > . > >languages (Java, C, C++). It isn't a "silver bullet", but it can speed > >up the development process as much as 5 times. > . > . > . > That's the narrow-sense development process, where > employed programmers only spend ten hours a week of > their time anyway. The rest goes to figuring out > hardware failures, planning lunch destinations, > tracking down what happened to all the bandwidth > someone just ordered, learning about the latest > corporate reorganization, ... Yes and no. If those 10 hours of actual coding now produce 50 hours worth of results, overall productivity goes up by a factor of five anyway (measured in terms of LOC, function points, whatever). I've seen that happen. On the other hand, if the programmer now spends 2 hours per week coding and an extra 8 hours vacuuming the cat, it doesn't help so much. I've seen this happen too. Andrew. -- There's only one game in town. You can't win. You can't break even. You can't quit the game. -- The four laws of thermodynamics. From nessus at mit.edu Thu May 3 03:41:18 2001 From: nessus at mit.edu (Douglas Alan) Date: 03 May 2001 03:41:18 -0400 Subject: do...until wisdom needed... References: <9be84s0q12@news1.newsguy.com> <9bfjoc0cjh@news2.newsguy.com> <9bfq560noo@news2.newsguy.com> <87n19fvdzo.fsf_-_@elbereth.ccraig.org> <9biukr$lu8$1@nntp9.atl.mindspring.net> <9cqpq9$dvm$1@nntp9.atl.mindspring.net> Message-ID: "Andrew Dalke" writes: > Douglas Alan replied: > >Procedural macros are best left to the experienced professional > >programmer to implement. The more casual programmer can significantly > >benefit from the work of the expert, though. > Hmmm. I am an experienced professional programmer, at least for my > field. And I don't want to touch procedural macros. From what I've > heard from others in private mail, too often non- "experienced > professional programmers" end up making their own dialect, and the > result is a Babel of code. The same thing is true when non-"experienced programmers programmers" make a new library module of any sort. Any bad library can be a nightmare to maintain and propagate bad coding style. I've seen quite the doozies in my time. > As one person > commented to me: > ] If you give people extensible syntax, and Andrew and I adopt > ] different dialects of python, then instead of getting a bug fix, I > ] will get, '`I am sorry, but I don't have time to learn your macro > ] system.' or even worse, `I haven't used regular python for so > ] long, that I forget how it works'. This is precisely what > ] happened to me [..when I..] decided writing my own lisp macros to > ] do physics in was a good idea. It was a terrible, terrible, > ] horrible mistake. I doomed myself to doing ALL the physics in the > ] world. Same thing happens without macros. I use all sorts of library routines in my code that I implemented to make my life much easier. Then when someone comes to me that doesn't have my group's module library, I either have to have them take our module library, or I have to program in a hamstrung manner. > My main expertise is developing infrastructures that allow widely > different tools to interoperate. As such, I aim to reduce the > amount of variety so people can work on getting their research done, > not figuring out how to use the tools. Nearly everything I hear > suggest that procedural macros don't help reduce complexity. All tools can be used for good or evil. You use the tool wisely, it makes your life easier; you use the tool foolishly and you make life difficult for you. If it's a good tool, I'd prefer to have the tool and the choice than be denied the tool. > I still maintain that having the Python source code available gives > at least comparable advantages to procedural macros. If someone > wants to implement new behaviour, it can be done without all that > much work. The big advantage is that all of these changes don't get > propagated willy-nilly. Reuse by diverging source code is extremely bad. It's the worst maintenance nightmare imaginable. > Either you take the hit of distributing a new Python-derived > language (as with Alice) or it's good enough that Guido accepts it > into the core, in which case it isn't a dialect. In either case, it > makes you think strongly about the worth of the new language > extension. Most likely the steep slope of that approach makes you throw up your hands and do things in a less productive and harder to maintain manner, no matter how much gain the extension would provide. > Yes, doing this required using a non-Python language for the > implementation, but as I've said I don't believe in restricting > myself to one language. Yes, it reduces the ability of just anyone > to modify the language, but you are already saying the only ones > qualified to change a language are "experienced professional > programmer"s, and they should have no problem with C. Yes, it calls > for more work to implement, but I'm not convinced it should be easy. There's just no way that I would modify the Python source for any project that I was working on, unless absolutely necessary. And even then I'd hand my head in shame and consider myself criminally negligent. > Other ways to get around the lack of procedural macros were > mentioned (besides changing the language core): > - calling a library function to parse an alternate language > - importing the new code via a modified import hook > (this could be made easier with the work on a library > to build ASTs for Python) > - writing a C extension which uses the metaobject interface, > as with the Persistence type in Zope. (This can only > change the object behaviour.) Well, no doubt what I'd do is just write a preprocessor for Python that implements procedural macros. But I'd feel bad about doing this -- it would be difficult to maintain Python's RAD interactive feel without spending a lot of effort on it. > So who all is affected by the lack of procedural macros in a way > that cannot be supported by one of these mechanisms? I suspect it's > a small audience. Not to say it wouldn't be an influential > audience, just that it would be small. It wouldn't be small if Python had procedural macros. Most people would love them -- just like most people love them in Lisp. > > The same thing is often true for classes > That's true. My clients don't have much of a problem using > classes/instances, but the ones without much CS training are > somewhat hesitant writing their own classes. But the complexity of > classes seems to be much less than procedural macros, since people > who aren't professional programmers can still learn to write them > well enough. I think classes are much more complicated conceptually than procedural macros -- learning how to use data abstraction, inheritance, and polymorphism properly is no small feat. Complicated macros can be a bit tricky to actually code and debug, but there's nothing conceptually difficult about them. > Me: > >> I can also point out the almost complete nonexistence of a major > >> package in computational chemistry or biology written in a language > >> supporting hygenic/procedural macros as an indicator that > >> *something* prevents their wider use in my field. > >There aren't any widely used languages that have procedural macros > >other than Lisp and its variants. > That's almost my point, but the other way around. If procedural > macros are the cat's meow then you'ld think that someone else beside > the Lisp'ers would implement it. People who haven't programmed in Lisp just don't know what they're missing, so they don't give it much thought. Look how long it took OO to catch on (another invention that grew out of Lisp). Most of the arguments people make against procedural macros today, people used to make about about OO. > So either a) new ideas take a long time to become mainstream, so > wait another decade, Indeed they do, but who wants to wait. > b) the rest of the world is too ignorant/ conservative/ > unambitious/ etc. Well, that's why it takes so long. OO was invented in the '70's and it took until the '90's for it to catch on. > c) there is a problem with the usefulness of procedural macros in > mainstream development They've never been used in "mainstream development" -- except to the extent that Lisp (and Dylan) have been used for mainstream development. Lisp succeeds well when it is used. The reason it is not more widely used as nothing to do with its macro mechanism. The main reason, I think, is that many people just don't like Lisp's syntax, which is a bit peculiar. The other reason is that it was far ahead of its time: it used GC and was a memory hog for its time and was something of a challenge to implement efficiently. These things gave it a bad rep back when most people wanted to program in Fortran or assembly or later C. It never recovered from this bad rep. GC was the death knell for any language in the mainstream, until Java, and that's very recent. > or d) it cannot be done in any language other than Lisp. That's not the case -- it's just not quite as "natural" since Lisp syntax just screams out for it. Lisp's syntax just made it *inevitable* that procedural macros would be invented for it, while the syntax of most other languages made it inevitable that the thought would never come to mind (except to someone who had already used Lisp). > My perception of things weighs things more towards c). It seems > that you weigh b) stronger than I do, with some complaint about a). > I still can't figure out how address the d) part without basically > quoting everything, in which case it's identical to having a > function that parses a string and exec's the result. Dylan proves that it can be done. (It's derived from Lisp, but has a more traditional syntax.) Macros are typically executed at compile-time, not run-time, which is often necessary for efficiency reasons. Dylan didn't catch on because it was a new language without a solid niche that desperately needed filling. (The only way a new language succeed is if people are *desperate* for something to fill a neglected niche.) > > And Lisp only really ever caught on in AI circles and for teaching > > programming at finer institutions of higher education. The > > reasons for that are complex and I think don't say much about the > > pros and cons of procedural macros, or even of Lisp in general. > "finer institutions of higher education"? Seems a rather biased > phrase. Bet my alma mater's football team could beat yours! :) > And its music department, and its film school, and its synchronized > swimming team, and its hospitality management program, and its > school of library science ... oh yeah, and its magnet lab (sorry, > that's an eight year old jibe :) Oh, I was just using a funny phrase like from a TV commercial. In any case, Scheme (a dialect of Lisp) is usually considered state of the art for teaching Computer Science 101. Scheme is what's used at MIT, Harvard, Yale, etc. |>oug From gs234 at cam.ac.uk Fri May 18 07:16:51 2001 From: gs234 at cam.ac.uk (Gaute B Strokkenes) Date: 18 May 2001 12:16:51 +0100 Subject: Python prints the wrong international letters References: Message-ID: <4absoqq53w.fsf@kern.srcf.societies.cam.ac.uk> On Thu, 17 May 2001, maxm at normik.dk wrote: > When I try to print the Danish letters ??? I get garbage instead. > >>>> print '?-?-?-?-?-?' > ??-??-??-??-?~-?... > > Has anybody got an idea as to how I can avoid this? Looks to me like they're being output as UTF-8, but your terminal (or whatever the windows equivalent of that is) is in ISO 8859-1 mode. Beyond that, I have no clue. -- Big Gaute http://www.srcf.ucam.org/~gs234/ I'm encased in the lining of a pure pork sausage!! From com-nospam at ccraig.org Wed May 2 09:09:25 2001 From: com-nospam at ccraig.org (Christopher A. Craig) Date: 02 May 2001 09:09:25 -0400 Subject: PEP 234: Iterators References: <3AEFFB6A.89780A80@letterror.com> Message-ID: <87ae4v3nju.fsf@elbereth.ccraig.org> Just van Rossum writes: > Roman Suzi wrote: > > What about xitems, xvalues, xkeys (as in xrange?) > > Please read the PEP: iterators largely make these > redundant. Eg. dict.iteritems() doesn't return a list of items (we > already have dict.items() for that) but an _iterator_, allowing you > to iterate over the items _without_ creating a list containing them > all... Much as xrange presently doesn't return a list of items, but an object that returns the next item with each successive call to __getitem__. I think his point was that having methods on the mapping objects named xitems, xvalues, and xkeys instead of iteritems, itervalues, and iterkeys would be inline with names of the present xrange and xreadlines functions. -- Christopher A. Craig "I wouldn't be surprised if the architecture of Intel's microprocessors were eventually linked to the eventual fall of mankind." Steve Gibson From ron.l.johnson at home.com Thu May 10 02:40:10 2001 From: ron.l.johnson at home.com (Ron Johnson) Date: Thu, 10 May 2001 06:40:10 GMT Subject: Reading & Writing Python OK, Now I need to Speak It References: <3AFA1BF5.2377412F@home.com> <01af01c0d911$7af6a5f0$d938a8c0@Hadfield> Message-ID: Mark Hadfield wrote: > From: "Don O'Donnell" >> >> > How do you say (pronounce) "__init__", for example. Having to say >> > > "double-underscore-double-underscore-init-double-underscore-double-underscor > e" > > "double-ugh" > > Come to think of it, don't you guys have a president with a name like > that? --- > Mark Hadfield Now, now. We don't remind you of your socialists; you don't need to remind us of our industrialists... -- Ron Johnson, Jr. Home: ron.l.johnson at home.com Jefferson, LA USA http://ronandheather.dhs.org "Is Python better or worse than Perl?" "Perl is worse than Python because people wanted it worse." -Larry Wall, 10/14/1998 From nas at python.ca Mon May 28 20:27:26 2001 From: nas at python.ca (Neil Schemenauer) Date: Mon, 28 May 2001 17:27:26 -0700 Subject: vi setup for pyton In-Reply-To: ; from tim@vegeta.ath.cx on Mon, May 28, 2001 at 10:14:05PM +0000 References: <3B12C9E6.5BFB8FB2@cornell.edu> Message-ID: <20010528172726.C17615@glacier.fnational.com> Tim Hammerquist wrote: > But for now, you probably want the tabstop option. > > :set tabstop=4 > :set ts=4 Bad idea. Lots of programs, including Python, assume that ts=8. Use Vim and ":set sts=4 et sw=4". Neil From cookedm+news at physics.mcmaster.ca Thu May 24 02:00:58 2001 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: 24 May 2001 02:00:58 -0400 Subject: PYTHONSTARTUP not working on debian? References: Message-ID: At some point, Bruce Sass wrote: > On Wed, 23 May 2001, Rainy wrote: > > > I'm running debian unstable, python 1.5, 2.0 and 2.1(compiled), > > and PYTHONSTARTUP is set to ~/.pythonrc.py, which contains > > line import time. When I start interactive session, and try > > time.time() for example, it gives me a name error, as if > > time isn't imported. What's wrong? > > Same setup here, ~/.pythonrc.py looks like this: > > --- > print "importing os, sys..." > import os, sys > > if sys.version[:3] == '2.1': > print "importing pydoc.help..." > from pydoc import help > --- > > It works OK from a text console, or when starting from the commandline > of a Konsole session... but not when started from Konsole's File menu. > So, there is something in how python gets started that affects if > .pythonrc.py is read (guessing, the difference between starting from a > shell commandline and doing "exec python"). > Probably because when it's run from the file menu, the environment isn't set up as you expect it. Here's a short program to test what environment it's sending: ---8<--- #!/usr/bin/env python import Tkinter, os if __name__ == '__main__': root = Tkinter.Tk() for e, v in os.environ.items(): Tkinter.Label(root, text='%s=%s'%(e,v)).pack() root.mainloop() --->8---- In general, if you set some environment variables in your .bashrc or .tcshrc, etc., those won't be set if that file isn't run (which it usually isn't when starting a X session!) If you use a .xsession file to start up your window manager, I suppose you could set PYTHONSTARTUP, etc. there, and it should be set globally in your X session. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From malamac at otenet.gr Wed May 2 09:26:21 2001 From: malamac at otenet.gr (Costas Malamas) Date: Wed, 2 May 2001 16:26:21 +0300 Subject: ZODB binary for Win32? Message-ID: <9cp20a$o0m$1@usenet.otenet.gr> Hi all, I am interested in playing with ZODB of Zope fame, but I donot have a unix machine handy or a VC++ compiler on my NT laptop. Is there any ready-made binaries for ZODB for Windows (NT/2k?) Couldn't find anything on the ZODB pages or the web. I am also wondering if I could 'extract' it from Zope. Any thoughts? Thanks, Costas Malamas From lep at aber.ac.uk Fri May 4 07:24:35 2001 From: lep at aber.ac.uk (Leighton Pritchard) Date: Fri, 04 May 2001 11:24:35 GMT Subject: Newbie question: exceptions in Learning Python References: <3af18204.1129701034@news.aber.ac.uk> Message-ID: <3af2913f.1199136016@news.aber.ac.uk> Many thanks to Alex, Gilles and Fredrik for clearing that up for me. -- Leighton Pritchard lep at aber.ac.uk From dougfort at downright.com Thu May 3 18:39:45 2001 From: dougfort at downright.com (Doug Fort) Date: Thu, 03 May 2001 18:39:45 -0400 Subject: How to tell a Python program where a shared library is? References: <3AF18F93.4E0784B0@erols.com> Message-ID: <3AF1DE31.2040105@downright.com> Edward C. Jones wrote: > Suppose I have a shared library, say "mymodule.so". How do I tell a Python > program where "mymodule.so" is? If necessary I can change the PATH environment > variable. How is this done? > > Thanks, > Ed Jones In Python 2.0 I could put my shared modules (or symlinks to them) in .../site-packages and they'd be found. In Python 2.1 I have had to add '.../site-packages' to the PYTHONPATH, but I still think it's a good approach, especially on a system that supports symbolic links. -- Doug Fort Senior Meat Manager Downright Software LLC ______________________________________________________________________ Posted Via Uncensored-News.Com - Still Only $9.95 - http://www.uncensored-news.com With Seven Servers In California And Texas - The Worlds Uncensored News Source From cribeiro at mail.inet.com.br Wed May 9 09:25:19 2001 From: cribeiro at mail.inet.com.br (Carlos Ribeiro) Date: Wed, 09 May 2001 10:25:19 -0300 Subject: Silly me, print? In-Reply-To: <10ihft0pmn11muq7kljiatgfid7l6c3bjp@4ax.com> References: <9sghftg7f1v5rsldgd03v8svces1i795mf@4ax.com> Message-ID: <5.0.2.1.0.20010509102044.02462e00@mail.inet.com.br> At 04:25 09/05/01 +0000, Courageous wrote: >Yep. Funny, programming in python all this time. I'm sure I'd never >known you could use a comma for that. Speaking of this, where in >the python documenation can I find information on the print statement? >I follow library index->print and get builtin types for some reason. I have seen someone else complaining about this a few weeks ago. It seems that the DOC [is being | will be] changed. That's because print is a statement; if you look at the reference manual index, there [is | was] no section on 'built-in statements' like print. p.s for you to feel better: a few days ago I could not remember the print to file syntax, and could nbot find it in the help after a simple search (just as you did). Then I did some interactive experiments to sort out the argument order (is it 'print >> file, ...' or 'print file >> ...'? :-). Carlos Ribeiro From sholden at holdenweb.com Sat May 26 11:31:29 2001 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 26 May 2001 11:31:29 -0400 Subject: asyncore: suggested patch References: Message-ID: Jonathan: I'd be interested to know whether you could try using the timeoutsocket module and see whether that is a natural fit with asyncore. Have you tried this? regards Steve "Jonathan Feinberg" wrote in message news:snhsck8z.fsf at pobox.com... > I wrote the following note to Sam Rushing some weeks back, and never > heard back from him, so I thought I'd go ahead and post it here. > > -------------------------------- > > First of all, thanks so much for your excellent asyncore and related > modules. > > I am implementing a "link checker", a program that takes a list of > URLs and returns a hash whose keys are the URLs and whose values are > the server status codes for those URLs, or error messages as > appropriate (such as 'host not found'). > > In the case that a host's address is bad, there was no problem; > connect() would raise a socket.error with 'host not found'. But in > the case where the host is okay, but the *port* is wrong (i.e., > http://www.foo.com:666/), I would poll endlessly. I found that I > could solve the problem by overriding the connect() method in my > subclass of async_chat, such that it takes an optional timeout > argument, as follows: > > def connect(self, address, timeout = 0): > self.connected = 0 > try: > self.socket.connect (address) > except socket.error, why: > if why[0] in (EWOULDBLOCK, EINPROGRESS) and timeout > 0: > r,w,e = select.select([],[self.socket],[],timeout) > if not w: raise socket.error('host not reachable') > elif why[0] in (EWOULDBLOCK, EINPROGRESS, EALREADY): > return > else: > raise socket.error, why > self.connected = 1 > self.handle_connect() > > I found that in the case where the host is legitimate, but there is > nothing listening on the specified port, Windows 2000 raises > EWOULDBLOCK, while NetBSD raises EINPROGRESS, which is why I check for > both. > > I like this solution, as it doesn't break any existing code, and > solves my problem. I don't like it, because I'm afraid that the use > of a timeout has implications that are beyond my ken. At any rate, I > present it to you with the thought that you may find it useful enough > to incorporate into asyncore. > > If you don't think it belongs in asyncore, I'll simply post this in > c.l.py, and let people ignore it as they please. :) > > -- > Jonathan Feinberg jdf at pobox.com Sunny Brooklyn, NY > http://pobox.com/~jdf From aleaxit at yahoo.com Wed May 23 10:37:40 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 23 May 2001 16:37:40 +0200 Subject: files via http References: <3B0BB901.594FB997@student.kuleuven.ac.be> Message-ID: <9eghv8030ce@enews1.newsguy.com> "Stijn Gunst" wrote in message news:3B0BB901.594FB997 at student.kuleuven.ac.be... > how can i download an entire website from a server via http. > those are ordinary sites which i can't telnet or ftp to. > i want to be able to specify a directory on a remote webserver into a > gui-frontend, push on a 'download'-button and get all the files and > subdirectories in that directory. > i don't know if it is possible, because this should be done over http > (no ftp- or telnet-access) See script websucker.py in directory D:\Python-2.1\Tools\webchecker (or equivalent in your installation). The only thing that's missing is the "gui-frontend", and surely that shouldn't be prohibitive for you to add, if websucker.py works satisfactorily for you in substantial terms. Alex From news at dorb.com Wed May 9 23:37:20 2001 From: news at dorb.com (Darrell) Date: Thu, 10 May 2001 03:37:20 GMT Subject: How can I work with pointers? References: <3glK6.64836$r3.12810072@typhoon.nyroc.rr.com> Message-ID: Thanks Neil! calldll did the trick, now to figure out how this Director thing works :) Get calldll built for Python21 here ==> http://ezwiki.com/python --Darrell ####################################################### import time, calldll from win32api import * from win32gui import * import win32api, win32gui, win32con, struct, array """ typedef struct tagCOPYDATASTRUCT { // cds DWORD dwData; DWORD cbData; PVOID lpData; } COPYDATASTRUCT; """ copyDataStruct="""IIP""" """32bit pointer, count, void pointer""" class MainWindow: def __init__(self): self._msgs=[] self._ar=[] self._scite=[] id=RegisterWindowMessage("SciTEDirectorInterface") message_map = { id:self.OnDirector, win32con.WM_COPYDATA:self.OnDirector1 } # Register the Window class. wc = WNDCLASS() hinst = wc.hInstance = GetModuleHandle(None) wc.lpszClassName = "SciteDirector test" wc.lpfnWndProc = message_map # could also specify a wndproc. classAtom = RegisterClass(wc) # Create the Window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = CreateWindow( classAtom, wc.lpszClassName, style, \ 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \ 0, 0, hinst, None) UpdateWindow(self.hwnd) self.registerDirector() def packMsg(self, msg): # Don't want ar to go away while being sent to another window print 'Msg out:', msg ar=array.array('c',msg) self._ar.append(ar) msg=ar.buffer_info() cds = struct.pack(copyDataStruct,0, msg[1],msg[0]) cds = array.array('c', cds) cds = cds.buffer_info() return cds def registerDirector(self): SDI = win32api.RegisterWindowMessage("SciTEDirectorInterface") w = win32gui.GetWindow(win32gui.GetDesktopWindow(),win32con.GW_CHILD ) cds = self.packMsg(":%s:macroenable:1"%self.hwnd) while (w): if (SDI == win32api.SendMessage(w, SDI, 0, 0)): #Replied with same SDI code so should #understand SDI's version of WM_COPYDATA win32api.SendMessage(w, win32con.WM_COPYDATA, self.hwnd , cds[0]) self._scite.append(w) try: time.sleep(0) w = win32gui.GetWindow(w, win32con.GW_HWNDNEXT) except: w = None cmd=""" :%(hwnd)s:askfilename: :%(hwnd)s:property:xyz=123 :%(hwnd)s:enumproperties:base: :%(hwnd)s:find:win32api: :%(hwnd)s:macrolist: """%{'hwnd':self.hwnd} self.perform(cmd) def perform(self, cmd): cds = self.packMsg(cmd) for w in self._scite: win32api.SendMessage(w, win32con.WM_COPYDATA, self.hwnd , cds[0]) def OnDirector(self, hwnd, msg, wparam, lparam): print 'OnDirector', wparam, lparam if lparam == 0: return sz = struct.calcsize(copyDataStruct) s = calldll.read_string(lparam, sz) dwData, cbData, lpData = struct.unpack(copyDataStruct, s) s = calldll.read_string(lpData, cbData) print 'S:',s def OnDirector1(self, hwnd, msg, wparam, lparam): print 'OnDirector1' sz = struct.calcsize(copyDataStruct) s = calldll.read_string(lparam, sz) dwData, cbData, lpData = struct.unpack(copyDataStruct, s) s = calldll.read_string(lpData, cbData) print 'S:',s def main(): w=MainWindow() while 1: if PumpWaitingMessages(): break time.sleep(0.1) if __name__=='__main__': main() ################## output Msg out: :1115962:macroenable:1 OnDirector 0 0 Msg out: :1115962:askfilename: :1115962:property:xyz=123 :1115962:enumproperties:base: :1115962:find:win32api: :1115962:macrolist: OnDirector1 S: :1115962:filename:E:\\scite\\scite\\src\\SciTEBase.cxx OnDirector1 S: :1115962:filename:E:\\scite\\director.py OnDirector1 S: :1115962:filename:E:\\scite\\wscite\\scintilla.iface From fredrik at pythonware.com Mon May 7 18:07:18 2001 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 07 May 2001 22:07:18 GMT Subject: sqlsafetext References: Message-ID: michael montagne wrote: > Below is a little function I use to handle such things as "o'brien" in SQL > strings. It works in VB and I'm trying to port the function to Python. If > I type it in interactively, replace returns what I would expect. > (o''brien), But the function doesn't work. Why? next time you post a question, maybe you could define "doesn't work" a bit more carefully (like, say, including any exceptions you got, etc). > def sqlsafetext(strText): > if strText=="": > return "Null" > else: > #print strText > import string > #replace single quotes with double single quotes > string.replace(strText,chr(39),chr(39) + chr(39)) saving the result of the "replace" call in a variable might help: strText = string.replace(strText,chr(39),chr(39) + chr(39)) or, using string methods instead of functions: strText = strText.replace("'", "''") strText = strText.replace('"', '""') > #replace double quotes with double double quotes > string.replace(strText,chr(34),chr(34)+ chr(34)) > #wrap in single quotes > strtemp="'" + strtemp + "'" where did "strtemp" come from? are you sure you didn't get a NameError exception on that line? > return strText Cheers /F From rcameszREMOVETHIS at dds.removethistoo.nl Tue May 15 20:42:28 2001 From: rcameszREMOVETHIS at dds.removethistoo.nl (Robert Amesz) Date: Wed, 16 May 2001 00:42:28 GMT Subject: The joys and jilts of non-blocking sockets References: <090520010110273027%timo@alum.mit.edu> Message-ID: Fredrik Lundh wrote: > Robert Amesz wrote: >> Perhaps I haven't made myself clear. The point I'm trying to make >> is that I'm suprised that an exception is raised for a case which >> is not exceptional at all. > > If you read up on socket behaviour, you'll notice that that error > means the connection couldn't be *immediately* established. If > that's an error or not depends on your application. Hmmm, if connecting to 'localhost' isn't immediate, what is? Because that's how I tested it. (Not that I'd rely on connect() *not* connecting immediately, but on my Windows box it obviously doesn't.) > And if you look in the Python docs, you'll notice that you can use > "connect_ex" instead of "connect" if you don't want the exception. /me looks in Python docs and gasps in suprise Oh my, how could I have overlooked that? That's pretty useful, thanks. /me studies timeoutsocket.py Oh, dear, connect_ex() is nowhere to be found in there. Tim O'Malley isn't going to like this. Robert Amesz From scarblac at pino.selwerd.nl Mon May 7 12:44:11 2001 From: scarblac at pino.selwerd.nl (Remco Gerlich) Date: 7 May 2001 16:44:11 GMT Subject: xrange question References: Message-ID: Grant Edwards wrote in comp.lang.python: > Definitely. For the past year or so I've been maintianing C > code written by somebody who didn't believe in for() loops. > Everything is a while loop: > > i = 0; > while (i { > [...] > i += 1; > } > > I've not idea why they were written that way. I change them > into for() loops as I run accross them, and it makes things > much easer to understand. I have that urge as well. That's because early in my CS study, we learned to write correctness proofs for programs. And they only taught us how to do that for while loops, since for loops etc are just syntactical sugar. So in the back of my mind I still tend to think about setting up a precondition, and loop with some invariant, until some guard condition isn't true anymore. But I only have it in Pascal and C, in Python it would be horrible :) -- Remco Gerlich From berning at teuto.de Mon May 7 17:39:15 2001 From: berning at teuto.de (Ulrich Berning) Date: Mon, 07 May 2001 23:39:15 +0200 Subject: socket.recvfrom() & sendto() References: <9d67he$1pc$1@saltmine.radix.net> <8zBJ6.38583$2U.15727108@news2.rdc2.tx.home.com> Message-ID: <3AF71603.6275F09C@teuto.de> Ron Johnson wrote: > The mis-understanding that I am having is that you can only bind > one socket to a server:port. Ergo, how do have multiple sockets > open at the same time? > > >>> import socket, select > >>> > >>> sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > >>> sock1.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > >>> sock1.setblocking(0) > >>> sock1.bind((socket.gethostname(), 50000)) > >>> sock1.listen(5) > >>> > >>> sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > >>> sock2.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > >>> sock2.setblocking(0) > >>> sock2.bind((socket.gethostname(), 50000)) > Traceback (most recent call last): > File "", line 1, in ? > socket.error: (98, 'Address already in use') Hi, I think, you want to something like that: import socket, select, os # Create a connection socket, bind it and listen on it connect_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connect_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) connect_socket.bind((socket.gethostname(), 50000)) connect_socket.listen(5) # Our server accepts connect requests forever while 1: # The accept() call blocks until there is a connect request. # The call returns a new socket, that should be used for further # communication. work_socket, addr = connect_socket.accept() # Start a new process (or thread) for client server communications # or use select() to do this in the same process child_pid = os.fork() if not child_pid: # Child process # The child process should close the connect socket immediately connect_socket.close() # This functions should do the communication with the client client_worker_function(work_socket) # When all work is done, the child can die sys.exit() The trick is the accept() system call, which returns a new socket that should be used for the client server communication. The connect socket can then listen on the defined port for the next connect request. Hope this helps, Ulli -------------- next part -------------- An HTML attachment was scrubbed... URL: From m.faassen at vet.uu.nl Sat May 26 10:05:19 2001 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 26 May 2001 14:05:19 GMT Subject: How Fast? References: <01052215095105.01539@avatar.cardomain.com> <20010524225655.H690@xs4all.nl> <0105241637541M.01993@avatar.cardomain.com> <9ekdmh$ugl$1@apollo.csd.net> <1pGP6.68017$eK2.13153662@news4.rdc1.on.home.com> Message-ID: <9eod6v$d64$1@newshost.accu.uu.nl> Nick Perkins wrote: >>>..write code almost as fast as you can type. >>..with Python I can stay in the flow longer. > Funny, I was just thinking about this today. I remember being told about a > guy who would code in VB, just typing almost continuously at ~40wpm. This > was intended to impress me, but made me wonder what that code looked like? Me too. Tell us if you find any samples. :) > I think that Python is especially well suited to eliminating any and all > repetetive typing. I find that the more I think about and refine a program, > the shorter it gets! ( I haven't experienced that in other languages ) I've had the same experience, though it happens in other languages as well. But perhaps not as easily. > I am curious about how long most programmers 'stay in the flow'. > Personally, I rarely type more than, maybe, 3 lines at a time before > stopping to think again. Sometimes it's much less, > but rarely more. I suppose it also depends on your definition of 'stopping > to think'. You might think for 2 seconds, or several minutes. I work in much the same way; type a few lines, stop, think. Erase lines again. :). If it's a common idion I may type more lines, like in the 1.5.2 idiom: result = [] for line in lines: line = string.strip(line) # or do more stuff here result.append(line) In 2.0 and up this can often be a list comprehension. > I can recall typing many lines of Java or COBOL without really thinking, but > that's because there was no way around it, you pretty much had to 'follow > the pattern'. In Python, there always is a way to improve repetetive code. Agreed. I dislike repetitive code; it's boring and time consuming so I spend inordinate amounts of time avoiding it. :) Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From scarblac at pino.selwerd.nl Wed May 23 04:08:29 2001 From: scarblac at pino.selwerd.nl (Remco Gerlich) Date: 23 May 2001 08:08:29 GMT Subject: Won't use global symbol table? References: <20010522.194123.1450573622.7698@kanchenjunga.mindspring.com> Message-ID: Rob Nikander wrote in comp.lang.python: > Shouldn't I be able to say this is a module... > > x = None > def f(): > # global x > if not x: > x = 1 > return x > > Unless I uncomment that global line I get the error: > > File "ubtest.py", line 6, in f > if not x: > UnboundLocalError: local variable 'x' referenced before assignment > > I thought python looked for a variable in the local symbol table, and if > it couldn't find it there, went to the global (to the module) symbol > table. Why do I have to explicitly tell it to do so in this instance? In your function, you assign to x. That makes it a local. This check is done at compile time. Then at runtime, 'if not x:' doesn't find the local variable and raises the exception. It would also be confusing if the 'if not x:' used the global, but 'x=1' created a new local variable. So Python doesn't guess and complains. -- Remco Gerlich From SBrunning at trisystems.co.uk Thu May 24 04:24:00 2001 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Thu, 24 May 2001 09:24:00 +0100 Subject: How do I upload files via a CGI script? Message-ID: <31575A892FF6D1118F5800600846864D78BC7C@intrepid> > From: briggs at softhome.net [SMTP:briggs at softhome.net] > I'm having the toughest time finding out how to upload a file via a > CGI script. I would prefer to use the cgi module, but I'll use > anything that works. 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 jkraska1 at san.rr.com Sat May 19 11:46:18 2001 From: jkraska1 at san.rr.com (Courageous) Date: Sat, 19 May 2001 15:46:18 GMT Subject: random numbers, threads and reproducibility References: Message-ID: >> I am developing a small class framework for Genetic Algorithms in >> Python, and wishing to create some threads, I face a problem: >> One of the requirements I want to keep is reproducibility. [snip astute observation regarding threads and randomness]. One way around this particular problem is to use cooperative multithreading with your own scheduler. Without any preemptive multitasking involved, the unfolding of your simulation will be completely deterministic. C// From whisper at oz.nospamnet Wed May 16 20:06:45 2001 From: whisper at oz.nospamnet (David LeBlanc) Date: 17 May 2001 00:06:45 GMT Subject: What can you do in LISP that you can't do in Python References: Message-ID: <9dv4ml$eb5$g@216.39.170.247> In article , James_Althoff at i2.com says... > > Steven D. Majewski writes: > >( Smalltalk, instead of having these different forms, has a way > > of slinging around unevaluated code blocks as parameters: > > > > object ifTrue: [ block of code to be evaluated ] > > ifFalse: [ block of code to be evaluated ] > > And such "slinging" can be *so* satisfying. I would really enjoy > "slinging" some unevaluated, unnamed code blocks around in Python when, for > example, I want to write GUI code like: > > window.showBusyCursorDuring(): > window.showStatusDuring(msg='Verifying search conditions'): > searchForm.verify() > window.showStatusDuring(msg='Executing query'): > resultSet = searchForm.executeQuery() > > :-) > > Jim > > > > This is more a question: Would this work?: sling = """ window.showBusyCursorDuring(): window.showStatusDuring(msg='Verifying search conditions'): searchForm.verify() window.showStatusDuring(msg='Executing query'): resultSet = searchForm.executeQuery()""" eval sling ??? Dave LeBlanc From robin at jessikat.fsnet.co.uk Mon May 14 03:32:04 2001 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 14 May 2001 08:32:04 +0100 Subject: Python COM and distribution issues References: Message-ID: <1MvskLA0n4$6EwPB@jessikat.fsnet.co.uk> In article , hungjunglu at yahoo.com writes >Python COM seems to aim for single-machine software design, because >in all the examples I have seen the _reg_clsid_ are ALL hard-coded by >hand. It's 128-bit all right, but how can anyone be absolutely sure >that it won't cause conflict on different machines? > >It is unrealistic to distribute Python modules and expect the users >to perform pythoncom.CreateGuid() and modify the _reg_clsid_ in all >the program files. > >(1) How do people handle the GUID problem? Or do people just hard- >code the GUID and hope for the best? > >(2) Has anyone done Python COM utilities for distribution? How do >people handle the GUID (Globablly Unique ID) problem? Has anyone >packed Python COM utilities into stand-alone executables (a la >py2exe)? > >(3) I tried to generate GUID dynamically instead of hard-coding, but >it broke PythonCom badly. In particular, the object browser does not >work anymore, and the whole operating system crashes when using >Python COM server objects from Visual Basic. Has anyone had similar >problem? If so, any pointer to the solution? If a class is registered >or unregistered a few times under different _reg_clsid_, does >something in the registry get corrupted? Where is a good starting >point to fix these problems? > >thanks, > >Hung Jung > > > I think you misunderstand the GUID generation mechanisms that M$ provide. By including various probabilistic arguments and values unlikely to be common to more than one CPU M$ claim in 'GUID Creation and Optimisations' ''' GUID Creation and Optimizations Because a CLSID, like an interface identifier (IID), is a GUID, no other class, no matter who writes it, has a duplicate CLSID. Server implementers generally obtain CLSIDs through the CoCreateGUID function in COM. This function is guaranteed to produce unique CLSIDs, so server implementors across the world can independently develop and deploy their software without fear of accidental collision with software written by others. Using unique CLSIDs avoids the possibility of name collisions among classes because CLSIDs are in no way connected to the names used in the underlying implementation. So, for example, two different vendors can write classes called "StackClass," but each would have a unique CLSID and therefore could not be confused. COM frequently must map GUIDs (IIDs and CLSIDs) to some arbitrarily large set of other values. As an application developer, you can help speed up such searches, and thereby enhance system performance, by generating the GUIDs for your application as a block of consecutive values. The most efficient way to generate a block of consecutive GUIDs is to run the uuidgen utility using the /n switch, which generates a block of UUIDs, each of whose first DWORD value is incremented by one. (For more information on using the uuidgen utility, see "The uuidgen Utility.") ''' -- Robin Becker From ben.hutchings at roundpoint.com Mon May 7 21:30:24 2001 From: ben.hutchings at roundpoint.com (Ben Hutchings) Date: 07 May 2001 18:30:24 -0700 Subject: No flock() in Windows!? References: <7kzt29he.fsf@pobox.com> <9d6ihu$708$6@216.39.170.247> Message-ID: David LeBlanc writes: > In article <7kzt29he.fsf at pobox.com>, jdf at pobox.com says... > > I'm fairly new to Python, and have been enjoying it. > > > > In rewriting an old Perl script into Python, I was staggered to > > discover that there is simply no fcntl support at all on the Windows > > platform. Such support is entirely platform-transparent in Perl, and > > I don't know how to work without it! > > > > How do you folks write cross-platform scripts that safely provide for > > advisory locking? > > > > I have searched the library docs and FAQ, I have searched the web and > > the Google Usenet archive. If I missed something, pointers will be > > gladly followed. > > > Windows supports locking down to the byte level on files using the > _locking() runtime library function. That's a VC++ function, not a Windows function. The Win32 API has the functions (Un)LockFile(Ex), which are available through the win32api module. -- Any opinions expressed are my own and not necessarily those of Roundpoint. From bellman at lysator.liu.se Tue May 15 20:31:24 2001 From: bellman at lysator.liu.se (Thomas Bellman) Date: 16 May 2001 00:31:24 GMT Subject: What can you do in LISP that you can't do in Python References: <3AFFFB0E.70A8B5BF@wag.caltech.edu> <9dpqra$5gl$1@newsy.ifm.liu.se> Message-ID: <9dshos$4j1$1@newsy.ifm.liu.se> kc5tja at dolphin.openprojects.net (Samuel A. Falvo II) writes: > Forth has very similar abilities, and almost never manages to use macros. Ah, yes, I had managed to momentarily forget about Forth. It too is very powerful in that way. The only Forth dialect I have studied and used in any depth, though, is the one in the British computer Jupiter ACE. (The Jupiter ACE is from about the same time as Sinclair ZX Spectrum, and is very similar to the ZX-81 and Spectrum. Not surprising when you know that some of the same people were involved... And the Forth manual, by Steven Vickers, is great fun to read!) Anyway, Forth has a lot of other limitations. It's really designed to handle integers, and a little bit of strings. Advanced data structures like lists or trees are a bit more of a chore... And you still can't pass around and manipulate *code* with the same ease as in LISP. Aahhh! You've made me long for doing some programming in Forth again! Got to find myself a Forth interpreter (or possibly write one myself :-), and find some project to do in Forth... You evil you! :-) -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "I don't think [that word] means what you ! bellman @ lysator.liu.se think it means." -- The Princess Bride ! Make Love -- Nicht Wahr! I doubt that Inigo was thinking of Forth words when he made that remark, though... From darwin at ukonline.co.uk Sun May 27 12:21:15 2001 From: darwin at ukonline.co.uk (darwin at ukonline.co.uk) Date: 27 May 2001 16:21:15 GMT Subject: AD : Multichannel OD Test Cards For Sale £25 Message-ID: <9er9hr$lob$415@neptunium.btinternet.com> email for info From rnd at onego.ru Mon May 14 01:42:06 2001 From: rnd at onego.ru (Roman Suzi) Date: Mon, 14 May 2001 09:42:06 +0400 (MSD) Subject: Python is also a Lisp compiler name? Message-ID: Hello! While searching for some things I found this: http://www.mindspring.com/~rtoy/software/cmu-user/node96.html It seems, there is a Lisp compiler, called Python ;-) Roman. From MarkH at ActiveState.com Wed May 30 23:31:00 2001 From: MarkH at ActiveState.com (Mark Hammond) Date: Thu, 31 May 2001 03:31:00 GMT Subject: version-number dependency in extensions (was Re: ConfigParser module in 1.52 is buggy?) References: Message-ID: <3B15BB88.70803@ActiveState.com> Neil Hodgson wrote: > Now where in Python's DLLs can loading be intercepted? PythonCom[xx] is > possible but it would require dropping the implicit links to Python[xx] and > PyWinTypes[xx] and using explict links and fixups. Not fun. However the > interception could create an earlier stage with a PyStub that just offers > the basic 4 COM entry points, does explict LoadLibrary[Ex]s and forwards the > basic 4 to PythonCom which would have to know to register PyStub as the > server. That would work fine for COM. However, as noted in the thread I pointed at, the problem is not limited to COM. The win32all installer tries to use Python, and it too has the same basic problem. In general, this change would mean that embedders can not expect their code to "just work". They would need to take special action or copy Python into their application directory. Pythonwin would not work as it stands (but this is simple to fix; pythonwin could get installed in the same dir as python.exe). PyXPCOM would not work. Any program _other_ than python.exe and pythonw.exe would need this special handling. This is not to suggest it is necessarily a bad thing, but it clearly is not a great thing . Are we just transferring the pain? Mark. From ruediger.maehl at dzsh.de Mon May 21 04:14:55 2001 From: ruediger.maehl at dzsh.de (Ruediger Maehl) Date: Mon, 21 May 2001 10:14:55 +0200 Subject: Parsing structured text file References: <3B082DE9.15346170@tihlde.org> Message-ID: Ken A. Redergaard schrieb in Nachricht <3B082DE9.15346170 at tihlde.org>... >I've got a text-file that is reasonably structured that I have to parse. >Are there any good modules that do this in python ? How about sgrep? See newsgroup comp.lang.python Subject: Announce: PySgrep -- Structured grep From: Dave Kuhlman Date: May 17, 2001 22:51 R?diger From MarkH at ActiveState.com Fri May 11 00:36:00 2001 From: MarkH at ActiveState.com (Mark Hammond) Date: Fri, 11 May 2001 04:36:00 GMT Subject: Python in Windows Tray? Error? References: <3AFB2FA6.3090803@ActiveState.com> <867kzo5zxf.fsf@hellcat.itga.com.au> Message-ID: <3AFB6C98.5090403@ActiveState.com> Gregory Bond wrote: > Mark Hammond writes: > > >>Get the latest ActivePython or win32all. >> > > Have. Win32all Build 139, using Python2.1 release. Same error. Sorry - I lied. win32all-139 just missed that fix. ActivePython 2.1 has it. Mark. From tanzer at swing.co.at Tue May 29 10:54:36 2001 From: tanzer at swing.co.at (Christian Tanzer) Date: Tue, 29 May 2001 16:54:36 +0200 Subject: wanted book recommendation for Object Oriented Programming In-Reply-To: Your message of "Tue, 29 May 2001 08:40:53 +0200." <200105290640.IAA03274@boris.cd.chalmers.se> Message-ID: Laura Creighton wrote: > Lucky Us, we get 5 undergraduate computer-science/engineering student > interns here this summer. (That will keep us on our toes.) Each of them > now gets a copy of > > Design Patterns > Design Patterns SmallTalk Companion > The Practice of Programming > The Python Standard Library (Fredrik Lundh's book is out) I'd recommend The Pragmatic Programmer by Hunt and Thomas over The Practice of Programming if I had to choose one (both are good IMO, but the former is better). > of their very own to keep. (And if Beazley's Essential Reference for > 2.0 ever gets out of the publishers they will get that as well.) > But I have found a hole. I need a book every bit as excellent > (and terse) as the rest of my list that teaches Object Oriented > Programming to somebody who has never studied it. I recommend Object-Oriented Software Construction by Bertrand Meyer (disclaimer: I read the first edition long ago and don't actually know the second edition. But it is the best introduction to OO I know of). I'd also strongly recommend Beck's Extreme Programming Explained. I think Beck's ideas are more important than the Design Patterns (although I'd also include those in the list of books they get). OTOH, I consider Booch's books on OO analysis and design to be overrated [again, I read only the first edition but at least looked at the second edition] -- lots of diagrams but little content. And the applications section is just a bad joke. -- Christian Tanzer tanzer at swing.co.at Glasauergasse 32 Tel: +43 1 876 62 36 A-1130 Vienna, Austria Fax: +43 1 877 66 92 From news at myNOSPAM.org Thu May 17 16:29:33 2001 From: news at myNOSPAM.org (Stephen Hansen) Date: Thu, 17 May 2001 20:29:33 GMT Subject: Evaluating python - a question References: <9e100t$8e1$1@news.netmar.com> Message-ID: Contrary to popular belief, I've never actually had to search my projects endlessly as I looked for such an error. So, either I don't typo, or its not quite so hard to find the typos when they do occur. Perhaps its just me, but dispite what everyone who doesn't know Python seems to always say, errors related to A) the theoretical 'ease' of misindenting something, and B) typos of variable names, never did show up for me. --S wrote in message news:9e100t$8e1$1 at news.netmar.com... > I'm just starting to look at Python as a language but there's one thing that > is bothering me regarding using it for large projects and that's the ease > with which I can put in a simple typo and not have it spotted by the > compiler. For example;- > I create a class ... > > class person: > > This class has an attibute of forename so > > me = person() > me.forename = 'Alan' > > is Ok but a simple typo (especially with my keyboard skills) of > > me.froname = 'Fred' > > will go undetected and I'll have to spend ages digging around to find a bug > which languages like C/C++/Pascal would throw out at compile time. > > Is there any mechanism in Python to detect typos like this as, in a large > program, they're bound to happen. > > Thanks - Alan > > > ----- Posted via NewsOne.Net: Free (anonymous) Usenet News via the eb ----- > http://newsone.net/ -- Free reading and anonymous posting to 60,000+ groups > NewsOne.Net prohibits users from posting spam. If this or other posts > made through NewsOne.Net violate posting guidelines, email abuse at newsone.net From michael at stroeder.com Wed May 30 14:39:17 2001 From: michael at stroeder.com (Michael =?iso-8859-1?Q?Str=F6der?=) Date: Wed, 30 May 2001 20:39:17 +0200 Subject: Small, Local Web/CGI Server Advice References: <67abb823.0105300435.260f47d2@posting.google.com> <3B152338.C6DC0D1C@stroeder.com> Message-ID: <3B153E55.AA6A0083@stroeder.com> Eugene Leitl wrote: > > So don't use traditional cgi-bin programs under Medusa, use > Bobo instead Yes, I know. But the original poster might be stuck with already existing traditional CGI-BIN programs. Ciao, Michael. From whisper at oz.nospamnet Fri May 4 22:11:52 2001 From: whisper at oz.nospamnet (David LeBlanc) Date: 5 May 2001 02:11:52 GMT Subject: mod_python on Win32 [new problem] References: <9curj4$emn$5@216.39.170.247> Message-ID: <9cvnh8$q7c$1@216.39.170.247> In article , dsavitsk at e- coli.net says... > > "David LeBlanc" wrote in message > news:9curj4$emn$5 at 216.39.170.247... > > * * * > > > From my httpd.conf: > > > > AddHandler python-program .py > > PythonHandler mptest > > PythonDebug On > > > > > > Good luck, > > > > Dave LeBlanc > > thanks for the reply. it seems that in the docs they say to use the line: > > "PythonHandler test" > > when what they mean is: > > "PythonHandler mptest" > > doug > > > I think them mean to say PythonHandler . Their doc coule be better. I also think that a def named Handler has to be in the .py file. I guess, now that I think about it, that there can only be one .py file per directory, unless one can do some sort of .extension magic. Dave LeBlanc P.S. Did you get it to run? From ngps at madcap.dyndns.org Wed May 23 11:13:02 2001 From: ngps at madcap.dyndns.org (Ng Pheng Siong) Date: 23 May 2001 15:13:02 GMT Subject: Netscape crashes M2Crypto/ZServerSSL References: <83ef2d59.0105210924.64cf3e4b@posting.google.com> Message-ID: <9egk1u$spv$1@dahlia.singnet.com.sg> According to Toby Angell : > I'm having a problem with ZServerSSL from M2Crypto 0.6 Snap 4. > From IE it works great. From Netscape 4.7 and Netscape 6, Zope crashes Can you provide a sample Zope page to trigger the crash? -- Ng Pheng Siong * http://www.post1.com/home/ngps Liverpool 2 - 1 Arsenal Liverpool 5 - 4 Alaves From djc at object-craft.com.au Mon May 7 00:42:40 2001 From: djc at object-craft.com.au (Dave Cole) Date: 07 May 2001 14:42:40 +1000 Subject: Sybase module 0.24 (Timothy Docker release) released Message-ID: What is it: The Sybase module provides a Python interface to the Sybase relational database system. The Sybase package supports almost all of the Python Database API, version 2.0 with extensions. The module works with Python versions 1.5.2 and later and Sybase versions 11.0.3 and later. It is based on the Sybase Client Library (ct_* API), and the Bulk-Library Client (blk_* API) interfaces. The 0.20 and later releases are a reimplementation of the module using a thin C wrapper on the Sybase-CT API, and a Python module to provide the DB-API functionality. It is still a work in progress, but should be good enough for most purposes. Timothy Docker sent a patch with the following changes: - con.c renamed to conn.c because NT still has the CON: device!!! - warnings from gcc -Wall fixed. - bug fix in CS_BLKDESC_blk_init() - missing & operator. - bug fix in CS_CONNECTION_ct_diag, CS_CONTEXT_cs_diag() - missing return NULL. - bug fixes to raise exception for unhandled properties in sybasect module. - ARRAY_INSERT now controlled by HAS_ARRAY_INSERT in sybasect.h - Initialisation via PyObject_HEAD_INIT() now conforms to example module in Python distribution. It should be possible to compile and install on NT. - rename max() macro to maxv() in numeric.c - created initial setup.py and ntsetup.py for use with distutils. Now you can just run the following command to install: bash$ python setup.py install Or on NT: > python ntsetup.py install Where can you get it: http://www.object-craft.com.au/projects/sybase/ - Dave -- http://www.object-craft.com.au From fredrik at pythonware.com Sat May 12 05:14:44 2001 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 May 2001 09:14:44 GMT Subject: Is this a bug? References: <3af2b89d.338629833@News.CIS.DFN.DE> Message-ID: <8a7L6.1640$Yu6.404853@newsc.telia.net> John Hopkins wrote: > This just came up in one of the mailing lists I track. Python apparently > requires that last '\' to be escaped, even though you're using "Raw". > > So myPath = r'c:\Windows\\' *should* work, though I haven't tried it. it doesn't give you a syntax error, but it doesn't really do what you expected: >>> myPath = r'c:\Windows\\' >>> print myPath c:\Windows\\ for the full story on backslashes, see FAQ entry 6.29: http://www.python.org/doc/FAQ.html#6.29 ... If you're trying to build Windows pathnames, note that all Windows system calls accept forward slashes too: f = open("/mydir/file.txt") # works fine! If you're trying to build a pathname for a DOS command, try e.g. one of dir = r"\this\is\my\dos\dir" "\\" dir = r"\this\is\my\dos\dir\ "[:-1] dir = \\this\\is\\my\\dos\\dir\\ ... Cheers /F From tim.one at home.com Tue May 15 02:38:25 2001 From: tim.one at home.com (Tim Peters) Date: Tue, 15 May 2001 02:38:25 -0400 Subject: Floating point errors? In-Reply-To: <3B00C02F.5254B831@my.signature> Message-ID: [Greg Ewing] > Is there even any such thing as a truly analog > computer? Atoms have discrete energy levels... I remember reading about Zeno's motion paradoxes as a kid, and thinking "hmm -- there must be a particular distance that's the smallest distance there is -- plus a smallest time". Later, when I finally read the refutation based on the mathematical convergence of 1 + 1/2 + 1/4 + 1/8 + ... to 2, I felt scammed. Like, it's nice that this mathematical abstraction converges under the rules of its game, but what do real numbers have to do with the real world? Luckily, I'm now old, and have given up my embarrassing youthful belief in the real world instead. if-this-is-reality-it-needs-major-refactoring-ly y'rs - tim From scarblac at pino.selwerd.nl Wed May 16 17:34:38 2001 From: scarblac at pino.selwerd.nl (Remco Gerlich) Date: 16 May 2001 21:34:38 GMT Subject: modifying vars() dictionary? References: Message-ID: Lance E Sloan wrote in comp.lang.python: > In the documentation, it says about vars(): > > The returned dictionary should not be modified: the effects on > the corresponding symbol table are undefined. > > Why are the effects undefined? Why doesn't it always work to set > a value for variable 'x' by assigning that value to the 'x' element > of the dictionary from vars()? Because you're not supposed to set things in it, and whether it works or not at the moment is a complete accident of implementation that might change at any moment. I never understand why people need this functionality, but if you really need it you can always use exec, or setattr() on a module or instance. > I've noticed that sometimes it works and sometimes it doesn't. In my > small example it worked, but a colleague who asked me about this > couldn't get it to work in a larger program. I assume that I'm just > lucky mine worked and that his problem may have something to do with > the size of the symbol table or the kinds of objects in it. Or the phase of the moon. It's *undefined*. -- Remco Gerlich From jwolff at ision.nl Thu May 31 21:41:30 2001 From: jwolff at ision.nl (Jeroen Wolff) Date: Thu, 31 May 2001 18:41:30 -0700 Subject: strange cgi print problem Message-ID: I've got a strange cgi print problem. When i run this script as user "nobody" on the console is works fine and generate nice output. When i launch it from my webbrowser, i shows only the output of HTMLHead() when i view the source. The print RIPEWhois("AS12394") output is only a space... Please can somebody help... Thx, Jeroen #!/usr/local/bin/python import string, os def HTMLHead(): print "Content-type: text/html" print print "" print "" def RIPEWhois( ASnr ): descr = "" goedeAS = 0 fp = os.popen("ripewhois "+ASnr+" -r") for regel in fp.readlines(): columns = regel[:-1].split(":") if len(columns) > 1: if columns[0].strip() == "aut-num" \ and columns[1].strip() == ASnr: goedeAS = 1 if columns[0].strip() == "descr" and goedeAS: descr = columns[1].strip() break fp.close() return descr HTMLHead() print RIPEWhois("AS12394") print "" From jkraska1 at san.rr.com Sat May 12 06:58:29 2001 From: jkraska1 at san.rr.com (Courageous) Date: Sat, 12 May 2001 10:58:29 GMT Subject: Need "sum" compatible checksum16 in Python References: <3AFCE8F7.6FE664B5@engineer.com> Message-ID: >I think I can make a nice neat python program out >of this mess except I need a 16 bit checksum for >an arbitrary string such as is generated by the >GNU utility "sum". You've already got some responses; while this isn't what you're looking for, I've found 16 byte MD5s to be pretty fast, myself (I'm using them in a project where absolute object identity is important). C// From mal at lemburg.com Tue May 1 17:13:55 2001 From: mal at lemburg.com (M.-A. Lemburg) Date: Tue, 01 May 2001 23:13:55 +0200 Subject: ANN: mxNumber -- Experimental Number Types, Version 0.2.0 References: Message-ID: <3AEF2713.E978A3A4@lemburg.com> Paul Moore wrote: > > "M.-A. Lemburg" writes: > > > The 0.2.0 release is an alpha release. Everything is still in flux, so > > expect bugs, strange behaviour etc. > > >python > ActivePython 2.1, build 210 ActiveState) > based on Python 2.1 (#15, Apr 19 2001, 10:28:27) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import mx.Number > >>> mx.Number.Integer(1500) <= 1 > 1 > >>> mx.Number.Integer(1500) <= mx.Number.Integer(1) > 0 > > Does this count as "strange behaviour"? Surely mx.Number.Integer > values should compare properly with Python integers? They do... I get these results with stock Python 2.1: >>> from mx.Number import * >>> Integer(1500) <= 1 0 >>> Integer(1500) <= Integer(1) 0 but something is still not working right: >>> Integer(1500) <= Integer(2000) 1 >>> Integer(1500) <= 2000 0 >>> Integer(1500) <= 2000L 0 >>> Integer(1500) <= 20000 0 >>> Integer(1500) < 20000 0 >>> Integer(1500) > 20000 1 Digging a little deeper in Python's (new) compare code, it seems that a few bits of my coercion patches did not make it into the core -- numbers are still coerced before comparing them; which fails for mx.Number types since they don't define a coercion function. -- Marc-Andre Lemburg ______________________________________________________________________ Company & Consulting: http://www.egenix.com/ Python Software: http://www.lemburg.com/python/ From aahz at panix.com Tue May 22 19:50:54 2001 From: aahz at panix.com (Aahz Maruch) Date: 22 May 2001 16:50:54 -0700 Subject: is it safe to stop a thread? References: <3B0AFDEF.44E29573@ugcs.caltech.edu> Message-ID: <9eeu0u$edh$1@panix3.panix.com> In article <3B0AFDEF.44E29573 at ugcs.caltech.edu>, Dustin Boswell wrote: > >I'm writing a client that needs to access various web sites >periodically, but the problem is that every once in a while a network >glitch will happen so that urlopen() hangs forever (hitting CTRL-C >shows it was on a read() ). This is similar to using Netscape and >having to click "stop" and then "reload" on a page that won't fully >load. Try timeoutsocket.py -- --- Aahz <*> (Copyright 2001 by aahz at pobox.com) Androgynous poly kinky vanilla queer het Pythonista http://www.rahul.net/aahz/ Hugs and backrubs -- I break Rule 6 "You do not make history; you can only hope to survive it." --G'kar From anton at vredegoor.doge.nl Sat May 5 10:33:24 2001 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 05 May 2001 16:33:24 +0200 Subject: operators and datatypes for sets References: <9c1jdj$phb$1@news.hccnet.nl> <9c3v5i$k7o$1@news.hccnet.nl> <9c42ag01mvu@news1.newsguy.com> <9cab20$lm8$1@news.hccnet.nl> <9cbaue0485@news1.newsguy.com> Message-ID: <9d12t8$meh$1@news.hccnet.nl> On Fri, 27 Apr 2001 10:34:23 +0200, "Alex Martelli" wrote: >"Anton Vredegoor" wrote >> http://home.hccnet.nl/a.vredegoor/universe/universe.html >I think it would be handy for a 'set' operand to "coerce" >the other operand (if the latter is a sequence) to 'set', >You can use the __coerce__ special method, or do it in >each operator (and its __rXXX__ version for completeness). Sorry I can't use __coerce__ , the python reference forbids it: "Finally, sequence types should implement addition (meaning concatenation) and multiplication (meaning repetition) by defining the methods __add__(), __radd__(), __iadd__(), __mul__(), __rmul__() and __imul__() described below; they should not define __coerce__() or other numerical operators." But then again I have used some operators already, so I will look into it someday. More example code would be welcome. >Also .has_subset. Implementation is trivial, just a >small factory function that you might as well expose: > >def make_set(set_or_sequence): > if isinstance(set_or_sequence, set): > return set_or_sequence > else: > return set(set_or_sequence) > >and just call this appropriately on "other operand". Thanks for this factory function idea, I have used it in an other way than you suggest here though. When creating a new set I first check whether a set with the same items already exists in the universe and if so I just return the existing set instead of creating a new set. This makes __contains__ a lot easier to implement. Also the module now supports sets in sets. Strangely enough very little coding was necessary since it was mostly already in there. It took me a long detour in acyclic digraphs with sinks having multiple incoming arcs before some mathematician friend pointed it out to me that there was nothing wrong with the program, since it could already do what I wanted because the __repr__ function was recursive. On the other hand, for what I wanted to do this was unnecessary. It was a non-problem, so the problem was solved. I just misinterpreted the output. I guess your earlier remarks about confusing __contains__ with has_subset were even more important than I thought. >Sounder implementation migh be to accept classes to >you not-known that "implement a set interface" or >"are adaptable to a set protocol" rather than just >do isinstance(), but unless/until PEPs 245/246 or some >variants thereof should prevail, it's never very >sure how best to test... maybe here, since you're >always using other.vector, you could be satisfied >with testing for that with hasattr(). > For the moment set(list) can be used to coerce a list into a set. Feedback on the module would be very welcome, especially if someone could provide an example of it behaving in an unexpected way. The url is the same as before. Anton. From mal at lemburg.com Tue May 15 10:10:00 2001 From: mal at lemburg.com (M.-A. Lemburg) Date: Tue, 15 May 2001 16:10:00 +0200 Subject: Trouble with unicode References: <3B011475.DEF4284B@lemburg.com> <0003845673517342_mailit@mail.isis.de> Message-ID: <3B0138B8.B2D9806F@lemburg.com> Charlie Clark wrote: > > >First you should check which encoding your Unicode file uses > >(e.g. sometimes Unicode refers to UTF-16 or just UTF-16-LE). Then > >you should read the file using codecs.open(): > Actually I now know that it is latin-1 > > ># replace encoding with 'utf-16' or 'utf-16-le' or 'utf-16-be' > >f = codecs.open(filename, 'rb', encoding) > >contents = f.read() > >f.close() > This is exactly what I was looking for. The only thing is having to use the > codec to read the file. I had expected something like > f = open(filename, "r") > contents = f.read() > contents = codecs.decode(contents, encoding) codecs.open() places a codec wrapper around the file object which provides (more or less) seemless encoding/decoding. You can write Unicode using the .write() method and the wrapped file object will encode it using the given encoding. .read() will do the same in the other direction, i.e. it returns Unicode. > or should I expect to start opening files with "rb" and an argument in the > future? I like the way Python encourages a standard way of doing things. We are thinking about enhancing the builtin open() to also handle encoded files. Basically, the codecs.open() mechanism will be replacing the open() one in case an encoding is given. > >Now you can convert the Unicode object contents into a plain > >string using some other encoding, e.g. Latin-1, and then > >write it back to a text file: > > > would do, if that was all I was doing with it. But it works fine as it is. > > Thanx a lot!!! > > Charlie Clark > > -- > Charlie Clark > Helmholtzstr. 20 > D?sseldorf > D- 40215 Sch?ne Gr??e von der D?sselstra?e ;-) > Tel: +49-211-938-5360 > http://www.begeistert.org -- Marc-Andre Lemburg ______________________________________________________________________ Company & Consulting: http://www.egenix.com/ Python Software: http://www.lemburg.com/python/ From lne at hrz.tu-chemnitz.de Thu May 3 15:33:57 2001 From: lne at hrz.tu-chemnitz.de (Lutz Neugebauer) Date: Thu, 3 May 2001 21:33:57 +0200 Subject: os.path.* routine problems In-Reply-To: References: Message-ID: On Thu, 3 May 2001, David Nedrow wrote: > I'm attempting to fix up a couple of small utilities that are part of > sgmltools-lite, but am running into my usual Python problem - I don't know > much about it. > > Here is the original segment: > > try: > pipe = os.popen("/bin/sh -c sgmlwhich >/dev/null 2>&1", "r") > retval = string.strip(pipe.readline()) > if retval != '' and pipe.close() == 0: > ETCSGMLCATDIR = retval > except: > pass > > > This may have worked for older versions of RedHat, but beginning with 7.1 a > number of changes have been made that require the logic to be modified. > Basically, the utility needs to attempt to run sgmlwhich. Depending on the > version of sgmlwhich, it may return a pointer to a directory or a > configuation file. If the return is a directory, ETCSGMLCATDIR is set to > that directory. If sgmlwhich returns a filename, the utility needs to parse > the config file and store the KEY=VALUE pairs. One of these will be > SGML_CATALOGS_DIR. The value for this key should then be assigned to > ETCSGMLCATDIR. > > The problem I am having is that none of my checks seems to be returning true > in the if-elif statement. Also, I had to remove the redirects from the popen > cmd, otherwise I did not receive the output of the cmd. > > > ETCSGMLCATDIR = "/etc/sgml" > import os, string > try: > cmd = "/bin/sh -c sgmlwhich" > retval = string.strip(os.popen(cmd).readline()) > if os.path.isdir(retval): > ETCSGMLCATDIR = retval > > elif os.path.isfile(retval): > entries = {} > for line in open(retval, 'r').readlines(): > print line > left, right = string.split(line, "=") > if left!='' and right!='': > entries[right] = [left] > ETCSGMLCATDIR = entries['SGML_CATALOGS_DIR'] > > except: > pass > > > Any pointers on what I doing wrong would be appreciated. if you remove try/except yuo get the exception thrown caused by the comment line in /etc/sgml/sgml.conf: # /etc/sgml/sgml.conf conformant with LSB Traceback (innermost last): File "sgml.py", line 14, in ? (left, right) = string.split(line, "=") ValueError: unpack list of wrong size try this: for line in open(retval, 'r').readlines(): print line list = string.split(line, "=") if len(list) == 2: entries[list[0]] = list[1] Lutz -- Lutz Neugebauer Lutz.Neugebauer at informatik.tu-chemnitz.de From aleaxit at yahoo.com Fri May 11 09:25:45 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 11 May 2001 15:25:45 +0200 Subject: inclusive-lower-bound, exclusive-upper-bound (was Re: Range Operation pre-PEP) References: <9db4i801beb@news2.newsguy.com> <3AFB0DB9.BDAE54A5@one.net.au> Message-ID: <9dgp8p0ok7@news2.newsguy.com> "Andrew Maizels" wrote in message news:3AFB0DB9.BDAE54A5 at one.net.au... > Alex Martelli wrote: > > > I disagree. Inclusive-lower-bound, exclusive-upper-bound > > is a VERY important and useful idiom, which we should ... > I can see where consistency is important, but why does Python do the > inclusive-lower-bound, exclusive-upper-bound thing? The inclusive-lower, exclusive-upper idiom, also called the "half-open range" idiom, is intrinsically simpler than closed-range alternatives. Which is why it has "taken over" in so many languages and frameworks: its simplicity has it all over the _apparent_ (surface!) "convenience" of closed-range. As an example of where this idiom has "taken over": in C, it is specified that, for an array x of N elements, while there is no element x[N] it IS correct to _take the address_ of x[N]. This must be allowed by any conformant implementation, and is included specifically for the purpose of letting the programmer easily specify an exclusive upper bound and use half-open ranges. The C++ standard library takes this further, of course, since just about _every_ standard algorithm consistently takes as arguments inclusive-start and exclusive-end iterators. But it IS just an extension of what Koenig explains in his book "C Traps and Pitfalls", about how always using half-open ranges helps avoid off-by-one errors that otherwise tend to plague programs. > From my point of view, there's one correct behaviour for range(1,5), and > it's NOT [1, 2, 3, 4]! It is a common phenomenon for human beings to consider "correct", "natural", or "right", something that is not optimal from the viewpoint of underlying mathematical reality. Fortunately, human beings are much more flexible than maths tend to be:-). My favourite example is how, for millennia, the concept of "zero" as a number was hotly rejected by the keenest thinkers -- Parmenides and Zeno made a particular career of this ("Non-being is not, and cannot be!"), but it was a widespread idea. As a result, no decent way to represent numbers and do operations with them was available -- addition was high mathematics, only wizards could multiply large numbers. Then, some Indian thinker (maybe under Buddhist influence, given the likely timeframe) came up with this weird "zero" idea -- the Arabs took it westwards -- Italian merchants took it from the Arabs, added double-entry bookkeeping -- and modern arithmetic and accounting were born. A few centuries later, we typically accept "zero" as a pretty natural concept (traces of "number" as meaning "more than zero" remain, but they're more or less like fossil traces, in natural language, in how we number our years, &c). This is not completely an aside... the ease of denoting EMPTY ranges is part of what makes a half-open interval simpler and handier as a general concept. range(x,x) is a nice way to denote empty ranges, more than range(x,x-1) would be if range was closed rather than half-open. More generally, range(x,y) has max(y-x, 0) items -- a VERY nice property, also easily expressed as y-x if y>=x. If range was closed, the number of items would be y-x+1, and that '+1' is the spoiler... cause of deucedly many off-by-one errors. Similarly, range(x,y)+range(y,z) = range(x,z), ANOTHER very nice property. Having such simple axioms means the behavior of 'range' can easily be symbolically expanded, and therefore also mentally understood, in more complex cases. Programs are easier to understand and prove correct, by having fewer '+1' and '-1' strewn around, when half-open ranges are the usage norm. One approach to help a programmer get used to half open ranges: with half-open ranges, we only need ONE basic concept, that of _FIRST_ index of some sequence. When we say we process range(x,y), we say that x is the first-index of what we process, and y is the first-index of what we do NOT process. With closed ranges, we would need TWO basic concepts, that of first AND that of _LAST_. One basic concept is easier to handle (mentally, symbolically, or in whatever way) than two of them. Say you want "the first N elements starting from the x-th one". Isn't range(x,x+N) an easier way to express this than range(x,x+N-1)? Or say that L is the length of the sequence and you want the _last_ N elements -- range(L-N,L) is, again, an easy and natural way to get their indices, isn't it? Say we get a list of strings that are to be catenated into one big string: as well as catenating them, we also want to record the places in the big string where the strings can be located, so we can still recover the original small-strings within the big one. A very natural approach: def catWithTracking(manystrings): start_at = [0] tot_len_so_far = 0 for astring in manystrings: tot_len_so_far += len(astring) start_at.append(tot_len_so_far) return ''.join(manystrings), start_at Nice, right? Not a +1 nor a -1 anywhere, and just one list of indices being computed and returned. OK, now, how do we get one small string back from the big one and the list of indices? def recoverOne(i, bigstring, indices): return bigstring[indices[i]:indices[i+1]] this is the slice-approach of course -- but then it IS nice that slice and range() behave just the same way, isn't it? Both half-open ranges... of course. If we need the INDICES inside the big string of the i-th original small string, it will be just as we do for slicing it: range(indices[i],indices[i+1]). No irregularity, everything smooth as pie. Now, of course, we can make even more arguments for half-open ranges in _slicing_ specifically. But they _are_ just "more of the same" wrt the general arguments for half-open ranges as a general idiom. Try designing your own libraries so that, whenever a start and a stop index are specified, the half open range approach is used... see if both the use and implementation thereof doesn't profit... Alex From montagne at boora.com Fri May 11 11:47:31 2001 From: montagne at boora.com (michael montagne) Date: Fri, 11 May 2001 15:47:31 GMT Subject: Setting search path Message-ID: I need some advice on the best way to handle this on WinNT. I really getting excited about Python and I'm thinking I'll use it more and more. But for each person in the offfice (100 people), I need to install Python on their machines. I'd like to create a directory on the network for all my scripts, modules, and packages. That way I can update the code in one place and all my users can share the same files. I'll still need a development path so on my machine I'd need another directory in front of the shared one. This also keeps all my code safe from upgrade overwrites. I've read about .pth files but I'm not sure that is best in my case. What is the standard way to handle this issue? -mjm From mlh at idi.ntnu.no Sun May 20 15:03:14 2001 From: mlh at idi.ntnu.no (Magnus Lie Hetland) Date: Sun, 20 May 2001 21:03:14 +0200 Subject: Parser for Minimal XML (or SML) Message-ID: <9e94ec$g1g$1@tyfon.itea.ntnu.no> I've just written a (toy) parser for SML (simple markup language) aka Minimal XML: http://www.hetland.org/python/#sml Feel free to play with it :) (As so often before, I wanted to see how little Python code would be needed; as it turned out it wasn't much.) -- Magnus Lie Hetland http://www.hetland.org "Reality is that which, when you stop believing in it, doesn't go away." -- Philip K. Dick From rpm at wag.caltech.edu Tue May 22 19:48:38 2001 From: rpm at wag.caltech.edu (Richard P. Muller) Date: Tue, 22 May 2001 16:48:38 -0700 Subject: What happened to os and os.path in Doc? References: <3B0A9683.E8F6254@wag.caltech.edu> Message-ID: <3B0AFAD6.FC9E37A2@wag.caltech.edu> Sorry about this question. I must have temporarily lost my mind. red-in-the-face-ly yrs, Rick "Richard P. Muller" wrote: > > Just browsed the latest docs, and I can't find the documentation for > either os or os.path. There is posix documentation there, but I had > normally accessed that through the os interface. Has this been > depricated? If not, what gives? > > os-less-ly yrs, > Rick -- Richard P. Muller, Ph.D. rpm at wag.caltech.edu http://www.wag.caltech.edu/home/rpm From aleaxit at yahoo.com Mon May 21 04:28:23 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 21 May 2001 10:28:23 +0200 Subject: How to Read/Write RTF and Word Files? References: <3b06b81e_3@news4.newsfeeds.com> Message-ID: <9eajj507n7@enews1.newsguy.com> "Greg Jorgensen" wrote in message news:Pine.LNX.4.33.0105201926390.6410-100000 at C800000-A.potlnd1.or.home.com.. . > On Sat, 19 May 2001, Dry Ice wrote: > > > How to Read/Write RTF and Word Files? ... > Microsoft Word uses a proprietary and undocumented format for .doc files. > The Word file format has changed significantly across versions of Word. > Whether by reverse-engineering or licensing the spec from Microsoft, quite > a few companies have implemented at least some Word import/export > capabilities. Yep. And there are opensource programs that attempt the same feat (presumably after reverse-engineering, in this case). http://www.fe.msk.ru/~vitus/catdoc/ offers such tools that manage to extract some text from MS Word (and Excel) files most of the time, and also points to other such tools. These tools aren't in Python, but you might use them from Python, or maybe recode in Python the algorithms & heuristics they embody. Alex From chris.gonnerman at newcenturycomputers.net Thu May 3 09:01:31 2001 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 3 May 2001 08:01:31 -0500 Subject: Where O Where Did My Data Buffer Go? References: <5.0.2.1.0.20010503033302.00a4d6e0@thewebsons.com> Message-ID: <007e01c0d3d1$2de9da60$a100000a@local> There are many ways to store the data. The main problem is going to be figuring out who the client is in order to show them the link to the right data. Does KBB have documentation on how this bizarre interaction is *supposed* to work? ----- Original Message ----- From: "Ben Ocean" To: "Chris Gonnerman" Cc: Sent: Thursday, May 03, 2001 5:38 AM Subject: Re: Where O Where Did My Data Buffer Go? > First a BIG THANK YOU to everyone that helped, ESPECIALLY Chris and Sheila! > Now, one more question for y'all... > What I *really* need to do is publish all this data to a Web page, which I > have, no problem. But then, I need to be able to make it so the visitor can > click a link and send that data to the client or call up a printable page > with the data. So, how can I re-call my script and pass the data back, or > somehow keep the data from the first call? Here's my broken code (notice > variable *dataOriginal*): > >>> > #!/usr/bin/python > > import cgi, os > import string > > print "Content-type: text/html\n\n" > form = cgi.FieldStorage() > formOriginal = form # do this to re-use the data for mailing back to > BladeChevy, etc. > > save = [] > for i in form.keys(): > v = form[i].value > save.append(i + ": " + v + "\n") > data = string.join(save,"") > dataOriginal = data # do this to re-use the data for mailing back to > BladeChevy, etc. > data = string.replace(data, "%%", "
") > array = string.split(data, "QueryWindowStatus") > dataOriginal = string.replace(dataOriginal, "\"", "\\\"") > > print # all sorts of html code > start = "
If you would > like us to help you purchase this car, href=\"http://www.bladechevy.com/cgi-bin/kbb.cgi?key=send&" > middle = "\">click here!
For a printable version, href=\"http://www.bladechevy.com/cgi-bin/kbb.cgi?key=print&" > finish = "\">click here!

 
\n" > aline = string.join([start, dataOriginal, middle, dataOriginal, finish]) > print aline > print # the rest of the html code > <<< > TIA, > BenO > > At 11:51 PM 5/2/2001 -0500, you wrote: > >I have been corresponding with Ben on this and I think everyone else > >would find a clarification of the problem useful. > > > >As I understand it, when the end user visits KBB via the framed page, > >KBB gets a "callback" URL as part of the request. At some point in the > >future KBB's web server will call Ben's server via that URL and send > >some arbitrary data. This does not appear to be directly related to the > >end user's experience. > > > >Ben is trying to catch the data being sent and do something with it > >(presently, email it to himself). > > > >BTW the concept of "data buffer" is irrelevant to web servers outside > >the Windoze world. The server in question is running Linux/Apache, > >so of course the data being sent via POST is in the sys.stdin stream. > > > >Also note for the record that calling cgi.FieldStorage() will *consume* > >the sys.stdin stream, so that subsequent sys.stdin.read() calls get > >nothing (i.e. EOF). > > > > > > > >-- > >http://mail.python.org/mailman/listinfo/python-list > > From aleaxit at yahoo.com Fri May 4 05:47:59 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 4 May 2001 11:47:59 +0200 Subject: Sorting using lambda not working in Py2.1? References: <9crvf1$3588$1@sp15at20.hursley.ibm.com> <9cs2mf02968@news2.newsguy.com> Message-ID: <9ctttj01ao1@news2.newsguy.com> "Marcin 'Qrczak' Kowalczyk" wrote in message news:slrn.pl.9f4d2h.nk7.qrczak at qrnik.zagroda... > Thu, 3 May 2001 18:57:51 +0200, Alex Martelli pisze: > > > This violates the semantic constraints on sort's optional argument: > > it must be a function that only returns 0 when arguments are to > > be considered EQUAL for sorting purposes. This will also return > > 0 when x>y -- not just when they're equal. > > Note that using different types for > Booleans > integers > ordering (less, equal or greater) > no matter if statically checked or not, would help to detect the error. It might, depending on whether (e.g.) cmp was re-specified to return "an ordering", while (e.g.) < is re-specified to return "a boolean", and so on, provided, of course, that sort was also respecified to require "an ordering" and it checked that such a type was actually returned. Right now, sort does check that the comparison function returns an int, but doesn't care whether it IS, as specified, -1 or 0 or 1 -- it treats all <0 as -1 and all >0 as 1 instead (it uses a specific check to allow this slight "laxity" wrt the specs). Of course, if one IS doing anything that is at all substantial in the comparison function, then the type issue is the least of one's worries; the semantics are subtler and might have been better specified in terms of a "<" function or other strict weak ordering (as of now, "x Message-ID: <070520011507593008%pecora@anvil.nrl.navy.mil> In article , Parnassus Submission wrote: > Matfunc.py > ---------- > > Matrix, Vector and Elementwise routines plus curvefitting > > 100% pure python math package (does not require numPy). Any conflicts with NumPy ?? From cribeiro at mail.inet.com.br Wed May 9 10:09:25 2001 From: cribeiro at mail.inet.com.br (Carlos Ribeiro) Date: Wed, 09 May 2001 11:09:25 -0300 Subject: Another non fatal bug in PythonWin Message-ID: <5.0.2.1.0.20010509110652.024683b0@mail.inet.com.br> I've got bitten by another non-fatal bug in PythonWin. This one happened when I: - selected a Python source code file on Windows Explorer; - Right-click -> edit on that file. The file was successfully opened. I don't have the slighest idea of what happened. >>> ERROR executing DDE command: self.Activate() Traceback (most recent call last): File "F:\Python21\Pythonwin\pywin\framework\intpyapp.py", line 289, in OnDDECommand exec command + "\n" File "", line 1, in ? File "F:\Python21\Pythonwin\pywin\framework\intpyapp.py", line 203, in Activate frame.SetForegroundWindow() win32ui: SetForegroundWindow failed - no error code is available Error executing DDE command. Traceback (most recent call last): File "F:\Python21\Pythonwin\pywin\framework\intpydde.py", line 22, in Exec self.app.OnDDECommand(data) File "F:\Python21\Pythonwin\pywin\framework\intpyapp.py", line 289, in OnDDECommand exec command + "\n" File "", line 1, in ? File "F:\Python21\Pythonwin\pywin\framework\intpyapp.py", line 203, in Activate frame.SetForegroundWindow() win32ui: SetForegroundWindow failed - no error code is available Carlos Ribeiro From glenfant.nospam at bigfoot.com Wed May 2 07:09:15 2001 From: glenfant.nospam at bigfoot.com (Gilles Lenfant) Date: Wed, 2 May 2001 13:09:15 +0200 Subject: help: cgi "post" problem (client side) Message-ID: <9copk9$2ic5$1@news6.isdnet.net> Hi, I'm making some CGI tests with Win98 and MS Personal Web Server. I installed this simple test cgi script: =======test.py======= import cgi cgi.test() ===================== cgi.test() is from the standard distribution and displays the headers, the environment variables and the cgi arguments (HTML fomated). This work and displays th cgi form parameters when I call it from a browser with this HTML: ======= ...
... ======= But when I do this through this script, this goes to a deadlock: =======runcgi.py======= import urllib params = {'param1': 'data1', 'param2': 'data2'} cparams = urllib.urlencode(params) # Deadlock in next line fh = urllib.urlopen('http://localhost/cgi-bin/test.py', cparams) # No deadlock with no "cparams" like this # fh = urllib.urlopen('http://localhost/cgi-bin/test.py') ======================= But aren't the HTML and runcgi.py supposed equivalent ? Did I miss something or should I use Apache or another Web server ? Thanks in advance for any hint. Gilles From strnbrg at c532352-a.frmt1.sfba.home.com Sat May 12 11:37:22 2001 From: strnbrg at c532352-a.frmt1.sfba.home.com (Theodore D. Sternberg) Date: Sat, 12 May 2001 15:37:22 GMT Subject: Can you change a Tkinter widget's master? Message-ID: In Tkinter, is there any way to change a widget's master? Assigning to the master attribute doesn't seem to have any effect. Setting (or resetting) the master would be the key to true compound widgets. For example, you could subclass Frame to take as constructor arguments several widgets (of any kind) and arrange them in some given way. You could of course pass the construction language as a string and then call eval on it. But this strategy would be way too cumbersome if you wanted to have several levels of nested widgets. Maybe this is too much to ask of Tkinter, since in Tk the identity of the master is fixed as part of the slave's name. Ted Sternberg Fremont California From m.hadfield at niwa.cri.nz Tue May 1 20:41:00 2001 From: m.hadfield at niwa.cri.nz (Mark Hadfield) Date: Wed, 2 May 2001 00:41:00 +0000 (UTC) Subject: Differences between Ruby and Python. References: Message-ID: <002301c0d2a0$8933af40$d938a8c0@Hadfield> > ...Presently, Ruby can't compare. But when > they can, beware. Beware of what, exactly? And Ruby is not a "they" it's an "it". Or is this a battle and are the Ruby army the enemy? --- Mark Hadfield m.hadfield at niwa.cri.nz http://katipo.niwa.cri.nz/~hadfield National Institute for Water and Atmospheric Research -- Posted from clam.niwa.cri.nz [202.36.29.1] via Mailgate.ORG Server - http://www.Mailgate.ORG From ron.l.johnson at home.com Wed May 9 00:32:37 2001 From: ron.l.johnson at home.com (Ron Johnson) Date: Wed, 09 May 2001 04:32:37 GMT Subject: socket.recvfrom() & sendto() References: Message-ID: Jonathan Feinberg wrote: > Ron Johnson writes: > >> Since the server can send messages to the client at random and >> irregular interevals, how can the client accept input from the >> user at the same time that it is "stalled" at a select() ? > > It is never "stalled" at a select(); asyncore uses non-blocking > sockets. select() returns immediately with lists of those sockets > which are ready to write and those sockets which are ready to read. Not to pick a nit, but doesn't execution stall at select() if there is no data coming in to the server. For example: a small chat server when no one happens to be chatting. -- Ron Johnson, Jr. Home: ron.l.johnson at home.com Jefferson, LA USA http://ronandheather.dhs.org "Is Python better or worse than Perl?" "Perl is worse than Python because people wanted it worse." -Larry Wall, 10/14/1998 From see at my.signature Tue May 1 01:30:10 2001 From: see at my.signature (Greg Ewing) Date: Tue, 01 May 2001 17:30:10 +1200 Subject: With or Using References: <81c5876c4a%tim@worthy.demon.co.uk> Message-ID: <3AEE49E2.63E4A508@my.signature> wrote: > Rather than typing jim each time, > jim.born=1960 > jim.haircolour='Brown' > jim.eyecolour='Green' def with(subject, **args): for attr, value in args.items(): setattr(subject, attr, value) jim = person() with(jim, born = 1960, haircolour = 'Brown', eyecolour = 'Green') -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From sill at optonline.net Tue May 22 10:43:45 2001 From: sill at optonline.net (Rainy) Date: Tue, 22 May 2001 14:43:45 GMT Subject: Python & Linux ? References: <3B0A0C89.1070108@bigpond.net.au> <3B0A469E.5080806@bigpond.net.au> Message-ID: On Tue, 22 May 2001 10:59:43 GMT, Peter Moscatt wrote: > Hi Remco, > > Yea, ya right.... it's difficult coming in from one enviroment (Win) to > a new one which is totally different. > So, if Linux programs aren't installable as such, what does the Software > Manager do. I thought it got the RPM files, uncompressed them then > installed ?? Well that's the thing - in windows you have the program itself that comes with an installer that installs that program and misc things like menu entries, while in linux you have a package manager that takes over this job (which makes sense because now every program doesn't have to recreate this functionality). > > Thanks for your help. > > Pete > > > Remco Gerlich wrote: > >>Peter Moscatt wrote in comp.lang.python: >> >>>I have just migrated from Win98 over to Linux. My programming platform >>>under Win98 was VB. >>>Now in Linux, I have decided to program using the Python platform. >>>I have bought myself a get started book and from what I can gather - >>>Python is a Interpreter and not a Compiler, therefore only being able to >>>develop scripts instead of installable programs. >>> >>>Have I got it all wrong here ?? >>> >> >>On Windows, this sort of thing is irritating, but then until a recent >>version, VB had the same thing, and it didn't bother people that much. >> >>On Linux, Python is usually already there. If the file starts with the >>appropriate line (#!/usr/bin/env python) and is executable, it works just >>like any "real" executable. There's no difference. >> >>And the notion of an "installable program" is something from Windows. >> > -- The point of philosophy is to start with something so simple as not to seem worth stating, and to end with something so paradoxical that no one will believe it. From aahz at panix.com Sun May 13 23:44:26 2001 From: aahz at panix.com (Aahz Maruch) Date: 13 May 2001 20:44:26 -0700 Subject: Python and Ruby , object oriented questions References: <3AFDFC02.29C58D14@earthlink.net> <87y9s0fvyo.fsf@litterbox.meowing.net> Message-ID: <9dnkaq$khl$1@panix6.panix.com> [Hey, Greg, just a friendly reminder to please include attributions for your quotes.] In article <87y9s0fvyo.fsf at litterbox.meowing.net>, A Meowbot wrote: >Ron Stephens: >> >> I am looking for reasons to avoid learning Ruby. > >Okay, this kind of thing has bugged me for the longest time. What is >the source of this meme, that there can be One and Only One Real True >Language, and all others must be banished to the hinterlands? > >I've found all along that the more languages I play with, the easier >it becomes to play with yet more of them. Do others find it works out >differently for them, that carrying more than one language around just >makes a mental mishmash of the others? While I agree with your rant to a certain extent, it's also true IMO that learning some languages can serve to add confusion. Trying to remember the syntax for a while loop or a function definition gets old rather fast. -- --- Aahz <*> (Copyright 2001 by aahz at pobox.com) Androgynous poly kinky vanilla queer het Pythonista http://www.rahul.net/aahz/ Hugs and backrubs -- I break Rule 6 "It's such a fine line between stupid and clever." --David St. Hubbins From mlh at idi.ntnu.no Mon May 28 12:19:31 2001 From: mlh at idi.ntnu.no (Magnus Lie Hetland) Date: Mon, 28 May 2001 18:19:31 +0200 Subject: Which book can be translated? References: <9eju9k$6dj$1@verence.demon.co.uk> Message-ID: <9ettqj$dh$1@tyfon.itea.ntnu.no> "limodou" wrote in message news:ce82f84e.0105241826.29bb6491 at posting.google.com... > -$Paul$- at verence.demon.co.uk (Paul Wright) wrote in message news:<9eju9k$6dj$1 at verence.demon.co.uk>... > > In article , > > limodou wrote: > > >I'm learning Python now, and I want to introduce it to my friends. But > > >many friends of mine know English little, so I wish to translate > > >Python books. But I don't know which book can be translated without > > >the trouble of copyright. > > > > > >Can anybody give me a books list? Thanks. > > > > has a beginners course in Python, > > written largely by Gareth McCaughan. > > > > You can translate the LiveWires stuff as long as you retain the > > licensing information on it. I believe someone's already translating it > > into Italian, though I'm not sure how far they've got. > > Thanks a lot. > I didn't quite catch your first post, so I'm not sure which language you want to translate into... If it is Italian (as mentioned above), Instant Python [1] and Instant Hacking [2] are already translated (both to Italian and some other languages). Feel free to translate them to any other language, as long as you don't change them, you notify me, and mention me as the author of the originals. [1] http://www.hetland.org/python/instant-python.php [2] http://www.hetland.org/python/instant-hacking.php -- Magnus Lie Hetland http://www.hetland.org "Reality is that which, when you stop believing in it, doesn't go away." -- Philip K. Dick From theservo at bellsouth.net Sat May 19 21:23:48 2001 From: theservo at bellsouth.net (Servo) Date: Sat, 19 May 2001 20:23:48 -0500 Subject: web page programs Message-ID: Hey Guys, I'm going to attempt to make a client side web page program that will ask the user to input some simple information (through text entries, list boxes, etc.) and it will then save the information to a file. At that point some computation will be performed on the data and the output shown, as a webpage. How would I go about doing this, if it is at all possible? Would it be possible to send the information via the post method to a Python script? Thanks, From ilya at glas.net Mon May 21 10:03:46 2001 From: ilya at glas.net (ilya at glas.net) Date: Mon, 21 May 2001 14:03:46 +0000 (UTC) Subject: Non-blocking I/O & M2Crypto Message-ID: <9eb782$a0v$1@news.sovam.com> Greetings, What is the right way of getting M2Crypto perform SSL handshake on a non-blocking socket? The ssl_dispatcher.py seems to do that before turning underlying socket into non-blocking mode. Any example would be much appreciated! Thanks, ilya From see at my.signature Wed May 2 00:10:38 2001 From: see at my.signature (Greg Ewing) Date: Wed, 02 May 2001 16:10:38 +1200 Subject: Hungarian notation (was RE: variable naming...) References: Message-ID: <3AEF88BE.B7A0BC0C@my.signature> Hungarian taken to the extreme of distinguishing integers from floats, etc. is certainly pointless in most languages nowadays, especially Python. Sometimes, though, type-related inflections are needed to distinguish things that would otherwise have exactly the same name. For example, Object Pascal code for the Mac abounds with things like type FooHandle = ^FooPtr; FooPtr = ^FooArray; FooArray = array[0..9999] of Foo; It can also be useful to distinguish type names from variable names (especially in a case-insensitive language), and to make it clear which scope an identifier belongs to. Python seems to have little need for either of these, either. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From mlh at idi.ntnu.no Sat May 19 15:48:32 2001 From: mlh at idi.ntnu.no (Magnus Lie Hetland) Date: Sat, 19 May 2001 21:48:32 +0200 Subject: Zope and Python 2.1 References: Message-ID: <009a01c0e09c$af7e8bc0$fa6ff181@ntnu.no> From: "Oleg Broytmann" > > On Sat, 19 May 2001, Magnus Lie Hetland wrote: > > > If you get them each time you start import ZODB in Python (like > > I did) it's kind of a problem... > > Thanks goodnes and hard-working DC people, I restart Zope seldom, and > almost never use ZODB outside of Zope. :) That's good for you, I guess -- but I need an object database (and not a web publishing solution), and ZODB seems to be an excellent choice, except for that it doesn't work properly with Python 2.1 yet. But I know they are working on it :) > Oleg. -- Magnus Lie Hetland http://www.hetland.org "Reality is that which, when you stop believing in it, doesn't go away." -- Philip K. Dick From robin at jessikat.fsnet.co.uk Thu May 17 03:47:29 2001 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 17 May 2001 08:47:29 +0100 Subject: memory leak in Python 2.1/FreeBSD? [was Re: Garbage collection on strike?] References: <3AFA6171.4020805@herts.ac.uk> <9denbe$klr$1@panix6.panix.com> Message-ID: In article , greg jorgensen writes .... > >The suspect code is a loop: > > f = open('filename', 'rb') > while 1: > buf = f.read(blocksize) > if not buf: break > # buf is sent over open ftp connection > conn.send(buf) > >(It's an overriden version of ftplib.FTP.storbinary that writes a '#' to >stdout for each block transferred). ... The return of an empty buffer may happen for reasons other than EOF especially on traditional UN*X systems. Typically some signal other than the expected one occurs and pre-empts the I/O signal. Looking in the fileobject.c source code it seems that this certainly is allowed for. >Any ideas on why this works on my Linux box (128 megs of RAM) but fails >reliably in the same place on the FreeBSD box (64 megs)? > >Thanks! > >Greg Jorgensen >gregj at pobox.com > > > -- Robin Becker From graham_guttocks at yahoo.co.nz Wed May 2 13:07:32 2001 From: graham_guttocks at yahoo.co.nz (Graham Guttocks) Date: Wed, 2 May 2001 10:07:32 -0700 (PDT) Subject: string interpolation with both local and module variables? Message-ID: <20010502170732.77223.qmail@web10304.mail.yahoo.com> Alex Martelli wrote: > Just change the second line of printmsg() to: > > message = makemessage('/tmp/test.txt', vars()) > > and makemessage() itself to, for example: > > def makemessage(file, vardict): > fp = open(file) > template = fp.read() > import Defs > localdict = Defs.__dict__.copy() > localdict.update(vardict) > text = template % localdict > return text Perfect. Thanks again Alex! Cheers, Graham __________________________________________________ Do You Yahoo!? Yahoo! Auctions - buy the things you want at great prices http://auctions.yahoo.com/ From aahz at panix.com Wed May 16 10:26:03 2001 From: aahz at panix.com (Aahz Maruch) Date: 16 May 2001 07:26:03 -0700 Subject: Touching Files On Windows References: Message-ID: <9du2lr$9v4$1@panix2.panix.com> [I'm sorry, I can't resist...] In article , Ben wrote: > >Is there a way to touch files under windows using python? "Mom! Dad! Don't touch that! It's eevillllllll....." -- --- Aahz <*> (Copyright 2001 by aahz at pobox.com) Androgynous poly kinky vanilla queer het Pythonista http://www.rahul.net/aahz/ Hugs and backrubs -- I break Rule 6 "It's such a fine line between stupid and clever." --David St. Hubbins From aleaxit at yahoo.com Fri May 18 13:05:45 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 18 May 2001 19:05:45 +0200 Subject: os.path.escape? References: Message-ID: <9e3kp9010u9@enews1.newsguy.com> "Mike C. Fletcher" wrote in message news:mailman.990192687.650.python-list at python.org... > Hi all, wondering if someone has such a beast they're willing to share. > Basically something that, given an arbitrary "name" by the user, eliminates > all system-specific special characters (i.e. on Win32 and Mac, lets " " > characters through, but not on *nix). Will settle for Win32 specific if I Why "not on *nix"...? Unix filenames are allowed to have spaces and lots of other strange things (you may have to quote them for use from the shell, but that's no different from Win either). Alex From news at myNOSPAM.org Fri May 11 02:00:57 2001 From: news at myNOSPAM.org (Stephen Hansen) Date: Fri, 11 May 2001 06:00:57 GMT Subject: Python Risk References: <3doft22t2w.fsf@mems-exchange.org> <005001c0d991$fcbb6a00$d938a8c0@Hadfield> Message-ID: Mark.... he was joking.... :) --S ""Mark Hadfield"" wrote in message news:005001c0d991$fcbb6a00$d938a8c0 at Hadfield... > From: "Andrew Kuchling" > > > > * Strings may now be enclosed in double quotes as well as in single > > quotes. There is no difference in interpretation. > > > > I mean, really, who ordered *that*? > > I don't know, but it makes it easy to put either double quotes or single > quotes inside a string, thus: > > " ' " ' " ' > > --- > Mark Hadfield > m.hadfield at niwa.cri.nz http://katipo.niwa.cri.nz/~hadfield > National Institute for Water and Atmospheric Research > > > > -- > Posted from clam.niwa.cri.nz [202.36.29.1] > via Mailgate.ORG Server - http://www.Mailgate.ORG From aleaxit at yahoo.com Tue May 29 03:11:58 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 29 May 2001 09:11:58 +0200 Subject: FAQs (was Re: win98: PY to EXE ?) References: <9euec2$ecm$05$1@news.t-online.com> Message-ID: <9evi2c017gf@enews2.newsguy.com> "Gerhard H?ring" wrote in message news:slrn9h5m04.17p.gerhard.nospam at lilith.hqd-internal... > On Mon, 28 May 2001 23:03:21 +0200, Sebastian Radestock wrote: > >Hello Newsgroup, > >how can I transform my own python source codes (*.py) to *.exe-files under > >windows 98? I want to use my python programs without the python command > >line! > > See my response in the thread "Packaging Python". It's one thread above in my > newsreader. Btw. this is a Frequently Asked Question (probably one of the most > frequently asked). Can anybody add this to the FAQ, if it isn't there already? It IS there (4.28), albeit with an old (still-working, but not the latest version) link to McMillan's installer. Like (in my experience) all frequently-asked questions (on EVERY Usenet group, btw), it doesn't stop being asked frequently just because the answer is right there and reasonably easy to find at http://www.python.org/doc/FAQ.html. In some groups the standard response to FAQ's is a rudely-worded "go read the FAQ, you $^%*!" -- it STILL makes no difference: people don't read FAQ documents, and keep frequently-asking the same old questions over and over again anyway. Oh well -- that's Usenet News. Alex From piet at cs.uu.nl Wed May 30 08:26:38 2001 From: piet at cs.uu.nl (piet at cs.uu.nl) Date: 30 May 2001 14:26:38 +0200 Subject: Silent python program References: <90B1648A0oviautronicano@195.0.200.200> Message-ID: >>>>> ovi at autronica.no (Olav) (O) writes: O> Can anyone tell me how to run a python program in "background" on win32 O> platform. I don't want any output to the screen. python script.py > nul -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From martin.franklin at westerngeco.com Thu May 31 06:20:30 2001 From: martin.franklin at westerngeco.com (Martin Franklin) Date: Thu, 31 May 2001 11:20:30 +0100 Subject: Compiling an Extension on AIX!!! References: <9eq5pf$l1u3$1@ID-82539.news.dfncis.de> Message-ID: <3B161AEE.20F0FE4E@westerngeco.com> All, Recently I have been creating and compiling 'c' extensions on my *nix platforms (Linux, Solaris, IRIX and yes AIX!) The extensions make some calls to some legacy code we have lying around. I make them by hacking the Python make system On al other platforms it compiles first time every time;-) on AIX however I was getting the following message from make:- [compo:bpse:/SRC/python/Extending/NewFileInfo/aix4] 14 % make xlc -DIBMRS -O -I/usr/local/include/python2.0 -I/usr/local/include/python2.0 -I/legacy/code/src/include -DHAVE_CONFIG_H -c -q32 ./NewFileInfo.c "/usr/include/sys/socket.h", line 76.21: 1506-247 (S) Incompatible type specifier "int". make: 1254-004 The error code from the last command is 1. Stop. So i looked in /usr/include/sys/socket.h and at line 76:- typedef __ulong32_t socklen_t; Then I tracked where it was being defined as an int........ /usr/local/include/python2.0/config.h Around line 147 /* Define to `int' if doesn't define. */ #define socklen_t int The wired thing is socklen_t is not defined in sys/types.h but in socket.h so the comment makes no sense. So I removed the offending #define and it compiles without error..... Is this a bug and as such should I report it to the bug tracker at sourceforge? Thanks for your time, Martin. From petar at metamarkets.com Mon May 21 14:44:48 2001 From: petar at metamarkets.com (Petar Karafezov) Date: Mon, 21 May 2001 11:44:48 -0700 Subject: sgmllib and entityref handling in python2.0 Message-ID: <86FC34EA3C4F074AA6BBFFE52ED83FED27C237@METAEXCH.sfo.metamarkets.com> Hello all - I've noticed an interesting behavior of SGMLParser defined in sgmllib. The issue - as I am seeing it is the way entityref was defined on line 23: ... entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]') ... This would match anything that looks like entityref and that ends on a non-alphabetic or numeric character. The W3C docs described that entityrefs end on ';' and so does the python docs when talking how SGMLParser works. The result of this is that a HTML fragment like: http://www.abc.com/page.html?a=1 &b=2 Would get parsed: http://www.abc.com/page.html?a=1 &b;=2 ---^ (extra semicolon included) This is happening, because the entityref search gets ended at the '=' (same happens at every character that's not a letter or a number - space for instance). I did change line 23 to: entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*);') and now I am getting the correct behavior. Could anyone share thoughts on this issue ?? Regards Petar Karafezov MetaMarkets.com 415-575-3015 ------------------------------------------- Investing Out Loud at http://www.metamarkets.com ------------------------------------------- From rnd at onego.ru Thu May 31 09:44:34 2001 From: rnd at onego.ru (Roman Suzi) Date: Thu, 31 May 2001 17:44:34 +0400 (MSD) Subject: Against PEP 240 In-Reply-To: <200105310958.LAA28329@boris.cd.chalmers.se> Message-ID: On Thu, 31 May 2001, Laura Creighton wrote: > "Nick Perkins" : > >On the other hand, the current system has never bothered me. I enjoy having > >tiny inaccuracies hidden from me. It all depends on coming to peace with > >the idea that a float is just a number that is very close to the number that > >I want it to be. > > The only thing necessary for the triumph of evil is for good men to do nothing. > - Edmund Burke (1729-1797) > > (Not to pick on Nick, you do have to in some way get peace with the floating > point to use it, though _my_ _word_ we are different people tempermentally. > Hidden inaccuracies are what keeps me up at night, sweating. No > hyperbole. But I think doing nothing rather than fixing the default > behaviour of python on treatment of numbers that have a period in them > is decimal, not rational that is the way to go, somebody try to talk us > out of it> is exactly what Burke was talking about. Financial applications better do in integers (long integers if you work for large enough company ;-) But in all other cases (save rocket science, some areas of physics and number theory) even float accuracy is more than enough for most applications. Noise usually have higher value than 7-th digit. If your algorithm diverges due to inaccuracies, choose another one. Why do you want to have more accuracy than double float? > Laura Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From aleaxit at yahoo.com Thu May 31 18:20:50 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 1 Jun 2001 00:20:50 +0200 Subject: Iteration index References: <9f63lo$rb0$1@zeus.polsl.gliwice.pl> Message-ID: <9f6g5m0gbo@enews2.newsguy.com> "Marek Augustyn" wrote in message news:9f63lo$rb0$1 at zeus.polsl.gliwice.pl... > Hello! > > 1. Do I have to use additional variable when I want to know iteration index? > Example: > > s = ('a', 'b', 'ala', 'a') > i = 0 # additional variable > for el in s: > print i, el > i += 1 You may work this in several ways, such as the one you used, or: for i in range(len(s)): print i, s[i] or for i, el in zip(range(len(s)), s): print i, el > 2. Are there block comments in Python? (like /* */ in C) Not quite, but triple-quoted strings can often serve a similar purpose of "commenting out" blocks of lines. Alex From m.mariani at imola.nettuno.it Fri May 18 10:48:11 2001 From: m.mariani at imola.nettuno.it (Marco Mariani) Date: Fri, 18 May 2001 16:48:11 +0200 Subject: Extending python with C In-Reply-To: ; from john.thai@dspfactory.com on Fri, May 18, 2001 at 11:03:17AM -0400 References: Message-ID: <20010518164811.A5678@zoidberg> On Fri, May 18, 2001 at 11:03:17AM -0400, John wrote: > I am trying to building an C extension module. How would I convert an > Integer in Python to an int * in C ? I know there's an "s" format specifier > for char *, but what about int *? If you're passing it as a parameter: if (!(PyArg_ParseTuple(args,"i",&myvariable)) { // no chance } else { // now myvariable has been filled } If you've got a python object pointer: myvariable = PyInt_AsLong(myobject) From doc at sympatico.ca Tue May 8 23:46:47 2001 From: doc at sympatico.ca (DOC) Date: Tue, 8 May 2001 20:46:47 -0700 Subject: How to convert binary file data? Message-ID: I must be missing something here. I am reading a file that has binary data and want to be able to handle/convert it... But I can't seem to figure out how to do it. >>># read in 1 byte: ...buf=x.read (1) >>># this is what's in buf ... buf '\xe0' >>># try the eval ...eval (buf) Traceback... ... SyntaxError: unexpected EOF while parsing >>># OK try string.atoi! ...string.atoi (buf) Traceback... ... ValueError: invalid literal for int(): ********* An odd char is shown for both of the above. Likely unicode for \xe0. So can someone tell me the right way to handle this? Thanks, DOC From MarkH at ActiveState.com Sun May 20 16:06:08 2001 From: MarkH at ActiveState.com (Mark Hammond) Date: Sun, 20 May 2001 20:06:08 GMT Subject: quick pythonwin corrupted installation question References: <3B0842C1.D2E52585@.com> Message-ID: <3B082430.8090002@ActiveState.com> {e.g. John Smith} wrote: > I recently had my registry corrupted and I now receive the following > message when trying to start Pythonwin 2.0: > > File "", line 1, in ? > File "C:\Program Files\Python20\Pythonwin\pywin\framework\startup.py", > line 49, in ? > exec "import %s\n" % moduleName > File "", line 1, in ? > File "C:\Program > Files\Python20\Pythonwin\pywin\framework\intpyapp.py", line 4, in ? > import win32api > exceptions.ImportError: No module named win32api > > win32api.pyc is in \Python20\win32 > There must be a path setting missing somewhere? The simplest solution is to reinstall. If you use ActiveState's installer, it even has a "repair" option. Mark. From Daniel.Kinnaer at Advalvas.be Thu May 3 14:04:56 2001 From: Daniel.Kinnaer at Advalvas.be (Daniel) Date: 03 May 2001 18:04:56 GMT Subject: Testing NNTP using Python Message-ID: <3af19dc8$0$43051$456d72a3@news.skynet.be> This is a testfile, please disregard. Posting this file using Python end of message From boogiemorg at aol.com Wed May 23 18:18:05 2001 From: boogiemorg at aol.com (David Morgenthaler) Date: 23 May 2001 15:18:05 -0700 Subject: Suggestion for os.path.join Message-ID: We use os.path.join() extensively to keep our code platform independent. But we sometimes have problems on win32 when the resulting path is passed to a C-extension -- not all C-extensions (e.g., gdchart) are smart enough to handle the result. Example: Python 2.1 (#15, Apr 23 2001, 18:00:35) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> PATH = 'D:/SARCrates/SARBoxResults' >>> import os >>> outfile = os.path.join(PATH,"subdir","outfile.png") >>> print outfile D:/SARCrates/SARBoxResults\subdir\outfile.png >>> The combination of '/'s and '\'s in the resulting path are not handled by gdchart.chart. I have similar problems with the PIL's ImageFont, etc. Suggestion: Change ntpath.join to give join a signature of something like os.path.join(path [, path2 [, ...]], [sep=s]). The following should do the trick. def join(a, *p, **parms): """Join two or more pathname components, inserting "\\" or sep as needed""" if parms.has_key('sep'): sep = parms['sep'] else: sep = "\\" path = a for b in p: if isabs(b): path = b elif path == '' or path[-1:] in '/\\:': path = path + b else: path = path + sep + b return path Then I get the following behavior, solving my problem: >>> PATH = 'D:/SARCrates/SARBoxResults' >>> outfile = join(PATH,"subdir","outfile.png") >>> print outfile D:/SARCrates/SARBoxResults\subdir\outfile.png >>> outfile = join(PATH,"subdir","outfile.png",sep='/') >>> print outfile D:/SARCrates/SARBoxResults/subdir/outfile.png >>> join for other platforms could simply ignore the separator parameter. David From tim.one at home.com Wed May 9 03:19:39 2001 From: tim.one at home.com (Tim Peters) Date: Wed, 9 May 2001 03:19:39 -0400 Subject: xrange question In-Reply-To: <9daj58$hfosb$1@ID-11957.news.dfncis.de> Message-ID: [assorted luminaries blame me for their inability to make a correct choice between "range" and "xrange" -- thanks! ] Here's a useful addition for your sitecustomize.py or PYTHONSTARTUP file: import __builtin__, random choices = range, xrange for name in "xrange", "range": setattr(__builtin__, name, random.choice(choices)) del __builtin__, random, choices, name Use that for a week at your site and see whether anybody notices. Either way, blame me . From eloy at rabinf50.uco.es Thu May 31 09:57:43 2001 From: eloy at rabinf50.uco.es (eloy) Date: Thu, 31 May 2001 15:57:43 +0200 Subject: Appliying method to list of objects Message-ID: Help, please. I couldn't find a cannonical (ti!mtowtdi) and efficient way to improve this: for i in list: i.dosomething() Perhaps map( lambda x: x.dosomething(), list ) But the lambda screeches, somehow: I guess there must be a better way to do it. Using apply()?. But how?. I'm a bit new, so sorry if this is an easy one :). -- Eloy _____________________________________________________________________ ---- Eloy Rafael Sanz Tapia -- ersanz at uco.es -- ma1satae at uco.es ----- ------------------ http://www.uco.es/~ma1satae ---------------------- ----------- GPG ID: 190169A0 / finger eloy at rabinf50.uco.es ---------- C?rdoba _ Espa?a _______________ Debian 2.2 GNU/Linux 2.2.19 rabinf50 From qrczak at knm.org.pl Tue May 29 14:18:06 2001 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: 29 May 2001 18:18:06 GMT Subject: Against PEP 240 References: <9f03m401qcu@enews2.newsguy.com> Message-ID: Tue, 29 May 2001 14:12:38 +0200, Alex Martelli pisze: > I'm not sure what various dialects of Lisp, Scheme, Prolog, Erlang, > Haskell, and other non-classic languages do, but I'd bet that SOME > of them take 7.35 as meaning 7.35 (aka 147/20, an exact rational > number). In Haskell it depends on the type as which the literal is used. It can mean either exact Rational or inexact Float or Double or whatever fractional type you define and use a literal as. It's specified as applying the overloaded function fromRational to an exact rational; an analogous mechanism is for integral literals (42 can be a Rational or Double too, but also an Integer or Int). If the context doesn't determine a type precisely, but requires that it's numeric, then the type is defaulted. Types to which numeric types are defaulted are specified per module. The default default is (Integer, Double), i.e. Integer is tried first, then Double. Relying on defaulting is not a good practice (ghc -Wall warns about it), it's better to specify the type somewhere. In Lisp (as an experiment shows, I don't have the specs) 7.35 is a floating point number. Rational literals are written thus: 147/20, and actual division thus: (/ 147 20), which yields 147/20, not 7.35. I would prefer to have rationals by default and floating point when requested (and to have integers which don't overflow by default). -- __("< Marcin Kowalczyk * qrczak at knm.org.pl http://qrczak.ids.net.pl/ \__/ ^^ SYGNATURA ZAST?PCZA QRCZAK From gerhard.nospam at bigfoot.de Tue May 1 18:50:20 2001 From: gerhard.nospam at bigfoot.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Wed, 02 May 2001 00:50:20 +0200 Subject: PLEASE Help with CGI Problem! References: Message-ID: <3AEF3DAC.678C2533@bigfoot.de> Ben Ocean wrote: > > Hi; > I NEED to get data from the buffer after it is sent to me from a foreign > host. Here's (apparently) how this would be scripted in perl: > >>> > read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); > @pairs = split(/&/, $buffer); > foreach $pair (@pairs) { > ($name, $value) = split(/=/, $pair); > $value =~ tr/+/ /; > $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; > $FORM{$name} = $value; > } > <<< > How would I script it in Python and what modules must I call? I could tell you how to do this in Python, but there is *really* no need to. The Perl snippet just parses a CGI POST request. Use the cgi module and cgi.FieldStorage(). Gerhard -- Sorry for the fake email, please use the real one below to reply. contact: g e r h a r d @ b i g f o o t . d e web: http://highqualdev.com From costas at meezon.com Sun May 20 07:42:19 2001 From: costas at meezon.com (Costas Menico) Date: Sun, 20 May 2001 11:42:19 GMT Subject: Python and Ruby , object oriented questions References: Message-ID: <3b07a53b.2521300@News.CIS.DFN.DE> Roman Suzi wrote: > >And I don't know about you, but after learning Python it is >extremely tough to write in Perl again... It's not religious, >it's probably objective. Agreed. I am doing it to lessen my dependence on Microsoft and find a better language. It so happens that they own a powerful product which resembles Python, in many respects, called Visual Foxpro, that I have used for many yeas. They are letting it die a slow and tortuous death to force us to use VB. Hundreds of thousands of programmers are being affected by this. Although I have a lot of experience with VB, it takes much longer to complete appications using it. I have looked at Perl (too convoluted). I have looked at PHP (cleaner but also convoluted). Python on the other hand has a nice and clean syntax (I got over the indentation requirement in two minutes), tons of support and hundreds of modules. I am trying to get more frustrated VFP programmers to check out Python. Costas From d98aron at dtek.chalmers.se Fri May 25 16:07:10 2001 From: d98aron at dtek.chalmers.se (Fredrik Aronsson) Date: 25 May 2001 20:07:10 GMT Subject: seg fault on asscessing undefined attr in __getattr__ References: Message-ID: <9eme1e$t4r$1@nyheter.chalmers.se> In article , Oleg Broytmann writes: > On Fri, 25 May 2001, Kong-Jei Kuan wrote: >> hi, i am still using python 1.52, and don't know if this happens to other >> versions, can some verify this? >> >> Python 1.5.2 (#0, Dec 27 2000, 13:59:38) [GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2 >> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >> >>> class A: >> ... def __getattr__(self, name): >> ... self.x >> ... >> >>> a=A() >> >>> a >> Segmentation fault > > Do you understand you've put your Python into infinite recursion? > > Oleg. ... and to break it you could for example do class A: def __getattr__(self, name): try: return self.__dict__[name] except KeyError: raise AttributeError # to make hasattr happy... /Fredrik From gball at cfa.harvard.edu Sat May 12 21:42:25 2001 From: gball at cfa.harvard.edu (Greg Ball) Date: Sat, 12 May 2001 21:42:25 -0400 (EDT) Subject: Which is more correct for compaing to None? Message-ID: > Both of these seem to work. Which is more correct? > > if foo is None: > print 'is' > > if foo == None: > print '==' I'm going to use 'foo is None' in future... The context I use this in is default arguments: def plot(seqy, seqy=None): if seqx is None: seqx = range(len(seqy)) # plot seqy vs. seqx ... In the newest version of Numerical Python, 'a == None' raises an exception if a is a Numpy array. 'is' should be completely safe since it just uses object identity (i.e. it doesn't ask the object how to do the comparison). I believe python guarantees there is a unique None object. In principle the object identity check is faster, particularly if foo happens to be an instance, since a lot less work gets done under the covers. It might even be faster than a truth test, but more importantly a truth test might not be the right behaviour in general, where foo == '' is meaningful for example. The standard library says $ grep 'is None' /usr/lib/python2.2/*.py | wc -l 280 $ grep 'is not None' /usr/lib/python2.2/*.py | wc -l 107 $ grep '== None' /usr/lib/python2.2/*.py | wc -l 0 grep '!= None' /usr/lib/python2.2/*.py | wc -l 0 with the first example that comes up appearing in BaseHTTPServer.py. --Greg Ball From tim.one at home.com Sun May 6 14:35:12 2001 From: tim.one at home.com (Tim Peters) Date: Sun, 6 May 2001 14:35:12 -0400 Subject: xrange question In-Reply-To: Message-ID: [John Flynn] > I'm puzzled about the purpose of xrange. Carlos Ribeiro gave some excellent answers, so I'll skip to this one: > ... > Secondly, it seems that the size of a sequence generated by xrange is > limited to INT_MAX. Is there a good reason for this? Just because it's a minor variant of range(), which is also limited to sys.maxint (which may be much bigger than INT_MAX, depending on the platform). If you're on a 32-bit platform, try range(2000000000) and see what happens . Given the way the interpreter is currently written, it's simply easier and faster to stick with native C longs when possible. This is becoming harder to live with over time, though, as 2**31 is no longer "essentially infinity" for all practical problems. So Python is slowly eradicating the user-visible differences between its bounded and unbounded integral types, and someday I expect neither range() nor xrange() will care about native C integer sizes. and-someday-after-that-people-will-implement-c-in-python-ly y'rs - tim From sax at no-host-at-all.no Fri May 11 08:14:20 2001 From: sax at no-host-at-all.no (Stefan Axelsson) Date: Fri, 11 May 2001 12:14:20 GMT Subject: Bubblesort (was: Re: Why aren't we all speaking LISP now?) References: Message-ID: <9dgl1m$a2d$1@foo.telia.com> In article , Roy Smith wrote: >And, finally, as Timothy says, it's also is a good segue into the >idea of algorithmic complexity. The first time they try to sort a >list of all the words in the dictionary, they discover what O(N^2) >means! If I tried to teach quicksort first, they would probably get >lost in the details, and not understand why such a seemingly simple >task was being made so complicated. I was going to keep quiet since I'm going away for the week and won't be here to keep the argument going, but I cannot hold my peace! ;-) In Haskell a quick sort is: qsort [] = [] qsort (x:xs) = qsort[y | y <- xs, y < x] ++ [x] ++ qsort[y | y <- xs, y >= x] Evidently doable from memory... And the above code could well be read out aloud and make sense, almost even to a rank beginner. "An empty list is already sorted, otherwise to sort a list prepend all elements that are smaller than the first with the first element, and append all elements that are greater than the first elements to the first elements. Of course you must sort the smaller and greater elements before concatenating them into a list, since the list wouldn't be sorted otherwise!" I'm sure that something equally elegant could be accomplished in Python (though I'm too new to Python I'm afraid), it has the prerequisites (list comprehension, lists etc), which is why I didn't feel too bad about the above Haskell code. It'd be a bit insulting an comp.lang.c for example ;-) ;-) The moral: it's not that HLL:s have sorting built in, it's that they enable you to express powerful concepts without being mired in detail. (Which incidentally, and IMHO, is why students always cry help when exposed to functional programing, the easy stuff that lasts a whole course on imperative programming is finished off in a few weeks, and then the real fun begins. ;-) P.S. And yes, for a practical application choosing the first element as the pivot element isn't perhaps the smartest course of action, the list could already be sorted for example. Stefan, -- Stefan Axelsson (For mail address see: http://www.ce.chalmers.se/staff/sax) From amdescombes at diligo.fr Wed May 30 03:55:17 2001 From: amdescombes at diligo.fr (Andre M. Descombes) Date: Wed, 30 May 2001 09:55:17 +0200 Subject: Reinitializing the python interpreter form Java References: <9eg3fs$aaq$1@wanadoo.fr> <3B0C256D.4F33D28E@accessforall.nl> <9elln0$1d6$1@wanadoo.fr> <3B12B37E.10C470DC@accessforall.nl> <9evj8t$e8i$1@wanadoo.fr> <3B13F8EF.A865F50E@accessforall.nl> Message-ID: <9f28va$j4l$1@wanadoo.fr> Ok, good Idea, but what will happen to the variables I pass that way, will they be still accessible from another function that I call? they shouldn't be there at all anymore, they should go out of scope as soon as I exit the function. Thanks again Ype, Andre "Ype Kingma" wrote in message news:3B13F8EF.A865F50E at accessforall.nl... > > For a second I was afraid this comes in the category > "you can't have your cake and eat it". > > But you have control over the locals/globals so you could easily > pass something using PyInterpreter.set(), or just do it directly: > > theLatestCopyOfYourGlobals['varName'] = valueYouWantToPass > > before doing the exec. Using varName in your function should do the trick then. > > Have fun, > Ype From duncan at NOSPAMrcp.co.uk Fri May 25 05:44:26 2001 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 25 May 2001 09:44:26 +0000 (UTC) Subject: speeding up string.split() References: Message-ID: Chris Green wrote in news:m2n182cs9c.fsf at phosphorus.tucc.uab.edu: > Is there any way to speed up the following code? Speed doesn't matter > terribly much to me but this seems to be a fair example of what I need > to do. You haven't given much to go on here. Any real speedups are likely to depend very much on what you want to do with the data after you have split it. > #!/usr/bin/python > from string import split > > for i in range(300000): > array = split('xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy 6' + > '1064 80 54 54 1 1 14:00:00.8094 14:00:00.8908 1 2') > Speedups to the above code: 1. The variable array is not used after it is assigned, and the assignment is constant. factor the assignment out of the loop. 2. After 1, the loop is empty, remove the loop. 1 and 2 together provide a massive speed improvement with no loss of functionality to the code as given. Alternatively: 3. Put the code inside a function. 4. Use the split method on the string instead of the split function 5. Use string concatenation instead of '+' 3, 4 and 5 together knock about 25% off the running time. 6. If whatever you intend to do with the data involves filtering it on the first field or two, then using "xxx...".split(' ', 1) is very much faster than splitting up all the fields. This can reduce the time by two thirds easily. 7. Use Perl, or C, or whatever else takes your fancy if speed is that critical. -- 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 maxm at normik.dk Mon May 21 05:38:31 2001 From: maxm at normik.dk (=?iso-8859-1?Q?Max_M=F8ller_Rasmussen?=) Date: Mon, 21 May 2001 11:38:31 +0200 Subject: PIl, text and Windows 2000 Message-ID: <7BD10B680501D411B9DF009027E06F32197D0E@exchange> > From: Ben [mailto:b.e.n. at .r.e.h.a.m.e...c.o.m] > I am currently having a particularly hard time getting some text down > onto a 2 bit png file using PIL and i was wondering > if anyone has been successful in doing this could you please provide > me with some pointers or sample code. Here is a script that automatically creates buttons from a default image and some text. Maybe there is something there to pilfer. regards Max M --------------------------------- buttonList = {} buttonList['02_home.gif'] = '?lwechselung' buttonList['02_01_somewhere.gif'] = 'Klares Bekenntnis zur Umwelt' buttonList['02_02_dude.gif'] = 'Hey Dude' import ImageDraw, ImageFont import Image # Set font arial = ImageFont.load('C:/root/pythonScripts/PILTest/phontz/Verdana_12_100.pil') im = Image.open("C:/root/pythonScripts/PILTest/redButton.gif") width, height = im.size middle = width/2 for fileName, theText in buttonList.items(): aCopy = im.copy() # render the text draw = ImageDraw.Draw(aCopy) draw.setfont(arial) draw.setink(255) textWidth, textHeight = draw.textsize(theText) textMiddle = textWidth/2 fontPlacement = middle - textMiddle print textWidth draw.text((fontPlacement, -3), theText) aCopy.save('C:/root/pythonScripts/PILTest/' + fileName) From nospam at newsranger.com Tue May 15 19:46:23 2001 From: nospam at newsranger.com (tla) Date: Tue, 15 May 2001 23:46:23 GMT Subject: making a web page with interactive figures Message-ID: I would like to venture into making a Web Page with interactive figures, but have never done any web programming and no idea which tools to use. I've been using Python for a few years (mostly numeric stuff -- data analysis and acquisition, etc.), and would like to stick with Python if possible. Could someone tell me if I can do the following things on a web page using Python and which tools would be appropriate. 1) Display two graphs, and when the user selects (clicks on) a point in one graph, have the other graph refresh with a new picture based on the selected point. 2) (I think this is harder than #1.) Given two simple figures, A and B, each composed of just few arrows and boxes, etc. , I would like to allow the user to grab (click and hold) an object in A, and move it around smoothly, and while this is being done, smoothly update the objects in B, in some predetermined way, depending on what's happening in A. 3) For any state in #1 and #2, generate a stereo sound file from two NumPy arrays and allow the user to listen to this. I assume, especially, for 2, but possibly for 1 and 3, that the user will need to have an executable that automatically runs on their computer. Is this the way this would work? What are my options for this? If I can't use Python for these, what should I use? Thanks for suggestions, Tom TA16 at cornell.edu From letter at tron-inter.net Tue May 29 17:48:18 2001 From: letter at tron-inter.net (Marko Djogatovic) Date: Tue, 29 May 2001 23:48:18 +0200 Subject: wxComboBox Events, Message-ID: <9f15f8$n8n$1@neptun.beotel.net> Hi, I've created a program using wxPython library. When I use combobox events, instead of one I recive two or more events. Why? Example: class SomePanel(wxPanel): def __init__(self, parent): ... self.cbo = wxComboBox(self, 300, "default", choices = ["aaa", "bbb"]) ... EVT_COMBOBOX(self, 300, self.EvtComboBox) ... def EvtComboBox(self, evt): print self.GetString() -------------------------------------------------------------------------- >>> aaa aaa aaa Thanks, Marko Djogatovic From invalid at email.com Wed May 16 11:24:39 2001 From: invalid at email.com (Erik de Castro Lopo) Date: Thu, 17 May 2001 01:24:39 +1000 Subject: Weirdness with Tkinter Text and Scroll widgets Message-ID: <3B029BB7.82FBA076@email.com> Hi there, I'm working on a little app which redraws text in a Tkinter Text window. What I'd like to be able to do is the following: # Get the current scroll bar poistion position = scroll.get () # Delete all text text.delete (0.0, END) # Insert the replacement text text.insert (END, new_text) # Set the scroll position back to where it was. scroll.set (position [0], position [1]) The problem I'm having is that no matter what the position of the scrollbar before the call to scroll.get (), the scollbar is always returned to the top after the end of this section of code instead of returning to the original position. The length of text in the widget before and after this section of code is the same (and greater than the size of the text widget). Anybody have any idea why its doing this or better still, how to fix it? Thanks in advance. From michael at stroeder.com Wed May 30 12:43:36 2001 From: michael at stroeder.com (Michael =?iso-8859-1?Q?Str=F6der?=) Date: Wed, 30 May 2001 18:43:36 +0200 Subject: Small, Local Web/CGI Server Advice References: <67abb823.0105300435.260f47d2@posting.google.com> Message-ID: <3B152338.C6DC0D1C@stroeder.com> dsavitsk wrote: > > i agree w/ the other poster that Medusa is the better choice, IMHO it depends. AFAIK the web application has to behave well. Therefore it does not make sense to deploy Medusa if your application has to wait for long-lasting blocking I/O operations (like slow database connection with only synchronous API calls). And AFAIK using traditional CGI-BIN programs also needs forking under Medusa. You're lost on Win98... Or did I get something wrong? Ciao, Michael. From lac at cd.chalmers.se Thu May 10 10:25:13 2001 From: lac at cd.chalmers.se (Laura Creighton) Date: Thu, 10 May 2001 16:25:13 +0200 (MET DST) Subject: Why aren't we all speaking LISP now? (Andy Todd) Message-ID: <200105101425.QAA06528@boris.cd.chalmers.se> Andy Todd quotes me and then writes: >However, The discussion is an interesting one but has one *major* >presumption; that the study of computer science is the study of >programming. Ah, you need to read what I wrote again. I said that at the University of Toronto people who studied computer science got computer science, not programming, and it was a bad fit because they didn't want to study computer science, they wanted to study programming. You also need to buy a good atlas an consult with it before asking me questions about the difference between and education in the United States and in the United Kingdom, because Toronto is in Canada. Laura From MarkH at ActiveState.com Mon May 14 03:09:09 2001 From: MarkH at ActiveState.com (Mark Hammond) Date: Mon, 14 May 2001 07:09:09 GMT Subject: DoEvents equiv? References: <3AFB253A.2060403@ActiveState.com> <3AFF74E1.458C5F8F@accessone.com> Message-ID: <3AFF8504.4030603@ActiveState.com> Helen Dawson wrote: > I wonder if PythonWin should spawn a separate process or thread for the > program it is debugging, instead of for the 'Break into running code' option? It should. It is unlikely to happen though. Komodo does exactly this, and seems to work fine for basically any type of Python program. [and if you could see the hoops Komodo jumps through to do this, it would be alot clearer why Pythonwin doesn't have that capability.] Mark. From orcmid at email.com Thu May 17 03:28:47 2001 From: orcmid at email.com (Dennis E. Hamilton) Date: Thu, 17 May 2001 00:28:47 -0700 Subject: floor() function and mathematical integers In-Reply-To: Message-ID: OK, we are standing in two different worlds here. I am completely clear on the implementation of floating-point arithmetic. But floor is not defined, for me, as an implementation, it is defined as a mathematical function. The Standard C Library defines an implementation. The definition I am looking at is "The floor function returns the largest integral value not greater than x, expressed as a double." (section 7.5.6.3, Returns) This is a completely clear statement about the implementation of floor() in the Standard C Library. (Harbison and Steele add to this and say the result is an exact mathematical integer. I like that idea, of course, but their statement isn't satisfied by 7.5.6.3 for me.) If I had my druthers, I would have there be a domain-error exception for floor(x) when x is outside the range for which consecutive integers are exactly representable. That is, I wouldn't deliver results outside the domain where the mathematical definition of floor() can't be rigorously honored. Having this specified in the definition of the library would also provide an important heads up that floor() is consistently implementable only over a restricted domain of doubles, and that the implementation enforces the restriction as a safeguard. My concern is with the promise that we make in specifying the library. Although the definition for the Standard C Library is accurate and precise (though quite subtle), I am not sure that it serves users of Python. Here's how far apart our perspectives are on this: >> In particular, the Peano axioms fail with respect to arithmetic on >> the ones that are too-much greater than 1. >Only matters if you're adding 1. It is the whole point of something being an integer that you can always add 1 and get the next greater integer. When we aren't delivering on that, I think it is very important to make it clear to people. Raising a domain error is an effective way to do that. It is also consistent with Python's producing an OverflowError for integer-range problems when other languages, like C, require that users deal with the consequences of the implementation. I don't think the design requirements for Python are the same as those that applied when C Language was first defined. By the way, I am not proposing any changes to Python. I am not concerned about that. I am concerned about the low level of things in Python and other languages, including Java and C# and the impact that has on users, ones led to believe that they are dealing with something higher-level and ones who will likely never consult the Standard C Library definition to get the scoop. These subtleties tend to be below the noise level around programming languages and that allows for lots of misunderstandings and wasted hours debugging. I am looking for the lesson in this. I was always pleased that C Language used "int" and "float" and "double," rather than "integer" and "real" as was done in Algol and Pascal. It could be viewed as a tip-off that these are types for implementations, and that they are limited in various ways. I don't know whether that was the intention. I admired the result. I was wondering whether I could be satisfied by a version of floor() that delivered a Python long integer. It would certainly satisfy the requirement of delivering an integer value. Nope. The domain restriction still seems important, especially since the typical use of floor is on a calculated intermediate result. I think the rub for me is that floor() is a number-theoretic function, in contrast with sqrt() or cos() where approximations are understood differently (and cos(2.0**500) is still problematic). Thanks for this conversation. It clarifies some things for me. I think when I want to offer implementations of mathematical objects, I will stick to the pure stuff (bignums and rationals), and when offering popular implementations (i.e., IEEE floats and 32-bit ints), I will keep them distinct. I can see the desirability of both. I don't think one approach alone will serve the needs of all users. And users deserve to know more clearly when they are relying on arithmetic schemes in which a large number of compromises have been made and there are boundary cases to be careful about. I don't think that we do a very good job of letting people know when things are not as simple as we encourage them to believe through our omissions. -- Dennis -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org]On Behalf Of Tim Peters Sent: Wednesday, May 16, 2001 18:41 To: Python-list Subject: RE: floor() function and mathematical integers [Dennis E. Hamilton] [ ... ] > > Here's my hypothesis: For the most part, we attribute integer-ness to > the numerals themselves, rather than to the *structure* consisting of > the objects and the operations over them. There's no confusion about floating-point that can't be cured by study. The repeated confusions I've seen over the decades amount to no more than that: people making bad assumptions about, and bringing fantasy expectations to, a system they've never bothered to learn. "Being around" floating-point for 1000 years won't make up for the lack of a deliberate effort to learn. Sorry. I am talking about integers here, not floating-point. But I guess the bigger question is about who computers and languages like Python are for. My father built his own cars and was raised in an era when people made and repaired their own bicycles, motorcycles, and small airplanes. I don't even change my own oil. I could. I don't. I can't remember how long it has been since I had to repair a flat. I never learned to drive with a standard transmission. I have no problem getting into the bits and bytes, obviously. I grew up with them, the same way my dad grew up in the age of the automobile. I am concerned that we appeal to people's naive understanding in our language and use of concepts and, when dissonance arises, we tell them to RTFM (or in this case, master IEEE 754). Maybe that is the way it will have to be. I just wonder if there isn't a smoother way. [ ... ] > I am not arguing, here, whether floor(x) as a real function is ill- > defined, though I think there is a case for that when x is a whole > number but not "an integer." I don't know what that means, unless you want floating-point operations to raise exceptions whenever they have an input x such that x+1==x -- in which case it's unrealistic. If you want integers and only integers, don't use fp. Well, unfortunately for floor(), the whole idea is to move from non-integers to integers. I must confess that in places where I care about it, as in j = (L + R)/2, or c = (N + b - 1)/b, the definition of "/" on positive-integer operands helps me out. I am not expanding my concern to floating-point operations that don't pretend to be number-theoretic. > I do claim that these over-sized floats are *not* integers in the > sense that they do not honor the standard laws of arithmetic for > integers in the available floating-point arithmetic system. floor() does the best job it can given what it knows, which is its input. If I compute 2.0**500 in 754 arithmetic, I in fact get the exact answer, and floor() of that has no business presuming "oh no, that's 'too big' to be an exact answer -- so I'll help Tim by complaining instead". If you're afraid of inexact results, don't use fp at all, or use it with the inexact trap enabled. I don't buy this example. If you knew that is what you were doing, you wouldn't need floor. If you didn't know that was what you were doing, the outcome is an accident. [ ... ] > Am I making myself understood? I am not looking for agreement, > just whether or not my perspective is understandable. Remains unclear to me: can you define precisely what it is you think floor() should do? Feel free to assume 754 arithmetic. BTW, note that Python isn't making up its own meaning for floor(); math.floor() inherits the function of the same name from the platform C library, and the C std mandates its behavior. When explaining why it returns "large" floats unchanged, I was explaining why the C committee chose to do that. Indeed, I don't know of any language that defines floor() in any other way. OK, I think I have addressed that. I am not sure why the C committee chose to do what they did. It is clear what the definition is, and it seems carefully crafted. I do not dispute that this is a fine approach for C Language. My concern is higher level than that. It seems I have failed to make that understood. fighting-the-universe-is-a-low-success-hobby-ly y'rs - tim -- http://mail.python.org/mailman/listinfo/python-list From hungjunglu at yahoo.com Wed May 16 17:21:42 2001 From: hungjunglu at yahoo.com (hungjunglu at yahoo.com) Date: Wed, 16 May 2001 21:21:42 -0000 Subject: How to distribute Python COM applications? Message-ID: <9dur16+t79r@eGroups.com> I have asked Mark Hammond, but no clear answers, yet. (He told me to look into regsvr32.) I am also starting to look at all installation aspects of Python COM. (registry items, DLLs, etc.) If I succeed, I'll let people know. So far I have succeeded in distributing Python COM client applications. It's the Python COM server part that is complicated. I know py2exe or Gordon installer are not enough, but besides that, more registry tweaking and DLL handling are needed. But meanwhile, if anyone already has experience in packaging and distributing Python COM applications (that is, without the end-user having to install ActiveState's Python or the win32all package explicitly), it'll be great to have a few more pointer to make this process easier. Any help is appreciated. regards, Hung Jung From aleaxit at yahoo.com Mon May 21 17:11:21 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 21 May 2001 23:11:21 +0200 Subject: Dependency Inversion Principle -- Python Way References: Message-ID: <9ec0b10iam@enews2.newsguy.com> "Sasa Zivkov" wrote in message news:mailman.990465422.19951.python-list at python.org... > Hi, > > I have read some discussions on this mailing list about DIP (dependency > inversion principle) and theoretically everything is clear to me. > > So if we have two classes A and B such that A->B (a depends on B) > and B->A then we have cyclic dependency. Yes. But take care that what defines "a dependency" is not language-independent. In Python (and any other signature-based-polymorphism setup, such as C++ templates!), "uses" does not necessarily create a dependency. If all the "using" code asks of the "used" one is that the latter provide methods x, y, z, ..., with certain sigs, then the dependency of the "using" code is on the method names and signatures, _intrinsically_. > One way to break this cycle is to use DIP. In pure sig-based pm, as I hope I just showed, the "inversion of dependency" turns out to be *intrinsic*. Which is part of the power of signature-based polymorphism, whether it be in the friendly guise of Python or the less-friendly one of C++ templates. > According to DIP we define an abstract interface C such that: > B uses C > A implements C > > and we finish with acyclic dependencies: A->B, B->C, A->C. > > > Now, I want to ask you about implementation. > > 1. Would you really declare class ("interface") C in python ? Not in Python as it stands today. > 2. Because python has only implicit interfaces is not is enough just to > implement C interface in A ? There is no "C interface" as a unity, or entity. Just sets of methods with signatures. Which isn't to say it could be even better to HAVE a way to express, objectify, 'C'. Though I would not narrowly call it an 'interface' but a 'protocol', and a more general concept than 'implements' is 'is-adaptable-to'. See PEP 246, at URL http://python.sourceforge.net/peps/pep-0246.html, for a dream-way it could be handled...!-) > 3. Finally if I decide not to really make C class but only > to implement this interface in A I will finish with almost the same > situation as at the beggining: two classes A and B where A->B and B->(C > part of A) > I am a little confused at this point :-) ... it seems like I did really > nothing. In a way, because, in sig-based polymorphism, there WAS no need to do anything special:-). But, if you defined a protocol, even if the language itself does not let you express this crucial design-idea, you would in fact have made a step forward. Instead of designing in terms of concrete classes, i.e., implementation, you'd have designed in term of the protocol, its user, and its supplier. It WOULD be even better if this key design idea could be expressed directly and explicitly in the language... Alex From lco at gofuse.com Mon May 14 19:28:17 2001 From: lco at gofuse.com (LC) Date: Mon, 14 May 2001 16:28:17 -0700 Subject: zip archive Message-ID: <9dpphe$b0g$1@nntp1-cm.news.eni.net> Can someone tell me how I can zip a .log file using a python script. Thanks LC From pbleyer at embedded.cl Tue May 29 18:53:36 2001 From: pbleyer at embedded.cl (Pablo Bleyer Kocik) Date: 29 May 2001 15:53:36 -0700 Subject: [ANN] xio, the cross platform serial IO python module References: Message-ID: grante at visi.com (Grant Edwards) wrote in message news:... > In article , Pablo Bleyer Kocik wrote: > > >Currently, the module implements port creation, opening, > >closing, configuration, reading, writing & status peeking. It > >has been tested under Linux-x86 and Win-9X. It contains a na?ve > >implementation of flow control (and pretty untested -- so > >beware!). > > An actual implimentation of flow control or an implimentation > of a wrapper around the flow control provided by the > OS-resident serial drivers? The current implementation is a wrapper to the native serial API, how I think it should be (mostly). I have code to emulate protocol signals with termios, but the code is messy -termios _is_ messy- and not completely portable -I suspect. This is one of the things I am working out, trying to device some *generic*, non-intrusive method to handle serial control signals. There's a lot of serial equipment we interface to, so I hope I can continue testing the module in many platforms. Cheers! From qrczak at knm.org.pl Sat May 26 15:39:29 2001 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: 26 May 2001 19:39:29 GMT Subject: Flatten... or How to determine sequenceability? References: Message-ID: Fri, 25 May 2001 10:44:57 -0400, Noel Rappin pisze: > As part of the algorithm, I need to determine whether each object in > the list is itself a sequence or whether it is an atom. Using the > types module would cause me to miss any sequence-like object that > isn't actually the basic type. So, what's the best (easiest, most > foolproof) way to determine whether a Python object is a sequence? There is no universal and formal distinction between sequences and atoms. For example strings may be considered either. IMHO data should not be encoded as a mix of unknown types of atoms and unknown types of sequences in the first place if it's necessary to distinguish atoms from sequences, but as something with more explicitly defined structure. -- __("< Marcin Kowalczyk * qrczak at knm.org.pl http://qrczak.ids.net.pl/ \__/ ^^ SYGNATURA ZAST?PCZA QRCZAK From sdm7g at Virginia.EDU Mon May 14 13:38:09 2001 From: sdm7g at Virginia.EDU (Steven D. Majewski) Date: Mon, 14 May 2001 13:38:09 -0400 (EDT) Subject: What can you do in LISP that you can't do in Python In-Reply-To: <9dov6001dr9@news2.newsguy.com> Message-ID: I was about to bring up Turing Completeness, but Alex beat me to it! But for an example to consider: Pretend for a moment that you had a problem where you absolutely required something like Lisp macros. In python, you could always the the equivalent behaviour with a python function that outputs a new python module that could be imported. Programs that write programs isn't a feature that only Lisp can do. However, because of Lisp's trivial syntax, as well as functions designed for reading lisp expressions, processing Lisp code is trivially easy. Lisp macros are written in a sort of substitution template. Doing the same thing in Python requires a Python parser. Of course, you just happed to have access to the one built into Python from the parser module. ( "import parser" ) However, other than occasionally eval-ing small expressions, I think most Python programmers would, rather than write some sort of textual code processing, would use the reflective features of the language manipulate classes, functions, code-objects, et.al. at a different level. I haven't followed Dylan for a while (Dylan is a language that's sort of like an Object-oriented Scheme in it's semantics, but with a more "algolish" syntax ) but, long ago, there was discussion of a macro system for Dylan, which was planned to be a non-textual transformation of deeper structures from the parse tree. If you were going to do macros for Python, that would be the way to do it -- however, I wonder if that style of macro would ever feel as natural as Lisp's. I suspect that Python programmers would STILL try to find another way to do it. There's a lot more to a computer language that a list of features! -- Steve Majewski From guido at digicool.com Wed May 23 14:02:06 2001 From: guido at digicool.com (Guido van Rossum) Date: Wed, 23 May 2001 14:02:06 -0400 Subject: [Python-Dev] New metaclass pattern (Was Re: Simulating Class (was Re: Does Python have Class methods)) In-Reply-To: Your message of "Wed, 23 May 2001 19:28:07 +0200." <020301c0e3ad$bb559790$e000a8c0@thomasnotebook> References: <020301c0e3ad$bb559790$e000a8c0@thomasnotebook> Message-ID: <200105231802.f4NI26408784@odiug.digicool.com> > [this message has also been posted to comp.lang.python] [And I'm cc'ing there] > Guido's metaclass hook in Python goes this way: > > If a base class (let's better call it a 'base object') > has a __class__ attribute, this is called to create the > new class. > > >From demo/metaclasses/index.html: > > class C(B): > a = 1 > b = 2 > > Assuming B has a __class__ attribute, this translates into: > > C = B.__class__('C', (B,), {'a': 1, 'b': 2}) Yes. > Usually B is an instance of a normal class. No, B should behave like a class, which makes it an instance of a metaclass. > So the above code will create an instance of B, > call B's __init__ method with 'C', (B,), and {'a': 1, 'b': 2}, > and assign the instance of B to the variable C. No, it will not create an instance of B. It will create an instance of B.__class__, which is a subclass of B. The difference between subclassing and instantiation is confusing, but crucial, when talking about metaclasses! See the ASCII art in my classic post to the types-sig: http://mail.python.org/pipermail/types-sig/1998-November/000084.html > I've ever since played with this metaclass hook, and > always found the problem that B would have to completely > simulate the normal python behaviour for classes (modifying > of course what you want to change). > > The problem is that there are a lot of successful and > unsucessful attribute lookups, which require a lot > of overhead when implemented in Python: So the result > is very slow (too slow to be usable in some cases). Yes. You should be able to subclass an existing metaclass! Fortunately, in the descr-branch code in CVS, this is possible. I haven't explored it much yet, but it should be possible to do things like: Integer = type(0) Class = Integer.__class__ # same as type(Integer) class MyClass(Class): ... MyObject = MyClass("MyObject", (), {}) myInstance = MyObject() Here MyClass declares a metaclass, and MyObject is a regular class that uses MyClass for its metaclass. Then, myInstance is an instance of MyObject. See the end of PEP 252 for info on getting the descr-branch code (http://python.sourceforge.net/peps/pep-0252.html). > ------ > > Python 2.1 allows to attach attributes to function objects, > so a new metaclass pattern can be implemented. > > The idea is to let B be a function having a __class__ attribute > (which does _not_ have to be a class, it can again be a function). Oh, yuck. I suppose this is fine if you want to experiment with metaclasses in 2.1, but please consider using the descr-branch code instead so you can see what 2.2 will be like! --Guido van Rossum (home page: http://www.python.org/~guido/) From aleaxit at yahoo.com Thu May 3 05:24:13 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 3 May 2001 11:24:13 +0200 Subject: Named code blockes References: <9c65pv01hhr@news2.newsguy.com> <9c9dco327ud@news2.newsguy.com> Message-ID: <9cr83v01880@news2.newsguy.com> "Douglas Alan" wrote in message news:lck83z55x6.fsf at gaffa.mit.edu... > "Alex Martelli" writes: > > > > By doing so, you lower the barier to allowing people to accomplish > > > what they want to accomplish. Isn't that what a high-level language > > > is all about? [snip] > Language extensions should be reserved only for those things that > cannot be elegantly or efficiently done in a library. I don't think > that anyone is saying differently. Why do you imply that I have said > otherwise? Because of that little word "all" in the above-quoted snippet. > Having one language that can do *everything* well is just one of those > unreachable ideals -- i.e., the type of ideal that you say you are > fond of. Unattainable yes, but it should act as a guiding principle. Some unattainable-goals work well as guiding-principles, other don't. I opine that "one language able to do everything well", which has been used VERY often in the past as "guiding principle" for language design, tends to NOT work well, because it tends to breed languages that are too big and complicated. > > This in no way impacts my assertion, of course. Python IS as great > > as it is in part *because* it never strove to be "the best language > > for EVERY purpose". "General-purpose" does not imply "best for > > every goal"... > > The holy grail should not be "best for every purpose" because that is > clearly a logical impossibility. "Well-suited for most purposes" > should be the unattainable goal. I disagree that it's unattainable, because I consider Python, as it stands today, to BE well-suited for most (programming) purposes. > If you aim low, you are almost sure to hit low. And if you aim for something requiring great complexity, you are almost sure to reach great complexity. "Perfection is reached, not when there is no longer anything to add, but when there is no longer anything to take away" (Antoine de Saint-Exupery)... If you want an unreachable-ideal worth aiming for, this particular mix of poetry and engineering (few in the 20th century have worked in both fields as much as Saint-Exupery -- he's mostly remembered as a poet and a novelist, but, as a pilot and manager/organizer of early airplanes, his daily life was more enmeshed with machines) might prove quite suitable -- conjoined, of course, with the little issue that a language (or machine) meant for human use must find ways and means to coexist with human complexity. ("Euclid alone has looked on Beauty bare", after all, and we can hardly rely on "O blinding hour, O holy, terrible day" effects in a language meant for frequent use by lots of people...:-). > In any case, nothing you can say will stop me from musing, both > publically and privately on how Python might be a better language. > I'm in the process of designing a variant of Python, so it is my duty > to do so. Best of luck in this endeavour! Python _variants_, such as Vyper (http://vyper.sourceforge.net/), may at worst leave Python "none the better, none the worse", even in the pessimistic hypothesis that nothing can be learned by studying the variant -- surely it is more realistic to hope that there WILL be interesting lessons to glean from the study of any variant of Python, be they from its successes, or from its failures. Alex From jepler at inetnebr.com Sat May 19 19:44:24 2001 From: jepler at inetnebr.com (Jeff Epler) Date: Sat, 19 May 2001 23:44:24 GMT Subject: Tkinter - how to right align Help Menu cascade?? References: <3B06276A.688FF5C4@engineer.com> <9e6a9f$eb5$m@216.39.170.247> Message-ID: > In article <3B06276A.688FF5C4 at engineer.com>, doug.hilton at engineer.com > says... >> This is a trivial thing, but I wan't my Help cascade right-aligned and >> cannot locate any options in the Tkinter docs. In tk 8.0 and later, if you use toplevel.configure(menu = XXX) to create a menu, that menu is treated in a system-dependent way. On Unix, this includes placing the menu with the title "help" on the right. AFAIR, this does *not* happen on Windows. It depends on the "system standard" is, and how the tk folks interpreted it. Otherwise, *don't* use -menu, but make a frame with menubuttons in it, and pack them using the "pack" method. Jeff From emile at fenx.com Wed May 16 14:59:41 2001 From: emile at fenx.com (Emile van Sebille) Date: Wed, 16 May 2001 11:59:41 -0700 Subject: Add a method to an existing class References: <20010516.100608.1372261796.19522@mead.troikanetworks.com> <9duhb2$q8b$1@news.unitel.co.kr> Message-ID: <9duitg$5isk$1@ID-11957.news.dfncis.de> If I understand correctly, this creates an instance method. >>> class myclass: val = 5 >>> inst = myclass() >>> def showval(self): return str(self.val) >>> inst.__repr__ = new.instancemethod(showval, inst, myclass) >>> inst 5 -- Emile van Sebille emile at fenx.com --------- "Pete Shinners" wrote in message news:9duhb2$q8b$1 at news.unitel.co.kr... > "Bruce Edge" wrote > > I have some idl generated classes. I'd like to add a __repr__ method to > > control default output representation. > > So, my question is, how does one add a method to an existing class when > > you don't have control of the class definition. > > hello bruce, this likely isn't the cleanest way to do this, but > it's the best i've been able to come up with. you can define a > new function (that takes self for the first argument) and assign > that method to the class of your instance. > > >>> class myclass: > ... val = 5 > ... > >>> inst = myclass() > >>> print inst > <__main__.myclass instance at 007F442C> > >>> def showval(self): return str(self.val) > ... > >>> myclass.__repr__ = showval > >>> print inst > 5 > > note that this will change the "repr" for all instances of the > class, but that should be fine for a __repr__ type of function. > > sadly, trying to assign the function to be a method of the instance > doesn't work. the function doesn't really become a "method" it > just remains a function, and it does get the "self" argument > filled when called. i would really like to know if there is a > clean way to actually make that function a full method? > > From jkraska1 at san.rr.com Wed May 16 01:57:47 2001 From: jkraska1 at san.rr.com (Courageous) Date: Wed, 16 May 2001 05:57:47 GMT Subject: Is this the correct way to emulate C++ function overloading? References: Message-ID: >Is this the correct way of doing this? No, not really. As another poster pointed out, you can determine the type of arguments at runtime with the right function calls. >on it's type/class, right? But what when you don't need to create >objects or want to do it with built-in types? Is there another way? Yep. Python is a _dynamic_ language. C// From kens at sightreader.com Tue May 1 18:22:30 2001 From: kens at sightreader.com (Ken Seehof) Date: Tue, 1 May 2001 15:22:30 -0700 Subject: Tabs and spaces (style) References: <9cn2e10j8h@news1.newsguy.com> Message-ID: <002f01c0d28d$379aafc0$04090a0a@upcast.com> Most people seem to be using spaces only, with indentation of 4. This is popular for those of us with a real code editor. "All tabs" is the next most popular, especially for people writing python on a Kaypro. :-) Hey Guido, please change your style guide ok? Mixing tabs and spaces is lame, and fortunately nobody does it anyway :-) Here's some data: spc tab gvr nmix 102 32 0 8 c:\python20\lib 1 15 0 0 ...\Pythonwin\pywin\framework 2 8 0 0 ...\Pythonwin\pywin\scintilla 31 0 0 0 C:\Python20\wxPython 2 7 0 0 C:\Python20\win32\demos 1 5 0 6 C:\Python20\win32com\client 23 0 0 0 C:\Python20\_xmlplus\dom 2 17 0 0 D:\qp\WebQ\QServer\medusa 5 0 0 0 C:\Python20\Orchard-python-0.3.1\Orchard 8 1 1* 2 C:\Python20\OpenGL\Demo\srenner 8 3 0 2 C:\Python20\OpenGL\Demo\tom 44 1 0 1 C:\Python20\Tools\idle spc = uses spaces only (usually 4 spaces) tab = uses tabs only gvr = uses Guidos suggested tab8+space4 combo nmix = mixes tabs and spaces sloppily (at least 3 lines of each) (* actually, on inspection, trees.py is a sloppy mix of spaces and tabs, not gvr style.) ---------------------------------------------------- Copyright (c) 2001 by Ken Seehof This document may not be distributed, copied, duplicated, or replicated, or duplicated in any form without express permission by Ken Seehof. Permission is hereby granted. kseehof at neuralintegrator.com ---------------------------------------------------- The opinions expressed herein are not necessarily those of George W. Bush. Alex Martelli says: > "Cantanker" wrote in message > news:Y4AH6.28530$ff.208353 at news-server.bigpond.net.au... > > What is the consensus about mixing tabs and spaces in a Python script? > > I don't think there is one. Guido's style guide recommends using both, > with a tabsize of 8, so I expect most Pythonistas follow that style. Fortunately most Pythonistas do not follow that style. :-) > Yet, for what it counts, I personally prefer setting my editors to always > save with spaces only (so _all_ tools will certainly see my source in just > the same way:-) and curse every time somebody posts code using tabs > (which some newsreading software hides completely from me)... Yay. Most Pythonistas follow your style. > Guido suggests that conversion to all-spaces (useful when a Windows > platform is involved) can be done upon transfer of the source to that > platform. But that doesn't cover all cases in which transformation tools > may not, or definitely WILL not, be involved, such as disks being shared > via Samba or NFS between heterogeneous platforms, sources that are > zipped or tgz'd and the zipfile or tarball put up for download, etc. It > seems to me that spaces-only is the only really cross-platform approach. > > Alex -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: tabcheck.py URL: From kdart at leviathan.kdart.com Mon May 14 01:33:06 2001 From: kdart at leviathan.kdart.com (Keith Dart) Date: Sun, 13 May 2001 22:33:06 -0700 Subject: Bug in Python large negative literal assignment? Message-ID: I seem to have found a bug in how Python assigns the largest negative literal: Python 2.1 (#1, Apr 23 2001, 15:49:36) [GCC 2.95.1 19990816/Linux (release)] on linux2 Type "copyright", "credits" or "license" for more information. Sourcing .pythonrc... Python> # I cannot assign the following: .more.. i = -2147483648 OverflowError: integer literal too large Python> # however, I can do it the following ways: .more.. i = -sys.maxint-1 Python> i -2147483648 Python> i = 0x80000000 Python> i -2147483648 Python> i = -2147483647 ; i = i - 1 Python> i -2147483648 Python> i = -2147483647-1 Python> i -2147483648 Python> i = -2147483648 OverflowError: integer literal too large But, no, can't assign a max negative number as decimal literal. \\|// (O O) -- --------------------oOOo~(_)~oOOo---------------------------------------- Keith Dart ---------------------------------------------------------------------------- Ever since my brain transplant I ... ============================================================================ From sholden at holdenweb.com Tue May 8 03:11:52 2001 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 8 May 2001 03:11:52 -0400 Subject: socket.recvfrom() & sendto() References: <9d67he$1pc$1@saltmine.radix.net> <8zBJ6.38583$2U.15727108@news2.rdc2.tx.home.com> <3AF71603.6275F09C@teuto.de> Message-ID: <#Ue#e541AHA.302@cpmsnbbsa09> "Ron Johnson" wrote in ... > Ulrich Berning wrote: > [Ulrich's suggestion] > This is exactly what I want! I might, though, try threading, > since global data must be kept: depending on what client1 does, > data is sent to client2..clientN. > > This is looking more and more like a chat program, where clients > and server are chatting back and forth, instead of clients chatting. > > Still, I have to think how the client can wait for a possible message > from the server while simultaneously letting the client do "stuff" > like send messages to the server. Threading at the client, too? > One thread waiting for chat from the server, while the other waits > for user input to send to the server? > > Something seems too complicated here... > Ron, you really should take a look at Medusa, Sam Rushing's asyncore-based technology. For your requirements it seems almost ideally-suited, and it's not *too* badly documented for a Python project ;-) regards Steve From ljohnson at resgen.com Wed May 23 13:21:07 2001 From: ljohnson at resgen.com (Lyle Johnson) Date: Wed, 23 May 2001 12:21:07 -0500 Subject: Extending python References: Message-ID: > Are there any docs which provide examples on how to extend python with > C/C++ other than the one at www.python.org?? I don't seem to understand how > to use PyObject *. If I pass a list or tuple to my C function, and in my > function I extract the list or tuple using "O" as a format specifier in a > call to PyArg_ParseTuple, how do I actually get the integers or strings from > the PyObject??? What I'm trying to do is pass a variable number of data to > my C function through an array. So is it proper to pass a list/tuple to my > C wrapper function and extract the elements into a dynamic array, which I > then pass to my C function? Please advise... If you have a pointer to a PyObject, and you know that the object is a "sequence" of some kind (including Python lists and tuples), you can extract the objects in that sequence using PySequence_GetItem(), e.g. PyObject* sequenceObj; PyObject* sequenceItem; int i, size; if (!PySequence_Check(sequenceObj)) { fprintf(stderr, "You filthy liar! This isn't a sequence!\n"); return; } size = PySequence_Size(sequenceObj); if (size == -1) { /* An error occurred... */ return; } for (i = 0; i < size; i++) { sequenceItem = PySequence_GetItem(sequenceObj, i); if (sequenceItem == NULL) { /* an error occurred */ return; } else { /* do something with this sequence element */ } } There are also APIs to deal directly with Python list and tuple objects (PyList_Size, PyList_GetItem, PyTuple_Size and PyTuple_GetItem) but you provide yourself with a lot more flexibility by using the abstract "sequence" APIs. Hope this helps, Lyle From news at dorb.com Wed May 30 21:19:33 2001 From: news at dorb.com (Darrell) Date: Thu, 31 May 2001 01:19:33 GMT Subject: idioms for abstract base classes References: Message-ID: You are exactly correct. Coming from C++, I was over engineering everything in sight. Then the Pythonic way was laid out before me by the brotherhood of comp.lang.python. The combination of Extreme and Python has been very rewarding. --Darrell zooko at zooko.com wrote: > > Python has dynamic structural typing, which gives rise to rapid prototyping, > flexible code re-use, and minimal hindrance to the programmer, as well as to > clear designs and readable code. USE the dynamic structural typing, and do not > attempt to regress to C++/Java style static/dynamic named types, like I did. > From loewis at informatik.hu-berlin.de Thu May 31 13:23:28 2001 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 31 May 2001 19:23:28 +0200 Subject: XML How-To References: <88630c8d.0105301259.55d724ab@posting.google.com> Message-ID: vdanovich at empireone.net (Vyacheslav Danovich) writes: > When using xml.sax module and the following file is given: > > > > Neil Gaiman > Glyn Dillon > Charles Vess > > > > and I know the title and the number of the 'comic' > How can I find out the value for ? You need to implement the startElement, endElement, and characters methods of a ContentHandler object. See the XML Howto, in particular http://py-howto.sourceforge.net/xml-howto/node9.html for details. If you have any specific questions, don't hesitate to ask. Regards, Martin From BPettersen at NAREX.com Fri May 11 16:01:29 2001 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 11 May 2001 14:01:29 -0600 Subject: ltrim on a block of text? Message-ID: <6957F6A694B49A4096F7CFD0D900042F27DB5A@admin56.narex.com> Say I have a variable s = """ void f(int x) { printf("%d\n", x); } """ and I want to transform it to a list of lines L such that '\n'.join(L) would give: """ void f(int x) { printf("%d\n", x); } """ i.e. I want to slice off the whitespace on the left of the entire block... Is there a good way to do this? My current approach seems a little fragile ;-) def ltrimBlock(block): """Trim all the whitespace on the left of a block of text.""" txt = block.split('\n') # the second line is more likely to contain the indentation # we want to remove (if it is present). if len(txt) > 2: first = txt[1] else: first = txt[0] count = 0 for c in first: if c in ' \t': count += 1 else: break return [ line[count:] for line in txt ] -- bjorn From israelrt at optushome.com.au Sat May 5 22:09:23 2001 From: israelrt at optushome.com.au (raj) Date: Sun, 06 May 2001 02:09:23 GMT Subject: Beginner's Language? References: <9cukad$nn68@news-dxb> <60c9ft0mvlkk9lvno6a67qnqomq7i621al@4ax.com> Message-ID: Education is different from vocational training. Vocational training is for plumbers and those who have to start-work-right-now. Education is about understanding the fundamentals and the theory that underlies the subject / the system / the "all". Education is meant for those capable of understanding the fundamentals and the theory that underlies the subject / the system / the "all". In this context, I stand by my previous statements: Lisp, Scheme, subsetted Ada, Smalltalk , Ruby , Python (and if approached judiciously, even Java and C++) can be used usefully as a language of discourse. Perl while admirable as a tool for sys admins and wannabe-hackers [ do you want your child to just become a sys-admin ? :-) ] is a linguistic mishmash that tries to be all things to all programmers and ends up becoming ( again to quote Larry Wall ) a "Pathologically Eclectic Rubbish Lister". If you really want to teach children to use a multiparadigm language, try Oz / Mozart. It is has functional, object oriented, logic and constraint based, features and has concurrency built in. Confusing ? Yes ! But unlike Perl, Mozart was DESIGNED and did not grow by a process of uglification / accretion. Accretion is not necessarily bad. Just look at Lisp with it brilliant metaobject protocol, multiple dispatch and CLOS. But to contemplate teaching Perl or Basic to children......... Phaugh ! From gerhard.nospam at bigfoot.de Thu May 31 20:50:10 2001 From: gerhard.nospam at bigfoot.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Fri, 1 Jun 2001 02:50:10 +0200 Subject: strange cgi print problem References: Message-ID: On Thu, 31 May 2001 18:41:30 -0700, Jeroen Wolff wrote: >I've got a strange cgi print problem. >When i run this script as user "nobody" >on the console is works fine and generate >nice output. >When i launch it from my webbrowser, i shows >only the output of HTMLHead() when i view the source. >The print RIPEWhois("AS12394") output is only a space... > >Please can somebody help... > >Thx, > >Jeroen > > > >#!/usr/local/bin/python > >import string, os > > >def HTMLHead(): > print "Content-type: text/html" > print > print "" > print "" > > >def RIPEWhois( ASnr ): > descr = "" > goedeAS = 0 > fp = os.popen("ripewhois "+ASnr+" -r") > for regel in fp.readlines(): > columns = regel[:-1].split(":") > if len(columns) > 1: > if columns[0].strip() == "aut-num" \ > and columns[1].strip() == ASnr: > goedeAS = 1 > if columns[0].strip() == "descr" and goedeAS: > descr = columns[1].strip() > break > fp.close() > return descr > > >HTMLHead() >print RIPEWhois("AS12394") > >print "" I don't know if this will help, but I'd try: - Using #!/usr/local/bin/python -u - and providing the full path to ripewhois Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://highqualdev.com public key at homepage public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From fredrik at pythonware.com Tue May 1 05:20:15 2001 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 01 May 2001 09:20:15 GMT Subject: Nested scope warning in PIL References: <3AEE2101.377BBA1@erols.com> Message-ID: Edward C. Jones wrote: > I installed RedHat 7.1 on a PC, Python 2.1, and then PIL. I get the following > nested scope warning: it's a real bug, spotted by 2.1's new compiler. a patch can be found here: http://mail.python.org/pipermail/image-sig/2001-April/001427.html Cheers /F From kosh at aesaeion.com Sun May 13 18:38:45 2001 From: kosh at aesaeion.com (kosh) Date: Sun, 13 May 2001 16:38:45 -0600 Subject: Zope and Python 2.1 References: <9dmvg7$8hi$1@tyfon.itea.ntnu.no> Message-ID: <9dn2mr$44$1@apollo.csd.net> please post to the zope at zope.org list for the best change of getting help with zope. Right now DC is updating zope for 2.1 but that is incurring many changes in it. Version 2.4 of zope will require python 2.1 and it is coming along pretty fast. If you look on zope.org the current zope news tells about the status of 2.4. Magnus Lie Hetland wrote: > > I just wondered... Has anyone been able to use Zope > and Python 2.1 together out of the box? (Including > possibly compiling them both out of the box, > without any arcane editing of setup files etc.) > > I get Python to work fine, but Zope seems to insist > on looking for a Makefile.pre.in which isn't there... > And the binary version has too old a version > on the C API so I get a ton of warnings... > > It seems that Zope doesn't even support Python 2.0 > "officially" yet; the installation instructions > state that you should have Python 1.5.2. I hoped > that meant "1.5.2 or newer"... But anyway, I would > have thought that a basic running distribution > should be possible? > > (The binary version seems to _work_ with 2.1... > But all the warnings make me a bit worried ;) > > My objective is to make a simple procedure for > installing python 2.1 and ZODB so that > newbies (or almost-newbies) can follow it. > > Any insights? Am I missing something obvious? > Should I just forget about the warnings? > > All help greatly appreciated. > > -- > > Magnus Lie Hetland http://www.hetland.org > > "Reality is that which, when you stop believing in > it, doesn't go away." -- Philip K. Dick > > > > From putsch at fiber.mxim.com Tue May 29 20:07:07 2001 From: putsch at fiber.mxim.com (Jeff Putsch) Date: Tue, 29 May 2001 17:07:07 -0700 Subject: Against PEP 240 In-Reply-To: ; from robin@jessikat.fsnet.co.uk on Wed, May 30, 2001 at 12:31:29AM +0100 References: Message-ID: <20010529170707.J19862@blue.mxim.com> On Wed, May 30, 2001 at 12:31:29AM +0100, Robin Becker wrote: > I prefer float literals as the default, but I fear this argument is > going against me. If that is the case I would prefer that a simple Having read most of this discussusion, I must agree with Robin. I too prefer float literals as the default. I feel, possibly incorrectly, and possibly risking offense to some that there are two primary reasons for this change: 1 Python lacks a rational literal. I understand that in some problem spaces this lack is critical and needs to be addressed. 2 There seems to be a feeling that life should be made easy for "uninformed" programmers. As for reason 1, I don't quite see why the current default behavior need be modified to add rational literals to the language. It seems to me the new feature should have the new syntax. With regard to reason 2, my feeling is that making life easy for "uninformed" programmers will simply encourage poor programming. Jeff. From to_infinity at mail.ru Thu May 24 14:17:24 2001 From: to_infinity at mail.ru (to_infinity at mail.ru) Date: Thu, 24 May 2001 18:17:24 +0000 (UTC) Subject: Serious offer. This is not ordinary offer as many in Internet. The New Way In Your Life Here!!! Message-ID: <9ejj7j$oeo$1495@relay2.kazan.ru> Hello, Dear Friend! Serious offer for You here. This is not ordinary offer as many in Internet. Would You like to improve Your life? Do You have financial difficulties?! Do You want to change Your life?! You need to come here!!! Here the New Way will open for You! Please visit http://paladin.hotmail.ru . The New Way In Your Life Here!!! You will not regret! Welcome to World Exclusive Club. This is not usual light-minded offer on Internet. Check it! From Bill.Scherer at VerizonWireless.com Thu May 17 10:19:13 2001 From: Bill.Scherer at VerizonWireless.com (Scherer, Bill) Date: Thu, 17 May 2001 10:19:13 -0400 (EDT) Subject: Simple yet powerful template library In-Reply-To: Message-ID: On Thu, 17 May 2001, Michele Beltrame wrote: > Hi! > > I need a simple but powerful template library (such as what HTML::Template > is for Perl), with some good usage examples. Suggestions? I'm quite happy with DocumentTemplate from Zope. (www.zope.org) It's easy to use outside of Zope, just pur the DocuemtnTemplate folder and ExtensionClass.so in your PYTHONPATH and away you go. DocumentTemplate provides looping and conditional constructs, and a straightforward way of handling Python sequences and class instances. > > Thanks in advance, Michele. Sure. > > -- > Michele Beltrame > mb at io.com > http://www.io.com/~mick/ > ICQ# 76660101 > ==> Sito di it.comp.lang.perl: http://www.perl-it.org > ==> Sei del triveneto e vuoi unirti ai Perl Mongers? Scrivimi! > -- > http://mail.python.org/mailman/listinfo/python-list > From stepheb at comm.mot.com Fri May 4 17:19:20 2001 From: stepheb at comm.mot.com (Stephen Boulet) Date: Fri, 04 May 2001 16:19:20 -0500 Subject: Windows editor? References: Message-ID: <3AF31CD8.8A8F8FF0@comm.mot.com> Does anyone use NEdit for windows? I love it under linux, and I understand you can get it running with cigwin. -- Stephen From nessus at mit.edu Mon May 7 03:30:44 2001 From: nessus at mit.edu (Douglas Alan) Date: 07 May 2001 03:30:44 -0400 Subject: do...until wisdom needed... References: <9be84s0q12@news1.newsguy.com> <9bfjoc0cjh@news2.newsguy.com> <9bfq560noo@news2.newsguy.com> <87n19fvdzo.fsf_-_@elbereth.ccraig.org> <9biukr$lu8$1@nntp9.atl.mindspring.net> <9cqpq9$dvm$1@nntp9.atl.mindspring.net> <9d53ku$o9j$1@slb6.atl.mindspring.net> Message-ID: "Andrew Dalke" writes: > >It wouldn't be small if Python had procedural macros. Most people > >would love them -- just like most people love them in Lisp. > I guess I'm stuck at the point trying to figure out how procedural > macros could be added to Python. Is it at all possible to come up > with a hand-waving/straw example? Everything I think of seems to > end up with a function that converts a large quoted string into a > new Python module, class or function. A procedural macro could be as simple as a function that takes a string as its argument and returns a string. The string handed to the macro implementation would be the text of the macro invocation. The string returned from the function would be the text used to replace the macro invocation in the original program. To make the programmer's life much easier, there would be a library of handy parsing and unparsing tools. This isn't the only possible approach, but I think it's the way I would do it. The approach described above is not "hygienic", which a macro mechanism really should be. It would need to be made *bit* more complicated to make it so. > >Look how long it took OO > >to catch on (another invention that grew out of Lisp). Most of the > >arguments people make against procedural macros today, people used to > >make about about OO. > I was under the impression that OO programming grew out of Simula-67. It grew out of Simula-67 too. The first true OO language was Smalltalk, which grew out of Lisp and Simula-67, and was invented in the '70's. OO made it's way back into Lisp in about two hours (okay slight exaggeration, but not by much) after the invention of Smalltalk. This happened so quickly due, in part, to Lisp's extensible syntax. > >OO was invented in the '70's and it took until the '90's for it to > > catch on. > Right delta, but it was invented in '60s. As to the later date, I > remember when Borland shipped Turbo Pascal 5.5 in May 1989. Its OO > ideas were based off of ideas from Apple's Object Pascal, released > in '86. I was using Turbo C++ in summer 1991 because Borland > shipped Turbo C++ that February. So I would have dated things to > "late '80s" and not "'90's". Just because some people were using OO, doesn't mean it had "caught on" in any serious way. I was doing OO in Lisp in 1980, but finding a job doing that would have been something of a challenge. > My apologies for using a loaded word there. I meant something that > was the equivalent to "widely used languages" "other than Lisp" > (which you include as a widely used language even though it "only > really ever caught on in AI circles and for teaching programming"). > All quotes yours. Lisp *is* widely used for AI. In fact, the vast majority of AI is done in Lisp. And Scheme *is* widely used for teaching Computer Science. If you want to see how popular macros are, you need look no farther than C. I don't think many C programmers would want to give up the macro mechanism. The problem with the macro mechanism for C is that it is cumbersome, flaccid, inelegant, and error-prone. These are not fundamental limitations of macro mechanisms in general -- just C's lame instantiation. > >Dylan proves that it can be done. (It's derived from Lisp, but has a > >more traditional syntax.) Macros are typically executed at > >compile-time, not run-time, which is often necessary for efficiency > >reasons. > Could you give an example of the Dylan syntax for doing macros? > Perhaps this would help with my mental block in understanding how it > could/should be applied to Python. define macro unless { unless ?test:expression ?:body } => { if (~?test) ?body } end macro; > > In any case, Scheme (a dialect of Lisp) is usually considered > > state of the art for teaching Computer Science 101. Scheme is > > what's used at MIT, Harvard, Yale, etc. > Just to double check, I looked up what language Yale uses for > their intro. classes > CPSC 201 "Introduction to Computer Science" uses Haskell, but > http://plucky.cs.yale.edu/cs201/ says > ] (Previously in this course we used the Scheme programming language. > ] In some ways Haskell can be viewed as a strongly-typed variant of > ] Scheme.) Well, I suppose one could argue that Haskell is now state of the art for teaching Computer Science, rather than Scheme. Haskell is newer than Scheme, and it is derived from ML, which is derived from Lisp. (Calling Haskell a dialect of Lisp or a dialect of Scheme would be a bit too strong of a statement.) I wouldn't have been displeased to have learned Haskell instead of Lisp in CS 101. But I still think that Scheme is preferable for teaching CS. > On a roll, I decided to check out Harvard: > CS50 "Introduction to Computer Science I" uses C > http://www.fas.harvard.edu/~lib50/ > CS51 "Intro. to CS II" uses LISP, C++, and Java > http://www.fas.harvard.edu/~lib51/write.cgi I took Computer Science at Harvard when I was in high school, and the equivalent of CS50 at the time was for dolts. The equivalent of CS51 was for students that had a clue. The most interesting part of the course was, by far, the Lisp section. And in the C section they just had us implement Lisp in C. > Judging from your email address, I'll assume you know about what MIT > uses for their intro courses. Yes, they use Scheme and the incredible textbook *Structure and Interpretation of Computer Programs*, which is the only book that anyone should ever use to teach Computer Science 101. |>oug From rnd at onego.ru Tue May 22 08:04:12 2001 From: rnd at onego.ru (Roman Suzi) Date: Tue, 22 May 2001 16:04:12 +0400 (MSD) Subject: Variable inheritance In-Reply-To: Message-ID: On 22 May 2001, Paul Foley wrote: > On Tue, 22 May 2001 11:58:34 +0400 (MSD), Roman Suzi wrote: > > > The badness of multiple inheritance is not bounded with the underlying > > language. It's bad design decision, because it artificially combines two > > classes, which very rarely reflect real situation. (I can't even give > > Virtually every creature on earth more sophisticated than a bacterium > inherits from two parents :-) But it never happens between CLASSES of creatures ;-) Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From pinard at iro.umontreal.ca Wed May 2 17:26:46 2001 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 02 May 2001 17:26:46 -0400 Subject: Forcing quote characters in repr(STRING), how? Message-ID: Hi, people. When using `repr()' on a string, Python automatically selects if it will use single or double quotes to enclose the produced representation of the string. Is there a clean way to force that choice to be, under user control, a particular quote character (either simple or double)? Thanks in advance. :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From aahz at panix.com Sat May 12 02:26:13 2001 From: aahz at panix.com (Aahz Maruch) Date: 11 May 2001 23:26:13 -0700 Subject: Blade of Darkness Message-ID: <9dil25$joo$1@panix2.panix.com> I just got my copy of Blade of Darkness today. Haven't played with it enough to determine whether I really like it, but I have to say that the coolness factor of a commercial action game written in Python is high enough that anyone who's into first-person "Street Fighter" type games should absolutely get it. -- --- Aahz <*> (Copyright 2001 by aahz at pobox.com) Androgynous poly kinky vanilla queer het Pythonista http://www.rahul.net/aahz/ Hugs and backrubs -- I break Rule 6 "Everyone is entitled to an *informed* opinion." --Harlan Ellison From see at my.signature Tue May 15 00:00:50 2001 From: see at my.signature (Greg Ewing) Date: Tue, 15 May 2001 16:00:50 +1200 Subject: Range Operation pre-PEP References: Message-ID: <3B00A9F2.D1B46C35@my.signature> Tim Peters wrote: > > For an extreme example, max(sys.stdin) Ha! I like it! I can just imagine a professor setting an assignment which says "Read characters from standard input up to EOF and return the one with the highest ASCII value" and some smart-alec student hands in a one-line Python solution. Pretty soon our one-liners will be even shorter than Perl's! Next-stop-APL-ly, -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From ullrich at math.okstate.edu Sun May 27 09:48:32 2001 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Sun, 27 May 2001 13:48:32 GMT Subject: Powersets of a list? References: <9els3j$2kap$1@ID-11957.news.dfncis.de> <9em0l10kdt@enews1.newsguy.com> <3b0fabc2.5506652@nntp.sprynet.com> <9eorfa0kj1@enews2.newsguy.com> Message-ID: <3b11015c.2099508@nntp.sprynet.com> On Sat, 26 May 2001 20:09:20 +0200, "Alex Martelli" wrote: >"David C. Ullrich" wrote in message >news:3b0fabc2.5506652 at nntp.sprynet.com... >> On Fri, 25 May 2001 18:19:10 +0200, "Alex Martelli" >> wrote: >> >> >"Emile van Sebille" wrote in message >> >news:9els3j$2kap$1 at ID-11957.news.dfncis.de... >> >> This seems to do it: >> > [znip] >> >> > I was wondering if, given a list [1,2,3], one can generate its power >> >set? >> > >> >What about a concise form such as...: >> > >> >def powerset(L): >> > N = len(L) >> > return [ [L[i] for i in range(N) if X&(1L<> > for X in range(2**N) ] >> >> In a lower-level language where sets are implemented >> as patterns of bits then the thing corresponding to >> range(2**N) _is_ the power set. But here surely >> all that shifting, etc, makes this extremely slow? > >I dunno, slow compared to what? It's going to be >O(2**N) of course, or O(N*2**N) or something like that... >that IS slow, but how do you >generate a powerset faster than that? There have been several power set routines posted. I suspect that they're all O(N*2^N), but when I time them (on Windows, starting with a list of length 15) some of them are at least 10 time faster than others. I haven't had any reason to get 2.x so I haven't, on aint-broke grounds. So I can't compare what you wrote with, for example, the routine I posted. Have you compared them? >> (Could be I finally have to give in and get 2.x >> to find out.) >> >> >or, to avoid consuming too much memory, a class >> >whose instances 'are' sequences of L's subsets >> >might be quite appropriate here: >> > >> >class Powerset: >> > def __init__(self, L): >> > self.L = L >> > self.N = N >> > self.S = N*N >> > def __getitem__(self, x): >> > if x<0: x+=self.S >> > if x<0 or x>=self.S: raise IndexError,x >> > return [self.L[i] for i in range(self.N) >> > if x&(1L<> >> ??? Presumably the string "N" is a reserved >> word in 2.x, with magic properties so that >> self.N = N becomes self.N=len(L) and >> self.S=N*N becomes self.S=2**self.N? > >Naah, I obviously just forgot to copy the line > N = len(L) >over from the previously quoted function >powerset to the first or second line of this >Powerset class's __init__ method. Trivial. So _was_ the N*N supposed to be 2**N as well? >> >I haven't supported slicing in this example, but >> >it wouldn't be terribly hard. Anyway, it lets >> >you do such typical tasks as: >> > >> > for sq in Powerset('ciao'): >> > print ''.join(sq) >> >> (Or maybe the fact that 4*4 = 2**4 has something >> to do with it...) > >To do with what? The line self.S = N*N in your code. Of course the self.N = N was supposed to be self.N = len(L), but it took me a long time to figure out what the heck the N*N was doing there. I still don't get it - if those two lines were self.N = len(L) self.S = 2**self.N then I'd see how your routine works, but when you say self.S = N*N I don't follow it at all. It's certainly possible that I just don't understand how the code works. But if you only tested it on lists of length <= 4 then it's possible that it doesn't work on longer lists: If N=4 then N*N = 2**N. So although I don't see how what you posted works, I _do_ see how it works for lists of length 4... (Since it was actual code, not just a suggestion, I assumed you'd actually run it. If it was meant as untested code then never mind. But assuming that you'd tested it I was puzzled how it could have passed the test - then when I saw the example with a sequence of length 4 that seemed like a possible explanation.) >Alex > > > David C. Ullrich ********************* "Sometimes you can have access violations all the time and the program still works." (Michael Caracena, comp.lang.pascal.delphi.misc 5/1/01) From soumitri at postmark.net Fri May 11 09:34:27 2001 From: soumitri at postmark.net (soumitri) Date: Fri, 11 May 2001 13:34:27 +0000 Subject: getting files in a dir and subdirs Message-ID: <20010511133427.23657.qmail@venus.postmark.net> Scott Hathaway wrote: > Does someone already have code that will return the filenames in a directory > and all subdirectories? If someone has already written it, I will not have > to start from scratch. > > Thanks, > Scott > hi Scott! I think the following works : # print all files in the dir-tree starting at *path* # first define a visit fn def visit(arg, dir, names) : for i in names : print os.path.join(dir, i) # here, path is the starting directory : os.path.walk(path, visit, None) Soumitri. From aleaxit at yahoo.com Thu May 17 18:09:28 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 18 May 2001 00:09:28 +0200 Subject: new.instancemethod References: Message-ID: <9e1i2v0qj0@enews1.newsguy.com> wrote in message news:mailman.990130053.9452.python-list at python.org... ... > IOW, for most of the examples I see where "instance-specific behavior" is > useful a reasonable strategy is for the instance to delegate immediately > back to the object/context that created (or uses) it to do something > meaningful on its behalf. > > Given that, I was wondering if anyone had a good example from actual > practice where the "instance-override-of-method"-type approach was the best Oh, *THAT*. Sure. For example, I have a lot of objects I'm analyzing, each represents a bridge hand and is an instance of a big class. Now I get a subset of the objects by some criteria and pass them to a new module I'm developing and just loaded dynamically into the framework. The module selects those objects to which a certain behavior I'm studying would be applicable and now needs to change the behavior of those objects for a few situations, then get back to the framework for a simulation run. In the framework I don't know exactly what out of the dozens or hundreds of behavior-snippets represented by methods in a bridge hand the new module may want to tweak and change with its own functions. In C++ I'd have to overdesign a Strategy design pattern representing ALL possible behaviors of a bridge hand, I guess. *shudder* hardly what one would call a reasonable approach to exploratory programming!-). In Python it's trivial. Say the behavior I'm studying is: "for a hand which by basic methods would bid a natural invitational 2NT, bid 3NT instead if it has a 6-carder or longer suit header by the A". The module will easily find "all hands with a 6-carder or longer headed by A" and for them, and them only, change the .ownbid method: def ownbid_tweaked(self, bidding_history): bid = self._save_ownbid(bidding_history) if str(bid)=='2N' and bid.force()=='INVITE': return bid(3, 'N', 'SIGNOFF') return bid def tweak_ownbid(obj): obj._save_ownbid = obj.ownbid obj.ownbid = new.instancemethod(ownbid_tweaked, obj, obj.__class__) (Sorry, just improvising -- don't have the original example at hand, so this is untested, but I hope it gives the general idea!). I'm sure contract-bridge research is not the only exploratory simulation based research field in which this would apply -- changing behavior of a few objects in certain cases, without bothering to make new classes. A class-centered person would no doubt prefer a class-focused approach here too: def tweak_ownbid(obj): Base = obj.__class__ class Tweak(Base): Base = Base def ownbid(self, bidding_history): bid = Base.ownbid(self, bidding_history) # &c, snipped obj.__class__ = Tweak this has its advantages, but keeping these per-method decorators as instance-specific/method-specific entries has pluses too, most particularly if you also start removing and juggling them around more freely. Alex From rnd at onego.ru Tue May 8 04:06:22 2001 From: rnd at onego.ru (Roman Suzi) Date: Tue, 8 May 2001 12:06:22 +0400 (MSD) Subject: make module for Python? Message-ID: Hello! I have not found it anywhere on the Web, but probably it has different name, so it's better to ask. I want a make-utility functionality (maybe not all, but basic) to be available from Python. (Similarly to the grep.py which provides grep functionality). Is there anything for this? If not, is it a good thing to develop "make.py" module for Python? I'd liked to have make dependence info not only for files, but for arbitrary class instances. Isn't it cool? The original make is not suitable for the later task, because it is not very flexible if dependence info changes rapidly. For example, if I develop a Python script to process some markup into web-site in HTML, dependence information from that markup need to be converted to Makefile, which is not so cool (otherwise, I will regenerate every object, which could be time-consuming). If I had an object which could control what need to be done with what objects - it will be much easier. (What I need is make-driven program, where control flow is defined by make-like rules, but applied not only to files but for objects.) Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From dalke at acm.org Wed May 9 14:30:18 2001 From: dalke at acm.org (Andrew Dalke) Date: Wed, 9 May 2001 12:30:18 -0600 Subject: Why aren't we all speaking LISP now? References: Message-ID: <9dc2d8$tck$1@slb6.atl.mindspring.net> Laura Creighton wrote: > What sort of teaching did the rest of you that took computer > science courses get? I learned Basic on my own followed by Pascal in high school. That was taught because the AP tests (which can give college credit or placement for high school work) require Pascal. Intro college courses were Pascal I and Pascal II. (My AP test gave me credit for Pascal I.) After Pascal I, people usually took a C/assembly course because that was a prerequisite for many of the more applied courses. Here's what I remember about the classes and languages used: Data structures - Lectures were all math and drawings, assignments were in Pascal because that's what the intro course taught (and because that's what the TA knew) Graphics - assignments could be done in Pascal, C or C++ Only language used in lectures was the Pascal-like one needed to read Foley&van Dam. The only graphics primitives we were allowed were "draw point" and "draw character" Operating Systems - C (used Tannenbaum's Minix book and code) Computer Organization - all hardware and math, with a bit of assembly for one of the projects. Databases - I don't think we needed to write any programs. The teacher didn't like programming, so it was all theory. Didn't even learn SQL. Discrete Math I & II - all math, no programming Ethics for Computer Science and Engineering - reading and discussing papers but no programming (not even to break into the CS machines, which a few friends of mine did anyway, using C). Numerical Analysis - Fortran, but I got away with C. I think this was an elective most people skipped. Fortran for Engineers - required for a physics degree but not for computer science Foundations of CS - all math, no programming Advanced C/C++ - taken mostly by people who knew that C++ was important for future work and jobs. Eg, there were a lot of city people (non-CS undergrads) taking this course. IBM 360 Assembly - I didn't take it, but it was offered. It was left over from years previous - the teacher for the class really loved 360 assembly. Programming languages - normally this is the 'implement a lisp' course. The year I took it it required almost no programming and was mostly a review of the literature. Did learn some APL though. I'm probably missing a few courses. What's interesting from this list the number of CS courses not doing programming. I always figured this was a consequence of the CS department being in the school of arts & sciences and being more math oriented. Where I went to grad school the CS department was in the engineering school and their undergrad assignments were much more implementation oriented and with less theory. That's not to say people at my undergrad all wanted to learn the theory. Andrew dalke at acm.org From new_name at mit.edu Fri May 18 13:40:24 2001 From: new_name at mit.edu (Alex) Date: 18 May 2001 13:40:24 -0400 Subject: C module calls python script: how to set exception in C References: Message-ID: > However, is it safe to call PyObject_Repr here, or can it itself err > again? Yes, you can get an error in the __repr__ method of a class, for instance. You may want something like callable_repr = PyObject_Repr(callable_repr); if (!callable_repr) { return NULL; } PyErr_Format(PyExc_TypeError, "%s blah", callable_repr); If it were me, I would probably just say that the callable passed to the function returned the wrong type, and let the user figure out what that was. HTH Alex. From nperkins7 at home.com Thu May 31 01:37:18 2001 From: nperkins7 at home.com (Nick Perkins) Date: Thu, 31 May 2001 05:37:18 GMT Subject: need code to gen all bit possibilities for 64 bits References: <9f4ipd$reu@freepress.concentric.net> Message-ID: big? there are 2**64 possible patterns of 64 bits. that is a big number. ..a very big number. ....a very very big number. ..oh, wait, I see, you don't want all of them, just some of them..(phew) ..so basically, what you need most is a way to generate some 64-bit binary numbers? ..representing a contiguous set of integers? (not sure what you need) "Bryan Webb" wrote in message news:9f4ipd$reu at freepress.concentric.net... > Hi, > I need code to generate bit configs for 64 bits. I know that this could > be big. I would like to be able to start and stop at a certain point and > write the results to a file to input to another program. > > Thanks for the help > Bryan Webb > > From grante at visi.com Mon May 7 23:46:44 2001 From: grante at visi.com (Grant Edwards) Date: Tue, 08 May 2001 03:46:44 GMT Subject: How to test if connected to the Internet References: <5c0eftcig5nrd25kr2leac9gkdpa2p69r6@4ax.com> Message-ID: On Mon, 07 May 2001 22:57:45 GMT, Ron Johnson wrote: >> Is there some (easy) example code available which lets me check if a >> connection to the Internet is established or not? If not, how can I >> dial-in to my ISP using Python? > >If using Linux/Unix, you could always try > /sbin/ifconfig eth0 |grep eth0 >and if you find eth0, then proceed with your Python script. That only tells you if there's an ethernet driver loaded. You still might not have an Internet connection. Or you're internet connection could be through a PPP or SLIP or PLIP device. The only way to determine if a particular IP address is reachable is to try to open a connection. -- Grant Edwards grante Yow! Sorry, wrong ZIP at CODE!! visi.com From bill at libc.org Mon May 7 11:36:11 2001 From: bill at libc.org (Bill Anderson) Date: Mon, 07 May 2001 21:36:11 +0600 Subject: [ZOPE] using re.compile(...) raises an HTTP401 (basic authencication) ?????? References: <9cphc3$cu9$1@news2.isdnet.net> <9crcjp$7ko$1@news2.isdnet.net> Message-ID: In article <9crcjp$7ko$1 at news2.isdnet.net>, "Gilles Lenfant" wrote: > Many thanks M. Penfold... > > But... curious behaviour, I don't see what kind of security issue may > raise from the re package. It does not play with OS features AFAIK. re can use quite abit of CPU. Imagine a server with users placing re using scirpts abou tthe place, and them being called frequently. it can get pretty hairy. Bill From skip at pobox.com Sun May 27 13:15:46 2001 From: skip at pobox.com (skip at pobox.com) Date: Sun, 27 May 2001 12:15:46 -0500 Subject: I really like Python but .... In-Reply-To: References: Message-ID: <15121.13890.12756.222135@beluga.mojam.com> Bill> HOWEVER, I can't get too excited about it until a true compiler Bill> for Python comes along. Check out Python2C. Don't know the current status, but the mailing list is very quiet, so it's almost certainly getting somewhat behind the current Python state-of-the-art. Python2C takes a module written in Python and generates an equivalent module written in C, which you can compile. Also, freeze, in the distribution as Tools/freeze, warrants a look. Neither one frees you completely from the need for an interpreter, though freeze bundles the interpreter into the generated executable. -- Skip Montanaro (skip at pobox.com) (847)971-7098 From fredrik at pythonware.com Tue May 8 02:51:31 2001 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 08 May 2001 06:51:31 GMT Subject: usage of reduce References: Message-ID: SC Zhong wrote: > I am using version 1.5.2 > would somebody tell me why the following does not work. > > >>> z > [(1,5),(2,6),(3,7)] > > >>> reduce(lambda x,y: x[1]+y[1], z) hint: what does the lambda expression return? does the return value support element access? (reduce calls the function on the first and second element in your sequence, and then on the resulting value and the third element) Cheers /F From aleaxit at yahoo.com Tue May 22 03:48:44 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 22 May 2001 09:48:44 +0200 Subject: Dependency Inversion Principle -- Python Way References: Message-ID: <9ed5kp019b6@enews1.newsguy.com> "Charles Medcoff" wrote in message news:rijO6.60718$V5.11537451 at news1.rdc1.mi.home.com... ... > In my mind people don't spend enough time thinking about communicating with > the next developer that has to look at your code, especially in the code > itself, not in supporting documentation. Young ones don't. Us old crufties must have come to realize the need to communicate *to OURSELVES a week from now* what the H**K we had in mind when we wrote this, that, and the other -- one learns not to be too clever and tricky &c AND to let the code be as direct an expression as feasible of one's design ideas. Comments and other supporting docs do not cut it as they may too easily get out of sync with what the code is actually doing... > I confess that I do most of my development in statically typed langauges > (C++/Java) so maybe that's some of my own experience/bias coming through. It seems to me that having code directly and explicitly reflect design intent is just as important whether the language's type checks happen at compile-time or run-time. Extreme Programming (XP) was born in Smalltalk (can hardly be accused of being a statically typed language) yet emphasizes *clear code* (rather than tricky code, over-general code, comments, docs, ...) as one of its cornerstones... Alex From James_Althoff at i2.com Wed May 9 16:11:18 2001 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Wed, 9 May 2001 13:11:18 -0700 Subject: Does Python have Class methods Message-ID: Magnus writes: :This is all very fancy and nice, but what is wrong with the following? : : def double(self, x): : return x*2 : : class Doubler: : double = double : : d = Doubler() : d.double(3) : # returns 6 The goal is to be able to write: Doubler.double(3) not Doubler().double(3) Your example yields: >>> Doubler.double(3) Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method must be called with class instance >>> IOW you want a "class method" -- preferably meaning "a method defined for and invoked on a class object independent of any instance of said class". Jim From usenet.2001-05-08 at bagley.org Tue May 8 20:23:27 2001 From: usenet.2001-05-08 at bagley.org (Doug Bagley) Date: 08 May 2001 19:23:27 -0500 Subject: Language comparisons References: <3AF801A4.BE4562D1@philips.com> Message-ID: "Nick Perkins" writes: > I guess what I mean to say is that I would consider the 'Same Thing' tests > to much more valid than the 'Same Way' tests. I feel somewhat the same way. I prefer the 'same thing' tests to the 'same way' test, but in my opinion, both kinds are interesting. However, since it is much easier to write tests in the 'Same Way', I have ended up with more of them. I do plan on adding more tests where the object is to accomplish a well defined task in the fastest manner, and I'm open to suggestions (email please). [...] > I would like to see a summary/comparison of 'Same Way' tests versus > 'Same Thing' tests. If some languages are consistently 'better' in > the 'Same Thing' tests than they are in the 'Same Way' tests, then > that might indicate a bias in the 'way'. Point taken ... I'll try to add that feature some time. > It's just that i have noticed that ( particularly in python ), > seemingly efficient programs can often be made much faster. > Things can usually be done many ways in python, and it is > rarely obvious which will be fastest. That matches my experience with Python too, but it may generally apply to interpreted languages, because it isn't as easy (as in C, for instance), to know how expensive any particular operation is without in-depth knowledge of the languages internals. That tends to come with experience. > ..Thanks for the website, keep up the good work! You're welcome! I'll try to keep improving it as it goes along. All constructive criticism is gladly received. Cheers, Doug From zope at thewebsons.com Tue May 1 17:31:54 2001 From: zope at thewebsons.com (Ben Ocean) Date: Tue, 01 May 2001 14:31:54 -0700 Subject: Is There a CGI Expert In the House?? Good Grief!! Message-ID: <5.0.2.1.0.20010501142749.009dcb60@thewebsons.com> Hi; I have been trying DESPERATELY to get the answer to this question. I was under the impression that Python was an ideal language for CGI scripting. Now, would SOMEONE PLEASE answer this question: Scenario: My client, BladeChevy.com, frames around Kelley Blue Book (KBB.com). The visitor fills out a form on KBB.com's page and submits it. The info is sent back to BladeChevy.com to a page I specify (in the cgi-bin directory). The data is sent back via the *data buffer* Question: What the &*()$)*_% is a data buffer and how the &*(&*% do I get the data out of it? TIA, BenO From jdf at pobox.com Mon May 7 20:25:49 2001 From: jdf at pobox.com (Jonathan Feinberg) Date: 07 May 2001 20:25:49 -0400 Subject: Bug in re.findall()? Message-ID: ActivePython 2.0, build 203 (ActiveState Tool Corp.) based on Python 2.0 (#8, Mar 7 2001, 16:04:37) [MSC 32 bit (Intel)] on win32 #----------------------------------------------------- import re r = re.compile("(?: (apple) | (banana) )\s*", re.X) tests = [ 'apple apple apple', 'banana banana banana', 'apple apple banana banana', 'apple banana apple banana' ] for t in tests: print r.findall(t) #----------------------------------------------------- [('apple', ''), ('apple', ''), ('apple', '')] [('', 'banana'), ('', 'banana'), ('', 'banana')] [('apple', ''), ('apple', ''), ('', 'banana'), ('', 'banana')] [('apple', ''), ('', 'banana'), ('apple', 'banana'), ('', 'banana')] ^^^^^^ should not be! Am I wrong? If you remove the \s* from the end of the regex, the problem goes away. -- Jonathan Feinberg jdf at pobox.com Sunny Brooklyn, NY http://pobox.com/~jdf From Peek at LVCM.comNOSPAM Sun May 27 13:52:59 2001 From: Peek at LVCM.comNOSPAM (Ken Peek) Date: Sun, 27 May 2001 10:52:59 -0700 Subject: Indentation style... Message-ID: Python allows the use of spaces or tabs (but not both!) to indent with. I think this was a mistake. I think tabs should be forced at the beginning of lines, and spaces should be forced after the first printable character is typed. The exception to this rule would be an empty line, and multiline strings. This indentation strategy would then be enforced by the interpreter/compiler. This will allow the programmer to set their editor to display a tab at whatever indentation spacing they like, and the original structure (which is part of the documentation of the code) is preserved. Most people that try Python at first hate it's indentation paradigm. BUT-- after a while they get used to it, then start liking and appreciating it very much. I think the reason is that on a large project with many programmers, the code has a tendency to kind of "look the same"-- making the code written by others easier to read and understand. Forcing tabs on the beginning of lines, and forcing spaces (for white space) after the first printable character (except for null lines and multiline strings) would be consistent with the philosophy of forcing "highly readable" code to be generated. Comments? From fredrik at pythonware.com Tue May 8 14:34:37 2001 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 08 May 2001 18:34:37 GMT Subject: socket.recvfrom() & sendto() References: <9d6r8d$67o$1@nntp6.u.washington.edu> <4VEJ6.39240$2U.16140998@news2.rdc2.tx.home.com> <9d9a1l$j64$1@nntp6.u.washington.edu> Message-ID: <1%WJ6.9419$sk3.2558296@newsb.telia.net> Donn Cave wrote: > Hm, wish I kept track of the famous quotations that appear here - > the one I'm thinking of ends "... now he has two problems." could it perhaps be: "Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. -- Jamie Zawinski, on comp.lang.emacs Cheers /F "I don't have time to write any useful software, so I've decided to devote myself to proposing various changes to the Python interpreter. -- Donn Cave, on comp.lang.python From aleaxit at yahoo.com Fri May 4 06:56:59 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 4 May 2001 12:56:59 +0200 Subject: puzzle/joke ;-) References: <9ctr4g$mc2$1@news1.simtel.ru> <9cts360191p@news2.newsguy.com> <9cu0f0$qcu$1@news1.simtel.ru> Message-ID: <9cu1ug01hov@news2.newsguy.com> "Alexander Semenov" wrote in message news:9cu0f0$qcu$1 at news1.simtel.ru... > "Alex Martelli" wrote in message news:9cts360191p at news2.newsguy.com... > > > repr(repr(repr(repr(repr('"'))))) > > `````'"'````` should be the equivalent in 13 characters, I > > Oh, I always wonder what for this perlish hack is exists in python. > Now I see... > :-) "perlish hack" seems a fair cop, I'll admit, and puzzle solving may be its main use...:-) Alex From strnbrg at c532352-a.frmt1.sfba.home.com Sat May 19 17:08:39 2001 From: strnbrg at c532352-a.frmt1.sfba.home.com (Theodore D. Sternberg) Date: Sat, 19 May 2001 21:08:39 GMT Subject: Tkinter wm_withdraw doesn't work Message-ID: Anyone know the correct way to translate the Tk-ism "wm withdraw ." to Python/Tkinter? As far as I can see, the implementation of the Wm class' wm_withdraw function tries to call a nonexistent member function called "tk()": I executed the following file: --------- file withdraw.py ------ from Tkinter import * root = Tk() wm = Wm() wm.wm_withdraw() root.mainloop() --------------------------------- ...and obtained the following result: $ python withdraw.py Traceback (most recent call last): File "withdraw.py", line 7, in ? wm.wm_withdraw() File "/usr/local/lib/python2.1/lib-tk/Tkinter.py", line 1457, in wm_withdraw return self.tk.call('wm', 'withdraw', self._w) AttributeError: Wm instance has no attribute 'tk' From dalke at acm.org Mon May 7 21:59:45 2001 From: dalke at acm.org (Andrew Dalke) Date: Mon, 7 May 2001 19:59:45 -0600 Subject: Splitting with quoted strings? References: <3AF71BC9.7E3B0947@home.net> Message-ID: <9d7jv8$6gr$1@slb0.atl.mindspring.net> Chris Barker wrote: >Is there any nifty way to do a string.split() that >doesn't split inside quotes? >'this that "the other" some more'.split() > >to give me ['this', 'that', 'the other', 'some', 'more'] > and used for *nix command lines, etc., so I > figured someone might have written a nice extension to do this. For the specific case of interpreting command lines, try shlex, which is part of the standard distribution but somewhat obscure. >>> import shlex >>> from cStringIO import StringIO >>> instream = StringIO('this that "the other" some more') >>> lex = shlex.shlex(instream) >>> while 1: ... w = lex.get_token() ... if not w: ... break ... print w ... this that "the other" some more >>> The caution about that module is it is designed for command lines so understands things like '#' for comments, as in >>> instream = StringIO('this # some comment\nthat') >>> lex = shlex.shlex(instream) >>> while 1: ... w = lex.get_token() ... if not w: ... break ... print w ... this that >>> You can modify that operation, but my point is there are many similar looking "quoted command-line" operations which don't work identically. Eg, are "quoted quotes ""doubled"" or \"backslash \"escaped". Andrew dalke at acm.org From news at dorb.com Sat May 26 17:10:43 2001 From: news at dorb.com (Darrell) Date: Sat, 26 May 2001 21:10:43 GMT Subject: Distributed computing in Python - Callback howto ? References: Message-ID: http://www.xs4all.nl/~irmen/ap/pyro.html --Darrell "Sasa Zivkov" wrote: > Hi, > > What options one have for distributed computing in Python ? > From aleaxit at yahoo.com Sat May 12 11:44:07 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 12 May 2001 17:44:07 +0200 Subject: Is this a bug? References: <3af2b89d.338629833@News.CIS.DFN.DE> <8a7L6.1640$Yu6.404853@newsc.telia.net> <3afd33ac.3862765@News.CIS.DFN.DE> Message-ID: <9djlog0d48@news1.newsguy.com> "Costas Menico" wrote in message news:3afd33ac.3862765 at News.CIS.DFN.DE... [snip] > To me the r'' syntax is inconsistent and works 99% of the time only. > I don't want to check if there is a BS at the end of a string and do > some magic to fix it. The r'' should be doing that for me. How would your dream r-architecture magically let you write x=r'ba\' # hypothetical rawstring with a trailing BS AND y=r'ba\' # hypothetical rawstring with a trailing BS' where y is meant to contain a backslash-quote combination and then the whitespace, the hash, etc? > I just don't understand why the parser can't be smart enough about > this. Maybe some unlimited reams of lookahead might let a parsed be 'smart' enough to disambiguate -- and maybe not, but I'm sure I don't want to be using a language which exhibits FAR TOO MUCH "black magic" trying to make things "convenient" for me, and having the meaning of \' depend on what comes a zillion characters afterwards (in what looks like a comment... and IS a comment if \' is string-end...) is well within the 'far too much' range for my personal tastes. Alex From dougfort at downright.com Wed May 16 21:12:15 2001 From: dougfort at downright.com (Doug Fort) Date: Wed, 16 May 2001 21:12:15 -0400 Subject: Embedding SSL in Python References: <3B030E1D.73B1F221@jump.net> Message-ID: <3b032556_4@news5.uncensored-news.com> Dick Norton wrote: > Hello, > > Has anyone had any success building POST for https by linking > something like cURL and OpenSSL with Python? I need to make > ssl POSTs under w2000 and I don't mind embedding Python (all > but the ssl POST is python and I'm not keen to change that). > > Alternatively is there a good 2.1 means of doing this? > Is m2Crypto the right thing? > > At present I'm doing a gross hack with cURL being invoked from > python - system("...") like stuff. This could be fixed if I had > a working makefile (perl woes) for the openssl ...6a for VC6 or > the ssl, libeay and RSAGlue .lib files built for VC6. Anyone have > pointers to binary openssl that includes .h files and those .libs? > > > > Thanks > Dick Norton > We use M2Crypto at http://www.stressmy.com It works quite well. -- Doug Fort Senior Meat Manager Downright Software LLC http://www.dougfort.net ______________________________________________________________________ Posted Via Uncensored-News.Com - Still Only $9.95 - http://www.uncensored-news.com With Seven Servers In California And Texas - The Worlds Uncensored News Source From rnd at onego.ru Tue May 22 04:28:48 2001 From: rnd at onego.ru (Roman Suzi) Date: Tue, 22 May 2001 12:28:48 +0400 (MSD) Subject: Variable inheritance In-Reply-To: Message-ID: PLease, look also at: http://www.geocities.com/tablizer/subtypes.htm#rucks Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From jacobs at darwin.epbi.cwru.edu Wed May 2 08:05:07 2001 From: jacobs at darwin.epbi.cwru.edu (Kevin Jacobs) Date: 2 May 2001 12:05:07 GMT Subject: Surprising (for me) benchmark results... References: Message-ID: <9cot5j$mb5$1@eeyore.INS.cwru.edu> Daniel Berln wrote: > Now, this is even assuming disk accesses are O(n), which they aren't. > Disk's are not based on technology that is determinstic. It's a fuzzy > technology. You can get probabilistic guarantees, like it'll be 99% of > the time O(n), but a blanket statement that Disk access is O(n) is plain > wrong. Sorry, but your analysis is faulty. Lets assume that the time it takes to read n blocks of data is t(n), and that we can express this as the linear function t(n) < a*n + b, when n > c for some arbitrarily large, but constant, a, b and c. Lets say that a is 100 seconds and b is 10 seconds and c is 100 blocks. This means that in amortized time, each block will be read within 100 seconds with a constant overhead of 10 seconds when more than 100 blocks are to be read. This sounds pretty reasonable, 'eh? Well, that is what O(n) means. I'd say that it safe to say that disk access is O(n), in the absence of pathological operating system conditions. If not, a lot of database researchers who make good livings under this assumption will want to have a word with you. > This is because disk drives ain't an exact technology. Most > drives these days use PRML, Partial Response Maximum Likelihood. Sure -- no biggie -- integrate the probability function times the expected read time for each read attempt add in some processing and transfer overhead and you'll get an expected read time. Given enough blocks, this number will follow some predictable distribution from which a reasonable upper bound may be obtained. Inflate that expected upper bound by a nice constant factor ('a' from above) and you're home free. Sure, it will be wrong once in a vanishingly small number of times, but under most reasonable assumptions this can be amortized in with other blocks that are read. So when dealing with big-O notation, the small amount of non-determinism is the least of our worries. (btw, if you don't buy my argument, there is a very well developed theoretical basis for the probabilistic analysis of algorithms. If you are interested I can supply many wonderful references.) > In reality, when you get down to it, it's non-deterministic in the average > case because you end up having to include probability in the calculations. > Worst case is much easier, and is deterministic, because there is no > probability involved. The analysis of many algorithms involves integrating over a probability distribution function to find the average case time complexity. While the algebra may get hairy, there is nothing wrong with doing so. Anyway, big-O notation _is_ a measure of worst-case behavior for a given distribution of inputs. Don't be fooled because its used in the context of putting an upper bound on the "worst best case", the "worst average case" and the "worst worst case" behaviors of an algorithm. For example, we can say that if the worst case behavior of an algorithm is O(n) then its average case and best case behaviors must also be O(n). Why, you ask? Well, if the worst case time for an algorithm is t_w(n) < a*n + c and the best time t_b(n) is less than or equal to t_w(n), then it must also be that t_b < a*n + c, as well. Thus the best-case time complexity is also O(n). This does not say that O(n) is _the best_ upper-bound -- its just saying that it _is_ an upper-bound. > If they are using reed solomon, figuring out which bits are wrong requires > solving simultaneous equations with t unknowns (where 2t=n-k, k is the > number of data symbols of s bits each, and n is the number of symbols, > including the new parity symbols (IE 2t+k = n)). This is just a smoke-and-mirrors argument. All of the variables you've defined are effectively constants (n here isn't the same n as before). They have well defined upper bounds defined by the disk geometry! So even if computing Reed-Solomon codes are O(m^10*n^10), m and n are constants and do not change the upper bound by more than a constant factor and do not change the big-O bound at all. Anyhow, just thought I'd inject a bit 'o computer science fun into your life. Theoretically, -Kevin -- -----------> Kevin Jacobs <-----------|-------> (216) 986-0710 <-------- Informatics Consultant | Department of Epidemiology Primary mail: jacobs at theopalgroup.com | & Biostatistics Alternate mail: jacobs at darwin.cwru.edu | Case Western Reserve University ---------------------------------------------------------------------------- From joshuar at isogen.com Tue May 1 16:50:57 2001 From: joshuar at isogen.com (Joshua Reynolds) Date: Tue, 1 May 2001 13:50:57 -0700 Subject: distutils Message-ID: <015a01c0d280$6c34f270$d50a1bac@abacus> Has anyone taken note that the version of the distutils package for Python 2.1 is "1.0.2pre" which by definition of the version.py in distutils is not a "StrictVersion" (i.e. it doesn't conform to some predefined version structure defined in the distutils.version module.)? -- Joshua Reynolds -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim.one at home.com Wed May 9 04:09:54 2001 From: tim.one at home.com (Tim Peters) Date: Wed, 9 May 2001 04:09:54 -0400 Subject: how can I convert invalid ASCII string to Unicode? In-Reply-To: Message-ID: [Tim] > otoh-7-bit-ascii-was-good-enough-for-god-to-write-the-bible-ly y'rs [/F] > surely he wrote that before 1968? > > are you sure he didn't use 5-bit baudot encoding (iirc, the > seventh bit used to be sanctified, before that hollerith guy > messed things up) God isn't limited by your Swedish notion of time, /F! 1968 is just another integer to Him, and since it's outside the range of the 7-bit ASCII ordinals He invented, not even an interesting one. Indeed, Kronecker amended his famous "God created the integers, all else is the work of man" on his deathbed, to "God created the integers, starting at 0 up to but not including 128, all else is the work of ...". He died before completing it. Historians still debate whether he would have amended "man" to "standards committees, among other servants of Satan". and-that's-the-true-story-behind-python's-famous-"ordinal-not-in- range(128)"-error-msg-ly y'rs - tim From SBrunning at trisystems.co.uk Wed May 16 03:47:14 2001 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Wed, 16 May 2001 08:47:14 +0100 Subject: Do I really need to learn Java? Message-ID: <31575A892FF6D1118F5800600846864D78BBF3@intrepid> > >Some would say Malbolge makes Intercal redundant, although I'll take > >Brainf*ck and Unlambda over either. > > I'll give you the benefit of the doubt and assume that you left out > Befunge purly accidentally. Bah! All mainstream languages. Check out for a selection of truly, uh, specialist languages. I await a SARTRE compiler with bated breath. Oh yes - six months ago or so, Ben Wolfson posted a Python implementation of unlambda, and Warren Focke countered with an implementation of Brainf*ck. Worth a google. 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 zope at thewebsons.com Tue May 1 12:50:35 2001 From: zope at thewebsons.com (Ben Ocean) Date: Tue, 01 May 2001 09:50:35 -0700 Subject: CGI Redirect In-Reply-To: <159436640585.20010501172451@buz.ch> References: <5.0.2.1.0.20010501080840.00a01c50@thewebsons.com> <5.0.2.1.0.20010501080840.00a01c50@thewebsons.com> Message-ID: <5.0.2.1.0.20010501094910.00a21b30@thewebsons.com> At 05:24 PM 5/1/2001 +0200, you wrote: > > Hi; > > I'm writing a CGI script and I need to redirect the visitor to >another page > > (as opposed to posting their form data). How do I do this? The perl > > equivalent would be: > > print "Location:http://blah.com\n\n"; > >This should work without the trailing semicolon in Python (assuming >that >nothing outputs any other headers before, of course!). Ah, yes, but in order to get the form to not toss up an HTTP 500 server error I have to put in the following: print "Content-type: text/html\n\n" How do I escape that? TIA, BenO From rnd at onego.ru Thu May 3 15:53:15 2001 From: rnd at onego.ru (Roman Suzi) Date: Thu, 3 May 2001 23:53:15 +0400 (MSD) Subject: libraries for plotting In-Reply-To: <20010503150931.A8236@cmat.edu.uy> Message-ID: On Thu, 3 May 2001, Walter Moreira wrote: >Hello, Python people. > >I was browsing the Plotting resources section on Python.Org and there are some >broken links (pgplot, plplot, ppgplot). What package do you suggest me for >plotting? It looks that there are many but some are small or not manteined any >more. I found Biggles on Parnassys but didn't try it yet. >DISLIN looks good, but it is not free :-( Do you really need plot utils _written_ in Python or usable _from_ Python? If the later, take look at the http://sal.kachinatech.com - there are plenty visualization tools there under proper category. >Thanks. > -- Walter Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/ _/ Thursday, May 03, 2001 _/ Powered by Linux RedHat 6.2 _/ _/ "A conclusion is simply the place where you got tired of thinking." _/ From paulp at ActiveState.com Tue May 15 15:47:31 2001 From: paulp at ActiveState.com (Paul Prescod) Date: Tue, 15 May 2001 12:47:31 -0700 Subject: ActivePython and ASP References: <3B005E5F.7DB9C1ED@iname.com> <3B00850C.F4CFD4A2@iname.com> Message-ID: <3B0187D3.D6A2C54D@ActiveState.com> Perhaps this describes your problem: http://starship.python.net/crew/mhammond/win32/InstallationProblems.html -- Take a recipe. Leave a recipe. Python Cookbook! http://www.ActiveState.com/pythoncookbook From aleaxit at yahoo.com Tue May 22 04:25:26 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 22 May 2001 10:25:26 +0200 Subject: Accessing VBA.Strings References: <48oO6.439$IB1.21884@news.siol.net> Message-ID: <9ed7pj01c6a@enews1.newsguy.com> "Tomaz Ficko" wrote in message news:48oO6.439$IB1.21884 at news.siol.net... > I want to use function chrW() from VBA.Strings class so I tried to use > Dispatch, but this is all I get: > > >>> from win32com.client import Dispatch > >>> q=Dispatch('VBA.Strings') ... > com_error: (-2147221005, 'Invalid class string', None, None) > > What am I doing wrong? Is 'VBA.Strings' registered as a COM coclass name (ProgID) in your registry? Look under HKEY_CLASSES_ROOT with e.g. regedit. It's not registered in mine, and I don't know if it can be or how one would go about it. Anyway, what would chrW do for you that you can't do with Python's own builtin unichr()...? Alex From jkraska1 at san.rr.com Wed May 9 00:08:33 2001 From: jkraska1 at san.rr.com (Courageous) Date: Wed, 09 May 2001 04:08:33 GMT Subject: os module documentation Message-ID: I go to my global module index, click on os ... and get next to nothing. How do I navigate to the documentation for the various methods in my os-specific module? C// From ron.l.johnson at home.com Mon May 7 23:21:28 2001 From: ron.l.johnson at home.com (Ron Johnson) Date: Tue, 08 May 2001 03:21:28 GMT Subject: socket.recvfrom() & sendto() References: <9d6r8d$67o$1@nntp6.u.washington.edu> <4VEJ6.39240$2U.16140998@news2.rdc2.tx.home.com> Message-ID: Grant Edwards wrote: > In article <4VEJ6.39240$2U.16140998 at news2.rdc2.tx.home.com>, Ron Johnson > wrote: > >>> Quoth Ron Johnson : [snip] >>> | The reason that I ask this is because, unlike with command/response >>> | client/server systems, the server must be able to send data to any >>> | client at any moment. AIM/ICQ would be similar model, even though >>> | I am not writing a chat program. [snip] >> >>So my fundamental question is: how does select() support multiple >>non-blocking TCP sockets, when you can only bind 1 socket to a port? > > The socket you bind to the port is the one that listens for > connections. You call accept() on that one socket you bound to > the port. When a connection request arrives, the accept() call > returns a _new_ socket that's connect to the IP/port address > that sent the request. If you call accept() again *on the same > socket you did the first time* it will wait for another request > to arrive and return another new socket connect to the new > requestor. > > Now you've got three open sockets: the first on that's doing > the listening for new conection requests and the two others > that are connected to something out on the 'net. You do read() > and write() calls on the latter two, and accept() calls on the > former. Thank you. Based on the Sockets HOWTO and everything I've read in the newsgroup archives, that, though, is the *conceptually* "easy" part: writing a server that waits for clients to tell the server to do something. I am trying to design a "peer-to-peer server", as non sequiter as that sounds. The central computer has a peer-to-peer relationship with each of the "peer/clients" so that the "peer/server" should be able to send a msg to any of it's "peer/clients" at any time, or the any "peer/client" without the client asking for anything. Would threading or forking be the solution to this problem? Ron -- Ron Johnson, Jr. Home: ron.l.johnson at home.com Jefferson, LA USA http://ronandheather.dhs.org "Is Python better or worse than Perl?" "Perl is worse than Python because people wanted it worse." -Larry Wall, 10/14/1998 From news at myNOSPAM.org Fri May 18 02:19:44 2001 From: news at myNOSPAM.org (Stephen Hansen) Date: Fri, 18 May 2001 06:19:44 GMT Subject: Python-Dev? Message-ID: <4a3N6.44267$mu1.11128445@typhoon.we.rr.com> Ouch. After somehow meandering to amk's webpage, and hitting the Python-dev summery, and then spending nearly two and a half hours (... i don't quite remember that much time passing ...) reading the discussion that's been going on, I'm wondering: is the python-dev mailing list open? Not for participating -- i'd be way out of my league -- but just to have pile in my inbox to read and keep up on things. Since I didn't see it on the 'mailing lists' section of python.org, I'm assuming its not.. but heck, might as well ask anyways. :) --Stephen (replace 'NOSPAM' with 'seraph' to respond in email) From new_name at mit.edu Thu May 17 15:02:59 2001 From: new_name at mit.edu (Alex) Date: 17 May 2001 15:02:59 -0400 Subject: Evaluating python - a question References: <9e100t$8e1$1@news.netmar.com> Message-ID: > Is there any mechanism in Python to detect typos like this as, in a > large program, they're bound to happen. Unit testing. Alex. From jkraska1 at san.rr.com Wed May 9 00:25:15 2001 From: jkraska1 at san.rr.com (Courageous) Date: Wed, 09 May 2001 04:25:15 GMT Subject: Silly me, print? References: <9sghftg7f1v5rsldgd03v8svces1i795mf@4ax.com> Message-ID: <10ihft0pmn11muq7kljiatgfid7l6c3bjp@4ax.com> >"Courageous" wrote in message >news:9sghftg7f1v5rsldgd03v8svces1i795mf at 4ax.com... >> >> Silly me, I can't for the life of me remember how -- or even recall if it's >> possible -- to print without a newline? >how's about with a comma Yep. Funny, programming in python all this time. I'm sure I'd never known you could use a comma for that. Speaking of this, where in the python documenation can I find information on the print statement? I follow library index->print and get builtin types for some reason. C// From shaleh at valinux.com Tue May 8 14:10:06 2001 From: shaleh at valinux.com (Sean 'Shaleh' Perry) Date: Tue, 08 May 2001 11:10:06 -0700 (PDT) Subject: Absolute TO Relative URLs In-Reply-To: <9d9bf6$soo$1@bob.news.rcn.net> Message-ID: On 08-May-2001 Satheesh Babu wrote: > Hi, > > Let us say I've an HTML document. I would like to write a small Python > script that reads this document, goes through the absolute URLS (A HREF, IMG > SRC etc) and replaces them with relative URLs. I can pass a parameter which > specifies the BASE HREF of the document. > > I'm not sure whether I should proceed with regex nightmare or are there any > easy solutions? > > Any help/pointers will be greatly appreciated. > More likely a combination of the approaches. There is a wonderful *ML parser framework derived from SGMLParser. You would just implement hooks for a, img, src, etc. Then once you find the item use a regex or string compare. From see at my.signature Wed May 23 21:30:40 2001 From: see at my.signature (Greg Ewing) Date: Thu, 24 May 2001 13:30:40 +1200 Subject: What can you do in LISP that you can't do in Python References: Message-ID: <3B0C6440.388358B7@my.signature> It occurs to me that there is one way in which an out-of-line def'ed function is *not* equivalent to a true inline code block: With nested scopes as they're currently done, there's no way to assign to a variable in an outer non-global scope. So, for example, sum = 0 def add_value(node): sum = sum + node.value for_each_node_of(my_tree, add_value) won't work! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From m.hadfield at niwa.cri.nz Wed May 23 19:16:26 2001 From: m.hadfield at niwa.cri.nz (Mark Hadfield) Date: Wed, 23 May 2001 23:16:26 +0000 (UTC) Subject: Suggestion for os.path.join Message-ID: <000f01c0e3de$630b6570$d938a8c0@Hadfield> From: "David Morgenthaler" > We use os.path.join() extensively to keep our code platform > independent. But we sometimes have problems on win32 when the > resulting path is passed to a C-extension -- not all C-extensions > (e.g., gdchart) are smart enough to handle the result. > > Example: > Python 2.1 (#15, Apr 23 2001, 18:00:35) [MSC 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license" for more information. > IDLE 0.8 -- press F1 for help > >>> PATH = 'D:/SARCrates/SARBoxResults' > >>> import os > >>> outfile = os.path.join(PATH,"subdir","outfile.png") > >>> print outfile > D:/SARCrates/SARBoxResults\subdir\outfile.png > >>> > > The combination of '/'s and '\'s in the resulting path are not handled > by gdchart.chart. I have similar problems with the PIL's ImageFont, > etc. There's your problem right there: > >>> PATH = 'D:/SARCrates/SARBoxResults' Why put '/'s in a Windows path in the first place? --- Mark Hadfield m.hadfield at niwa.cri.nz http://katipo.niwa.cri.nz/~hadfield National Institute for Water and Atmospheric Research Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. Gratuitous new text to fool news server. -- Posted from clam.niwa.cri.nz [202.36.29.1] via Mailgate.ORG Server - http://www.Mailgate.ORG From dsh8290 at rit.edu Wed May 30 11:30:07 2001 From: dsh8290 at rit.edu (D-Man) Date: Wed, 30 May 2001 11:30:07 -0400 Subject: No swap function in Python? In-Reply-To: <3B150A65.5D4986FC@europem01.nt.com>; from boltong@europem01.nt.com on Wed, May 30, 2001 at 04:57:41PM +0200 References: <3B150A65.5D4986FC@europem01.nt.com> Message-ID: <20010530113007.B20411@harmony.cs.rit.edu> On Wed, May 30, 2001 at 04:57:41PM +0200, Bolton, Gawain [ADC:4808:EXCH] wrote: | There doesn't seem to be a "swap" function in Python two swap the values | of two variables. I was wondering why this is. | | Unfortunately writing a generic swap function swap(a,b) with no return | type in Python doesn't work with immutable arguments (like strings) of | course. Which made me think that a swap could be done like this: | | (a,b) = (b,a) | | But I'm not completely convinced doing this is safe. In tests I've done | it works, but I'm not sure whether this works in all cases with all | types... Finally, if the behaviour is guaranteed, is this an efficient | way of doing a swap? This is the way it is done in Python. What it does is create a tuple containing b and a (the right-hand-side of the statement) then unpack it into the tuple on the left-hand-side (containing a and b respectively). It works with all types because tuples are heterogeneouse containers and don't care what type of object it contains. It is entirely up to your client code what you want to do with the tuple and the objects contained in it. It is your client code that you must ensure the types make sense for the operations it wants to perform on it. This is really not a problem because of Python's strong dynamic typing mechanism, and has nothing to do with swapping techniques. Another solution, if you really don't like tuple packing and unpacking, is : temp = b b = a a = temp del temp but I think it is obvious that this technique consists of 3 (4) statements instead of just one and the creation and deletion of a new variable. My guess is that the tuple technique is more efficient as well as being more concise, but you would need to profile it to be sure. -D From bh at intevation.de Wed May 30 11:46:52 2001 From: bh at intevation.de (Bernhard Herzog) Date: 30 May 2001 17:46:52 +0200 Subject: No swap function in Python? References: <3B150A65.5D4986FC@europem01.nt.com> Message-ID: <6q1yp6j0ur.fsf@abnoba.intevation.de> Pierre Barn writes: > in article 3B150A65.5D4986FC at europem01.nt.com, Bolton, Gawain > [ADC:4808:EXCH] at boltong at europem01.nt.com wrote on 30/05/01 16:57: > > > Which made me think that a swap could be done like this: > > > > (a,b) = (b,a) > > You can do a, b = b, a > As you discovered. > > > is this an efficient > > way of doing a swap? > > It is Well, if a and b are local variables, the more traditional idiom temp = a; a = b; b = temp is a tad faster, at least on my machine, because a, b = b, a actually constructs the intermediate tuple object. Of course, a, b = b, a is much easier to read, which outweighs the minuscule speed advantage of the other form. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://mapit.de/ From aahz at panix.com Fri May 18 07:53:03 2001 From: aahz at panix.com (Aahz Maruch) Date: 18 May 2001 04:53:03 -0700 Subject: pythonic tree-walking idioms References: <9dvsa4$dt0$1@news.netmar.com> <3b04d42e$1_2@newsfeeds> Message-ID: <9e32ev$mne$1@panix2.panix.com> In article <3b04d42e$1_2 at newsfeeds>, Shak wrote: > >Thanks... appreciate all the responses... however I didn't realize that >"yield" was a python keyword... seems ruby-like to me... It's not, yet. It's part of an experimental patch on Python. However, you can probably achieve a similar effect with little effort in current CVS Python and iterators. -- --- Aahz <*> (Copyright 2001 by aahz at pobox.com) Androgynous poly kinky vanilla queer het Pythonista http://www.rahul.net/aahz/ Hugs and backrubs -- I break Rule 6 "It's such a fine line between stupid and clever." --David St. Hubbins From dalke at acm.org Fri May 11 21:01:19 2001 From: dalke at acm.org (Andrew Dalke) Date: Fri, 11 May 2001 19:01:19 -0600 Subject: ltrim on a block of text? References: Message-ID: <9di22g$ous$1@nntp9.atl.mindspring.net> Bjorn Pettersen wants to turn >s = """ > void f(int x) { > printf("%d\n", x); > } >""" into >""" >void f(int x) { > printf("%d\n", x); >} >""" The original string should likely be \\n because otherwise the \n is embedded in the string. Here's a function which does what you want def ltrimBlock(s): lines = string.split(string.expandtabs(s), "\n") w = len(s) for line in lines: line2 = string.lstrip(line) if line2: w = min(w, len(line)-len(line2)) new_lines = [] for line in lines: new_lines.append(line[w:]) return string.join(new_lines, "\n") >>> print ltrimBlock(""" ... void f(int x) { ... printf("%\\n", x); ... } ... int i = 4; ... """) void f(int x) { printf("%\n", x); } int i = 4; >>> Andrew dalke at acm.org From Jason.Tishler at dothill.com Tue May 1 14:36:29 2001 From: Jason.Tishler at dothill.com (Jason Tishler) Date: Tue, 1 May 2001 14:36:29 -0400 Subject: Building Cygwin-Python extension modules - export strategies In-Reply-To: <011b01c0d1cf$67209d40$d938a8c0@Hadfield>; from m.hadfield@niwa.cri.nz on Mon, Apr 30, 2001 at 11:43:54PM +0000 References: <011b01c0d1cf$67209d40$d938a8c0@Hadfield> Message-ID: <20010501143629.E584@dothill.com> Mark, On Mon, Apr 30, 2001 at 11:43:54PM +0000, "Mark Hadfield" wrote: > Jason has told me that he prefers Option 1. Perhaps he would like to explain > why. I guess that I don't really have very strong arguments to support my position. My preference for Option 1 is mostly due to inertia (many modules already used DL_EXPORT) and the normal human instinct to avoid pain -- one stops banging their head when it hurts too much. :,) But seriously, there is one (albeit small) advantage to Option 1. Which is the ability to build the shared extension using either the traditional Misc/Makefile.pre.in or newer Distutils method. > Since Jason is the Cygwin Python demi-god Hmm...demi-god. What are you going to call me after I write my sixth Python script? :,) > But lets talk about this and tease out any more pros and cons. You may want to try the distutils-sig at python.org list too. You may have better luck there. Jason -- Jason Tishler Director, Software Engineering Phone: +1 (732) 264-8770 x235 Dot Hill Systems Corp. Fax: +1 (732) 264-8798 82 Bethany Road, Suite 7 Email: Jason.Tishler at dothill.com Hazlet, NJ 07730 USA WWW: http://www.dothill.com From costas at meezon.com Thu May 24 14:55:11 2001 From: costas at meezon.com (Costas Menico) Date: Thu, 24 May 2001 18:55:11 GMT Subject: A new metaclass pattern, class methods References: <3B0BE4D2.3B38E410@python.net> Message-ID: <3b0d5845.4074548@News.CIS.DFN.DE> Thomas, I believe I may have a simpler. Please feel free to comment on the code below. costas """ Example from the animal kingdom (Penguins are birds, birds and dogs are animals.) to show how to make class methods, class variables and instance methods, instance variables. Based on previous discussions and ideas from the Python newsgroup. Conventions used: o All class classes end with Meta. E.g. ClassMeta o Before using you must create your meta class object. There should be only one instance (singleton) of this in the system. E.g. Class = ClassMeta() o To create an instance of a class you use the Class.New(args). You can create as many instances as you need o Future fix: Create a global class Class that tracks singleton Class instances plus other default behavior in a global dictionary. Steps to make your own classes. 1) Define a class name that ends with Meta. Inherit if necessary from 2) Define an nested class called New. Inherit .New (if necesary) Don't forget to initialize the superclass in your __init__ and if you have a destructor destroy() to also call the superclass. 3) Code your class methods and variables inside Meta 4) Code your instance methods and variables inside New 5) Create a singleton of your Meta class. 6) Use this to create as many objects as needed. Author: costas menico / costas at meezon.com """ class AnimalMeta: totalAnimals=0 # class variables allAnimals = 'Are mobile' def getInstances(self): return AnimalMeta.totalAnimals def name(self): return 'animal class' class New: def __init__(self, name='animal instance'): AnimalMeta.totalAnimals+=1 self.name = name def name(self): return self.name def destroy(self): AnimalMeta.totalAnimals-=1 class BirdMeta(AnimalMeta): totalBirds=0 #class variables allBirds = 'Have wings' def name(self): return 'bird class' class New(AnimalMeta.New): def __init__(self, name='bird instance'): AnimalMeta.New(name) # initialize superclass BirdMeta.totalBirds+=1 self.name = name def destroy(self): AnimalMeta.New.destroy(self) BirdMeta.totalBirds-=1 def name(self): return self.name class DogMeta(AnimalMeta): totalDogs=0 #class variables allDogs = 'Bark' def name(self): return 'dog class' class New(AnimalMeta.New): def __init__(self, name='dog instance'): AnimalMeta.New(name) # initialize superclass DogMeta.totalDogs+=1 self.name = name def destroy(self): AnimalMeta.New.destroy(self) DogMeta.totalDogs-=1 def name(self): return self.name def bark(self): return 'woof' class PenguinMeta(BirdMeta): totalPenguin = 0 # class variables allPenguins = 'Live in cold climate' def name(self): return 'penguin class' class New(BirdMeta.New): def __init__(self, name='penguin instance'): BirdMeta.New(name) # initialize superclass PenguinMeta.totalPenguin+=1 self.name = name def destroy(self): BirdMeta.New.destroy(self) PenguinMeta.totalPenguin-=1 def name(self): return self.name def song(self): return 'Penguins rock' # Metaclass creation. Required before creating classes. # You should only have one of each Meta. Animal=AnimalMeta() Bird=BirdMeta() Dog=DogMeta() Penguin=PenguinMeta() #-------------------------------------------------------- # Tests # Object instantation. Here do anything you want. aMommaPenguin=Penguin.New('momma') aPappaPenguin=Penguin.New('pappa') aBabyPenguin=Penguin.New('baby') aDog=Dog.New('fido') #print some info print aMommaPenguin.name print aPappaPenguin.name print aBabyPenguin.name print aBabyPenguin.song() print aDog.name print 'Tot Penguins:', Penguin.totalPenguin print 'Tot Animals:', Penguin.totalAnimals print 'Tot Birds: ', Bird.totalBirds print 'Tot Animals: ', Bird.totalAnimals print 'Tot Dogs:', Dog.totalDogs print 'Tot Animals:', Dog.totalAnimals print 'Total Animals:', Animal.totalAnimals #reduce animals and dogs by one aDog.destroy() del aDog print 'Tot Animals:', Dog.totalAnimals print 'Tot Dogs:', Dog.totalDogs del aMommaPenguin,aPappaPenguin,aBabyPenguin del Animal, Bird, Dog, Penguin From laurent.pointal at wanadoo.fr Sun May 6 08:55:54 2001 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Sun, 06 May 2001 12:55:54 GMT Subject: Windows editor? References: Message-ID: "Brandon J. Van Every" wrote in : >What's a good Python editor for programming under Windows, specifically >Windows 2000? According to Google archives it seems this question hasn't >been asked in awhile. ConTEXT, at http://www.fixedsys.com/context/ Written by a programmer which has not found a programmer editor corresponding to his need. Just force use of spaces in place of tabs, and use 4 chars tabs, and its ready for Python (the 'big' problem I have with it is that it dont correctly do color syntaxing with multilines """ or ''' strings). Just try it, its free (we switched from IDLE to ConTEXT). A+ Laurent. From jkraska1 at san.rr.com Sat May 12 13:59:33 2001 From: jkraska1 at san.rr.com (Courageous) Date: Sat, 12 May 2001 17:59:33 GMT Subject: Why aren't we all speaking LISP now? References: <989424635.15477.0.nnrp-12.c1c3e154@news.demon.co.uk> Message-ID: >>Too many people have taken a lisp class and think that >>recursion matters all that much to lisp programmers. Not so. >Really? Almost all of the Scheme programs I've written use >tail-recursion. Yes, really. I've seen more than one 100,000 line Lisp monstrosity. Recursion is rare, and occurs where recursion is appropriate. My experience is that, while indeed the Lisp environment is optimized to make recursion feasible, professional Lisp programmers, while a tad more likely to use recursion than the next guy, only do so on problems in which recursion is the obviously appropriate answer. I don't know what your professional Scheme experience is, but I do know that the presentation which Lisp gets in most universities is both misrepresentative and wrong-headed. Lisp is a _general purpose_ programming language. In academia, where it is apparently vogue to pigeon-hole everything into neatly assembled categories of things, Lisp gets a biased presentation not covering its true capabilities and true general use amongst programmers who use it. Lisp is not "the recursion language," notwithstanding its presentation as such in academic circles. The majority of Lisp programs I've seen are dominated by map/ lambda forms, basic OOP with multimethod dispatch, heavy use of multiple inheritance in mixin-style programming, and so forth. The s-expression is exploited in a variety of ways. Hash tables are used frequently. Lists are often abused, where other containers would be better choices. Those are typical Lisp programs. Pell-mell use of recursion? No way. Not for anything but a recursive problem. C// From grante at visi.com Tue May 22 00:50:22 2001 From: grante at visi.com (Grant Edwards) Date: Tue, 22 May 2001 04:50:22 GMT Subject: more troubles with my program References: <_6kO6.8119$Zb.85054@typhoon.mw.mediaone.net> Message-ID: On Tue, 22 May 2001 11:11:01 +0800, Malcolm Tredinnick wrote: > (for example, float('elephant') doesn't have a reasonable result. Elephants are actually quite decent swimmers. -- Grant Edwards grante Yow! Hello, GORRY-O!! I'm at a GENIUS from HARVARD!! visi.com From ngps at madcap.dyndns.org Fri May 18 12:07:07 2001 From: ngps at madcap.dyndns.org (Ng Pheng Siong) Date: 18 May 2001 16:07:07 GMT Subject: Embedding SSL in Python References: <3B030E1D.73B1F221@jump.net> Message-ID: <9e3hbb$ktt$1@violet.singnet.com.sg> According to Dick Norton : > Alternatively is there a good 2.1 means of doing this? > Is m2Crypto the right thing? Latest M2Crypto snapshot works with Python 2.1. Check it out: http://www.post1.com/home/ngps/m2 Cheers. -- Ng Pheng Siong * http://www.post1.com/home/ngps Liverpool 2 - 1 Arsenal Liverpool 5 - 4 Alaves From max at alcyone.com Tue May 1 11:32:13 2001 From: max at alcyone.com (Erik Max Francis) Date: Tue, 01 May 2001 08:32:13 -0700 Subject: Hungarian notation (was RE: variable naming...) References: Message-ID: <3AEED6FD.3807C275@alcyone.com> John Schmitt wrote: > Now, if you write a program that uses the above-mentioned struct in a > bunch > of places, what will you do when it's time to refactor? Supposing > that > someone decides that we in fact need floats rather than ints to > represent > points? Search and replace? Hand editing? That's a good waste of my > time. Worse yet, the approach that's (too) frequently taken is to leave the inconsistency. This, as well as misleading or inaccurate notations introduced by programs for the reasons you mention above -- because there's no universally agreed-upon method of notation and even if there was, engineers don't always remember it off the top of their heads -- means that often enough the notations on the identifiers you're looking at in a block of foreign code are misleading or _wrong_. You're better off actually looking up the definitions of those variables, rather than betting on the Hungarian notation you see being accurate and useful -- which is what you really should be doing anyway. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Guided by the blue light that takes you away / I'm on my way home \__/ Neneh Cherry Maths reference / http://www.alcyone.com/max/reference/maths/ A mathematics reference. From aahz at panix.com Thu May 10 12:46:14 2001 From: aahz at panix.com (Aahz Maruch) Date: 10 May 2001 09:46:14 -0700 Subject: Use of Py_BEGIN_ALLOW_THREADS? References: <3AF6CE77.47FC4228@rfa.org> Message-ID: <9degkm$i4a$1@panix3.panix.com> In article <3AF6CE77.47FC4228 at rfa.org>, Bill Eldridge wrote: >Aahz: >>In article <3AD42A5F.73AE10EC at rfa.org>, Bill Eldridge >wrote: >>> >>>I'm calling a C function from Python, and that C function in turn calls >>>another C function #2 with a C callback function. >>> >>>Somewhere it seems like with threads it disappears - all of the debug >>>messages in function #2 come out, but the C callback never gets called. >> >>So you're saying that this works correctly if you don't use threads? > >I'm saying it works correctly if I have a C main program >instead of a Python main, with the C being as simple as: > >void main() { > call_audio_stuff(); >} Okay, but that's not testing with threads. >I didn't try using the Py_BEGIN_ALLOW_THREADS until >my initial try with a Python main program didn't work. Py_BEGIN_ALLOW_THREADS should only, repeat *ONLY*, be used if you're writing a C extension where it is safe to have multiple Python threads concurrently *executing* in that block of code. Even with that, unless you're a thread wizard, your Python code should never share instances of the objects you're creating (e.g. never share a file object across threads). >>What happens if you have multiple threads, but only one thread calls the >>original C function? My suspicion is that you're getting cross-thread >>contamination in your C code because it isn't thread-safe. > >I can try doing the call_audio_stuff as an individual thread >from Python... Do it. >>Note that you should *ONLY* use Py_BEGIN_ALLOW_THREADS if your code is >>"thread hot"; that is, not just thread-safe, but designed to allow >>multiple threads into the same code at the same time. In the absence of >>Py_BEGIN_ALLOW_THREADS, your C code is considered to be one Python >>bytecode and executes as a single unit. > >How exactly do I make it "thread hot"? Essentially, in a thread-hot code block, there is zero static storage; everything is purely local on the stack or unique malloc'd data. >I'm not specifically sure why I need the threads at all, >as some have indicated to me. Again, the thing that's >failing follows: Well, I don't know why you're using threads, either, but you're definitely doing something screwy if this works unthreaded and fails threaded. -- --- Aahz <*> (Copyright 2001 by aahz at pobox.com) Androgynous poly kinky vanilla queer het Pythonista http://www.rahul.net/aahz/ Hugs and backrubs -- I break Rule 6 "Everyone is entitled to an *informed* opinion." --Harlan Ellison From magnus.heino at rivermen.se Mon May 7 07:45:44 2001 From: magnus.heino at rivermen.se (Magnus Heino) Date: Mon, 7 May 2001 13:45:44 +0200 Subject: Tail... Message-ID: <9d61t8$qed$1@taliesin.netcom.net.uk> How can I know if a file changes? Just like the tail command, I want to know when lines are added to a file, and be able to read them. My first thougt was to use select or something, but I dont get it to work. If I register on POLLIN I get events all the time... :-P /Magnus From tgl at sss.pgh.pa.us Wed May 23 18:45:56 2001 From: tgl at sss.pgh.pa.us (Tom Lane) Date: Wed, 23 May 2001 18:45:56 -0400 Subject: [NOVICE] Re: sequence integrity insite begin-commit? In-Reply-To: <990656235.1454.0.camel@ZOOstation.cc> References: <988808414.28339.0.camel@ZOOstation.cc> <990656235.1454.0.camel@ZOOstation.cc> Message-ID: <22753.990657956@sss.pgh.pa.us> Rob Brown-Bayliss writes: >> So what I am doing is begining a transaction, inserting the data, >> selecting the last_value from the sequence and then commiting the >> transaction. last_value is wrong. currval() will work. See the many prior discussions of sequences in the mailing list archives. regards, tom lane From robin at jessikat.fsnet.co.uk Thu May 24 14:35:10 2001 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 24 May 2001 19:35:10 +0100 Subject: Python 2.0 quick reference... References: <20010523205623.C690@xs4all.nl> Message-ID: I just got the version with dark magenta change lines and rather regret the colour/format changes since the initial release. In particular my default visited link colour is darkmagenta and I think darkmagenta on the steelblue looks less than obvious. Anyhow thanks a lot for this and how do we tell that it has been updated as the 16 May 2001 date didn't change. -- Robin Becker From cobrien at Radix.Net Tue May 1 16:18:17 2001 From: cobrien at Radix.Net (Cary O'Brien) Date: 1 May 2001 16:18:17 -0400 Subject: Sockets: Sending/receiving arbitrary amounts of data References: Message-ID: <9cn5m9$auq$1@saltmine.radix.net> In article , Neil Schemenauer wrote: >Daniel Klein wrote: >> What if the server doesn't know in advance how much data will >> be sent from the client? > >You need to build this into your protocol. A lot of existing >protocols use terminators to signal the end of data like "\r\n" >or something similar. I like using Dan Bernstein's netstring >protocol: > > http://cr.yp.to/proto/netstrings.txt > >Just an example, if you want to send an arbitrary string the >sender would use: > > def write_string(s, sock): > sock.send("%lu:" % len(s)) > sock.send(s) Woops! Are you *SURE* that the python send will retry in the face of short writes? The docs say send returns the number of bytes sent, so you probably need to check the send return value, slice off what was sent, and try again. > sock.send(",") > > data = "Hello World" > write_string(data, sock) > >reciever: > > def read_string(sock): > size = "" > while 1: > c = sock.recv(1) > if c == ":": > break > elif not c: > raise IOError, "short netstring read" > size = size + c > size = int(size) > s = sock.recv(size) You gotta retry the recv() also if your data is bigger than the socket buffering. But someone else pointed this out. -- cary > if len(s) != size: > raise IOError, "short netstring read" > if sock.recv(1) != ",": > raise IOError, "missing netstring terminator" > return s > > data = read_string(sock) > >Obviously the global "sock" must be an open socket connecting the >two programs. Some advantages of the netstring protocal is that >it is efficient, especially for large messages. It makes it much >easier to dynamicly manage memory since the reciever knows in >advance how much data is coming. It is also 8 bit clean which >means you can send arbirary data and do things like embed >netstrings inside of other netstrings. > > Neil > From news at myNOSPAM.org Sat May 12 10:53:47 2001 From: news at myNOSPAM.org (Stephen Hansen) Date: Sat, 12 May 2001 14:53:47 GMT Subject: static attribute References: <9djgnt$570uu$1@hades.rz.uni-sb.de> Message-ID: <%7cL6.38125$mu1.7524622@typhoon.we.rr.com> The class definition is actually in the scope of its methods. In order to access it, you must do something like: class Name: _allNames = {} def __init__(self, name): self.name = name Name._allNames[name] = self HTH, --Stephen (replace 'NOSPAM' with 'seraph' to respond in email) "Uwe Schmitt" wrote in message news:9djgnt$570uu$1 at hades.rz.uni-sb.de... > hi, > > i tried to use a static attribute _allNames as follows: > > > class Name: > > _allNames={} > > def __init__(self,name): > self.name=name > _allNames[name]=self > > > X=Name("Xclass") > > but i get NameError.... whats wrong ? > > yours, uwe > > -- > Uwe.Schmitt at num.uni-sb.de Universit?t des Saarlandes > phone: +49 (0)681/302-2468 Geb. 36.1, Zi. 4.17, PF 151150 > D-66041 Saarbr?cken > http://www.rocksport.de http://www.rocksport.de/first_ride.mp3 > From nessus at mit.edu Wed May 9 20:02:02 2001 From: nessus at mit.edu (Douglas Alan) Date: 09 May 2001 20:02:02 -0400 Subject: Unix [was: do...until wisdom needed...] References: <3dlmo62sfx.fsf@mems-exchange.org> Message-ID: Ben Hutchings writes: > Andrew Kuchling writes: > > (Someday I have to borrow the time machine and incite someone to > > write a free Unix for the 386 when it first came out. Unix + X > > would have been serious competition for Windows 3.x, and we might > > not be in so much of a software monoculture right now.) > Only if Unix had been more compatible with Unix, and with ordinary > human beings. A free and popular Unix would have only had to be compatible with itself. DOS, which was the competition at the time, not Windoze 3.1, was certainly no more compatible with human beings than Unix was. |>oug From aleaxit at yahoo.com Sun May 20 18:05:50 2001 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 21 May 2001 00:05:50 +0200 Subject: ANN: Yats 0.1 References: <3b064fab@dnews.tpgi.com.au> <990384522.941898@rexx.com> Message-ID: <9e9f1u01a2l@enews1.newsguy.com> "Dave Kuhlman" wrote in message news:990384522.941898 at rexx.com... > There is a list of (mostly) Python template systems at: > > http://webware.sourceforge.net/Papers/Templates/ > > Both YATS and DTML (from Zope) should be added to that list. ...and maybe yaptu (says he hopefully), see: http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52305 > Python certainly is rich in this area. Does anyone have any > comments on how these different systems solve slightly different > problems or are better and worse for slightly different tasks? YAPTU serves the purpose of offering a general text-templating (aka text-embedded Python) in a few dozen lines...:-). [OK, so it IS _slightly_ kludgey, but, hey, it IS general and tiny...:-)]. Alex From cg at schlund.de Sun May 27 08:27:49 2001 From: cg at schlund.de (Carsten Gaebler) Date: Sun, 27 May 2001 14:27:49 +0200 Subject: Change dbhash values in place using next() loop? Message-ID: <3B10F2C5.624F87FC@schlund.de> Hi there! I have a DBM file with values formatted like "a:b" where a and b are strings. Every once in a while I'd like to set a=b for every item of the file. I tried the following: import dbhash db = dbhash.open("my.db", "w") while 1: (k, v) = db.next() (a, b) = v.split(":") v = "%s:%s" % (b, b) db[k] = v This works for about half of the items, but the others remain unchanged. Does changing the values change the ordering of the file? Any ideas besides looping over db.keys() (which at the moment is 16 MB in size) or creating a temporary file and then os.system("cp -f temp.db my.db")? Regards Carsten. From nperkins7 at home.com Fri May 11 17:40:32 2001 From: nperkins7 at home.com (Nick Perkins) Date: Fri, 11 May 2001 21:40:32 GMT Subject: Module Browsing? References: Message-ID: pydoc and pydoc.help are exactly what I wanted! ( that's it, I am finally switching to 2.1 for good. ) Thanks, everyone! From nessus at mit.edu Mon May 7 04:25:12 2001 From: nessus at mit.edu (Douglas Alan) Date: 07 May 2001 04:25:12 -0400 Subject: Choosing a programming language as a competitive tool References: <9cvphc$6f0$3@slb4.atl.mindspring.net> <9d49ks02aad@news1.newsguy.com> Message-ID: "Alex Martelli" writes: > "Douglas Alan" wrote in message > > That's not true -- no one would ever even think of teaching Computer > > Science in Perl, > I'm not too sure, although I have no certain knowledge to the > contrary. Okay, well, if you ask me, if they use Perl they are not teaching "Computer Science" when they do so -- they are teaching computer engineering for the insane, or something like that. Perhaps a bit of Perl would be appropriate when teaching about regular expressions, but only by someone who is ignorant as to the fact that there are much better languages out there for such things (e.g., Python). > > Python would also be a good language for teaching Computer > > Science. (Not as good a language as Scheme, though, which is a > > dialect of Lisp.) > So, comparing them as "dialects of Lisp", what do you believe makes > Python not as good as Scheme for teaching CS? Well, I said that Python "is practically a dialect of Lisp" not "is a dialect of Lisp". The reason that Python is not as good for teaching Computer Science as Scheme is, is (1) because Python is not a straight forward translation of lambda calculus into a programming language, the way that Scheme is; (2) because you'd have a hard time using the textbook *Structure and Interpretation of Computer Programs*, which is the only book that should ever be used for teaching Computer Science 101. > But some CS introductory courses might target another kind of > student -- one better served by Python's "prettiness" and ease of > use for many tasks, with the mechanics of OO already built-in rather > than needing to be constructed, but still pretty well "exposed" and > tweakable for didactical purposes. I think for Computer Science 101, it's a wonderful exercise for the student to construct the basics of OO, the way one would do in a course that uses Scheme. > Maybe it depends on how many _other_ CS courses the typical student > of that introductory course is expected to take over his or her > academic career. It may make a difference whether the introductory > course is likely to be just the first of many CS courses, or, at the > other extreme, pretty likely to be the only one, or one of two/three > at most. *Structure and Interpretation of Computer Programs* touches on just about every important concept of Computer Science, and it can be taught in a single semester. This is why it is such an incredible textbook. If you could only take a single course to become a "Software Engineer", this wouldn't be the book to use. If you wanted a single course in "Computer Science", it would definitely be the one. It would also be the best textbook for starting a Computer Science major. |>oug From rnd at onego.ru Fri May 25 10:59:58 2001 From: rnd at onego.ru (Roman Suzi) Date: Fri, 25 May 2001 18:59:58 +0400 (MSD) Subject: Flatten... or How to determine sequenceability? In-Reply-To: <5.1.0.14.2.20010525104111.00aa3d78@pop.openwave.com> Message-ID: On Fri, 25 May 2001, Noel Rappin wrote: > I'm writing code that needs to flatten a multi-dimension list or tuple into > a single dimension list. > > [1, [2, 3], 4] => [1, 2, 3, 4] > > As part of the algorithm, I need to determine whether each object in the > list is itself a sequence or whether it is an atom. Using the types module > would cause me to miss any sequence-like object that isn't actually the > basic type. So, what's the best (easiest, most foolproof) way to determine > whether a Python object is a sequence? What is your definition of sequence-object? Probably you could check if try: s[0] # sequence except: # not sequence > Thanks, > > Noel Rappin Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From tdelaney at avaya.com Sun May 13 20:28:59 2001 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 14 May 2001 10:28:59 +1000 Subject: Python Risk Message-ID: > >> > * Strings may now be enclosed in double quotes as well > as in single > >> > quotes. There is no difference in interpretation. > >> > > >> > I mean, really, who ordered *that*? > >> > >> I don't know, but it makes it easy to put either double > >> quotes or single > >> quotes inside a string, thus: > >> > >> " ' " ' " ' > > > >So you would want to add _all_ that syntax just to save a single '\' > >character in typing . I mean how often do you have > quotes in your > >strings... > > > > This dual quote syntax has saved my b many times. Visual Foxpro > actually allows "xx'xxx" or 'xxxx"xxxxx' or [zzzz"yyy'wwww] > > When building expressions or taking user input sometimes you cannot > expect users not to enter a ' or " in the data. > > E.g. > > select * from file where name="O'Brien" Ah - but what about select * from file where quote="O'Brien quoted "OK"" Won't work. If the user can enter the criteria, you must always assume that they will enter both single and double quotes. So you always need to "fix" the data - for most SQL databases you double the quotes that match the delimiters, and single-quote is the most standard delimiter. So the better select statements there would be ... select * from file where name='O''Brien' select * from file where quote='O''Brien quoted "OK"' Besides, it's more aesthetically pleasing than select * from file where quote="O'Brien quoted ""OK""" Tim Delaney From 045521104 at telia.com Thu May 10 10:49:51 2001 From: 045521104 at telia.com (Martin Johansson) Date: Thu, 10 May 2001 14:49:51 GMT Subject: search in textfiles Message-ID: Hi! Is there any useful modules that I can use for searching for keywords i textfiles and then present the textfiles that have the keywords in them on a homepage? Martin pt00mjo at student.bth.se From Steven_Shaw at adc.com Tue May 15 01:19:32 2001 From: Steven_Shaw at adc.com (Steven_Shaw at adc.com) Date: Tue, 15 May 2001 05:19:32 +0000 (UTC) Subject: Todo.py Message-ID: <4A256A4D.001D4917.00@ssxrgw01.savillemailbr.com> I noticed that at least some todo items at: http://www.python.org/cgi-bin/todo.py?req=all seem to have been completed already. e.g. unicode support and lexical closures Is there a better place to find the todo items for Python? Know of any work in the area of optional static typing and/or compilation to c/objective-c/dylan? cheers, Steve. -- Posted from austpt.lnk.telstra.net [139.130.68.152] via Mailgate.ORG Server - http://www.Mailgate.ORG From akuchlin at mems-exchange.org Wed May 16 11:08:56 2001 From: akuchlin at mems-exchange.org (Andrew Kuchling) Date: 16 May 2001 11:08:56 -0400 Subject: TeX's paragraph breaking algorithm Message-ID: <3ditj1e3g7.fsf@mems-exchange.org> My hack of the week: an implementation of the paragraph breaking algorithm used in TeX, and described in a chapter of Knuth's _Digital Typography_ book. You have an ObjectList class that simulates a list. After filling the sequence with a bunch of Box, Glue, and Penalty objects representing a paragraph, you can get a list of optimal indexes at which line breaks should be inserted. http://www.amk.ca/files/python/tex_wrap-1.00.tar.gz An initial attempt at implementing this failed because I started with the second, more optimized version given in that chapter, and got completely confused. By starting over with the first, simpler and clearer, outline, I actually managed to get it to work. If you have an application for the module, please let me know. I'm planning to try integrating it into Reportlab in place of the existing paragraph-breaking algorithm. A wackier project would be to implement support for .tfm files and .dvi output, and try using Python as a page formatting language. --amk From kens at sightreader.com Fri May 4 16:52:57 2001 From: kens at sightreader.com (Ken Seehof) Date: Fri, 4 May 2001 13:52:57 -0700 Subject: Simple Dictionary Question References: <5.0.2.1.0.20010504115631.00a0c810@thewebsons.com> Message-ID: <00dd01c0d4dc$337122c0$04090a0a@upcast.com> You need to include more of your script (maybe the whole thing). There is no clue about what v is supposed to be, or what i is supposed to be, or what the script is trying to do. BTW, I've got this DNA analysis script with the line: x = z+5 But the protein synthesis algorithm doesn't handle guanine correctly. Why? (:-)) - Ken ----- Original Message ----- From: "Ben Ocean" To: Sent: Friday, May 04, 2001 11:59 AM Subject: Simple Dictionary Question > Hi; > I have this in a cgi script: > >>> > if form.has_key("token"): > if i == "bladename": > bladename = v > if i == "bladephone": > bladephone = v > if i == "bladeemail": > bladeemail = v > if i == "token": > token = v > <<< > Now, if the form has *token* it may have the others; if the others are > present *token* will be as well. For some reason if mare than key *token* > is present, the whole thing falls apart and all the values get set to None. > Why? > TIA, > BenO From lac at cd.chalmers.se Thu May 31 14:17:24 2001 From: lac at cd.chalmers.se (Laura Creighton) Date: Thu, 31 May 2001 20:17:24 +0200 (MET DST) Subject: Python -> C++ compilation Message-ID: <200105311817.UAA02750@boris.cd.chalmers.se> Everything that Courageous says is absolutely true. This is the voice of grim personal experience, here. Laura From BPettersen at NAREX.com Fri May 18 19:03:42 2001 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 18 May 2001 17:03:42 -0600 Subject: Python 2.0 quick reference... Message-ID: <6957F6A694B49A4096F7CFD0D900042F27D3E5@admin56.narex.com> > From: Andrew Kuchling [mailto:akuchlin at mems-exchange.org] > > Simon Brunning writes: > > I'm not familiar with Lynx. Which is consultant-speak for > 'I've never heard > > of it'. Could someone point me at it? (I did a quick > google, but most of the > > links point at some obscure browser.) > > Precisely. I ran the quickref through lynx and put the .txt file at > www.amk.ca/files/python/ . At 110K it's a bit big for Misc/quickref, > though, and while it's readable, it's not optimal for plain text. > Maybe w3m or links can do better? You might want to change the permissions to something more liberal... http://www.amk.ca/files/python/quickref.txt gives me a Forbidden -- you don't have permission error. -- bjorn From aahz at panix.com Thu May 31 13:28:32 2001 From: aahz at panix.com (Aahz Maruch) Date: 31 May 2001 10:28:32 -0700 Subject: Against PEP 240 References: <%a9R6.15145$lP5.7779204@news1.rdc2.pa.home.com> <3B15DDD1.8B49A643@my.signature> <3B1674D8.67690A5A@san.rr.com> Message-ID: <9f5v00$4li$1@panix2.panix.com> In article <3B1674D8.67690A5A at san.rr.com>, Darren New wrote: > >BCD is good for high precision small range. Float is good for lower >precision wider range. Science is generally limited by the number of >significant digits in your real measurements. You can't know how close >that star is down to the inch. Hence, using binary for FP gives you more >precision in the same number of bits. One can have floating-point BCD, which is what I'm currently working on. It's a real pleasure to write 1.2e2346257231235019862340987162305961293865 * 2.0 and get 2.40e2346257231235019862340987162305961293865 Note carefully the mantissa with its trailing zero. -- --- Aahz <*> (Copyright 2001 by aahz at pobox.com) Androgynous poly kinky vanilla queer het Pythonista http://www.rahul.net/aahz/ Hugs and backrubs -- I break Rule 6 "Characters exist to suffer, you know. An author needs a little sadism in her makeup." --Brenda Clough From cherokee at atlantic.net Fri May 11 01:22:00 2001 From: cherokee at atlantic.net (cherokee at atlantic.net) Date: Thu, 10 May 2001 22:22:00 -0700 Subject: freeze problem Message-ID: <3AFB76F8.CBA537DE@atlantic.net> Hello All I have two files: foo.py my python program I want to freeze bar.so a shared object I need to use in foo.py The simple version of foo.py is import bar print "TEST" bar.test() If I run python foo.py it works properly. I need to freeze foo.py with the shared object bar.so. When I run freeze on this guy I get the statement: generating table of frozen modules Warning: unknown modules remain: bar Now run "make" to build the target: foo I have read in the README that this warning is generally tied to python being made using shared libraries, but this is not the case ... python was built using static linking. Does this comment also mean that no extended python code can be frozen? or am I just overlooking something very basic? Thanks From robin at jessikat.fsnet.co.uk Tue May 29 19:52:06 2001 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 30 May 2001 00:52:06 +0100 Subject: Against PEP 240 References: <9f155606df@enews2.newsguy.com> Message-ID: In article <9f155606df at enews2.newsguy.com>, Alex Martelli writes >"Robin Becker" wrote in message >news:XLHUlFB4W$E7EwGh at jessikat.fsnet.co.uk... > ... ... >Tradition and intra-language consistency point in different directions >depending on what other languages you're considering. Besides, I >have oodles of code in languages "used for floating point arithmetic" >that's FULL of decorated literals to specify single-precision or double >precision -- it seems quite traditional for floating-point fans to decorate >their literals with tasteful 'd', 'e', and/or 'f', not to speak 'l' >sometime. so then it ought to be easy for either side and then the default ought to rest with the existing python tradition. >> If we're forced to use 'f' or 'F' I don't mind. We can do double >> precision in the same way ie use 'D'. ... the word here is 'forced' I don't want this and I don't want an easy way into possibly very large computations ie let's use rationals and Newton's method to solve for a root of x^2 = 2 A naive user might expect an exact result. ... > >> The exponentiation notation can then be used by both rationals and >> floats. > >I'd LOVE to be able to write 1e8 to mean 100000000, an int, rather >than having to count zeros... but that may be because of the lira's >notoriously low value, and in a bit more than 6 months we're gonna >switch over to Euros worth 1936.27 liras, so the need may abate:-). if we're allowed this notation it again allows very large computations to be set up with ease eg (1.0e100000000-1)/pi >> Are complex numbers, floats and rationals and ints to be freely mixable? > >I don't see why numeric types should be any less mixable if/when >PEP 240 takes over than they are now. if they are do we get to see/hook the various conversion methods. > > >Alex > > > -- Robin Becker From phd at phd.fep.ru Sat May 12 05:39:01 2001 From: phd at phd.fep.ru (Oleg Broytmann) Date: Sat, 12 May 2001 13:39:01 +0400 (MSD) Subject: Python in Mandrake 8.0 BSDDB broken? In-Reply-To: Message-ID: On Sat, 12 May 2001, Gerhard [iso-8859-1] H?ring wrote: > >This is certainly FAQ. How can I add a FAQ entry? Whom should I contact? > > You could add it to http://python.faqts.com You will have to register, but it's > a matter of a minute. I want Python FAQ to be on python.org. BTW, I've been contacted by the right person. Soon the Q and A will appear in the FAQ (in THE python FAQ on python.org). Oleg. ---- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From grante at visi.com Mon May 7 12:25:04 2001 From: grante at visi.com (Grant Edwards) Date: Mon, 07 May 2001 16:25:04 GMT Subject: xrange question References: Message-ID: In article , Paul Prescod wrote: >John Flynn wrote: > >> Firstly, I can't see how 'xrange' does anything that can't be done more >> efficiently with 'while'. I think xrange must have a purpose I'm not seeing. > >xrange gives you a simple way to do a for-loop over a large array. You >could do a while instead but you can always replace for-loops with while >loops. But for-loops are usually clearer than while-loops because the >one statement does variable declaration, initialization and iteration. Definitely. For the past year or so I've been maintianing C code written by somebody who didn't believe in for() loops. Everything is a while loop: i = 0; while (i Message-ID: On Tue, 22 May 2001, Peter Moscatt wrote: > Python is a Interpreter and not a Compiler, therefore only being able to > develop scripts instead of installable programs. > > Have I got it all wrong here ?? Partly wrong. Yes, Python IS interpreter. No, there is no big difference in scripts vs. "programs". Scripts ARE programs in UNIX/Linux! Oleg. ---- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From dalke at acm.org Mon May 7 12:37:10 2001 From: dalke at acm.org (Andrew Dalke) Date: Mon, 7 May 2001 10:37:10 -0600 Subject: Choosing a programming language as a competitive tool References: <9d3t3901nlq@news1.newsguy.com> <9d5q1m0785@news2.newsguy.com> Message-ID: <9d6j0j$fu3$1@slb7.atl.mindspring.net> Alex Martelli wrote: >"Konrad Hinsen" wrote >> Python lists correspond exactly to what they call lists in >> their daily life! > >Maybe to some of them -- if order is "somewhat important", but >not TOO much. > >> Konrad, who doesn't link items on his shopping lists. > >Suppose for the sake of argument that you do not care at >all about the order of items on your shopping lists. Then, >they're really sets. The platonic ideal of a shopping list is really more like sets, but they are implemented using a list, which is why there are usability problems with order and with duplicates. It's that implementation that more people are used to using. And shopping lists aren't even lists, because I can write them in all sorts of non-linear ways, like: Stuff for cake: flour frosting: powdered sugar cocoa mint(?) ... Pie Apple or cherry? shortening (draw arrow to flour item under cake) So once again, real life analogs break down if you look too close. Andrew dalke at acm.org From aahz at panix.com Thu May 17 07:31:31 2001 From: aahz at panix.com (Aahz Maruch) Date: 17 May 2001 04:31:31 -0700 Subject: inclusive-lower-bound, exclusive-upper-bound (was Re: Range Operation pre-PEP) References: <9dmh8i$qvj$5@216.39.170.247> <3AFF069A.45256580@one.net.au> Message-ID: <9e0cqj$6ct$1@panix6.panix.com> In article , greg jorgensen wrote: > >That's an understatement. The installed base of working C code is vast, >and C is among a handful of languages still in use thirty years after it >was first implemented. s/in use/in widespread use/ and I'll agree with you. -- --- Aahz <*> (Copyright 2001 by aahz at pobox.com) Androgynous poly kinky vanilla queer het Pythonista http://www.rahul.net/aahz/ Hugs and backrubs -- I break Rule 6 "It's such a fine line between stupid and clever." --David St. Hubbins From whisper at oz.nospamnet Thu May 10 14:07:09 2001 From: whisper at oz.nospamnet (David LeBlanc) Date: 10 May 2001 18:07:09 GMT Subject: Python Risk References: <9dc4eq$fb9$1@panix3.panix.com> Message-ID: <9delcd$708$8@216.39.170.247> In article <9dc4eq$fb9$1 at panix3.panix.com>, aahz at panix.com says... > In article , > Tim Peters wrote: > > > >That said, Guido's ability to say "no!" and make it stick is what's kept > >Python Python so far. If he vanished, there would be no lack of programmers > >to keep Python going, but I'm not sure it would remain Python for long. I > >expect it would splinter, with Andrew Kuchling reviving the 1.2 codebase, > >John Skaller merging 2.2 with O'Caml, and Barry Warsaw renaming his variant > >(with builtin Mailman support) to >>thon. > > ...and the Timbot would just keep channeling Guido from beyond the grave. > And of course _his_ version would be python :-) Dave LeBlanc From schmitt at num.uni-sb.de Fri May 25 14:14:04 2001 From: schmitt at num.uni-sb.de (Uwe Schmitt) Date: 25 May 2001 18:14:04 GMT Subject: tkinter and listbox Message-ID: <9em7dc$6baur$1@hades.rz.uni-sb.de> hi, i'm using a listbox which has nubers as entrys. so i'd like to use a fixed width font in this listbox... is this possible ? if yes, how ? yours, uwe. -- Uwe.Schmitt at num.uni-sb.de Universit?t des Saarlandes phone: +49 (0)681/302-2468 Geb. 36.1, Zi. 4.17, PF 151150 D-66041 Saarbr?cken http://www.rocksport.de http://www.rocksport.de/first_ride.mp3 From cribeiro at mail.inet.com.br Tue May 8 18:49:17 2001 From: cribeiro at mail.inet.com.br (Carlos Ribeiro) Date: Tue, 08 May 2001 19:49:17 -0300 Subject: Range Operation pre-PEP In-Reply-To: <20010508161715.D16486@xs4all.nl> References: Message-ID: <5.0.2.1.0.20010508193255.0244a070@mail.inet.com.br> At 16:17 08/05/01 +0200, Thomas Wouters wrote: > > >>> for i in 1 .. 5: > > ... print i > > 1 > > 2 > > 3 > > 4 > > 5 > >I like, though the endpoint is debatable. Maybe Greg W. wants to do some >usage testing ? :) I think the syntax is clear enough to avoid discussions like does-it-start-from-one-or-zero? Let the a..b syntax delimit the range *including* both the minimum and maximum values. BTW it's pretty close to the range syntax in other languages (such as Pascal, for enumerated constants and sets). > > Or in extended form to specify a step: > > > >>> for i in (1, 3) .. 5: > > ... print i > > 1 > > 3 > > 5 > >I don't like this. If anything, it should be the other way 'round >("1 .. (5, 3)") but even better would be something more obvious, such as > >(1 .. 5) % 3 This one is a little bit harder. Where did you take the 3 on the example above? I could not understand the logic of '(1 .. 5) % 3'. I think that the range operator should specify the step; something like '1 .. 5 % 2' is clearer in my opinion. The use of '%' as 'step' operator is highly debatable, though. Why not use any of the characters [!@#$&] ? (if we keep going this way '%' is going to be the most overloaded operator in the history of programming languages :-) > > The new operation ".." generates xrange object > > on by following rule: > >I'd suggest it create an Iterator rather than an xrange object. Iterators >are new in the CVS tree, and will be in Python 2.2. Very neat things ;) Agreed. In fact, xrange could be internally substituted by iterators. As for other types of range constructors: in Pascal, you can use the syntax above to construct ranges for enumerated types or sets. The catch is that only scalar types can be used. This makes sense in Pascal, because the same syntax is also used to specify sets. In Python, similarly, the same syntax could be used (in the future) to implement set libraries. OTOH, ranges built with floats may experience problems caused by the limited precision, so that's a good reason to avoid it. Fixed point decimals don't suffer from the same problems, though, and are a better candidate. Carlos Ribeiro From dsh8290 at rit.edu Sun May 20 14:58:19 2001 From: dsh8290 at rit.edu (D-Man) Date: Sun, 20 May 2001 14:58:19 -0400 Subject: Messaging in Py? In-Reply-To: <990383771.423366@rexx.com>; from dkuhlman@rexx.com on Sun, May 20, 2001 at 06:36:04PM +0000 References: <990383771.423366@rexx.com> Message-ID: <20010520145819.B15876@harmony.cs.rit.edu> On Sun, May 20, 2001 at 06:36:04PM +0000, Dave Kuhlman wrote: | How about SOAP? Isn't SOAP emergining as a dominant protocol for | messaging, for making requests across HTTP, and for Web services? According the the xml-rpc site the xml-rpc guys used to work for MS. They left after sharing the xml-rpc idea. Now they maintain xml-rpc, which is a simple way for using RPC (from the client's perspective, anyways). SOAP is what the other MS guys ended up with after they bloated xml-rpc with excess features. I haven't used either system yet so everything above is hearsay (not my opinion and not my experience; yet ), from the xml-rpc web site. -D From tim.one at home.com Sun May 27 17:41:08 2001 From: tim.one at home.com (Tim Peters) Date: Sun, 27 May 2001 17:41:08 -0400 Subject: Long names are doom ? In-Reply-To: <20010527150003.Z690@xs4all.nl> Message-ID: [Thomas Wouters] > There are basically two choices wrt. allowing reserved words as > vrbl names: > > 1) allow them everywhere, in any situation. ... > ... > 2) Allow them in certain locations only, like calling functions > with keyword arguments, attribute-referencing/assignment and 'def' > statements inside classes (but not outside.) ... > ... > Guido agreed with #2 already (pending implementation). I'm > not sure what his opinion of #1 is, I'll channel him, then: no way. Most keywords in Python serve to distinguish among *kinds* of statements, via the "first word" on a line. If the first word is "def", it's a function definition; if "else", an else stmt; etc. This is helpful for people and simple parsing tools more than for Python's parser. But people and simple tools won't be bamboozled by keywords in, e.g., attribute positions, not any more than they're bamboozled now by keywords inside string literals. As a first cut, you might, e.g., try replacing dotted_name: NAME ('.' NAME)* with dotted_name: NAME ('.' anyname)* anyname: NAME | 'and' | 'assert' | 'break' | ... | 'while' i.e. explicitly list all the reserved words as alternatives in a new more-inclusive NAME-like production. Then see what breaks and fix it . From dimitarh at inktomi.com Fri May 4 20:19:06 2001 From: dimitarh at inktomi.com (Dimitar Haralanov) Date: Fri, 4 May 2001 17:19:06 -0700 Subject: Simple Dictionary Question References: Message-ID: <20010504171906.186e17a0.dimitarh@inktomi.com> I assume that v is the value of the *token* in which case, you have to set it to the value after you make sure that the *token* is there: if form.has_key("token"): v = form["token"].value ... Mitko On Fri, 04 May 2001 11:59:06 -0700 Ben Ocean wrote: > Hi; > I have this in a cgi script: > >>> > if form.has_key("token"): > if i == "bladename": > bladename = v > if i == "bladephone": > bladephone = v > if i == "bladeemail": > bladeemail = v > if i == "token": > token = v > <<< > Now, if the form has *token* it may have the others; if the others are > present *token* will be as well. For some reason if mare than key *token* > is present, the whole thing falls apart and all the values get set to None. > Why? > TIA, > BenO > > From sanner at scripps.edu Mon May 28 13:26:05 2001 From: sanner at scripps.edu (Michel Sanner) Date: Mon, 28 May 2001 10:26:05 -0700 Subject: Tcl interpreter run by Tkinter quits ! Any clue ? Message-ID: Hello, I started working on a Python-Tkinter based vusial programing environment and I am running into the following problem: The whole application quits and I get the following message: TclExecuteByteCode: done instruction at pc 4: stack top 0 != entry stack top-1 Source: "11291968callit"TclExecuteByteCode execution failure: end stack top != start stack top The application is fairly complex, using threading for events queuing, data flow and execution of computational nodes. It is not happening every time :( which makes it hard to debug ! If anyone has (even just a beggining of) a clue I would appreciate it very much. Thanks ----------------------------------------------------------------------- >>>>>>>>>> AREA CODE CHANGE <<<<<<<<< we are now 858 !!!!!!! Michel F. Sanner Ph.D. The Scripps Research Institute Assistant Professor Department of Molecular Biology 10550 North Torrey Pines Road Tel. (858) 784-2341 La Jolla, CA 92037 Fax. (858) 784-2860 sanner at scripps.edu http://www.scripps.edu/sanner ----------------------------------------------------------------------- From notehead2 at hotmail.com Sat May 5 22:48:11 2001 From: notehead2 at hotmail.com (John) Date: Sun, 06 May 2001 02:48:11 GMT Subject: Time objects and ADO References: Message-ID: Okay, I'm part of the way there. I located the mx extensions from Marc Lemburg ( http://www.lemburg.com/files/python/ )that handle COM dates. Here is what I am doing now. All this works the way I want it to functionality-wise, but the type check part is a hack: item = recordset.Fields.Item(j).Value # There has to be a better way to tell the type # of the time object than this!!! # Seems like this should be the way to do it, but it doesn't work... # if type(item) is DateTimeType: if str(type(item)) == "": # Use the string representation of the time item = str(DateTimeFromCOMDate(item)) Any help on figuring out how to do the type check would be much appreciated. -John "John" wrote in message news:CG1J6.231$Hw5.25353 at newsread2.prod.itd.earthlink.net... > Hi, > > I'm reading in records from an ADO recordset and putting each field in a > Python list. > > When I print out the list, the datetime fields from the ADO recordset print > out like this...