From bkelly at sourcereview.net Thu Mar 20 03:11:14 2003 From: bkelly at sourcereview.net (Brett Kelly) Date: Thu, 20 Mar 2003 08:11:14 GMT Subject: Install Python-2.1.3 problem References: <500532df.0303192336.53c450d0@posting.google.com> Message-ID: On Wed, 19 Mar 2003 23:36:22 -0800, Albert wrote: > I download the open source Python-2.1.3 from Python home page. My > platform is RedHat 7.2 .After uncompress, I type " python setup > install" The following word displayed : > File "setup.py", line 57 > extlist = [ext for ext in extlist if ext.name == modname] > ^ > SyntaxError : invalid syntax > > how to solve it? You might consider getting the current stable version of python (2.2) -- Brett Kelly bkelly at sourcereview.net http://inkedmn.homelinux.org From neal at metaslash.com Sat Mar 22 14:42:37 2003 From: neal at metaslash.com (Neal Norwitz) Date: Sat, 22 Mar 2003 14:42:37 -0500 Subject: int to string conversion: newbie question References: Message-ID: On Sat, 22 Mar 2003 14:16:59 -0500, Kristofer Wouk wrote: > I know I'm dumb, but I can't figure this out. How do I convert from > an int to a string? Take your pick: >>> '%s' % 53 '53' >>> str(53) '53' >>> '%d' % 53 '53' Neal From peter at engcorp.com Thu Mar 13 15:37:49 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Mar 2003 15:37:49 -0500 Subject: How do I check for pending UDP input? References: <3e70e58f@news.nz.asiaonline.net> Message-ID: <3E70EC1D.557A4E4F@engcorp.com> Colin Brown wrote: > > Hi, I am developing a multi-process application for theatrical lighting > using Python and communicate between processes via UDP. > > I need to keep some of the connections asynchronous and need to > be able to either get the last packet sent or return an empty string. > > My current code uses select with a small timeout to read in outstanding > packets until a timeout occurs returning the previous packet read if any. > > This is not elegant. Does anyone have experience with using SIOCINQ > and IOCTLS in Python to find if a datagram is pending? What's not elegant? Select should return instantly when the socket on which you are waiting becomes "readable" (as opposed to how you appear to describe it, where it always waits until the timeout before returning). This is the accepted way of doing this sort of thing, so you should probably redefine "elegant" and be happy. :-) -Peter From me at privacy.net Tue Mar 18 20:22:42 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Wed, 19 Mar 2003 13:22:42 +1200 Subject: Witch globalizacion (was: RE: Recommended Linux Laptops, supp liers?) In-Reply-To: References: Message-ID: sismex01 at hebmex.com wrote: >>...And to think there are people busy >>protesting against "globalization"... *WICH* globalization?!... >> >>Alex > > "Witch" globalization. Salem is a global village now? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From mis6 at pitt.edu Tue Mar 18 09:56:46 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 18 Mar 2003 06:56:46 -0800 Subject: PEP 312 (and thus 308) implemented with a black magic trick References: <2259b0e2.0303171358.5a6fe337@posting.google.com> <3E766255.5D06489A@alcyone.com> Message-ID: <2259b0e2.0303180656.77027337@posting.google.com> "Sean Ross" wrote in message news:... > Hi. > > "Erik Max Francis" wrote in message > news:3E766255.5D06489A at alcyone.com... > > > > How does this suggestion different from the use of a single colon in PEP > 312, ... > > > Actually, it wasn't a suggestion, it was merely a hack. The OP was just > trying to see if it could be done, > as they stated in their post... > > "Michele Simionato" wrote... > > I am not suggesting it. This is simply a proof of concept. > > They were not suggesting an alternative syntax to PEP312, they were playing > around with code. > '~' just happens to be easier than ':' to intelligently isolate and replace > in Python code because it > has fewer possible uses/meanings. > Beside that, there is the problem that ":x" is not a valid Python expression, whereas "~x" is grammatically correct. Using ":x" would give a syntax error, using "~x" makes happy the interpreter, instead. At this point my truly evil metaclass can fool it ;) continuing-to-explore-Python-dark-side-ly yours, Michele From aleax at aleax.it Sun Mar 23 05:51:25 2003 From: aleax at aleax.it (Alex Martelli) Date: Sun, 23 Mar 2003 10:51:25 GMT Subject: A library approach to the ternary operator References: Message-ID: David Abrahams wrote: ... >> somewhat important to pick a better name for the function...!). >> Another likely name might be "pick". > > y = choose(x < 0 and [22.5] or [f(x)]) > y = ternary(x < 0 and [22.5] or [f(x)]) > y = pick(x < 0 and [22.5] or [f(x)]) > y = cond(x < 0 and [22.5] or [f(x)]) > y = if_(x < 0 and [22.5] or [f(x)]) > > I guess I like the last two, and the last one best of all, because > in my mind there's a nice association between the function name and > the adjacent condition. My preferences differ -- using an ordinary, well-pronounceable English word such as 'choose' or 'pick' seems to make for clearer and more readable code than arbitrary abbreviations such as 'cond' for 'conditional' (no doubt familiar to LISPers, but, since the function's workings are SO different from Lisp's COND, I do not think the familiarity is necessarily an advantage) or things such as 'if_', hard to pronounce distinctly from keyword 'if'. Of the above proposals, I think 'choose' would probably make it likeliest that the function becomes widely used, 'if_' would probably make it least likely. Matter of opinions, of course. >>> to be worth using. Having a function name ("select") there gives us >>> something to attach a nice verbose comment to, while the above, since >>> it uses only language primitives, remains obscure. >> >> Yes, I concur. Moreover, this ternary.py can easily be widely >> spread and popularized > > or spurned, as the case may be ;-) Yes, if people don't like it they won't use it, and need never even bother to learn it -- it gives Pythonistas a chance to make their choices in the matter entirely. That's part of why I like it. >> to establish a usage base for 'choose' IF people like the approach >> (I'm not gonna guess if they will) -- this may help make a case for >> 'choose' as a built-in, later, if and only if people like and use it >> so much as to warrant that. > > It's always nicer to have a transition plan that goes through a > library-only approach first without making core language changes. > That gives the concept a chance to live or die on its own without > forcing people to accept more than they can stomach. Exactly! Well put. Alex From a.schmolck at gmx.net Mon Mar 17 16:24:07 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 17 Mar 2003 21:24:07 +0000 Subject: OT: Aspergers link References: <4fm07vg66gr4o4c74gb7ie5v85vlom1vhf@4ax.com> <0vv17v4vn4khffgr2io0otrnni8sc6rug7@4ax.com> <%dica.80722$zo2.2065641@news2.tin.it> <7f2b571b.0303161642.320e0997@posting.google.com> Message-ID: Carl Banks writes: > > It is real. The primary reason to understand this is that, if > > two people who both have Asperger's Syndrome have children, there > > is a statistically higher rate of autism. > > If that's the *best* reason you can come up with that Asperger's is a > disease and not a strong personality type, then you are standing on > weak grounds indeed. > > I don't doubt what you've said true, but simply having a predisposition to > having autistic children doesn't mean you have a mental illness. Some > people have a predisposition to have children with Down's Syndrome. Does > that mean they have a mental disease? No. Your counter example has an entirely different logical structure. alex From LogiplexSoftware at earthlink.net Tue Mar 18 13:09:03 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 18 Mar 2003 10:09:03 -0800 Subject: OT: Recommended Linux Laptops, suppliers? In-Reply-To: <15991.23384.738422.39519@montanaro.dyndns.org> References: <017701c2ecff$f3ee94f0$21795418@dell1700> <1048006236.1107.158.camel@software1.logiplex.internal> <15991.23384.738422.39519@montanaro.dyndns.org> Message-ID: <1048010943.1107.179.camel@software1.logiplex.internal> On Tue, 2003-03-18 at 09:46, Skip Montanaro wrote: > >> That would be better. At least that would have firewire too :-) > > Cliff> In the PC world, firewire is more of a convenience than a > Cliff> necessity. Especially with USB 2.0. My Gf's Dell has firewire > Cliff> and it collects dust bunnys. > > Cliff, you obviously don't have an iPod... ;-) Those are pretty cool. I've been looking at those little 10GB MP3 players that double as USB HDD's. Not quite as cool as the iPod, but at least they'll work with Linux... -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From dcengija_remove_ at inet.hr Mon Mar 31 10:36:32 2003 From: dcengija_remove_ at inet.hr (Davor Cengija) Date: Mon, 31 Mar 2003 17:36:32 +0200 Subject: Is Python overhyped (just like Java)? References: Message-ID: <8268913.kGbvMSBJ7B@lothar.cengija.com> Roy Smith wrote: > abpillai at lycos.com (Anand B Pillai) wrote: >> [Python] is a true object-oriented language in the spirit of >> Smalltalk/Java whereas C++ is not one. > > I'm all for C++ bashing, but in what way do you think C++ is not "a true > object oriented language"? I've heard C++ guys bash Python as not > object oriented because Python doesn't support private data. "You mean > I can bypass the accessor functions and touch an object's data > directly!?" That was the first question I asked myself when switched from java to python. It does feel a little bit strange to be able to dig through the objects without any limits, but finally, clear documentation is the way to go ("Private. Don't use directly"). After all, it is posible to reach private data in java objects as well, by using reflection (some limitations apply, but it's completelly off-topic here). Davor -- Davor Cengija, dcengija_remove_ at inet.hr From s at hotmail.com Mon Mar 3 13:29:16 2003 From: s at hotmail.com (Stephan) Date: Mon, 03 Mar 2003 19:29:16 +0100 Subject: IOError - Errno 5 Message-ID: Hi, Does someone know what this means: Error Type: IOError Error Value: [Errno 5] Input/output error It happens when writing to 'sys.stderr'. I see that I have problems writing, but I can't figure out what this 'Errno 5' really wants to tell me. Maybe you can point me to a list of all these reason-codes. Have looked for myself but not found anything. Thanks a lot! Stephan From whisper at oz.net Sat Mar 8 18:38:21 2003 From: whisper at oz.net (David LeBlanc) Date: Sat, 8 Mar 2003 15:38:21 -0800 Subject: Recommended Linux Laptops, suppliers? In-Reply-To: <3e6a571b$1_1@spamkiller.newsgroups.com> Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Brad Clements > Sent: Saturday, March 08, 2003 12:46 > To: python-list at python.org > Subject: OT: Recommended Linux Laptops, suppliers? > > > Sorry this is OT > > I'm looking to buy a notebook/laptop. I would like to run Linux on it. I > don't want to buy a notebook with Windows installed. I don't want > to pay for > that OS since I'm just going to discard it. If you don't object to Lindows (I do), they're selling an inexpensive Linux laptop - $800! www.lindows.com > -- > > I have a Toshiba Tecra 720CDT that I'd like to replace, I paid an > incredible > amount for it years ago.. cutting edge, etc. :-( Why not put Linux on the Tecra? There is also the theory that if you never run the MS OS product on the machine you buy, you can get a refund of the license fee. Don't recall all the details, but you must have never run it or accepted the EULA or some such nonsense. David LeBlanc Seattle, WA USA From m.winter at auckland.ac.nz Wed Mar 5 21:29:46 2003 From: m.winter at auckland.ac.nz (Markus Winter) Date: Thu, 06 Mar 2003 15:29:46 +1300 Subject: How does Python compare with RealBasic? Message-ID: Hi all, I've just started programming in RealBasic and now came across Python (mainly because a molecular visualisation app I'm interested in is using Python as it's script language). I intend to write my first program (a DNA sequence analysis program) and wondered how Python compares to RB ... Thanks for any advice. Best Regards Markus -- Dr. Markus Winter Tel: 0064 (0)9 373 7599 (wait for message then type extension) 83960 \\|// (o o) -. .-. .-oOOo~(_)~oOOo-. .-. .-. .-. .-. .-. .-. .-. .-. .-. ||X|||\ /|||X|||\ /|||X|||\ /|||X|||\ /|||X|||\ /|||X|||\ /|||X|||\/|||X\ |/ \|||X|||/ \|||X|||/ \|||X|||/ \|||X|||/ \|||X|||/ \|||X|||/ \|||X|||/ ' `-' `-' `-' `-' `-' `-' `-' `-' `-' `-' `-' `-' `-' `-' From jwbaxter at spamcop.net Fri Mar 14 20:38:08 2003 From: jwbaxter at spamcop.net (John Baxter) Date: Fri, 14 Mar 2003 17:38:08 -0800 Subject: P.E.P. 3.0.8 ??? References: Message-ID: In article , "Tim Peters" wrote: > For monumental decisions like > this, he likes to wander in the Amsterdam desert, fasting for 40 days first. AARGH...that would seem to *invite* being hit by a bus. Wander carefully, Guido! --john From aleax at aleax.it Tue Mar 25 04:22:21 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 25 Mar 2003 09:22:21 GMT Subject: Understanding sockets? References: Message-ID: G wrote: > Hi Dennis, > > thanks, > your code works. > however, it does not work if the client is indefinitely running. > i would like to have a client that is always running and continually > sending and receiving messages from the server. i do not know > how to do this using sockets. Sockets come in two kinds and neither serves your expressed purposes directly. STREAM sockets, the usual kind, have no concept of "message": an open socket lets you push a stream of bytes to the counterpart, and/or get some bytes that the counterpart has pushed onto you, but there is no concept of any "message boundary" intrinsic in it -- so you'll have to superimpose such boundaries by layering some higher-level protocol upon the stream-sockets. DATAGRAM sockets do have a concept of "message" -- a finite set of bytes being sent and received -- *BUT* they do not guarantee sequencing and reliability -- datagrams may arrive in an order different from the one in which they were sent, and may even fail to arrive altogether without any notification to you of that. So, if you want to build upon datagram sockets, again you need a higher-level protocol, this time to acknowledge message receipt and possibly sequencing, resend when an ack fails to arrive, ignore duplicate copies of the same msg, etc. This is much more complicated than just marking message boundaries, so, in practice, don't do it -- use datagrams only when reliability and sequencing issues are livable with. In practice, you're almost invariably better off looking for already-existing protocols built on top of stream sockets and programming to those. Most often you can find existing implementations of such protocols in Python, either in the standard library or freely available for downloading. But, to pick the right protocol for your purposes, such purposes need to be better described than you have done so far. Alex From max at alcyone.com Tue Mar 11 22:16:33 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 11 Mar 2003 19:16:33 -0800 Subject: "Tuples are for heterogeneous data, lists are for homogeneous data." References: Message-ID: <3E6EA691.E0E30AFC@alcyone.com> Arthur wrote: > The subject line is a Guido quote from today's dev list. > > Is the point Guido making performance related, or is it something > else? I > have used lists extensively for heterogenous data, and wonder what it > is I > am losing by so doing. Nothing, it's just a style guideline. I'm aware of no optimizations that would provide a penalty for not using lists/tuples in this way. I tend to use tuples for either data that have a fixed number of elements (like coordinates, if I don't represent them with separate attributes), or for data that have a fixed number of (or easily found pattern of) elements but contain heterogeneous data (like the first is an int, the second is a string, the third is an object of some class). -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Who, my friend, can scale Heaven? \__/ _The Epic of Gilgamesh_ EmPy / http://www.alcyone.com/pyos/empy/ A templating system for Python. From matthew at newsgroups.com Sun Mar 30 19:54:54 2003 From: matthew at newsgroups.com (matthew) Date: Mon, 31 Mar 2003 12:54:54 +1200 Subject: Plex question (self.answered so ignore) In-Reply-To: References: Message-ID: self.state_name. matthew wrote: > Hi, > > I'm using Greg Ewing's Plex (v.cool) but for the life of me I can't > figure out how to get the name of the current state. Any help much > appreciated. Thanks. matthew. > > class PPF_Scanner(Scanner): > > def event_end(self, scanner): > > for func in callbacks[current_state_name]: > etc... > self.begin('') > > try: > lexicon = Lexicon([ > # EVENT: Position > (Str("(0)"), Begin('position')), > State('position', [ > (Any("XxYy") + coordinate, set_coordinate), > (Any("Tt") + turret_pos, set_turret_position), > (whitespace, IGNORE), > (eoln, event_end) > ]), etc... > From LogiplexSoftware at earthlink.net Mon Mar 17 18:50:17 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 17 Mar 2003 15:50:17 -0800 Subject: OT: Recommended Linux Laptops, suppliers? In-Reply-To: <3e6a571b$1_1@spamkiller.newsgroups.com> References: <3e6a571b$1_1@spamkiller.newsgroups.com> Message-ID: <1047945017.1108.54.camel@software1.logiplex.internal> On Sat, 2003-03-08 at 12:45, Brad Clements wrote: > Sorry this is OT > > I'm looking to buy a notebook/laptop. I would like to run Linux on it. I > don't want to buy a notebook with Windows installed. I don't want to pay for > that OS since I'm just going to discard it. > > I see that Microsoft still has a lock on the big-brand manufacturers, and I > haven't found any (Dell, Toshiba, Sony, HP, etc..) that will ship a notebook > with Linux on it (or no OS at all). > > Apple's are pretty much out of the price range, and I prefer an Intel/AMD > box anyway. Though, I do like the new Apple notebooks :-( > > So, can anyone suggesting a white-box manufacturer of notebooks that aren't > crap, don't weigh more than 8 lbs, run more than 2 hours on battery? You might take a look at these: http://www.qlilinuxpc.com/products/laptops/index.html http://www.emperorlinux.com/ http://www.aslab.com/products/laptops/laptops.html -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From whale at mycameo.com Mon Mar 24 23:49:42 2003 From: whale at mycameo.com (whale) Date: 24 Mar 2003 20:49:42 -0800 Subject: Apache mod_python problem? Message-ID: <457a5e09.0303242049.58916675@posting.google.com> I use Apache2.0.44 and mod_python3.0.1. I add ProxyPass and PythonHandler directives in httpd.conf ## httpd.conf ProxyPass /test/ http://www.test.com ProxyPassReverse /test/ http://www.test.com AddHandler python-program .htm .html PythonHandler mptest And mptest.py: from mod_python import apache def handler(req): req.write('Hello!!') return apache.OK ex. My apache server is www.server.com. When I browsed the local server request(ex. http://www.server.com/1.html), I received 'Hello!!' response, the python handler worked well. But when I browse the proxy request(ex. http://www.server.com/test/1.html), the response I received is the original content of http://www.test.com/1.html, not 'Hello!!'. The proxy requests didn't seem to be processed by mod_python handler. How could I pre-process the proxy request before mod_proxy module? Thanks a lot!! From rdavis at lulupress.com Thu Mar 27 20:14:05 2003 From: rdavis at lulupress.com (Rich Davis) Date: Thu, 27 Mar 2003 20:14:05 -0500 Subject: __import__ woes In-Reply-To: <20030328011801.24753.33823.Mailman@mail.python.org> References: <20030328011801.24753.33823.Mailman@mail.python.org> Message-ID: <3E83A1DD.8000403@lulupress.com> Ok, I'm trying a "Hello World" Python/C API test. When I try the following, mod is null. PyObject *modname, *mod, *mdict, *func, *stringarg, *args, *rslt; Py_Initialize(); modname = PyString_FromString("test"); mod = PyImport_Import(modname); When I try to "__import__" from the command-line like >>> __import__("test") >>> test.doIt("test string") Traceback (most recent call last): File "", line 1, in ? NameError: name 'test' is not defined >>> it doesn't seem to work. However, "import" does. >>> import test >>> test.doIt("test string") test string >>> Can anyone point me in the right direction to a)get __import__ to work, so I can b) get PyImport_Import() to work. Thanks, Rich From none at of.your.business Fri Mar 14 00:45:00 2003 From: none at of.your.business (lynx) Date: Fri, 14 Mar 2003 00:45:00 -0500 Subject: How to change font size in IDLE? References: Message-ID: On Fri, 14 Mar 2003 00:49:58 +0000, wangjc wrote: > The default font size in IDLE is too small. if you're on a unix-like system, this might work: $ cat >> $HOME/.idle [EditorWindow] font-name= courier-new font-size= 14 ^D -- PGP/GnuPG key (ID 1024D/3AC87BD1) available from keyservers everywhere Key fingerprint = FA8D 5EA4 E7DC 84B3 64BC 410C 7AEE 54CD 3AC8 7BD1 "...if you can fill the unforgiving minute with sixty seconds' worth of distance run..." From do-not-spam-ben.hutchings at businesswebsoftware.com Tue Mar 18 05:22:10 2003 From: do-not-spam-ben.hutchings at businesswebsoftware.com (Ben Hutchings) Date: 18 Mar 2003 10:22:10 GMT Subject: Finding child pids References: Message-ID: In article , Bernhard Herzog wrote: [re popen] > Don't use a string. Use a list of strings with one string for each > argument. E.g. instead of > > "mycommand arg1 arg2" use ["mycommand", "arg1", "arg2"] > > This has the additional benefit that you don't have to worry about > quoting. Aha! Unfortunately this does not appear to be documented. (In fact I don't see any documentation of the type of the command given to popen.) From des.small at bristol.ac.uk Fri Mar 21 08:53:25 2003 From: des.small at bristol.ac.uk (Des Small) Date: Fri, 21 Mar 2003 13:53:25 GMT Subject: What's up with rebinding assignment? References: Message-ID: Beni Cherniavsky writes: > Once upon a time, Just threw in a great (IMHO ;-) idea on pytohn-dev: > > http://mail.python.org/pipermail/python-dev/2003-February/032764.html > > The idea was to add am ``:=`` rebinding operator, one that changes a > visible binding without making it local to the current scope:: > > def bind(): > x = 1 > def rebind(): > x := 2 > rebind() > print x > > would print 2. I dislike this syntax a great deal, but I have pined for an outer-scope mutating facility ever since scopes went lexical. There are many idioms (in, say, Lisp, but don't say that too loud) that naturally exploit such a device - it's at the heart of what a lot of people mean by 'closures'. Since 'global' already exists to declare non-default scope for a variable, I would propose the alternative, with your example: def bind(): x = 1 def rebind(): lexical x x = 2 rebind() print x where 'lexical' just hooks to the innermost use of a variable that isn't itself declared lexical. I wouldn't use it here though, I'd use it for things like: def accumulator(val=0): def inner_acc(amount): lexical val val = val + amount # I don't like +=, so there. return val return inner_acc(val) Since I don't expect the Python Priesthood (Bot-hood?) to be pleased about this, I would want to market it as a less harmful version of 'global'. It does do much the same thing, after all, and has much the same conventions. > My question is: is there a chance this will make it into Python? > Nobody seems to have noticed it... Will a PEP help? I don't know how the politics works, but Alex Martelli has said that the best way to get stuff in is to make an idea visible and hope that Someone Important adopts it like unto their own brainchild. Naively, if we hang around discussing this ("Operator, Lisp luser!" "Keyword, C++ buffoon!") for a bit maybe we'll attract some attention. Des. > > -- > Beni Cherniavsky > -- Des Small / Scientific Programmer/ School of Mathematics / University of Bristol / UK / Word falling / Image falling From me at privacy.net Mon Mar 17 22:40:05 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 18 Mar 2003 15:40:05 +1200 Subject: Question about embedding Python In-Reply-To: References: Message-ID: Del Iablo wrote: > In order to do this I've tried encapsulating the Python variables inside a > script variable structure in the C++ code, called ScriptVariable. This > struct contains a PyObj pointer to the variable in the dictionary. I can > then do runtime conversion (e.g., PyInt_AsLong) to get the value. You haven't got a pointer to the variable, you've got a pointer to the current *value* of the variable. More precisely, you've got a reference to the object currently associated with a particular key in the dictionary. When you "change the value of the variable", you're associating that key with a different object. But your C pointer is still referring to the object which was previously associated with that key. > If I do not re-get the pointers to the variables before attempting to cast > them, the program crashes As has been pointed out, this could be due to your not incrementing the reference count of the object. But even if you fix that, the above problem will remain. > I'd like to avoid doing the dictionary lookup every time if possible. Am I > just stuck doing it every time? Yes. The only way to find out what object is currently associated with a key in a dictionary is to look it up. There's no getting around that. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From andersjm at dancontrol.dk Tue Mar 4 06:24:17 2003 From: andersjm at dancontrol.dk (Anders J. Munch) Date: Tue, 4 Mar 2003 12:24:17 +0100 Subject: Why no RE match of A AND B? References: <3E6270DC.3060904@tiscali.co.uk> <_Fw8a.106840$Hl6.9851028@news010.worldonline.dk> <3E629E43.D8661813@alcyone.com> <3E62A8BD.BB7A7CA6@alcyone.com> <3e6317e7$0$16108$edfadb0f@dread11.news.tele.dk> <3E6321E3.C43FBAF2@alcyone.com> <3e63441f$0$16163$edfadb0f@dread11.news.tele.dk> <3E63B0C5.EEA2A1EC@alcyone.com> Message-ID: <3e648ca6$0$16153$edfadb0f@dread11.news.tele.dk> "Erik Max Francis" wrote: > "Anders J. Munch" wrote: > > > Taking statistical evidence from a hypothetical scenario, hm. > > It's a judgement call. > > > How can one miss what one doesn't know? > > Well, since I keep saying in the parts that you're clipping, I won't > bother repeating myself again. I'm sorry, I don't follow you. If you have written something earlier that addresses "How can one miss what one doesn't know?" then I am unable to find it. - Anders From dagurp at heimsnet.is Thu Mar 13 07:06:04 2003 From: dagurp at heimsnet.is (=?ISO-8859-1?Q?Dagur_P=E1ll_Ammendrup?=) Date: Thu, 13 Mar 2003 12:06:04 +0000 Subject: py2exe and ftplib Message-ID: Hi! I made a script that among other things allows you to upload files with ftp. It works fine but if I compile it to .exe with py2exe I get this error when trying to upload: exceptions.AttributeError'NoneType' object has no attribute 'sendall' Any ideas? -Dagur From piet at cs.uu.nl Mon Mar 24 16:09:36 2003 From: piet at cs.uu.nl (Piet van Oostrum) Date: 24 Mar 2003 22:09:36 +0100 Subject: xml.dom.minidom on os x References: <20030323215111818+0100@news.freenet.de> Message-ID: >>>>> Sascha Ernst (SE) wrote: SE> hello, SE> i tried the following code, a code example from the Python Library SE> Reference, and just get the message "failed". there seems to be no SE> problem importing xml.dom.minidom or using parseString(). i compiled SE> python 2.2.2 myself on os x 10.2.4 without any flags for ./configure For me it works (also python 2.2.2 on OSX 10.2.4, but compiled on 10.1.5). Python 2.2.2 (#1, Oct 17 2002, 12:05:06) [GCC 2.95.2 19991024 (release)] on darwin -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From antonmuhin at sendmail.ru Thu Mar 6 11:46:35 2003 From: antonmuhin at sendmail.ru (Anton Muhin) Date: Thu, 06 Mar 2003 19:46:35 +0300 Subject: python vs. perl readability In-Reply-To: References: Message-ID: Hilbert wrote: > Hello, > > A friend of mine uses perl at work, I'm converting > to python. I've showed him a couple of times how > much easier it is to read python code than perl, but > last night he sent me this: > (I know it's ajoke, just wanted to share...) > > > ------- > import sys > > z,x,y= "}{|}A|k{|kA|}=BE1)|BF}))|$}:~pI~/;@Go{H%{&A?|if }:~pJ"\ > "IJ-1~#>=0:GoAG at HG;o{G;%-I&{?|m,kJ,j=C?;/@~o{~D:Gl[c]("\ > ")?","G$p:%~;%~;el!]':p%break~;![':p%# "%if c=='%while o%\n%m[k]%+=1%\t%if not %c=j[o]%-=1%sy"\ > "s.std%[0]*64000,0,0,open(sys.argv[1]).read()%if l.has"\ > "_key(c)%in.read(%out.write(chr(%=1%,o".split('%'),"HG"\ > "&%/~!#?}{;$@ABCDEFIJ" > > for i in range(len(x)):z=z.replace(y[i],x[i]) > z=z.split('|') > for o in range(9): > exec("def %c():\n\tglobal k,m,o,j\n\t%s\n"%(chr(97+o),z[o])) > l={'>':c,'<':d,'-': b,'+':a,',':e,'.':f,'[':g,']':h} > i() > ------------------------------ > > > Hilbert > > Another recipe: 1. Write some small script in Python. 2. zip it. 3. Convert into string. 4. Place this string into new script. 5. Unzip it and call eval. Anton. From imbosol-1047165134 at aerojockey.com Sat Mar 8 18:34:50 2003 From: imbosol-1047165134 at aerojockey.com (Carl Banks) Date: Sat, 08 Mar 2003 23:34:50 GMT Subject: Shelve doesn't appear to restore references properly???? References: <9418460a.0303081459.761325e6@posting.google.com> Message-ID: Muppet wrote: > Ok. This is a little fiddly to describe, so I'm going to describe it > and then show some sample code. > > The problem is that references between objects do not appear to work > properly in shelve. When restoring from a shelve, objects which are > shared in the original data appear to come back unshared - that is, > where there was one object originally, after being restored from a > shelf there are many identical copies. > [snip] > > Now, I'm trying to figure this out: is that the correct behavior? A shelved object cannot share data with another shelved object. That is a known and accepted limitation of shelves, and, because of how shelves work, is not likely to go away. > Am I > doing something stupid (source code below)? Is there any easy way of > restoring state *fully*, so that information encoded as which objects > are shared between other objects is also restored? Yes, you can pickle a dict. See the cPickle module. I daresay you should have done it that way from the start: unless there are too many muppets to fit in memory, or you need fast lookup of only a few items, there is not much benefit of a shelf over a pickle. (Because the objects share data, the latter possibility seems unlikely to me.) Nevertheless, you know your code better than I. If pickling a dict won't do, then you can work around the limitation of shelve using the __getstate__ and __setstate__ methods. I will be happy to elaborate if you wish. -- CARL BANKS From max at alcyone.com Wed Mar 19 17:15:20 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 19 Mar 2003 14:15:20 -0800 Subject: Does Python do try: except: finally: ? References: <20030319135147.A1830@ash.int.ca.pason.com> Message-ID: <3E78EBF8.5C59646F@alcyone.com> Joseph Wilhelm wrote: > >>> try: > ... print "Foo" > ... except: > ... print "Oof" > ... else: > ... print "Bar" > ... > Foo > Bar > >>> > > That what you need? Probably not: >>> try: ... print 'foo' ... raise ValueError ... except: ... print 'oof' ... else: ... print 'bar' ... foo oof The else clause is only executed in the case where there's no error, quite contrary to what is usually intended by a try..except...finally clause. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Patriotism is the virtue of the vicious. \__/ Oscar Wilde Bosskey.net: Counter-Strike / http://www.bosskey.net/cs/ A personal guide to Counter-Strike. From gustav at morpheus.demon.co.uk Thu Mar 6 15:35:10 2003 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: Thu, 06 Mar 2003 20:35:10 +0000 Subject: Thread processing References: <8yvty3v0.fsf@morpheus.demon.co.uk> <3e671efd$0$31961$edfadb0f@dread12.news.tele.dk> Message-ID: "Anders J. Munch" writes: > "Paul Moore" wrote: >> >> I can use a Queue to have the threads notify when they have finished, >> but that means rewriting the thread procedures to do the notification, >> which isn't really what I want. > > Don't rewrite. Wrap. > [...] > > Write all the logic for collaboration with the main thread just once > in wrapped_threadprocedure, and you can keep the individual thread > procedures simple and framework agnostic. Doh. This just proves I was getting so wound up over this that I wasn't thinking straight. I really should have known how to do something like this. Thanks for pointing out the obvious... Paul. -- This signature intentionally left blank From paddy3118 at netscape.net Thu Mar 6 14:04:12 2003 From: paddy3118 at netscape.net (Paddy McCarthy) Date: 6 Mar 2003 11:04:12 -0800 Subject: Books Database References: Message-ID: <2ae25c6b.0303061104.55f1b6d@posting.google.com> Eliran Gonen wrote in message news:... > Hello ! > > I want to ask you what do you think is the best way to keep > a list of books with other data (such as year and author) in a > file ? > > And what way should be used to parse it ? > > Is something like: > > <.database> > > name=Example > author=Somedood > year=1969 > > name=Wuffy > author=Puffy > year=2010 > > ....etc > > > Is alright ? > > Thanks ! You've already got some good answers, I'd second YAML and also ask you to take a look at PYX, (http://www-106.ibm.com/developerworks/xml/library/x-matters17.html) It is easier to write than XML but can express what XML can. It also has Python support. Cheers, Pad. From pwatson at redlinec.com Mon Mar 3 19:26:58 2003 From: pwatson at redlinec.com (Paul Watson) Date: Mon, 3 Mar 2003 19:26:58 -0500 Subject: basename and .ext Message-ID: I would like to see os.path.basename() have an optional second parameter for a filename extension. This would be more similar to the UNIX basename command. Does anyone else see this as a good idea? From cummingscs at netscape.net Tue Mar 4 21:41:01 2003 From: cummingscs at netscape.net (Steven Cummings) Date: Tue, 04 Mar 2003 21:41:01 -0500 Subject: PEP 308: an additional "select/case" survey option Message-ID: <565F542A.4C2A6F03.0EE20915@netscape.net> Will this syntax be pursued separately if it does not become the lead nomination for PEP308? I wouldn't mind seeing both this switch-case syntax in addition to what I've already selected in the PEP308 vote. /S "Clark C. Evans" wrote: >After some encouragement by Raymond, I'd like to add one more >item to the survey, if you like what follows perhaps you can >even *change* your vote (Raymond?) to include: > > Q accept switch-case > Z deny everything else! > >Dedication: > > To those who hate the terinary operator beacuse it isn't pythonic... > >Background: > > After looking over much of my Python source code, I found that > where I thought I needed a terinary operator, I ended > up taking one of two paths: > > if 0 == quantity: exit = 'no exit' > elif 1 == quantity: exit = 'a door' > else: exit = '%s doors' % quantity > > Or, the more concise mapping-idiom: > > exit = { 0: 'no exit', > 1: 'a door' }.get(quantity, > '%s doors' % quantity) > > The latter construct has two advantages over the if/else > statement level solution: > > 1. It's clear that I'm making an assignment to exit; > in effect the "exit =" isn't duplicated and this > aids in authoring/maintenance/reading. > > 2. The ugly '== quantity' isn't duplicated for each line, > once again improving maintenance. > > > However, the mapping-idiom has three problems: > > 1. The conditional switch isn't exactly "obvious" here > unless you're a Python vetran, this hurts in the > maintenance arena; besides the 'else' case is ugly. > > 2. It doesn't short-circut cleanly, to do a short-circut > you need to use lambda's... ick; further, it results in > the construction of a mapping which may not really help > out optimizations. > > 3. It really doesn't facilitate the use whitespace/indentation > to re-inforce a visual representation of the program's > structure. > >Philosophy: > > The whole rationale for this construct is to reduce data > duplication (both the assignments and conditional tests) > to increase maintenance. > > The goal is not to save on vertical screen realistate by > enabling multi-line constructs to be "jumbled" into a > single line. It seems that many people are asking for the > terinary option for the latter. > > Instead, this proposal seeks to engage Python's unique approach > to syntax by using whitespace to enhance the visual representation > of the program's structure. Many Python converts are here exactly > beacuse Python is very readable and thus maintainable. This proposal > is here soley to re-enforce this "pythonic" approach to coding. > >Proposal: > > The proposal introduces a 'select' or 'switch' keyword which creates > an indented expression block. Instead of the following, > > exit = { 0: 'no exit', > 1: 'a door' }.get(quantity, > '%s doors' % quantity) > > You could write, > > exit = select quantity > case 0: 'no exit' > case 1: 'a door' > else: '%s doors' % quantity > > This proposal gives you the power of the mapping-idiom without > the uglyness. It expresses the intent of the construct in a > very human readable manner using whitespace smartly. > > While the above is "good", it assumes an equality operator. So > that the structure is more generic, his proposal allows an optional > operator (a function taking 2 or more value and returning a boolean) > immediately following the 'case' label, > > z = 1.0 + select abs(z) > case < .0001: 0 > case > .5: .5 > else: -sigma / (t + 1.0) > > Note that the examples given in the proposal are thus > very easily expressed using this notion: > > data = select hasattr(s,'open') > case true: s.readlines() > else: s.split() > > z = 1.0 + select abs(z) > case < .0001: 0 > else: z > > t = v[index] = select t > case <= 0: t - 1.0 > else: -sigma / (t + 1.0) > > return select len(s) > case < 10: linsort(s) > else: qsort(s) > > The 'operator' need not be binary, one could, for example, > provide a terinary operator, such as: > > def between(cmp,rhs,lhs): return cmp >= rhs and cmp <= lhs > > score = select die > case 1: -2 > case 2: -1 > case between 3,4: 0 > case 5: +1 > case 6: +2 > else: raise "invalid die roll %d " % roll > >Summary: > > The proposal thus creates a flexible mechanism for avoiding > the excessive duplication of assignment and equality fragments > within a conditional assignment nest; it does so through a > new expression structure which, like the rest of Python, uses > indentation for structure. > > This proposal thus provides the pratical benefit of a terinary > operator, while at the same time opening the door to a rich > (and quite readable) conditional assignment mechanism. > > In particular, this proposal rejects the rationale for 'terinary' > operator as a way to trade horizontal screen realestate for > vertical space; as this rationale is in direct opposition to > the fundamental principle of readability. And as such, the > proposal explicitly does not include a way to include multiple > case labels on the same line. > >Credits: > > Alex Martelli for validating the elimination of needless-duplication > of code as the primary goal for the construct; and > > Carel Fellinger for presenting the idea of a plugable predicate/operator > > Raymond Hettinger for asking me to write this up more or less formally > > > >-- >http://mail.python.org/mailman/listinfo/python-list > -- Steven Cummings Columbia, MO Email: cummingscs at netscape.net AIM: cummingscs ICQ: 3330114 __________________________________________________________________ The NEW Netscape 7.0 browser is now available. Upgrade now! http://channels.netscape.com/ns/browsers/download.jsp Get your own FREE, personal Netscape Mail account today at http://webmail.netscape.com/ From BPettersen at NAREX.com Thu Mar 13 22:02:33 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 13 Mar 2003 20:02:33 -0700 Subject: Excel COM automation Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192022DDA46@admin56.narex.com> We have a trivially simple Python app in production that loads Excel through COM, opens an Excel file, and saves it as tab-delimited. Today we had a silent failure, and tracked it down to two instances of our app trying to use the Excel object at the same time. Is this supposed to work (and if so, what steps are we missing)? And if it's not supposed to work, is there a way to determine that the COM object is "busy"? -- bjorn From fabien.henon at caramail.com Sat Mar 1 20:12:07 2003 From: fabien.henon at caramail.com (Fabien HENON) Date: Sun, 02 Mar 2003 01:12:07 +0000 Subject: Ordinal not in range(128) Message-ID: <3e614c68$0$227$626a54ce@news.free.fr> I have written a POV-RAY editor for Linux using Python and Tkinter. It mostly uses the text widget of Tkinter. You can find it at : http://pyvon.sourceforge.net As you can add comments in POV-RAY scripts, people who are using extended character (?,?,...) get the following message : UnicodeError: ASCII encoding error: ordinal not in range(128) Here is the code that writes what is inside the text widget to a file. #-------------------- snip --------------------------- def save(event=None): global filename global scene_idx scene_contents = text.get(1.0, END) if scene_contents: try: fd = open(General_Buffer[scene_idx][0], 'w') for line in string.split(scene_contents, '\n'): fd.write(line) fd.write('\n') fd.close except: write_permissions() #---------------- snap --------------------------------- How can I work that problem around ? Thanks, Fabien HENON From andrew-pythonlist at puzzling.org Fri Mar 7 06:48:16 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Fri, 7 Mar 2003 22:48:16 +1100 Subject: Observer pattern thoughts In-Reply-To: <877kbbv75f.fsf@cassandra.evansnet> References: <20030306154232.7eb31309.gry@ll.mit.edu> <877kbbv75f.fsf@cassandra.evansnet> Message-ID: <20030307114816.GE13439@frobozz.local> On Fri, Mar 07, 2003 at 09:49:00AM +0000, Tim Evans wrote: > > The only thing that you might be missing is that you are not going far > enough. Rather than requiring lambdas to pass arguments, harness even > more of Python's dynamic nature and use this: > > class NewObservable: > def __init__(self): > self.observers = [] > > def register(self, func, *args, **kw): > self.observers.append((func, args, kw)) > > def notify(self): > for func, args, kw in self.observers: > func(*args, **kw) > > # meanwhile, in a class on the other side of town: > ob1.register(self.method, someval) > ob2.register(self.method, otherval) > > Working out how to write un_register is left as an excercise for the > reader. I'd be tempted to do the unregister function like this: class RegisteredFunc: def __init__(self, func, args, kwargs, observable): self.func = func self.args = args self.kwargs = kwargs self.observable = observable def unregister(self): observable.observers.remove(self) class NewNewObservable: def __init__(self): self.observers = [] def register(self, func, *args, **kwargs): rf = RegisteredFunc(func, args, kwargs, self) self.observers.append(rf) return rf def notify(self): for rf in self.observers: rf.func(*rf.args, **rf.kwargs) I'm posting this because I suspect this idea (returning a handle to the registered function from NewNewObservable.register) might not be immediately obvious, but I find it is a very nice abstraction. When I first saw this idea (in Twisted, I think), I went "Oh! What a good idea," so now I'm sharing it :) -Andrew. From ncoghlan at email.com Wed Mar 5 07:30:09 2003 From: ncoghlan at email.com (Nick Coghlan) Date: Wed, 05 Mar 2003 22:30:09 +1000 Subject: os.execv In-Reply-To: References: Message-ID: <3e65f1a0$1_2@news.brisbane.pipenetworks.com> Ulrich Petri wrote: > "Skip Montanaro" schrieb im Newsbeitrag > news:mailman.1046828168.14751.python-list at python.org... > >> >>> import os >> >>> os.execv("/usr/bin/find", ("find", "/ -name test")) >> find: / -name test: No such file or directory >> >>Maybe >> >> os.execv("/usr/bin/find", "find", "/", "-name", "test") >> I don't have an interpreter handy, but wouldn't the version below achieve the 'split literal on whitespace" effect? >>> os.execv("/usr/bin/find", *"find / -name test".split()) Regards, Nick. -- Nick Coghlan | Brisbane, Australia ICQ#: 68854767 | ncoghlan AT email DOT com Mobile: 0409 573 268 | http://oneofthesedays.not.there "Let go your prejudices, lest they limit your thoughts and actions." From bh at intevation.de Fri Mar 7 12:29:08 2003 From: bh at intevation.de (Bernhard Herzog) Date: 07 Mar 2003 18:29:08 +0100 Subject: Observer pattern thoughts References: <20030306154232.7eb31309.gry@ll.mit.edu> <6qwujbmlhj.fsf@salmakis.intevation.de> <3E68D058.3080505@bioreason.com> Message-ID: <6qr89jm6fv.fsf@salmakis.intevation.de> Mitch Chapman writes: > Bernhard Herzog wrote: > > Bound methods for the same method of the same object are equal even if > > the bound methods are not identical: > > [snip] > > Is this true for ZODB Persistent objects? I've had trouble > unregistering Persistent callables because they sometimes seem not to > compare equal. (This has happened under Python 2.1.3 and > StandaloneZODB-1.0, so things may have changed.) Looking at the > workaround code, it seems that the methods may not compare equal > even when the instances do. That may well be the case. Bound methods are only equal if they belong to the same object, i.e. the ids of the objects are equal. Methods belonging to equal but not identical objects should never be equal. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From aleax at aleax.it Fri Mar 14 04:53:56 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Mar 2003 09:53:56 GMT Subject: How to change font size in IDLE? References: Message-ID: wangjc wrote: > The default font size in IDLE is too small. Googling for: idle font size shows you a lot of posts dealing with this, such as this one from me: http://tinyurl.com/7gfd Alex From aleax at aleax.it Thu Mar 13 13:45:56 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Mar 2003 18:45:56 GMT Subject: Pausing until threads are done References: Message-ID: Christos TZOTZIOY Georgiou wrote: > On Thu, 13 Mar 2003 07:50:52 GMT, rumours say that Alex Martelli > might have written: > >>Don't use the thread module in your application code: it's a very low >>level module, meant basically as an engine for module threading, which >>is the one you _should_ be using, > > Why _should_ he? The question mark actually refers to "should", so I am > asking about the reasoning. The poster is asking how to perform a task that's elementary with threading and hard with module thread. If there is no reason to use thread instead of threading, and there's at least one reason to use threading instead, then it would be absurd to use module thread in application-level code. > Actually, this is not a question directed only to Alex; I have also read > others posting "don't use thread, you should use threading" or similar > remarks, but the reasoning seems to be "dogmatic" (in quotes because I > don't mean it in an offensive way) a la snickers-ads: "Just do it." There is no "reasoning" involved, when I offer a suggestion whose form is just "you should do this instead of that" -- it's just advice. When there are trade-offs I often point them out (over and over AND over again, since nobody ever seems to bother checking out the archives, FAQs, etc -- sometimes one does get a bit bored at the 100th repetition and may end up skipping it). When there is no trade-off, when doing Y instead of X only has DIS-advantages, then what's the point of listing the advantages of X each time, particularly when one such obvious advantage is an immediate answer to the poster's specific question? > I would offer the following reasoning: "you _should_ use the threading > module since it offers a much better abstraction of threading, but if > you feel comfortable using directly the thread module, locks and queues, > do so." As long as you continue "...and don't ask on c.l.py how to perform any task that is even slightly hard in thread and obvious in threading such as the specific task you're asking about here", I guess such a weird message might be consistent. But why waste time and energy with the "if you feel comfortable" provision, when the poster is specifically asking about how to do something that's hard in one case (the case that offers no compensating advantages) and easy in the other (the one that everybody keeps suggesting, for the obvious reason that is IS the one application code should use, "comfortableness" quite apart)...? Alex From imbosol-1046792639 at aerojockey.com Tue Mar 4 11:15:25 2003 From: imbosol-1046792639 at aerojockey.com (Carl Banks) Date: Tue, 04 Mar 2003 16:15:25 GMT Subject: Code speedup tips References: Message-ID: Sean Richards wrote: > On Sun, 2 Mar 2003 09:07:18 -0500, Justin Shaw wrote: > >> What are you using to draw the results? I have coded up some of >> Wolfram's stuff and had a bottle neck in the drawing of the pictures. > > Hi, > > I am using a Tkinter PhotoImage to draw the CA. I ran the python > profiler over the new improved code and it uses ~25% of the processing > time to draw the picture. So you are right there is a bottle neck in the > drawing of the picture. Did you come up with a quicker way of displaying > the array as an image? Again, setting an image pixel-by-pixel is almost always the wrong way to do it. I don't know anything about this PhotoImage thing, but I warrant there's a way to set every pixel at once, maybe using data passed in a string. Find it, then use Numeric operations to get the data in the required format, then use the Numeric tostring method to extract the data into a string, and finally pass in the string. To exemplify, here is how I would convert Numeric data into an image using Python Imaging Library: img = Image.fromstring('L',(width,height), ((1-lattice)*255).astype(Int8).tostring()) (One other thing: Python has added a buffer protocol, to be supported by objects that store raw data. If Numeric and PhotoImage both support it, you might not need the tostring call. In fact, the example above didn't require it on my system.) -- CARL BANKS From peter at engcorp.com Thu Mar 20 16:52:40 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Mar 2003 16:52:40 -0500 Subject: How to create a CDATA XML node References: Message-ID: <3E7A3828.DD32B0DC@engcorp.com> Antun Karlovac wrote: > > How do I implement a CDATA node in Python? I'm using dom.minidom as > follows:- > > impl = xml.dom.minidom.getDOMImplementation() > doc = impl.createDocument( None, "element", None ) > root = doc.documentElement > > Then I want to create my CDATA node. The reason I want a CDATA node is > because I want to preserve all the HTML formatting tags (i.e. the >

's here) in the text node:- > > longDescText = '

There will be more text here.

' > longDescText = longDescText > longDescNode = doc.createElement( 'longdescription' ) > longDescTextNode = doc.createTextNode( longDescText ) > longDescNode.appendChild( longDescTextNode ) > root.appendChild( longDescNode ) > > I can't anything in either the docs, or the Python & XML O'Reilly > book. Am I blind or summat? CDATA is, I believe, used only in the XML source file itself to in effect "escape" the content and avoid portions thereof from being interpreted as XML syntax. When using DOM, you should be able just to create a simple text node. Upon export, technically, the toxml() method or whatever means you are using must scan the content of the text node and perform appropriate escaping to ensure that the output text of that node will not be mistaken for XML syntax. This might use lots of ሴ crap, or it might be smart enough to see that using CDATA would be better, but I don't believe there's any defined, standard way of forcing a CDATA to be used on output. I bet some implementations don't even scan their text node data before dumping it either... -Peter From fperez528 at yahoo.com Fri Mar 21 14:32:05 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 21 Mar 2003 12:32:05 -0700 Subject: [SciPy] Crash prevents me from plotting References: <3e7b5f41@news.swissonline.ch> Message-ID: F. GEIGER wrote: > Anyone SciPy using here? Seems to be a great package, so I downloaded it > today. Alas, I could not get it to plot. A couple of points: 1. Scipy is evolving so fast, that you will be far better off building the CVS code directly. In scipy, the _alpha_ designation right now is for real, especially concerning the wxpython-related code. The numerical core is more stable, but interaction with wxpython is still very much in flow. 2. You should join the scipy-user list, where you'll get very quick help. Scipy is a fantastic project, and improving quickly. Hang in there, I'm sure you'll quickly find a combination which works well for you (maybe with some help from the list). Cheers, f. From johnroth at ameritech.net Tue Mar 4 09:34:48 2003 From: johnroth at ameritech.net (John Roth) Date: Tue, 4 Mar 2003 09:34:48 -0500 Subject: code coverage tool References: <7h3n0kbjpnk.fsf@pc150.maths.bris.ac.uk> <7h3el5njnqv.fsf@pc150.maths.bris.ac.uk> Message-ID: "Michael Hudson" wrote in message news:7h3el5njnqv.fsf at pc150.maths.bris.ac.uk... > Alex Martelli writes: > > > Michael Hudson wrote: > > > > > Alex Martelli writes: > > > > > >> Haven't tried pyCover, but I _have_ noticed the hotshot "profiler" has > > >> all the hooks one needs to use it in a simple statement-coverage mode, > > >> and it seems to have very low overhead when used that way; > > > > > > I've probably done for that in 2.3, alas. > > > > meaning that hotshot doesn't work any more in 2.3, or that > > it's become high-overhead, or...? > > The overhead is probably somewhat higher because of the way line trace > events are generated in 2.3 is what I meant. Fallout from the removal > of SET_LINENO. > > I haven't actually tried it, so I might be hopelessly wrong... That shouldn't affect the profiler, but it might affect the debugger, and hence pyCover. I really should fire up 2.3 and give it a test. Don't hold your breath, though. John Roth > > Cheers, > M. > > -- > : exploding like a turd > Never had that happen to me, I have to admit. They do that > often in your world? -- Eric The Read & Dave Brown, asr From wangjc at sas.upenn.edu Thu Mar 13 19:49:58 2003 From: wangjc at sas.upenn.edu (wangjc) Date: Fri, 14 Mar 2003 00:49:58 +0000 (UTC) Subject: How to change font size in IDLE? Message-ID: The default font size in IDLE is too small. --------------------------------------- Congressional Office E-Mail: lientony at seed.net.tw TEL: 886-2-23586586 --------------------------------------- From intentionally at blank.co.uk Tue Mar 11 07:59:33 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 11 Mar 2003 12:59:33 +0000 Subject: A possible lazy evaluation system? Message-ID: I one mentioned that I thought it was sensible to label function parameters in some way to modify the call mechanism. The obvious analogy is 'var' parameters in Pascal, though I was thinking more of a 'lazy' modifier. It occured to me that, instead of a fully lazy parameter system, a simpler approach may be to lable parameters as lambdas. You could then write something like... def IF (c, lambda x, lambda y) : if c : return x () else : return y () ...and call it with... IF (y != 0, x/y, 1000000) The 'lambda' asserts that the parameters expression gets converted to a parameterless lambda instead of being evaluated immediately. The same notation in declarations of __call__ could provide the same capability to all callables. The question is - is this a sane suggestion? From mig at mig.com Sat Mar 1 10:20:16 2003 From: mig at mig.com (news) Date: Sat, 1 Mar 2003 15:20:16 -0000 Subject: Perl Vs Python References: <7DT6a.104385$zL6.65899@news2.central.cox.net> <3E5D1440.815454C2@engcorp.com> Message-ID: <1046532247.85765.0@ersa.uk.clara.net> "Peter Hansen" wrote in message news:3E5D1440.815454C2 at engcorp.com... > > By the way, you really should use a different email address instead of > burdening Microsoft with your need for privacy (via "someone at microsoft.com"). They burdened us with their operating system. From peter at engcorp.com Tue Mar 18 12:51:10 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Mar 2003 12:51:10 -0500 Subject: script filename and autorun References: <3e77229a$1@newsflash.abo.fi> Message-ID: <3E775C8E.C919C351@engcorp.com> Lexy Zhitenev wrote: > > "Simon Dahlbacka" wrote in message news:3e77229a$1 at newsflash.abo.fi... > > 2) is it enough with just a key "python > > c:\whateverthepathistomyprogram\prog.py" in ...\Run or do I also need full > > path to python? > > It is enough on WinNT, 2000 and XP, but it won't work on Win9x branch. You > will have to write full path to interpreter. Of course it has to be > installed. I was surprised by this conclusion, so I tested it out just now myself on Win98 SE. I put a "Peter Test" key in Run, with "c:\runtest.py" in it. It consists of this: import time f = open('c:/runtest.log', 'a') print >>f, "I was run!",time.time() f.close() I rebooted and after logging in again, there was a runtest.log file with the expected content. So I guess it actually works with a properly configured machine even on Win98. -Peter From plehmann at fred.net Thu Mar 13 20:36:49 2003 From: plehmann at fred.net (Paul E. Lehmann) Date: Thu, 13 Mar 2003 20:36:49 -0500 Subject: Space Between Rows Message-ID: Using Tkinter how does one add space between two rows? I just want to add space between two rows not space above AND below a row. It seems as if pady or ipady will add space both above and below and not just either above or below a row. From tjreedy at udel.edu Wed Mar 19 12:21:24 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Mar 2003 12:21:24 -0500 Subject: PEP 312 (and thus 308) implemented with a black magic trick References: <2259b0e2.0303171358.5a6fe337@posting.google.com> Message-ID: <6aicncBJyofaOuWjXTWcow@comcast.com> "Andrew Bennetts" wrote in message news:mailman.1048071128.22193.python-list at python.org... > On Mon, Mar 17, 2003 at 01:58:28PM -0800, Michele Simionato wrote: > > Today I had an illumination on how to implement both PEP 312 and 308 > > in current Python. I think I will share the idea, even if I would *not* > > recommend to use such a dirty trick in production code. > > Nasty. :) > > So, who's going to be the first to implement ++x using this technique? If, as I understand, this meta technique relies on source text, this should work. But not if it looks at code: >>> def f(): return ++1 ... >>> import dis >>> dis.dis(f) 0 SET_LINENO 1 3 SET_LINENO 1 6 LOAD_CONST 1 (1) 9 UNARY_POSITIVE 10 RETURN_VALUE 11 LOAD_CONST 0 (None) 14 RETURN_VALUE Compiler seems to optimize away second unary positive. Terry J. Reedy From aleax at aleax.it Thu Mar 13 13:29:06 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Mar 2003 18:29:06 GMT Subject: Why sys.exit does not exit ? References: <20030313154726.6433cf4a.me@nospam.pls> Message-ID: Gerhard H?ring wrote: > Giorge wrote: >> Hi all, here is a small code snippet that should >> tell something about what I'm trying to do: >> >> import sys, os, thread, time >> from threading import * >> [...] >> The problem here is that the sys.exit call doesn't >> terminate the program, which exits after the sleep >> call. >> >> Can you help ? thanks. > > sys.exit only exits the main thread. In order for the program to finish, > you have to complete all other threads, too. ...or set the other threads to daemonic, so their continuing existence does not inhibit process termination (but I'm not sure how that would play with a thread being in a system-call, such as time.sleep). Alex From missedby2inches at gmx.net Fri Mar 7 02:38:28 2003 From: missedby2inches at gmx.net (Two Inches) Date: Fri, 07 Mar 2003 08:38:28 +0100 Subject: IndentationError: two many levels of indentation Message-ID: We've got this error when we tried to execute code that was created with a generator tool. The code had about 500 levels of indentation (nested if blocks). It is no problem for us to change the generator. However, I couldn't find this limitation in the language reference. Shouldn't it be in there? What is the exact limit? Is there any technical rational for this limit? From pyth at devel.trillke.net Mon Mar 3 12:12:41 2003 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 3 Mar 2003 18:12:41 +0100 Subject: My CTO is learning Python.... In-Reply-To: ; from aahz@pythoncraft.com on Sat, Mar 01, 2003 at 02:17:55PM -0500 References: Message-ID: <20030303181241.F22015@prim.han.de> Aahz wrote: > In article , > Bjorn Pettersen wrote: > > > >...time to run screeming from the building . His problem, is that > >"There doesn't seem to be any good books on Python". Pressed a little > >more, it was refined to "either the documentation assumes you've never > >programmed before, and spends volumes of text introducing loop > >constructs etc." (that was the commentary on the Tutorial ), "or, > >the author seems to be in love with the language purely for its advanced > >and obscure features" (he'd hoped 'Thinking in Python' would be like the > >C++/Java equivalent...). Pressed a little bit further, he commented: > >"what I'm really looking for is a quick introduction for someone that > >allready knows C++ or Java". > > Python Essential Reference yip, i came from c++ and java and enjoyed it. especially since it explained some of the "introspection" internals which give a good idea of whats going on. holger From jon+usenet at unequivocal.co.uk Fri Mar 14 17:46:27 2003 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 14 Mar 2003 22:46:27 GMT Subject: Website using Python--what's best architecture? CGI? References: Message-ID: In article , Gilles Lenfant wrote: >> I would like to create a commercial website using Python. It seems >> that straight CGI would be the easiest option, but I'm wondering what >> its top capacity would be, and also what other options are commonly >> available for a website that I will be hosting through a commercial >> host. Here are some specific questions: > > CGI is for mainly static sites with some forms processing and low traffic. > For a highly dynamic site (data/objects driven browsing), you should > consider using another solution (Webware, Zope, Quixote...). Or something like jonpy (http://jonpy.sf.net/) which means you can prototype your system using CGI and move to mod_python or FastCGI later with no code changes... ;-) From erellon at narod.ru Sat Mar 22 15:18:07 2003 From: erellon at narod.ru (erellon) Date: 22 Mar 2003 12:18:07 -0800 Subject: Documenting Python packages Which system is better to choose? Message-ID: Greetings. i am currently maintain PyANT project (porting Jakarta ANT to Python) and right now I think thick documenting system is better to implement. Right now I am choosing between Pydoc, Epydoc and Happydoc. But maybe anybody knows any other that has Javadoc-like syntax and object-orinted interface (not just command-line). Maybe anybody can recommend other ? Best Regards, Ivan V. Begtin From exarkun at intarweb.us Thu Mar 20 13:54:34 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 20 Mar 2003 13:54:34 -0500 Subject: Am I misusing socket.setdefaulttimeout here? In-Reply-To: <15994.253.243228.801114@montanaro.dyndns.org> References: <15994.253.243228.801114@montanaro.dyndns.org> Message-ID: <20030320185434.GB2880@meson.dyndns.org> On Thu, Mar 20, 2003 at 11:57:17AM -0600, Skip Montanaro wrote: > Socket timeouts are available in 2.3. I'm trying to use them to check URLs > on a couple web servers without hanging indefinitely due to downed servers: > > #!/usr/bin/env python > > import socket > import urllib2 > import sys > > TIMEOUT = 30.0 > socket.setdefaulttimeout(TIMEOUT) > > f = urllib2.urlopen("http://www.mojam.com/") > data = f.read() > > When I execute the above, it returns immediately (that is, not 30 seconds > later) with this traceback: > > Traceback (most recent call last): > File "chksrvrs.py", line 11, in ? > data = f.read() > File "/Users/skip/local/lib/python2.3/httplib.py", line 1155, in read > return s + self._file.read() > IOError: [Errno 35] Resource temporarily unavailable > > Do I misunderstand something about socket timeouts or do they not play well > with urllib and friends (I tried both urllib and urllib2). > > Thx, > from twisted.web import client from twisted.internet import defer, reactor TIMEOUT = 30.0 URL_LIST = ['http://www.mojam.com/'] dList = [client.getPage(u) for u in URL_LIST] for d in dList: d.setTimeout(TIMEOUT) d = defer.DeferredList(dList) pages = [] d.addCallback(pages.extend).addCallback(lambda R: reactor.stop()) reactor.run() print pages # Or whatever > Skip > Jp > > -- > http://mail.python.org/mailman/listinfo/python-list -- Examinations are formidable even to the best prepared, for even the greatest fool may ask more the the wisest man can answer. -- C.C. Colton -- up 13:58, 4 users, load average: 0.55, 0.57, 0.47 From usenet at prettyhipprogramming.com Wed Mar 12 18:45:17 2003 From: usenet at prettyhipprogramming.com (Joel) Date: Wed, 12 Mar 2003 23:45:17 GMT Subject: win32com: Accessing MAPIOBJECT References: <3e6fc198$0$83879$a1866201@newsreader.visi.com> Message-ID: grante at visi.com (Grant Edwards) wrote in news:3e6fc198$0$83879$a1866201 at newsreader.visi.com: > In article , Bjorn > Pettersen wrote: >>> From: Joel [mailto:usenet at prettyhipprogramming.com] > The only thing I can find on Mark's site has to do with > SpamBayes. > > What is an "Outlook plugin", and how does it help in fetching > the full message headers? He's referring to my desire to process the Outlook messages for use with SpamBayes. Spambayes is a python based spam filter and Mark Hammond has written a plugin for that works Outlook. Unfortunately something is befouled with my version of Outlook. The plugin installed ok and worked fine until the next time I restarted Outlook. The next time I brought up Outlook, the plugin was gone, and I get an error when I try to restart it. I don't think the plugin is to blame as I've had other strange happenings with Outlook before. I also would prefer to use something other than the plugin simply because I can easily switch e-mail applications if I need to. Joel From simonb at webone.com.au Fri Mar 7 18:12:58 2003 From: simonb at webone.com.au (Simon Burton) Date: Sat, 08 Mar 2003 10:12:58 +1100 Subject: Generators and co-routines References: Message-ID: On Fri, 07 Mar 2003 11:32:47 +0800, Simon Wittber (Maptek) wrote: > Hello python people! > > I am rewriting the User class for my mud system, and am trying to use a > generator function to simulate a co-routine, which helps me maintain > state much more elegantly than the previous while loop with humungous > amounts of if / elif statements. > > I have a server class, which loops through all connected users, calling > the .poll() method. > > The .poll() method checks if the user is logged in, if not, calls the > .login() method (which is the co-routine/generator). My problem is the > .login() method is not being called! I put a print statement at the > start of the function, and nothing gets printed. I am entirely unfamilar > with python generators, if someone can enlighten me, please do so! > i'd hate to RTFM you, but it seems you don't know what your doing! Try experimenting; you don't just "call" login... you iterate through it... send me your code if you want. cheers, and i'm glad your coding again :) Simon Burton. From aleax at aleax.it Thu Mar 13 03:31:37 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Mar 2003 08:31:37 GMT Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <58q36vgv1ga8ovde5ftub9t8ugaa2pnum5@4ax.com> <3E62778F.EED49083@alcyone.com> <3E629E93.B94F7631@alcyone.com> <0bkv6v8akrd0db5i66eu685t5pmviuf0bk@4ax.com> Message-ID: Stephen Horne wrote: > On Wed, 12 Mar 2003 17:54:37 -0500, Jack Diederich > wrote: > >>A groups.google link to a post where (in the footnotes) I mention that >>'lambda' is both A: a long keyword, and B: one of the few keywords that >>never starts a line (hence it jars the eye). > > I don't really see the relevance of the fact that "'lambda' never > starts a line". Other frequently used words (such as built-in function > names) also never start a line - 'reduce' is as long as 'lambda' for a Some built-in function names OFTEN "start a line" -- setattr, for example (you're far more rarely going to use setattr EXCEPT at the start of a line). > start. What is the relevance of the distinction between keywords and > standard identifiers in this issue? No idea, just wanted to correct the previous strange assertion;-). Alex From aleax at aleax.it Thu Mar 13 12:45:24 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Mar 2003 18:45:24 +0100 Subject: Flying With Python (Strong versus Weak Typing) In-Reply-To: References: Message-ID: <200303131845.24895.aleax@aleax.it> On Thursday 13 March 2003 04:41 pm, sismex01 at hebmex.com wrote: > > HAH! That's what YOU think. Her purring is absolutely _unique_ (how > > many cats can purr so LOUD as to wake you up in the morning?!) and > > your pale imitation thereof just can't compare -- sorry! > > > > Alex > > Heh heh heh :-) > > And what do you do? Feed her and pet her -- what else? > How can one get angry with a little critter that > wakes you up by basicly saying "I'm happy"? :-) Exactly. Particularly when she's irresistibly cute. > Heh, cats are funny that way. ^o.o^ Cats are the best manipulators in the world -- but they always do get away with it, _because_ they're also so cute and funny... Alex From dave at pythonapocrypha.com Mon Mar 10 11:55:26 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Mon, 10 Mar 2003 08:55:26 -0800 (PST) Subject: add an indent to a stream In-Reply-To: References: Message-ID: On Mon, 10 Mar 2003, Manuel M Garcia wrote: > I often need to add an indent to a stream, usually so the output of > pprint or traceback is indented so I can tell debugging output from my > program's actual output. > > Below is a class to help do this. I think I got the details right. > The 'print' statement, when used with commas, is more complicated than > I thought. > > What is the exact rule for when the 'print' command inserts a space > because of a comma? I guess it has something to do with the attribute > 'softspace'. Does the stream indenter have to worry about this? It's external to the indenter, I think. > class IndentStream: > """Stream with indent at start of each line. > > Indent can be a string or > the number of spaces you wish to indent. > > """ > > def __init__(self, indent=' ', stream=None): > if stream is None: > self._stream = sys.stdout > else: > self._stream = stream > try: > indent = ' ' * indent > except TypeError: > pass > self._indent = indent > self._nl_indent = '\n' + indent > self._indent_size = len(indent) > self._comma = 0 > self.softspace = 0 > > def write(self, s): > comma = not s.endswith('\n') > s = s.replace('\n', self._nl_indent) > if not self._comma: s = self._indent + s > if s.endswith(self._nl_indent): s = s[:-self._indent_size] > self._stream.write(s) > self._comma = comma Doesn't the above behave the same as: class IndentStream: def __init__(self, indent=' ', stream=sys.stdout): self.stream = stream stream.write(indent) self.indent = indent def write(self, s): self.stream.write(s.replace('\n', '\n' + self.indent)) ?? -Dave From skip at pobox.com Wed Mar 19 16:02:11 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 19 Mar 2003 15:02:11 -0600 Subject: Does Python do try: except: finally: ? In-Reply-To: <20030319135147.A1830@ash.int.ca.pason.com> References: <20030319135147.A1830@ash.int.ca.pason.com> Message-ID: <15992.56019.25414.686120@montanaro.dyndns.org> Jerry> Does Python do a block like: Jerry> try: Jerry> do_something() Jerry> except: Jerry> do_something_else() Jerry> finally: Jerry> do_cleanup() Nope. Jerry> To get around this I do: Jerry> try: Jerry> try: Jerry> do_something() Jerry> except: Jerry> do_something_else() Jerry> finally: Jerry> do_cleanup() Jerry> Is this the way it has to be done? Yup. Skip From mlh at furu.idi.ntnu.no Tue Mar 25 09:07:08 2003 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Tue, 25 Mar 2003 14:07:08 +0000 (UTC) Subject: In need of a binge-and-purge idiom References: <698f09f8.0303232304.608bc8cf@posting.google.com> <698f09f8.0303242326.60c2f3b5@posting.google.com> Message-ID: In article <698f09f8.0303242326.60c2f3b5 at posting.google.com>, Jeremy Fincher wrote: >mlh at furu.idi.ntnu.no (Magnus Lie Hetland) wrote in message news:... >> You should add "if acc" before you yield acc -- I don't want an empty >> acc (that only means several separators in a row -- which amounts to a >> single separator in my case). > >That makes sense. To be truly general, that should be a named >argument with a default to not return empty values. > Maybe. I wasn't really looking for a general function/generator, but for an idiom (i.e. a way of solving this with basic tools). An unrealistic wish, perhaps :) > >> And, with that statement in place, you'd >> get the same duplication as before, as far as I can see. What is new >> about this (except putting it inside a generator)? > >Simply that once writing it, the ugliness is contained in that one >function, and all your code that needs the behavior you describe can >be written much more beautifully :) Indeed. >Jeremy -- Magnus Lie Hetland "Nothing shocks me. I'm a scientist." http://hetland.org -- Indiana Jones From gradha at titanium.sabren.com Tue Mar 18 16:27:54 2003 From: gradha at titanium.sabren.com (Grzegorz Adam Hankiewicz) Date: Tue, 18 Mar 2003 22:27:54 +0100 Subject: Looking for a specific html parser In-Reply-To: <1579260.71CaRllVEo@lothar.cengija.com> References: <1215917.HbSNDBvpua@lothar.cengija.com> <19fc7v4m78rkb0m8s6bc4l8oun7prnnnfv@4ax.com> <1579260.71CaRllVEo@lothar.cengija.com> Message-ID: <20030318212754.GB10975@pedos.es> On Tue, Mar 18, 2003 at 09:07:47AM +0100, Davor Cengija wrote: > Basically, I need a DOM like parser for HTML, with xpath > capabilities. xml.dom might help me, but before that I obviously > need some kind of html-tidy. I required something similar for a small script and I found most useful to create first an HTMLParser which translated all code to xml and feed that into Python's minidom. It's quite easy to do if your input HTML is 'correct', otherwise the xml parsing will surely fail, unless you filter all through tidy, of course. -- Please don't send me private copies of your public answers. Thanks. From jasonou at yahoo.com Tue Mar 4 01:45:57 2003 From: jasonou at yahoo.com (Jingzhao Ou) Date: Mon, 3 Mar 2003 22:45:57 -0800 (PST) Subject: Help! Cannot open a file in a class In-Reply-To: <20030303233647.A16293@tibia.amotlpaa.bogus> Message-ID: <20030304064557.4344.qmail@web80101.mail.yahoo.com> Hi, Steven, My problem is solved. Thanks a lot!!! I like Python a lot. It is very great! I will continue learning it. Best regards, Jingzhao --- Steven Taschuk wrote: > Quoth ouj: > > I am new to Python. I write a class that opens a file and reads the > > data from the file. > > > > class Cvdoc: > > def __init__(self): > > ...... > > fd = file('vdoc.dat', 'wr') > > print dir(fd) > > fd.readlines() > > 'wr' is not a valid mode; file() is just ignoring the 'r' and > opening the file for writing, causing your code to fail when it > tries to read. > > If you want to be able to both read and write in the file, you > want 'r+' or 'w+'. > > >>> f = open('foo', 'w+') > >>> start = f.tell() > >>> f.write('spam') > >>> f.seek(start) > >>> f.read() > 'spam' > > (Note also that you have to use tell and seek to move back to the > start of the file, to read the data you wrote.) > > See the Library Reference, section 2.2.8 ("File Objects"). > > -- > Steven Taschuk "The world will end if you get this wrong." > staschuk at telusplanet.net (Brian Kernighan and Lorrinda Cherry, > "Typesetting Mathematics -- User's Guide") > > -- > http://mail.python.org/mailman/listinfo/python-list From lp at your-pants-coder.dk Thu Mar 6 22:05:51 2003 From: lp at your-pants-coder.dk (Larz) Date: 07 Mar 2003 03:05:51 GMT Subject: Python in a Nutshell: Real Soon Now! References: <5hQ9a.22180$zo2.647510@news2.tin.it> Message-ID: Alex Martelli wrote in news:5hQ9a.22180$zo2.647510 at news2.tin.it: >> I thought US readers, at least, might be interested to know that UPS >> have just delivered my complimentary copy of "Python in a Nutshell". >> By using a fine, almost onion-skin, paper they have made an excellent >> volume that is quite manageable to read and carry around. Nice job, >> Alex ... should be on the bookshelves any time now! > > Thanks! I was impressed by UPS and ORA this time -- *my* copy also > arrived today, and I heard from an Italian guy who reviews technical > books for an important local site -- HE also got his review copy > today... Python in a Nutshell? Aww, and I just went and bought the cookbook ;P Oh well, they're so damn expensive I think I'll just have to make do with the cookbook! Anyway, what I've read so far is great! Nice work! :) -- - Lars http://coder.dk/sohofaq.php - Uofficiel WOL SOHO 77 FAQ To mail me remove your pants. From gh at ghaering.de Mon Mar 31 22:27:53 2003 From: gh at ghaering.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Tue, 1 Apr 2003 05:27:53 +0200 Subject: PySqlite for the Python 2.3a In-Reply-To: <5B880349CA70D4119B7500D0B74C62D9010F8006@EXCHANGE> References: <5B880349CA70D4119B7500D0B74C62D9010F8006@EXCHANGE> Message-ID: <20030401032752.GA2344@mephisto.ghaering.test> * Driver, David [2003-03-31 20:30 -0600]: > So, I emailed a few days ago saying that I was going to try to compile > pySqlite and install it for 2.3. Well after a few evenings of dinking around > in the source code, I now know that I have no understanding of the C++ > languages or of building an install package for windows. PySQLite is written in Python and C, no C++ involved ;-) I don't plan to make an "official" package for 2.3 alphas, but I could provide an "unofficial" one. > Is there any plans to do an installer for the alphas? Is there another > way to get the package installed for windows? If you want to compile it yourself, it's certainly possible. There's an INSTALL.win32 file in the source distribution that describes how to do this. To build using mingw32 (which I'd recommend, instructions for MSVC6 and Borland are also in the INSTALL.win32 file) you can either compile a statically linked libsqlite.a yourself or download the sqlite-mingw zip file from the SF files section: http://sourceforge.net/project/showfiles.php?group_id=54058 Just download it, put it in ../sqlite relative from your PySQLite source tree and issue a "python setup.py build --compiler=mingw32". Details can be found in the INSTALL.win32 file. Let me know how it goes. Btw. PySQLite has its own mailing list, to which I'll cc this message. Gerhard -- mail: gh at ghaering.de web: http://ghaering.de/ From mis6 at pitt.edu Thu Mar 13 12:36:05 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 13 Mar 2003 09:36:05 -0800 Subject: Can __iter__ be used as a classmethod? References: <3e649aa3_4@news.bluewin.ch> <2259b0e2.0303041023.43e8b81f@posting.google.com> <4B89a.6715$zo2.218162@news2.tin.it> Message-ID: <2259b0e2.0303130936.45735c4e@posting.google.com> Alex Martelli wrote in message news:... > Greg Ewing (using news.cis.dfn.de) wrote: > what happens if you're multiply inheriting from > a class C and a class D and both have class methods? Should > we have a FURTHER custom metaclass generated then? Magic > gets blacker and blacker... > > What do you find so horrible with classmethod as it stands > that would come close to justifying such an excursion into > exhoterism in order to get rid of it? > > > Alex You have a point here. Not that I would be opposed to automatic generation of metaclasses (in some future version of Python, maybe), but it is true that for the time being classmethods are a much simpler solution. Still, I would prefer to have them in the standard library, but this is a matter of personal taste. I agree that this point on multiple inheritance is a quite strong argument for using them over metamethods. Michele From mixo at beth.uniforum.org.za Mon Mar 3 02:02:49 2003 From: mixo at beth.uniforum.org.za (mixo) Date: Mon, 03 Mar 2003 09:02:49 +0200 Subject: connecting two process through a socket Message-ID: What I am trying to do is combine two daemons. The first daemon logs is status in various ways: file,syslog and status files which take the form /path/to/status/dir/currentpid/file. The other daemon is a threading tcpip server which listen on port 3030 (configurable). The problem I have here is that I need to get the pid of the first daemon so that second daemon can feed data to clients. So, what I am considering is having the first daemon send data to the second through a socket. Is there a way to have the two daemons connected this way, and having the second daemon shutdown when the socket is closed? And how can I make sure that clients do not connect to the first daemon, only the second? In other words, can I have a socket server that is connected to another server as a client? ---------- --------- | | | | ------->client1 | daemon1 |<------->| daemon2 | ------->client2 | | | | ------->clientn ---------- --------- From intentionally at blank.co.uk Tue Mar 11 09:50:35 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 11 Mar 2003 14:50:35 +0000 Subject: Overloading operators for currying, a PEP309 suggestion References: <6qptoyezny.fsf@salmakis.intevation.de> Message-ID: <6itr6vkqtoncbob5tvmvbst713bs86lp2o@4ax.com> On 11 Mar 2003 15:38:41 +0100, Bernhard Herzog wrote: >Stephen Horne writes: > >> I would prefer defining the __len__, __getitem__, __setitem__ and >> __delitem__ methods to allow direct manipulation (and creation and >> deletion) of the closure. > >That would mean that the length of a function with no arguments is 0, >right? Probably > That's bad and will likely introduce subtle bugs because then all >functions with no arguments are suddenly considered false. Why would a function object be treated as a boolean? >What about other callable objects? Classes, methods or instances that >have a __call__ method (They might even implement it through >__getattr__)? Good point. From phil at river-bank.demon.co.uk Sat Mar 29 20:06:35 2003 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Sun, 30 Mar 2003 01:06:35 +0000 Subject: namespace problems in pyqt In-Reply-To: <%2rha.70$6U5.65818@newsfep2-win.server.ntli.net> References: <%2rha.70$6U5.65818@newsfep2-win.server.ntli.net> Message-ID: <200303300106.35358.phil@river-bank.demon.co.uk> On Sunday 30 March 2003 12:29 am, Tom Chance wrote: > Hullo, > > I've got a problem that's come about by not wanting to create a new > class for a dialogue box in PyQt. Previously, I had a class for the > dialogue which included a function connected to a button in the dialogue. I > made the class for the dialogue box in Qt Designer, imported that class, > inherited it in a new class, into which I put the function (so it overrode > the empty function declaration in the original class), like so: > > class Inherited(QDialog): > /all the pyqt stuff/ > connect signal to function2 > > class Inheritor(Inherited): > def function2: > /so some stuff/ This isn't valid Python. > Now that function isn't in that dialogue's class... it's in the namespace > that is calling the class instance, e.g.: > > def function1(self): > /do some stuff.../ > instance = Inherited() > > def function2(self): > /do some stuff.../ Are these class methods or functions? Functions don't (to be more accurate, shouldn't) have self arguments. > How can I connect the button in Inherited to function2()? I've been told > you can connect a Qt signal to a global function, but I can't work out how; > I've tried declaring "global function2", and I've read through the Qt docs, > but I cant' figure it out, so I'm obviously just being dumb and missing > something here. Can someone give me a hand? It isn't clear which function2() you want to connect to. Either way, simply use the name in the call to connect(), ie. QObject.connect(sender,SIGNAL('sig()'),Inheritor.function2) ...or... QObject.connect(sender,SIGNAL('sig()'),function2) See http://www.riverbankcomputing.co.uk/pyqt/docs/x232.html Phil From irmen at -NOSPAM-REMOVE-THIS-xs4all.nl Thu Mar 13 17:10:33 2003 From: irmen at -NOSPAM-REMOVE-THIS-xs4all.nl (Irmen de Jong) Date: Thu, 13 Mar 2003 23:10:33 +0100 Subject: Upload of binary files In-Reply-To: <3E70A399.7C3E43A5@engcorp.com> References: <8b5e42a6.0303121653.6d452403@posting.google.com> <3e7050b4$0$49113$e4fe514c@news.xs4all.nl> <3E70A399.7C3E43A5@engcorp.com> Message-ID: <3e7101d7$0$49117$e4fe514c@news.xs4all.nl> Peter Hansen wrote: >>This won't do. It is not guaranteed that a single read() returns >>all of your data. > > > Since when? I know with sockets you don't get a guarantee that > recv() gets all the data, but the docs on read() for a file > object say: > > read ([size]) > Read at most size bytes from the file (less if the read hits EOF before > obtaining size bytes). If the size argument is negative or omitted, > read all data until EOF is reached. I *may* indeed be wrong here, but consider this: I was thinking.. "from your CGI code you're actually reading from a socket, that's wrapped in a file-like object". Sockets behave like I said. So I thought: the read() behaves like this too. Even more so because there is no such thing as "EOF" on sockets. How can the read() know when all data have been read? Irmen PS a read() on a *true* file would read everything, ofcourse, like you pointed out. From james at anchor.net.au Thu Mar 27 06:10:26 2003 From: james at anchor.net.au (James Gregory) Date: 27 Mar 2003 11:10:26 +0000 Subject: session information in cgi scripts In-Reply-To: References: Message-ID: <1048763426.14913.12.camel@pirate.bridge.anchor.net.au> On Wed, 2003-03-26 at 09:35, Dale Strickland-Clark wrote: > James Gregory wrote: > > >Hi all, > > > >I'm relatively new to python, and this is the first time I've tried to > >use it for web stuff. > > > >Simple qn: Is there a module that implements session data? Or rather, > >what is the module that implements session data? I'm using python as a > >CGI so storing stuff in my own webserver isn't really an option. I > >looked on http://python.org/doc/current/modindex.html and nothing leapt > >out at me. > > > >Thanks, > > > >James. > > > > > > There's two main ways to maintain session data. 1: Store it at the > server and identify it with a unique session id in a cookie. 2: store > it all in cookies and hidden form fields. You can mix the two > approaches too. Each has advantages and disadvantages. > > Either way, I'm not really sure how a module could help you in this > one respect without dictating the wider architecture of your > application. What I had in mind was something like the following: a module which contained a class that inherited from dict. This quasi-dict's constructor would read in the appropriate cookie containing a session id and unpickle the session info from a file in /tmp or something. The destructor (I am assuming that python lets you define a destructor even though it is garbage collected) for said dict would simply pickle its contents and write it to disk. As I understand it the dict would be destroyed at the end of the program's execution - ie after any changes to this session data had been performed. So then after the class definition it would just instantiate one of these things and make it global. Is something like this possible? Would the garbage collector do things in the appropriate order? How do I define a destructor? And most importantly: has someone already done this? Thanks, James. From cnetzer at mail.arc.nasa.gov Fri Mar 14 19:50:41 2003 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: 14 Mar 2003 16:50:41 -0800 Subject: Newbie question about function return values In-Reply-To: References: Message-ID: <1047689441.650.144.camel@sayge.arc.nasa.gov> On Fri, 2003-03-14 at 16:19, John Machin wrote: > Chad Netzer wrote in message news:... > > > > def sectors(x): > > if ((x % 512) != 0): > > x = x + 1 > > return sectors(x) > > else: > > return x > > > > > > BTW - There are better methods of finding the next larger power of two. > (2) "power of 2" seems totally irrelevant. Oops, you are right. The task was to find the next higher multiple of 512 (as you stated). > Try this: > > def round_to_higher_mult_of_512(x): > return ((x + 511L) // 512L) * x > # 'L' just in case rounded-up file size >= 2GB ??? >>> round_to_higher_mult_of_512(511) 511L >>> round_to_higher_mult_of_512(513) 1026L I'll suggest this instead: # Will automatically promote to long int in python 2.2.x def round_to_higher_mult_of_512(x): return (x//512 + 1) * 512 -- Bay Area Python Interest Group - http://www.baypiggies.net/ Chad Netzer (any opinion expressed is my own and not NASA's or my employer's) From aleax at aleax.it Mon Mar 31 04:34:56 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 31 Mar 2003 09:34:56 GMT Subject: A default in the __init__ is like a class variable? References: <35404b41.0303300501.27ae4054@posting.google.com> Message-ID: <4ZTha.34933$Jg1.803143@news1.tin.it> Jens Gelhaar wrote: > Is this a feature? > >>>> class test: > ... def __init__(self,t=[]): > ... self.t=t > ... >>>> t1=test(); t2=test() >>>> t1.t.append("feature?") >>>> print t1.t > ['feature?'] >>>> print t2.t > ['feature?'] >>>> > > I know why both t has the same list, but I would not expect this. Each > instance should have it's own list. That's not what you've coded! When you code: self.t = t you are NOT ensuring that each instance will have their own list -- on the contrary, you're specifically asking for multiple instances to be able to share one list. Python does no copies unless you explicitly ASK for copies! It's not just a matter of the default value, mind: x = range(3) a = test(x) b = test(x) here a.t is x, b.t is x, a.t is b.t. You coded it that way!!! So ANY mutation done through any of these references to the one and only underlying object, e.g. a.t.append('uh?'), will OF COURSE be visible through all references equally -- they're all references to the SAME object, so how could it possibly be otherwise?! Just change the body of __init__ to: self.t = list(t) and NOW your code is expressing EXACTLY what your later words said -- each instance WILL have its own attribute, AND that attribute will MOST definitely be a list, whatever type argument t is (you'll get an exception if t is of such a type that no list can be built from it). If you really mean it when you say "each instance should have its own list", then CODE it that way -- it's as simple as this. If you mean something slightly different, then code it in condign slightly different ways. Again, it IS as simple as this. Python does what you TELL it to do -- it does NOT try to read your mind and impose what somebody thinks "should" happen but is different than _what you have ACTUALLY coded_. This crucial language design choice is part of what makes Python simple AND powerful at the same time. Alex From mchermside at ingdirect.com Thu Mar 13 10:37:03 2003 From: mchermside at ingdirect.com (Chermside, Michael) Date: Thu, 13 Mar 2003 10:37:03 -0500 Subject: Jython 2.2 Message-ID: <7F171EB5E155544CAC4035F0182093F03CF78F@INGDEXCHSANC1.ingdirect.com> I'm curious... does anyone know how Jython 2.2 is coming - how much of it works, and whether there is an estimated release date? -- Michael Chermside From spam at magnetic-ink.dk Mon Mar 17 01:08:40 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Mon, 17 Mar 2003 06:08:40 +0000 (UTC) Subject: twisted.conch example References: <3E7547AA.DB9D3B29@engcorp.com> Message-ID: Peter Hansen wrote: > This may be of little help, but it's the best I can offer: > Twisted apparently comes with a "full" suite of unit tests, > as [...] Also, twisted.conch comes with a command line ssh-client, conch, from which you might glean something. The script, however, is surprisingly simply -- basically two lines: #v+ from twisted.scripts.conch import run run() #v- // Klaus -- ><> unselfish actions pay back better From aahz at pythoncraft.com Mon Mar 17 10:54:22 2003 From: aahz at pythoncraft.com (Aahz) Date: Mon, 17 Mar 2003 10:54:22 -0500 Subject: PyCon: Last week for pre-reg! Message-ID: <20030317155422.GA24764@panix.com> Friday, March 21 is the deadline if you want to get the $200 pre-conference price. PyCon will cost $250 at the door, and there is no single-day rate. http://www.python.org/pycon/reg.html PyCon DC 2003 The first PyCon will be held 26-28 March, 2003, at George Washington University's Cafritz Conference Center in Washington DC. There will be a development sprint Mon/Tues before the conference. PyCon is a community-oriented conference targeting developers (both those using Python and those working on the Python project). It gives you opportunities to learn about significant advances in the Python development community, to participate in a programming sprint with some of the leading minds in the Open Source community, and to meet fellow developers from around the world. The organizers have worked hard to ensure that the conference be affordable and accessible to all. We look forward to seeing you there. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Register for PyCon now! http://www.python.org/pycon/reg.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Register for PyCon now! http://www.python.org/pycon/reg.html From johnp at reportlab.com Thu Mar 13 07:11:11 2003 From: johnp at reportlab.com (John Precedo) Date: Thu, 13 Mar 2003 12:11:11 +0000 Subject: Python UK conference on a Budget Message-ID: <77t07vka60cjjrfvejmid4kd7p5etm2elc@4ax.com> Python UK conference on a Budget ================================ If you don't have a generous company or a rich uncle to pay for you to fly to the Python UK conference, you may want to know about the cheapest ways of getting to Oxford from Europe for the Python UK conference.... What is the Python UK conference? --------------------------------- The 2003 Python UK Conference will take place in Oxford, on Wednesday April 2nd and Thursday 3rd, at the Holiday Inn Oxford. The keynote will be given by Guido van Rossum (the Python language founder), and the talks will be on subjects ranging from jython to XP. Other speakers include: Sarah Lees, Ulrich Eisenecker, Lois Goldthwaite, Alan Griffiths, Duncan Grisby, Jacob Hall?n, Chris Hills, Kevlin Henney, Jon Jagger, Jaako Jarvi, Simon Peyton Jones , Nico Josuttis, Andrew Koenig , Angelika Langer, Hamish Lawson, Marc-Andr? Lemburg, Alan Lenton, Randy Marques, Alex Martelli, Hubert Matthews, Mark Radford, Arno Schmidmeier, Jeremy Siek, Julian Smith, Nathan Sidwell, Herb Sutter, Daveed Vandevoorde, Guido van Rossum, Andy Todd, JC van Winkel, Chris Withers, and Willem Wakker, More information at the web site: http://www.python-uk.org/ Getting there from Europe ------------------------- Flying by the budget airlines is the best way - check to see if these airlines fly from your location and compare prices: * Buzz (http://www.buzzaway.com/) * Ryanair (http://www.ryanair.com/) * Easyjet (http://www.easyjet.com/) As a rough guide, these are the best prices I found, but check the airlines' sites for the latest information. All prices are one way for a single adult on either Monday 31 March or Tuesday 1 April, booked via the web. Check for prices for the days either side of the one you intend to travel, you can sometimes make a substantial saving if you can find somewhere to cool your heels 24 hours. All of these prices were available on the respective web sites as of last night, but prices and availably may change. * Amsterdam: 32.50 EUR EASYJET (http://www.easyjet.com/) Amsterdam to London Gatwick * Barcelona: 29.99 EUR RYANAIR (http://www.ryanair.com/) Barcelona-Girona (GRO) to London Stansted (STN) * Berlin: 70.00 EUR BUZZ (http://www.buzzaway.com/) Berlin Schoenefeld (SXF) to London Stansted (STN) * Dijon: 76.00 EUR BUZZ (http://www.buzzaway.com/) Dijon - Burgundy (DIJ) to London Stansted (STN) * Dusseldorf: 44.35 EUR BUZZ (http://www.buzzaway.com/) Dusseldorf (DUS) to London Stansted (STN) * Geneva: 60.00 CHF EASYJET (http://www.easyjet.com/) Geneva to London Gatwick * Hamburg: 14.99 EUR RYANAIR (http://www.ryanair.com/) Hamburg L?beck (LBC) to London Stansted (STN) * Lyon: 23.00 EUR EASYJET (http://www.easyjet.com/) Lyon to London Stansted * Madrid: 46.50 EUR EASYJET (http://www.easyjet.com/) Madrid to London Gatwick * Milan: 9.99 EUR RYANAIR (http://www.ryanair.com/) Milan Bergamo (BGY) to London Stansted (STN) * Munich: 37.00 EUR EASYJET (http://www.easyjet.com/) Munich to London Stansted * Paris: 47.50 EUR EASYJET (http://www.easyjet.com/) Paris Charles de Gaulle to London Luton * Prague: 2225.00 CSK EASYJET (http://www.easyjet.com/) Prague to London Stansted * Rome: 47.00 EUR EASYJET (http://www.easyjet.com/) Rome Ciampino to London Stansted * Zurich: 52.50 CHF EASYJET (http://www.easyjet.com/) Zurich to London Gatwick (Ryanair also lists flights from a number of destinations including Brussels S. Charleroi and Frankfurt-Hahn (HHN) at 0.01 EUR!) Getting from the airport to Oxford ---------------------------------- BY PUBLIC TRANSPORT This depends on which one you fly to. STANSTED The 757 bus operated by National Express goes directly from Stansted Airport to Oxford. The length of the journey is listed as 2 hours 50 minutes on their web site. The fare is ?14.00 for an economy single, or ?20.00 for an economy return (open for six months, so you can chose which day you come back on). GATWICK The X80 bus operated by Oxford Express goes directly from both the North and South Terminal to Oxford. The journey length is approximately 2 hrs (5 minutes or so less from the North Terminal). The fare is ?20.00 for an economy single, or ?21.00 for a Next Day Return. These routes are both 'high frequency turn up and ride services'. You can buy the tickets on the day from the driver, in advance though the National Express web site (http://www.nationalexpress.com/). (A fee of ?1.50 may be payable when you confirm the return reservation). The Oxford Bus company also runs an 'airline' bus service from Gatwick (North and South Terminals) directly to Oxford. A one way adult ticket costs ?20.00, with a Period return (open for 3 months) for ?23.00 More information on their web site (http://www.theairline.info/) BY CAR If you're planning to use a car to get from the airport to the conference, the best thing to do would be to share a ride. There should be something up on the site soon (probably a Wikki) to allow you to co-ordinate ride-shares, meeting up and so on. -- John Precedo (johnp at reportlab.com) Developer Reportlab Europe Ltd (http://www.reportlab.com) From me at privacy.net Mon Mar 10 23:16:30 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 11 Mar 2003 17:16:30 +1300 Subject: Time<->Weather (Re: A suggestion for a possible Python module) In-Reply-To: References: Message-ID: Alex Martelli wrote: > Italian is > even farther from English in terminology (e.g., in common speech we > do not distinguish between 'time' and 'weather', using the same > word, 'tempo', for both Oh, no! Do you realise the implications of this? Whenever we hear about the PSU using their time machine for some nefarious purpose, they may actually be talking about a *weather* machine instead! This could be quite disturbing... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From luke at ukonline.co.uk Wed Mar 12 17:30:48 2003 From: luke at ukonline.co.uk (Luke McCarthy) Date: Wed, 12 Mar 2003 22:30:48 -0000 Subject: Simple thing about printing References: Message-ID: lol "Paul Watson" wrote in message news:v6vbmr5plchpaf at corp.supernews.com... > Use the doc, Luke. Use the doc. > > > "Paul Watson" wrote in message > news:v6vbjgrklv5r7d at corp.supernews.com... > > While this PEP is about a larger issue, the answer to your question is in > > the first sentence of the abstract. > > > > http://www.python.org/peps/pep-0259.html > > > > The answer is also in the tutorial. > > > > > http://www.python.org/doc/current/tut/node9.html#SECTION00910000000000000000 > > 0 > > > > > > > > "Luke McCarthy" wrote in message > > news:d7Nba.8804$EA6.1433105 at newsfep2-win.server.ntli.net... > > > It's funny how you use Python for a while and then something very simple > > > comes up and stops you. > > > How can I print without a newline being automatically inserted at the > end? > > > > > > Luke McCarthy > > > > > > > > > > > > From exarkun at intarweb.us Wed Mar 12 14:03:31 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Wed, 12 Mar 2003 14:03:31 -0500 Subject: I don't understand PEP 308. In-Reply-To: <2635252.1047490747@dbforums.com> References: <2635252.1047490747@dbforums.com> Message-ID: <20030312190331.GC30375@meson.dyndns.org> On Wed, Mar 12, 2003 at 05:39:07PM +0000, Tetsuo wrote: > > I saw there's a debate over it, and decided to read it. I didn't read > much, but what I can understand is that it proposes an if-then > statement. ^^^^^^^^^ It proposes an if-then expression. Jp -- up 9 days, 11:59, 6 users, load average: 0.23, 0.25, 0.20 From r.erens at eurosys.nl Thu Mar 20 07:49:52 2003 From: r.erens at eurosys.nl (Roger Erens) Date: Thu, 20 Mar 2003 13:49:52 +0100 Subject: help with filling a struct for use in win32api.SendMessage() Message-ID: <6D9E338D57C2D411AC5800105AF41E123A1B58@mailnt.eurosys.nl> Hello, I'd like to make an MS windows application show up and present me some data. I ought to use the windows API-calls FindWindow and SendMessage, but I don't really know how to create the arguments needed for the latter call. Could someone give me some directions about how to construct the 'xxx' in the code fragment below? Should I use something like ctypes or Pyrex? Thanks in advance, Roger hApp = win32gui.FindWindow( 'MyApp', None) # this seems to work if hApp: SendMessage(hApp, win32con.WM_COPYDATA, 0, xxx) This is the (C) documentation I have for MyApp: obtain the handle: hV = FindWindow( "V", NULL ); if hV is not NULL, commands can be sent: Status = SendMessage( hV, WM_COPYDATA, (WPARAM)hWnd, (LPARAM)pData ); ... pData = Pointer to a COPYDATASTRUCT, via windows.h defined as: typedef struct tagCOPYDATASTRUCT { DWORD dwData; // Specifies up to 32 bits of data to be passed to the receiving application. DWORD cbData; // Specifies the size, in bytes, of the data pointed to by the lpData member. PVOID lpData; // Points to data to be passed to the receiving application. This member can be NULL. } COPYDATASTRUCT; dwData is always 0x53445256 cbData is minimal sizeof(VRC_HEADER) lpData always points to a VRC_HEADER structure. typedef struct { DWORD Magic; DWORD Command; BYTE Data[1]; } VRCHEADER From h_schneider at marketmix.com Thu Mar 20 10:37:01 2003 From: h_schneider at marketmix.com (Harald Schneider) Date: Thu, 20 Mar 2003 16:37:01 +0100 Subject: AW: Detect IP changes In-Reply-To: <3E79DCF7.4030307@freemail.hu> Message-ID: <000101c2eef6$8d76bdd0$0100a8c0@tbird> Thank you -- I see .. it works great, you'r the absolute GURU! All the best, Harald > -----Urspr?ngliche Nachricht----- > Von: Nagy L?szl? Zsolt [mailto:nagylzs at freemail.hu] > Gesendet: Donnerstag, 20. M?rz 2003 16:24 > An: Harald Schneider; comp.lang.python > Betreff: Re: Detect IP changes > > > > >Is there a reliable way to detect the change of a dynamic IP > address ? > >If I use socket.gethostbyname('my_dynip_name') I still get > the old IP, even > >thougt my system's DNS has been refreshed with the new > name-address binding > >... > >A solution should be platform independent. > > > >Thanks for your answers! > > > > > I forgot to mention that you should set COMMON_HOST and > COMMON_PORT to > a service near you. > For example, a mail server of your ISP. Any server that can > be connected > in a Jiffy. > > Laci 1.0 > > > From david.bear at asu.edu Thu Mar 13 20:52:28 2003 From: david.bear at asu.edu (David Bear) Date: Thu, 13 Mar 2003 18:52:28 -0700 Subject: while semantics References: <3e7121c2$0$80693$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: > In article , David Bear wrote: >> I think I'm confusing myself regarding semantics for a while loop. >> >> while (conditionX): >> do something >> while (conditionY): >> do something else >> while (conditionZ): >> do something >> here conditionX becomes False >> print something >> print something else >> >> Will the outer while loop cause all nested whiles to end as soon as >> conditionX is false? > > No. conditionX will only be checked once per "outer loop". If > you're in one of the inner loops, you stay there until that > loop's condition is false. > >> or will 'print something' be reached, then 'print >> something else' and so on untill it reaches the outer scope? > > Neither. You'll stay inside in Z loop until conditionZ > becomes false. Then you'll stay in the Y loop until conditionY > becomes false. After both the Z and Y loops have terminated, > conditionX will be checked again. > What about while (condition): do stuff do more stuff condition becomes true do even more stuff Will while terminate AS SOON as condition is true, or will it evaluate all statements in the block? From shendley at email.unc.edu Mon Mar 24 20:02:14 2003 From: shendley at email.unc.edu (Sam) Date: 24 Mar 2003 17:02:14 -0800 Subject: Passing params to single instance of wxApp Message-ID: <3088fc9a.0303241702.11bdbe2e@posting.google.com> I want my app to only allow one instance, the problem is that it is associated with a file type so when another of that file type is opened I end up with two instances. I used the wxSingleInstanceChecker to stop this from occuring but I really want to pass the params (i.e. new filename) to the running app. Any ideas? I tried the below solution but it doesnt work cause the two processes have differnt instantiations of the object.Thanks in advance guys, I looked through the demos, manuals, documentation, and the web, and couldnt find a solution, you all are my last hope. If anyone is curious this is how I fixed the general single instance problem class MyApp(wxApp): def __init__(self, params): self.params = params self.checker = btChecker( self.name) self.checker.setOwner(self) wxApp.__init__(self) def main(params): print params checker = btChecker('PTC- ' + str(wxGetUserId())) if checker.IsAnotherRunning(): checker.alreadyRunning(params) else: app = MyApp(params) app.MainLoop() class btChecker(wxSingleInstanceChecker): def __init__(self, str): wxSingleInstanceChecker.__init__(self, str) def setOwner(self,owner): self.owner=owner def alreadyRunning(self, params): if params != []: self.owner.CheckFile(params[0]) if __name__ == '__main__': main(argv[1:]) From tomchance at gmx.net Sat Mar 29 19:29:51 2003 From: tomchance at gmx.net (Tom Chance) Date: Sun, 30 Mar 2003 00:29:51 +0000 Subject: namespace problems in pyqt Message-ID: <%2rha.70$6U5.65818@newsfep2-win.server.ntli.net> Hullo, I've got a problem that's come about by not wanting to create a new class for a dialogue box in PyQt. Previously, I had a class for the dialogue which included a function connected to a button in the dialogue. I made the class for the dialogue box in Qt Designer, imported that class, inherited it in a new class, into which I put the function (so it overrode the empty function declaration in the original class), like so: class Inherited(QDialog): /all the pyqt stuff/ connect signal to function2 class Inheritor(Inherited): def function2: /so some stuff/ Now that function isn't in that dialogue's class... it's in the namespace that is calling the class instance, e.g.: def function1(self): /do some stuff.../ instance = Inherited() def function2(self): /do some stuff.../ How can I connect the button in Inherited to function2()? I've been told you can connect a Qt signal to a global function, but I can't work out how; I've tried declaring "global function2", and I've read through the Qt docs, but I cant' figure it out, so I'm obviously just being dumb and missing something here. Can someone give me a hand? Cheers, Tom From s.ernst at web.de Sun Mar 23 16:09:07 2003 From: s.ernst at web.de (Sascha Ernst) Date: 23 Mar 2003 21:09:07 GMT Subject: additional information References: <20030323215111818+0100@news.freenet.de> Message-ID: <20030323220915670+0100@news.freenet.de> when try parseString in the python-environment, i get the following error-messages: Traceback (most recent call last): File "", line 1, in ? File "/BinaryCache/python/python-3.root~193/usr/lib/python2.2/xml/dom/ minidom.py", line 965, in parseString File "/BinaryCache/python/python-3.root~193/usr/lib/python2.2/xml/dom/ minidom.py", line 951, in _doparse File "/BinaryCache/python/python-3.root~193/usr/lib/python2.2/xml/dom/ pulldom.py", line 340, in parseString File "/BinaryCache/python/python-3.root~193/usr/lib/python2.2/xml/sax/__ init__.py", line 93, in make_parser xml.sax._exceptions.SAXReaderNotAvailable: No parsers found i guess there is something wrong with my installation, but what exactly? regards, sascha From exarkun at intarweb.us Sat Mar 1 13:51:12 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sat, 1 Mar 2003 13:51:12 -0500 Subject: for i in list - change a list inside a for loop? In-Reply-To: References: Message-ID: <20030301185112.GB27223@meson.dyndns.org> On Sat, Mar 01, 2003 at 07:37:03PM +0100, Klaus Meyer wrote: > Hi, > > it is OK to change a list inside a for loop? > Example: > > x=range(100) > for i in x: > del x[-1] > Nope. This is Bad. Same goes for most mutable types, you shouldn't change them while you're iterating over them. > > Another Question: > How to remove a found element from a list in a for-loop? > > x=["A", "B", "C", "D"] > for i in x: > if i=="C": del x[this one, but how?] > for i in range(len(x) - 1, -1, -1): if x[i] == "C": del x[i] Iterating backwards prevents the indices from being kicked out of sync when you delete an element (try it going forward if you don't see why this might be a problem). Iterating over the indices of the list lets you know where you are at all times, but it can be slightly less convenient. You could iterate over indices and values... rev_x = x[:] rev_x.reverse() for (i, v) in zip(range(len(x) - 1, -1, -1), rev_x): if v == "C": del x[i] In 2.3, enumerate() has been added, but it only goes forward. For lists, you could solve this by... def rev_enumerate(sequence): rev_seq = sequence[:] rev_seq.reverse() return enumerate(rev_seq) As you can see, this is just a simple abstraction of the previous example. Jp -- http://catandgirl.com/view.cgi?44 -- up 20 days, 22:29, 4 users, load average: 0.45, 0.27, 0.26 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From morden at shadows.net Fri Mar 28 15:59:34 2003 From: morden at shadows.net (morden) Date: Fri, 28 Mar 2003 12:59:34 -0800 Subject: 2.2.1 crashes on Linux (RH7.3) trying to load python shared library timemodule.so In-Reply-To: References: Message-ID: Martin v. L?wis wrote: > morden writes: > > >>1. Why does 2.2.1 goes looking for timemodule.so in >>/usr/lib/python2.2/lib-dynload/ even though I've built it statically >>with prefix /u/local > > > That is hard to believe, unless you have added somehow > /usr/lib/python2.2 to sys.path. Are you sure your app is linked with > the library you have built? Yes, the warnings that linked gives for my app point to the sources of 2.2.1: /u/local/lib/python2.2/config/libpython2.2.a(posixmodule.o): In function `posix_tmpnam': /usr/local/src/Python-2.2.1/./Modules/posixmodule.c:4505: the use of `tmpnam_r' is dangerous, better use `mkstemp' /u/local/lib/python2.2/config/libpython2.2.a(posixmodule.o): In function `posix_tempnam': /usr/local/src/Python-2.2.1/./Modules/posixmodule.c:4453: the use of `tempnam' is dangerous, better use `mkstemp' The crash happens in Py_Initialize before I get a chance to mess with sys.path Here's the top of the stack: #102 0x080c5f48 in builtin___import__ (self=0x0, args=0x81cd22c) at Python/bltinmodule.c:40 #103 0x0806b114 in PyCFunction_Call (func=0x81c7d28, arg=0x81cd22c, kw=0x0) at Objects/methodobject.c:80 #104 0x080551e0 in PyObject_Call (func=0x81c7d28, arg=0x81cd22c, kw=0x0) at Objects/abstract.c:1684 #105 0x0808df0f in PyEval_CallObjectWithKeywords (func=0x81c7d28, arg=0x81cd22c, kw=0x0) at Python/ceval.c:3049 #106 0x080548a2 in PyObject_CallFunction (callable=0x81c7d28, ---Type to continue, or q to quit--- format=0x8144f27 "OOOO") at Objects/abstract.c:1725 #107 0x080a2821 in PyImport_Import (module_name=0x81d4130) at Python/import.c:2048 #108 0x080a2faa in PyImport_ImportModule (name=0x81466c3 "site") at Python/import.c:1574 #109 0x080a97ab in initsite () at Python/pythonrun.c:443 #110 0x080a7c90 in Py_Initialize () at Python/pythonrun.c:173 >>2. How could I tell configure that I want modules statically linked with >>libpython.a? > > > I'm not sure I understand this question. Which modules? The ones of > the standard Python distribution? They are never linked with Yes. Stuff like timemodule.so that my program tries to load dynamically. > libpython.a: they are *part* of it. Your own modules? which configure > do you want to tell something, then? > configure of Python 2.2.1 of course! From skip at pobox.com Sat Mar 22 18:15:16 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 22 Mar 2003 17:15:16 -0600 Subject: CGI: how to get referer header? In-Reply-To: <3E7CDA7E.7070308@NOmyrealCAPSbox.com> References: <3E7C5215.6070209@NOmyrealCAPSbox.com> <3E7CDA7E.7070308@NOmyrealCAPSbox.com> Message-ID: <15996.61060.221180.526307@montanaro.dyndns.org> Skip> They should be available in the environment as HTTP_USER_AGENT and Skip> HTTP_REFERER. Take a look at >> Thanks for the help. I tried using HTTP_USER_AGENT and HTTP_REFERER, >> but I get similar results, a tuple containing an empty dictionary. Sorry, I should have given a specific example. Try this: import os print "Referer:", os.environ.get("HTTP_REFERER", "") print "User Agent:", os.environ.get("HTTP_USER_AGENT", "") Skip From mwh at python.net Tue Mar 18 07:04:40 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 18 Mar 2003 12:04:40 GMT Subject: [Q] Databases -- Gadfly vs Metakit vs SQLite References: <698f09f8.0303172102.751bc668@posting.google.com> Message-ID: <7h3r894j2y0.fsf@pc150.maths.bris.ac.uk> tweedgeezer at hotmail.com (Jeremy Fincher) writes: > "David LeBlanc" wrote in message news:... > > There has been discussion on python-dev about merging the python only > > version (no C coded kjbuckets) of Gadfly into the next distro of Python > > (2.3), but I don't recall what was decided. > > I believe they decide it was better off left as an external package, > since most people don't expect that "Batteries included" means "SQL > database included." And because the developers don't want to be landed with maintaining a large wodge of code they don't understand. Cheers, M. -- That's why the smartest companies use Common Lisp, but lie about it so all their competitors think Lisp is slow and C++ is fast. (This rumor has, however, gotten a little out of hand. :) -- Erik Naggum, comp.lang.lisp From skip at pobox.com Fri Mar 7 10:17:54 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 7 Mar 2003 09:17:54 -0600 Subject: bsddb crashes on windows In-Reply-To: <5.1.0.14.0.20030307105920.01a36010@131.103.204.244> References: <20030307020101.12244.35865.Mailman@mail.python.org> <5.1.0.14.0.20030307105920.01a36010@131.103.204.244> Message-ID: <15976.47138.80321.755378@montanaro.dyndns.org> Jarek> Will [the new bsddb] be compatible with current bsddb code? >> >> There are two components to compatibility you need to consider, the >> API at the Python level and the format of the bits written to >> database files. There is a backwards compatibility API in the new >> bsddb package which is compatible with the previous module's API. >> The file format will of necessity change, because the version of the >> underlying library with Python for Windows will jump from 1.85 to >> 4.1.25. Vijay> Does this mean that if I use bsddb3 with Python 2.2 I wont have Vijay> to make any change when I use the same code base with Python 2.3. Correct. You can still call bsddb.hashopen(...) to open a database file. Assuming you use the same underlying version of Berkeley DB under 2.2 and 2.3 (say, db-3.3.11 or db-4.1.25), you won't even have to fiddle with your files. Take a look at http://www.python.org/dev/doc/devel/whatsnew/whatsnew23.html for a description of the new bsddb module. I'll try and embellish that a bit, since it seems to be a point of some confusion. Skip From intentionally at blank.co.uk Tue Mar 11 07:44:37 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 11 Mar 2003 12:44:37 +0000 Subject: Summary of PEP 308 Vote for a Ternary Operator References: <3E6D54C6.E645557D@alcyone.com> <1jm0k-nl3.ln1@beastie.ix.netcom.com> Message-ID: On Tue, 11 Mar 2003 01:24:17 -0800, Dennis Lee Bieber wrote: > Whereas I felt the so-called official vote mechanism -- wherein >listing any option at all, even if with "reject" was still a favorable >vote for that option -- was so confusing it wasn't worth my time to >figure out. I saw that as 'this is worse than no change, but not as bad as the alternatives'. From dave at pythonapocrypha.com Tue Mar 25 13:32:44 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 25 Mar 2003 10:32:44 -0800 (PST) Subject: is win api available in native python In-Reply-To: References: <3e7e5a37_4@newsfeed> <33803989.0303240746.facc13@posting.google.com> <3e7faa23_4@newsfeed> Message-ID: On Tue, 25 Mar 2003, David Bolen wrote: > BTW, you don't mention your Windows platform, but the > InternetAutodialHangup API is a Windows CE specific API. Tiny correction: the MSDN docs say Win95 or later (assuming IE 4 or later). On my W2k machine: >>> from ctypes import windll >>> windll.wininet.InternetAutodialHangup <_ctypes.ExportedFunction object at 0x007A4BF8> -Dave From exnihilo at NOmyrealCAPSbox.com Wed Mar 26 23:49:59 2003 From: exnihilo at NOmyrealCAPSbox.com (nihilo) Date: Thu, 27 Mar 2003 04:49:59 GMT Subject: CGI: how to get referer header? In-Reply-To: References: <3E7C5215.6070209@NOmyrealCAPSbox.com> <3E7CDA7E.7070308@NOmyrealCAPSbox.com> Message-ID: <3E8282F9.6060806@NOmyrealCAPSbox.com> Tim Roberts wrote: > nihilo wrote: > > >>Skip Montanaro wrote: >> >>> Skip> They should be available in the environment as HTTP_USER_AGENT and >>> Skip> HTTP_REFERER. Take a look at >>> >>> >> Thanks for the help. I tried using HTTP_USER_AGENT and HTTP_REFERER, >>> >> but I get similar results, a tuple containing an empty dictionary. >>> >>>Sorry, I should have given a specific example. Try this: >>> >>> import os >>> >>> print "Referer:", os.environ.get("HTTP_REFERER", "") >>> print "User Agent:", os.environ.get("HTTP_USER_AGENT", "") >> >>This works great. Thanks so much for the help ;-) > > > But do you understand why? I think it's important to understand why one > works and the other doesn't. This particular issue, for example, is not a > Python issue in any way: it is a CGI issue. > > In CGI, you do not get direct access to the HTTP headers at all. > Everything in the HTTP headers is disbursed to environment variables before > the CGI program is invoked. The content of the request is routed to the > stdin of the CGI program. > > Thus, cgi.parse_header does not fetch a header and parse it. Rather, you > give it a STRING to be parsed. That string usually comes from an > environment variable, which came originally from the HTTP headers, but > cgi.parse_header doesn't actually go looking for a header. Thanks for the explanation. I did indeed wonder why I was getting HTTP header stuff from the environment, but it makes sense now. thanks, nihilo From bob at rsballard.com Sat Mar 8 14:23:14 2003 From: bob at rsballard.com (Bob Ballard) Date: Sat, 08 Mar 2003 13:23:14 -0600 Subject: Fixes to zipfile.py [PATCH] References: <87heae244i.fsf@christoph.complete.org> Message-ID: <3E6A4322.9010908@rsballard.com> You should try using python to control winzip from the command line as you can any other shell too. should do what you want. See, http://www.winzip.com/xcmdline.htm Bob John Goerzen wrote: > Hello, > > I have an instance where I need to use zipfile.py for reading large > (50,000-file, 500MB or larger) ZIP files. Unfortunately, it is rather From mchermside at ingdirect.com Tue Mar 18 13:30:27 2003 From: mchermside at ingdirect.com (Chermside, Michael) Date: Tue, 18 Mar 2003 13:30:27 -0500 Subject: file objects choices? Message-ID: <7F171EB5E155544CAC4035F0182093F03CF7B2@INGDEXCHSANC1.ingdirect.com> > are there any existing python file i/o types that can be represented > by file objects other than: > -direct files (regular, directories) specified for the open function > -stdin, stdout, stderr streams via sys module > -input from piped commands of output from program executed by os/ > another program StringIO and cStringIO. Also sockets via the makefile() method of socket objects. I'm sure there are a few others also. And there are quite a few user-defined things that intentionally mimic the file "protocol" since it's easy to do. -- Michael Chermside From skip at pobox.com Wed Mar 5 13:35:30 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 5 Mar 2003 12:35:30 -0600 Subject: help! advocacy resources needed fast In-Reply-To: <20030305175648.GE8640@isis.gerrietts.net> References: <20030305175648.GE8640@isis.gerrietts.net> Message-ID: <15974.17266.62617.835625@montanaro.dyndns.org> Geoff> The bottleneck is in Zope; some portion of this could be blamed Geoff> on the dynamic nature and complexity of our pages, but some Geoff> portion is pushing DTML through a Python parser on every request. Have you tried Zope Page Templates (ZPT)? Are they faster or slower than DTML? Geoff> We have spent a year refactoring key components, and building Geoff> caching solutions to minimize the impact of load. We're still Geoff> having some problems, and the problems look to increase. What sort of caching do you do? Squid or Apache, or something wedged into Zope? Geoff> The guy who's pushing Java, he's got a nice easy answer, because Geoff> Sun's marketing budget makes his case for him. I have a harder Geoff> time: anecdotal evidence about increase in programmer Geoff> productivity, short turnaround times, shallow learning curve. Are those advantages touted for Java as well? System performance or not, your management isn't probably going to be happy trading off a 2-10x performance boost for a 2-10x reduction in productivity. ;-) Geoff> And when it comes right down to it, we need examples of sites Geoff> doing the same kind of highly-dynamic, high-volume business we're Geoff> doing, in some python toolkit, and succeeding. Check out the Twisted success stories: http://www.twistedmatrix.com/services/success Sam Rushing mentions "long-running, high performance network servers" on the Medusa page, and goes on to say: Medusa is un use now in several mission-critical applications, ranging from custom web servers at extremely high-traffic sites to distributed data processing systems. Check here: http://www.nightmare.com/medusa/index.html Perhaps Sam can give you more details behind his statements. My guess is that since Andrew Kuchling has taken over some/all the maintenance of Medusa that Quixote also uses it. You might check here: http://www.mems-exchange.org/software/quixote/ Geoff> As dire as I've made things look, every engineer who touches the Geoff> Python code, wants to work in Python. We like Python, we're good Geoff> at Python, and Python has proven to be our engineering Geoff> department's competitive advantage. So, it's not like I'm Geoff> standing out there alone. It's just that I'm the guy nominated Geoff> most likely to come up with an architecture we could live with. If you know it's DTML and ZPT is faster, perhaps you can get enough performance boost by switching heavily accessed pages to ZPT, giving yourself a bit more breathing room. Skip From oren-py-l at hishome.net Thu Mar 20 06:50:43 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Thu, 20 Mar 2003 06:50:43 -0500 Subject: why * is not like unquote (scheme) In-Reply-To: References: Message-ID: <20030320115043.GB81021@hishome.net> On Thu, Mar 20, 2003 at 01:26:07PM +0200, Amir Hadar wrote: > Hi > > I'me tring to create a factory function that create a class as follow: > > def CreatePreviewFrame(*addins): > class tmp(cPreviewFrame,*addins): > pass > return tmp > > I checked a simpler case: > (1,2,*(3,4)) > and this is also syntax error. > > but I can path parameters to a function as follow: > > def f(a,b): > print a,b > > l = ("a","b") > f(*l) > > So why doesn't it work in all cases? The * is specific to calls. It does not apply to other places in the systax where a comma-separated list is acceptable. You can do what you want using the exec statement or by directly creating the class object with new.classobj() instead of using the class statement. Oren From maxm at mxm.dk Tue Mar 4 16:34:11 2003 From: maxm at mxm.dk (Max M) Date: Tue, 04 Mar 2003 22:34:11 +0100 Subject: Sorry ... In-Reply-To: References: Message-ID: <3E651BD3.20003@mxm.dk> Lance LaDamage wrote: > If I shocked you by my various errors, it's because one thing ... and > prepare for the shock ... : I would not say that I was shocked. I have seen the same errors many other places. Even in professional work. You just had many of them collected in a short piece of code ;-) > I am an 11 year old child who enjoys to program in Visual Basic and have > recently learned Python because a chat friend had a chatbot (written in > Python) and I was required to develop most of it. That is great. Python is great fun. I wish it was around when I was a kid. I guess you will enjoy it even more than VB. > I'm very interested in > programming and I rely on the help of other programmers to help you (because > my mother and father can't.) If anyone can offer me any tips or help, I > would appreciate it. You can just ask here, and you will most likely get help. What you did, writing a piece of code and then asking for comments, is probably the best way to get help. It is much easier to help with something concrete than a more general question. And though you might not think of it as such, my critiscism of your code was an attempt to help you. For a beginning 11 year old programmer your code was actually very good! -- hilsen/regards Max M Rasmussen, Denmark http://www.futureport.dk/ Fremtiden, videnskab, skeptiscisme og transhumanisme From cce at clarkevans.com Wed Mar 5 10:52:39 2003 From: cce at clarkevans.com (Clark C. Evans) Date: Wed, 5 Mar 2003 15:52:39 +0000 Subject: PEP 308: an additional "select/when" survey option In-Reply-To: References: <882b0a41.0303020225.3caf0334@posting.google.com> <20030305005906.GA56890@doublegemini.com> Message-ID: <20030305155239.GB61411@doublegemini.com> Terry/Erik, thank you for taking the time to read the proposal and respond. On Wed, Mar 05, 2003 at 09:38:21AM -0500, Terry Reedy wrote: | ternary Apologies. Just trying to get some attention, I didn't mean to trash the ternary proposal; in fact, I'd like to see a conditional expression make it into Python. | > operator as a way to trade horizontal screen realestate for | > vertical space; as this rationale is in direct opposition to | > the fundamental principle of readability. | | How does 'C op1 b op2 c', when performing a conditional selection | operation, violate the 'fundamental principle of readibility', | whatever that is, any more than any other five-token expression, such | as 'a + b * c' or 'a <= b <= c'? In general, Python code tends to naturally use less an 80 columns due to its use of line breaks and indentation to indicate scope. As a result, Python tends to be a bit 'hoizontally slim' compared to most languages, and I feel this enhances readability. For example, the if/else statement structure requires at least one line per option. In contrast, when a line goes past 80 columns (in violation of the Python style guide) it is usually the result of a complex expression. And, unlike the other operators out there, this conditional expression is quite complicated due to is branching behavior. Therefore, I would expect that usage of a single-line ternary operator would, on average, increase the 'fatness' of Python code and, on average, increase the insidents of 80 column violations. So, while I agree we need a construct which allows for conditional logic within an expression, I disagree that such a construct should be a one-liner. I also think that a bulk of the opposition on this list to a ternary expression is somehow related to this stylistic argument; perhaps subconciously. And, as such, I'd rather not have the baby (a conditional expression) thrown out with the bathwater (one-line expressions). On Tue, Mar 04, 2003 at 11:33:35PM -0800, Erik Max Francis wrote: | I understand that. I (on autopilot) retyped what you wrote, but I | understood what you were suggesting. As I said, it is really beyond the | scope of PEP 308; it should be in another PEP. Quoteth the PEP: A natural extension of this syntax is to allow one or more 'elif' parts: (if : elif : ... else: ) This will be implemented if the proposal is accepted. | It's something that could degenerate to a ternary (or trinary, but not | terinary) operator, but it in and of itself is a more generalized | construct and so is not appropriate for a PEP 308 vote. If you want to | suggest a generalized select/when (or whatever you want to call it) and | propose that, that's fine, but it would be for another PEP. | | Take people who wanted to implement ternary operators in terms of a | special syntax for zero-argument lambdas and a new builtin; this | degenerates to a ternary (or can be used as one), but really deserved to | be suggested under another PEP; and, indeed, it was. Yes, but this isn't a separate item. The proposal has two differences: 1. It requires that each part of the conditional be on its own line and properly indented. (if : elif : ... else: ) or, in this proposal, select when : when : ... else: This aspect follows from the current Python style, which favors new lines and indentation to determine scope. 2. It provides a "defaulting" mechanism so that the variable tested (lhs) doesn't have to be duplicated again and again. select when ? : when ? : ... else: This construct is similar to SQL's CASE/SELECT and a minor (but essentail) improvement on the syntax for the case where is duplicated again and again. Neither of these differences make it a 'different PEP' Best, Clark From donn at drizzle.com Thu Mar 20 23:29:08 2003 From: donn at drizzle.com (Donn Cave) Date: Fri, 21 Mar 2003 04:29:08 -0000 Subject: calling a program without waiting for it to finish References: Message-ID: <1048220946.89614@yasure> Quoth Alex Martelli : ... | You can take specific, platform-dependent action to terminate such | processes in a function run at your Python program's termination | (see standard library module atexit). E.g., killall will work on some | systems for such purposes. For example, #!/usr/local/bin/python import os import signal import time os.spawnv(os.P_NOWAIT, '/bin/ping', ['ping', 'www.python.org']) time.sleep(5) signal.signal(signal.SIG_IGN, signal.SIGHUP) os.kill(-os.getpid(), signal.SIGHUP) Notes: - spawnv() invokes the specified command directly without a shell, which is particularly advantageous when the command is calculated from input data and therefore not reliably safe from shellisms that could radically affect your command. - The above works only when the python script was started directly from an interactive shell, in which case (assuming Berkeley job control) it will be a process group leader - running in its own process group, with process group ID == process ID. Any process forked by the python script will belong to that same process group. - kill(-n, x) means send signal x to process group n. I expect that may be enshrined in POSIX 1003.1, don't know for sure though. - signal(SIG_IGN,) is to survive my own signal. - You can use setpgrp() to effect more elaborate process control, but not often will it be worth the trouble. Donn Cave, donn at drizzle.com From belred1 at yahoo.com Sat Mar 29 20:28:33 2003 From: belred1 at yahoo.com (Bryan) Date: Sun, 30 Mar 2003 01:28:33 GMT Subject: Is Python overhyped (just like Java)? References: Message-ID: <5Lrha.281709$6b3.1176700@rwcrnsc51.ops.asp.att.net> i have a real world example of this. at my company, we had a project that was done in c++. it was basically server socket code, xml parsing, string manipulation, redundant lookup tables, and file I/O. the engineer who worked on it left the company. the engineer who took it over didn't know a bit a python. he learned python in about a weekend. and rewrote the entire project in python plus added more features than the c++ version had it done in about 1 week and polished/optimized in another week. the end result was about 1/10 the size. all the complexity was gone. as for speed... the c++ version processed 10,000 entries in about 2 seconds. the python one is about 3 seconds. for this particular project that one second difference per 10,000 records is completely lost in the noise. we are having this same kind of excellent results in other projects too. so, from my own personal experience and others around me, the increased productivity with less complexity you get from python over c++ is mind-boggling. bryan "Alex Martelli" wrote in message news:omqha.31133$Jg1.677484 at news1.tin.it... > Ajay na wrote: > > > Can some-one please explain why one would want to use Python? > > One word: *PRODUCTIVITY*. > > > What is wrong with C++? > > One word: *COMPLEXITY*. > > > > In my opinion, the problem with C++ has nothing to with the language > > semantics. The problem is that when people are confronted with a powerful > > language like C++, they tend to want to optimize everything to death. > > That's when they get themselves in trouble. > > You're over-generalizing. Not all users of C++ are so naive as to > have failed to read Knuth -- "Premature optimization is the root of > all evil in programming". But the point is -- by choosing a lower > level language, like C++, at the start of your project, rather than > a higher level one, like Python, you ARE optimizing WAY prematurely. > > > > Those who use Python know they are sacrificing a lot in terms of memory > > and > > speed. But if they took the same attitude toward C++, they can actually > > get a lot of flexibility, code reuse, simplicity, and all the other > > benefits of > > OO programming at over half the cost of using Python! The problem is that > > Whaddya mean "over half the cost"? > > I'm putting the final touches on a talk I'll give to PythonUK next > week (it's held together with the ACCU conference) on "Python for > C++ and Java programmers". One example I give is a task for which > C++ is quite suited, with its standard library -- reading a text file, > breaking it into whitespace-separated 'words', building an index from > each word to the line numbers on which it appears, and showing the > index with words in alphabetical order, one per line, each followed > by the line numbers on which it appears. > > Thanks to the excellent support given for these tasks by the standard > library, the C++ source is ONLY twice as big as the Python source for > the same job (a more usual ratio is around 5:1). This holds for both > the simplest versions, and the slightly more complicated ones with > somewhat better optimization. The runtimes on my box (Linux Mandrake > 9.0, gcc 3.1, Python 2.3) are, when the programs are run on the 4.4 MB > of the "King James Bible" in plain ASCII text: 17.4 seconds for the > simplest C++, going down to 15 with optimizations; 11.2 seconds for the > simplest Python, going down to 8.1 with optimizations (CPU times are > in very similar ratios). Of course, this basically reflects the > excellence of Python's intrinsics (dictionaries, lists, strings) > versus the lesser quality of C++'s library implementation (maps, > vectors, strings) -- with different implementations, you may see > different ratios. > > But what won't change is, the Python program IS smaller, because > Python it's a higher-level language -- AND each statement is > intrinsically cleaner and simpler, so the development time ratio, > for programmers who have perfectly mastered both languages and > the respective standard libraries, is even more extreme than the > ratio in program sizes. The simplest and most flexible C++ you > can write is still way bigger, more complicated, and less flexible > than the most refined and optimized Python code it may make sense > to write -- it's as simple as this. For tasks to which Python is > extremely well suited (text processing of all kinds, including XML > parsing, for example), you may ALSO get better running time than > C++ with the standard library would give you -- in general, C++ > lets you develop faster code, but oh what a price in terms of > productivity you pay for that! > > And the funniest thing is, there IS no need to pay that price -- > 90% of your program's runtime is likely to be taken up by 10% > of your program's source code, or some such ratio. By writing > Python first, you'll often get an application with acceptable > performance; if not, you profile it, find out the hot-spots, > optimize those in Python terms, and if that's still not enough, > it's EASY to recode the hot-spots in faster ways while still > leaving MOST of your application in Python. There are many > ways to do such recoding (even without counting the still > experimental 'psyco' selective just-in-time optimizer), and > among them are ways to integrate C++, such as SciPy's "weave" > and the Boost Python Library (if you don't know Boost, DO > give it a look -- it WILL increase your C++ productivity, and > not just by easing integration of C++ to Python, either). > > > people who don't understand C++, are afraid to use the 'virtual' features > > of > > that language because it's 'too expensive'. But that's stupid...because > > Python's 'virtualness' is even more expensive! > > It's quite inconsiderate of you to imply that Python users are > "people who don't understand C++", when among those users are > people like Andrew Koenig (author of "Ruminations on C++" and > other great C++ books, as well as a towering figure of C++ > development -- the algorithm for name lookup in the C++ language > is called "Koenig lookup" because HE developed it...!), Bruce > Eckel (author of best-sellers "Thinking in C++" and "Thinking > in Java"), and so many others whose C++ competence is in all > likelihood AT LEAST as good as yours. > > > > Nope...I'm not trolling...I want someone to give a solid and intelligent > > argument about why I should switch from C++ to Python! > > You shouldn't *SWITCH*! If you hadn't already made the huge > investment to master all the complexity of C++, it might be > best to avoid it -- but, if you HAVE made it, count it as a > "sunk cost", as I do, and see how best to leverage it. Learn > Python (a trivial investment compared to learning C++), and > use BOTH Python and C++ in your development. You'll find that > Python gives you extremely high productivity and flexibility, > letting you prototype, experiment, refactor whole architectures > from the inside out and back again -- even if you knew the > final product MUST be delivered in C++ due to contractual > requirements, you'd STILL be better off doing the early phases > in Python ANYWAY. Once the program is working, benchmark it; > most often, you'll find you're done -- in a FRACTION of the > time. If the performance isn't satisfactory, profile it, and > start optimizing -- including recoding parts in C++, e.g. > with weave or the Boost Python Library. In the end, you'll use > both Python and C++ in the same program, *each for what it does > best*: Python for most of the code, C++ for the bottlenecks. > It's as simple as this, really! > > And your programming productivity will soar... > > > Alex > From pmagwene at speakeasy.net Wed Mar 5 22:36:55 2003 From: pmagwene at speakeasy.net (Paul M) Date: Wed, 05 Mar 2003 22:36:55 -0500 Subject: How does Python compare with RealBasic? In-Reply-To: References: Message-ID: Markus Winter wrote: > Hi all, > > I've just started programming in RealBasic and now came across Python > (mainly because a molecular visualisation app I'm interested in is using > Python as it's script language). I intend to write my first program (a DNA > sequence analysis program) and wondered how Python compares to RB ... > While Python isn't the only way to go for bioinformatics (lot's of folks like to use that other "P" language ;), I'd say that Python is probably much preferable to any type of basic for your intended task. Unless your writing your sequence analysis program purely as an exercise, you might want to check out the available python tools for bioinformatics at: http://biopython.org/ In fact, even if you're writing your program as a learning experience you might want to see how others have done similar things. Cheers, Paul From cce at clarkevans.com Tue Mar 4 21:57:08 2003 From: cce at clarkevans.com (Clark C. Evans) Date: Wed, 5 Mar 2003 02:57:08 +0000 Subject: single-line terinary operators considered harmful In-Reply-To: References: <882b0a41.0303020225.3caf0334@posting.google.com> Message-ID: <20030305025708.GA58956@doublegemini.com> On Wed, Mar 05, 2003 at 02:14:06AM +0000, Dennis Reinhardt wrote: | The weakness is that Python has a "dangling else" ambiguity which requires | indentation to disambiguate (i.e. the if-else must occupy two lines | minimum). Why is this a weakness? I like indentation. I use Python exactly beacuse it uses indentation to show me structure. The biggest problem I have with all of the 'terinary' options is that they are single-line solutions. The only solution that the terinary operator needs to solve is a way to provide for conditional logic within an expression intead of forcing the programmer to use statements. After the select/case option presented previously, my second best option would be something like... var = (if 1 == x: 'yes' else: 'no') Where the 'else' must be in the same column as the corresponding if. Getting it to fit on a single line is just an unnecessary distraction, and, IMHO, one that is bogging down the whole discussion down... and preventing a good mechanism to express conditional logic within an expression. Grins, Clark From mal at lemburg.com Thu Mar 13 07:06:30 2003 From: mal at lemburg.com (M.-A. Lemburg) Date: Thu, 13 Mar 2003 13:06:30 +0100 Subject: Local Python Meeting in Duesseldorf, Germany In-Reply-To: <3E6708BA.4000601@lemburg.com> References: <3E625AE8.6070806@lemburg.com> <200303050841.34188.bplatzen@sosnetz.de> <3E65F9B1.8070509@lemburg.com> <200303052156.04062.bplatzen@sosnetz.de> <3E6708BA.4000601@lemburg.com> Message-ID: <3E707446.70502@lemburg.com> This is an annoucement for a local Python meeting in Germany, so please excuse that the rest of this message is in German. --------------------------------------------------------------------- * D?sseldorfer Python Treffen Einige Python-Enthusiasten wollen sich am 17.03. um 20 Uhr ganz ungezwungen im Tigges treffen. Vortr?ge u.?. sind nicht geplant. Alle Python-Freunde/innen sind herzlich eingeladen. Vielleicht gibt es ja doch mehr davon in der Region um D?sseldorf, als wir bisher annahmen :-) * Wie kommt man zum Tigges ? Hier ist ein elektronischer Fahrplan: http://efa.vrr.de/ Die Haltestelle hei?t "Bilk-S". Das Tigges liegt in unmittelbarer N?he des S-Bahnhofs Bilk: Brunnenstra?e Nr.1. Hier einige weitere Infos: http://www.linux.de/groups/show.php3?place=D%FCsseldorf Das sollte reichen, um das Tigges zu finden :-) Bis dann, -- Marc-Andre Lemburg eGenix.com Professional Python Software directly from the Source (#1, Mar 13 2003) >>> Python/Zope Products & Consulting ... http://www.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ Python UK 2003, Oxford: 19 days left EuroPython 2003, Charleroi, Belgium: 103 days left From max at alcyone.com Sun Mar 9 22:11:08 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 09 Mar 2003 19:11:08 -0800 Subject: pep 308: why doing (almost) nothing suffices References: <3E6BF37E.4FEBD4FF@alcyone.com> Message-ID: <3E6C024C.F06FFDBD@alcyone.com> "Edward K. Ream" wrote: > Thanks for pointing this out. However, this does not change the fact > that > Python already provides more than enough tools for this job. Of course it does. No one has ever disputed that, as it's painfully obvious. You can reformulate every conditional operator into a statement or a more convoluted expression (the and/or tricks with single-element lists or lambdas). The question is whether or not a conditional operator is warranted on its own merits, not whether its presence is required to have a Turing-complete language. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Age ain't nothing but a number \__/ Aaliyah CSBuddy / http://www.alcyone.com/pyos/csbuddy/ A Counter-Strike server log file monitor in Python. From peter at engcorp.com Mon Mar 31 12:47:31 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 31 Mar 2003 12:47:31 -0500 Subject: How do I append to a file using ftplib? References: Message-ID: <3E887F33.CD6B7D9A@engcorp.com> JD wrote: > > How do I append to a file using ftplib? Can't figure this out, am I missing > something? Are you trying to append to a file you are retrieving, or to one you are storing to the server? What have you tried so far? If you're using retrbinary(), for example, it would seem pretty obvious what to do (pass it callback that works on a file opened in append mode) but maybe you've been stumped by something that isn't part of the core problem.... help us out with some background here. -Peter From jzgoda at gazeta.usun.pl Thu Mar 27 16:41:40 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Thu, 27 Mar 2003 21:41:40 +0000 (UTC) Subject: OT: Re: Prime number algo... what's wrong? References: <1MudnTyOEK1mauGjXTWcqg@speakeasy.net> <3E835DC2.3678BD7F@engcorp.com> Message-ID: Lulu of the Lotus-Eaters pisze: > I've mentioned to Phil (the site maintainer for the prime number > resources) that I think he is overbroad in his block--only three > countries (USA, UK, Australia) are engaging in direct aggression. Please, take Poland into account. Our men are also involved in "direct aggression". -- Jarek Zgoda http://www.zgoda.biz/ JID:zgoda at jabber.atman.pl From phil at river-bank.demon.co.uk Sun Mar 9 05:08:22 2003 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Sun, 9 Mar 2003 10:08:22 +0000 Subject: Python on Sharp Zaurus SL-5500 PDA In-Reply-To: <20030309014020.14029.qmail@web20905.mail.yahoo.com> References: <20030309014020.14029.qmail@web20905.mail.yahoo.com> Message-ID: <200303091008.22920.phil@river-bank.demon.co.uk> On Sunday 09 March 2003 1:40 am, Lance Ellinghaus wrote: > Has anyone ported the latest version of Python to the Sharp Zaurus > SL-5500 PDA? If so, where can I get it? Python 2.2 for the SL-5000 is available from http://www.riverbankcomputing.co.uk/zaurus/ There shouldn't be any problem running it on a 5500. Python 2.3 will be ported as soon as it is released. Phil From alloydflanagan at attbi.com Tue Mar 11 12:00:28 2003 From: alloydflanagan at attbi.com (A. Lloyd Flanagan) Date: 11 Mar 2003 09:00:28 -0800 Subject: is there a nmore pythonic way ? References: <3e6dbc5e$0$2688$626a54ce@news.free.fr> Message-ID: "shagshag13" wrote in message news:<3e6dbc5e$0$2688$626a54ce at news.free.fr>... > hello, > > i need to use module.function passed from command line, by now i use : > > if __name__ == '__main__': > args = sys.argv[1:] > if len(args) == 0: A zero-length string evaluates to false, so you can just: if not sys.argv[1:]: > ## print help information and exit: > usage() > sys.exit(2) > > im = '.'.join(sys.argv[1].split('.')[:-1]) > func = sys.argv[1].split('.')[-1:][0] How about pos = sys.argv[1].rfind('.') im, func = sys.argv[1][:pos], sys.argv[1][pos+1:] I don't know if that's more pythonic, but I found it a lot more readable than using split and join in this case. > > exec("from %s import %s" % (im, func)) > > -> and then func() > > is there a more correct way to do it ? > > thanks, You're welcome. I'm hoping somebody will post a different solution I haven't thought of :). From revanna at mn.rr.com Fri Mar 7 18:46:12 2003 From: revanna at mn.rr.com (Anna) Date: Fri, 07 Mar 2003 23:46:12 GMT Subject: OT: polyamory (was Re: [OT] Re: Python training time) References: <9j4c6v0gbooth50533vu0l0tan7cluib7q@4ax.com> <7h34r6giqdl.fsf@pc150.maths.bris.ac.uk> Message-ID: On Thu, 06 Mar 2003 13:23:31 +0000, Michael Hudson wrote: > Alex Martelli writes: > >> Not sure if you've already counted me, but I should point out that MANY >> advanced Pythonistas are poly -- we're not averse to coding in (e.g.) C, >> C++, pyrex, Fortran, or other programming languages, as and when the job >> requires it... > > It's bizarre that at one stage I could claim to know to some degree C, > C++, Eiffel, Haskell, Python, scheme, Common Lisp and some others that I'm > probably forgetting. Nowadays, I only often program in C and Python and > 90+% of the C is for the Python core. I do try to keep my CL neurons > working, but the others have faded quite a lot. Time to learn a new > language, I guess. > > Cheers, > M. Heh - not until we're done with Europython. That oughta keep you busy for a while, eh? Anna From jjl at pobox.com Sun Mar 9 13:32:38 2003 From: jjl at pobox.com (John J Lee) Date: Sun, 9 Mar 2003 18:32:38 +0000 Subject: automatic (un-)pickling / overwriting self In-Reply-To: References: <6c492956.0303070109.2e51963e@posting.google.com> Message-ID: On Fri, 7 Mar 2003, Alex Martelli wrote: > Clemens Hermann wrote: [...] > > while working on a cgi-admin interface i got a little problem with > > pickle. > > I use a hierarchical class structure to keep users, permissions, etc. > > As the amount of data is quite small i just pickle the top class > > instance that references the rest. > > So far so good... > > > I am looking for a way to automatically pickle the top class whenever > > one of the referenced object changes. > Sounds like what you *think* you want would be ZODB. > That's pretty hard indeed, to put it mildly; you'd basically have > to wrap every "referenced object" into the Observed side of an > Observed/Observer patter, catch EVERY change (a VERY tall order > indeed, with the amount of indirections being unbounded) and do > a callback to the top-class Observer. ... or use ZODB. Actually, what you *really* may be something like Zope or webware. (caveat: not entirely sure I understand what you mean by cgi-admin interface). John From imbosol-1048399290 at aerojockey.com Sun Mar 23 02:36:44 2003 From: imbosol-1048399290 at aerojockey.com (Carl Banks) Date: Sun, 23 Mar 2003 07:36:44 GMT Subject: Is Python the Esperanto of programming languages? References: <3oyea.61654$68.41484@nwrdny01.gnilink.net> <3E7ABD93.7DFBCFB@alcyone.com> <3E7BA475.2A0B41C6@alcyone.com> <3E7CDFA5.7FED4917@alcyone.com> <3E7D0A3B.58763752@alcyone.com> Message-ID: Erik Max Francis wrote: > Carl Banks wrote: > >> "I go" is ambiguous in tense the same way. > > "I go" is correct (if awkward) grammar, so exactly how is that > ambiguous? Did you read the rest of my post? I'm guessing not. I'll play the game at your level one more time. You and I are both aware that speakers learning English say "he go" when they mean "he went." But those same people also say "I go" when they mean "I went." And *you* seem to be amazingly and persistently ignorant of this fact. You incorrectly believe the ambiguity of "he go" is because the grammar is incorrect. That is flatly not the reason, because "I go" is ambiguous, too, and "I go" is correct grammar. The lack of an -s on "go" is NOT what makes the words "he go" ambiguous. What does make "he go" (and "I go", and "he goes") ambiguous is the fact that non-native English speakers often use the wrong tense. The lack of -s on the verb merely aroused your suspicion that this wasn't a native speaker, but even that's superfluous because the guy's accent already reavealed this. The ambiguity of "he go" (and "I go", and "he goes") is hardly a problem with good speakers of English. If a person who speaks good English were to say "he go" at any point, there would not be any ambiguity in the meaning. It would mean "he goes" and nothing else. Is that clear enough? Now, if you have another question, be sure to include the password "appeal to ignorance" in your reply so I know you've read the whole post. Thank you, -- CARL BANKS P.S. "I go" isn't awkward. You never said "I go all the time"? From max at alcyone.com Mon Mar 3 20:22:49 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 03 Mar 2003 17:22:49 -0800 Subject: A suggestion for a possible Python module References: Message-ID: <3E63FFE9.8A757617@alcyone.com> Lance LaDamage wrote: > I have noticed that there is one thing that everyone wishes to do in > Python > ... reverse a string. Who's everyone? I can't remember needing desperately to reverse a string once in my entire programming life. > As you know, in Visual Basic, the function for > performing this operation is indeed StrReverse(s). It's pretty trivial in Python as it is: >>> s = 'hello' >>> l = list(s) >>> l.reverse() >>> ''.join(l) 'olleh' -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ I am the king of sorrow \__/ Sade REALpolitik / http://www.realpolitik.com/ Get your own customized newsfeed online in realtime ... for free! From antonmuhin at sendmail.ru Fri Mar 7 09:05:03 2003 From: antonmuhin at sendmail.ru (Anton Muhin) Date: Fri, 07 Mar 2003 17:05:03 +0300 Subject: This sucks. In-Reply-To: <2614138.1047017673@dbforums.com> References: <2614138.1047017673@dbforums.com> Message-ID: Tetsuo wrote: > No matter how much I look at my code, I can't see how 0>=10. I fixed a > few things today, but the program still beyond fails. > > Here's a link to the program: > > http://hoverboarder.tripod.com/base.txt > > Here's the algorithm I used: > > http://www.ca-osi.com/article.php?sid=429 > > -- > Posted via http://dbforums.com And a note: why did you implement list function? list class seems to do more or less the same or I'm missing something? Anton. From aleax at aleax.it Tue Mar 25 07:48:05 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 25 Mar 2003 12:48:05 GMT Subject: STR that should be file? References: <3e802e94$1_2@read01.nntp.se.dataphone.net> <2JXfa.9228$i26.219290@news2.tin.it> <3e804e5a$1_4@read01.nntp.se.dataphone.net> Message-ID: <9eYfa.9466$i26.225393@news2.tin.it> j2 wrote: >> file is the name of a built-in type (the type of file objects). So, >> file.write is an unbound method of the type, which needs to be called >> with an instance of the type as its first argument -- and the first >> argument you're using is 'block', a string, whence the traceback. >> >> You're using name 'file' for a local variable in the following >> function getFile (don't do that -- it's NOT a good idea to name >> your own variables with names of builtin types!), but that does >> not in the least affect function handleDownload. > > I must admit i do not fully understand what all that means, but i seem to Hmmm, yes, unbound methods are the most obvious thing in the world. But just using a different variable name than 'file' (aFile, myfile, somefile, ...) throughout your original code would give a clearer error message -- that the variable name isn't seen in the download callback function that tries to use it -- that's the key point. One function doesn't see the local variables of another *unless it's lexically contained in it* (so, another solution would be to move the def statement for the download function to INSIDE the get-file function). > have some reading to do. Anyway, now the code works, and i can atleast > fix the given problem.. and THEN get around to actually learning stuff > (yes, backwards way, i know) Well, yes, in theory, but, it IS pretty common to "learn by doing". That's why (with some surprise to me) the Python Cookbook is a hit with _some_ beginners -- it gives too little theory (one does need to go back and study elsewhere to understand why and how certain things work), but LOTS of examples and discussions, and some people do learn best from that. > Thankyou so much. You're most welcome! Alex From bkc at Murkworks.com Tue Mar 11 18:07:06 2003 From: bkc at Murkworks.com (Brad Clements) Date: Tue, 11 Mar 2003 18:07:06 -0500 Subject: Flying With Python (Strong versus Weak Typing) References: <37a869bc.0303102102.4533973@posting.google.com> Message-ID: <3e6e6972$1_1@spamkiller.newsgroups.com> Uh, excuse me.. We said "replace your magnetos with a solid-state electronic ignition running (insert lang here)" Now, does that change your mind? -- Novell DeveloperNet Sysop #5 _ "lynx" wrote in message news:pan.2003.03.11.17.07.09.865575 at of.your.business... > On Mon, 10 Mar 2003 21:02:34 +0000, Hasoob ahs wrote: > > > In an interview at http://www.artima.com/intv/strongweak4.html Guido > > van Rossum was asked if "he would be comfortable enough with the > > robustness of Python systems to fly on an airplane in which ALL the > > control software was written in Python". Guido's answer was clear but > > I would like to hear from other Python programmers. > > i know something about your average civilian airplane, and how hard/easy > it is to control even if it were to lose most of its electronics. i'd be > comfortable, yes. > > i've also read some stories about what sort of certification process > avionics software has to go through, and what sort of development > processes and documentation demands are placed on such; i think i might be > comfortable flying even were the plane programmed in QBasic. > well, under VFR conditions, anyway. ;-) > > -- > PGP/GnuPG key (ID 1024D/3AC87BD1) available from keyservers everywhere > Key fingerprint = FA8D 5EA4 E7DC 84B3 64BC 410C 7AEE 54CD 3AC8 7BD1 > "...if you can fill the unforgiving minute > with sixty seconds' worth of distance run..." > From xxdigitalhellxx at hotmail.com Fri Mar 14 09:42:17 2003 From: xxdigitalhellxx at hotmail.com (sik0fewl) Date: Fri, 14 Mar 2003 08:42:17 -0600 Subject: Flying With Python (Strong versus Weak Typing) In-Reply-To: <_Xjca.126515$Hl6.11314509@news010.worldonline.dk> References: <37a869bc.0303102102.4533973@posting.google.com> <95cs6vo5k8rm15cd1iv0389kqfa2d2k7ht@4ax.com> <_Xjca.126515$Hl6.11314509@news010.worldonline.dk> Message-ID: > Perhaps that is an idea for Python 3000. A completely new name instead > of Python, using a word that does not yeat exist, so that we only get > hits unique to that name. ;-) > > > from random import choice > syllables = 'ja va perl c ++ py thon for tran eif fel a da'.split() > > nSyllables = 2 > nWords = 100 > result = {} > for i in range(nWords): > result[''.join([choice(syllables) > for w in range(nSyllables)])] = 1 > > uniqueWords = result.keys() > uniqueWords.sort() > print ', '.join(uniqueWords) > > > There's some good names in there ... > > ++++, ++eif, ++fel, ++py, ++tran, a++, aa, ac, afel, afor, aja, aperl, > athon, c++, ceif, cfel, cfor, cperl, da++, daa, dafel, daja, daperl, > dapy, datran, dava, eif++, eifa, eifda, eifeif, eifperl, eifthon, > fel++, felc, felda, feleif, felfor, felja, felthon, felva, for++, > fora, forc, forfel, forfor, forperl, forpy, forthon, fortran, jac, > jafor, perl++, perla, perlc, perleif, perlfor, perltran, py++, pyperl, > python, pyva, thona, thoneif, thonfel, thonfor, thonthon, thontran, > tran++, tranda, traneif, tranja, tranperl, tranthon, tranva, va++, > vada, vaeif, vaja, vava > > > Sorry ... it's friday and I am not in the mood for working. > Put my vote in for tranthon :) -- Ryan +1 Tranthon From aleax at aleax.it Thu Mar 13 14:22:53 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Mar 2003 19:22:53 GMT Subject: Threads with independant IO streams References: Message-ID: Tim Peters wrote: > The print statement passes the object to be printed to sys.displayhook() > for display. You could try supplying your own displayhook function. The print statement does not use sys.displayhook in any Python version I've seen -- sys.displayhook is used by the interactive interpreter to display the values returned by expression-statements. So, is somebody spoofing the timbot, or am I in a dangerously low blood-sugar condition? I'd better go to dinner right now, just in case... Alex From matt at mondoinfo.com Fri Mar 14 16:27:55 2003 From: matt at mondoinfo.com (Matthew Dixon Cowles) Date: 14 Mar 2003 21:27:55 GMT Subject: Tkinter Text widget scrolling References: Message-ID: On 13 Mar 2003 06:08:43 -0800, student wrote: > Hi, Hi! > I'm fairly new to python, and just started working with Tkinter > I want to know if theres a way to change the scroll range in the > text widget. > When text gets larger than the viewable size of the text widget, the > scroll is automatically resized, however i want to override this so > theres a little white space underneath insted of having the last > liine at the bottom. > Due to the nature of the application i'm writing, simply adding > space at the bottom won't do, i need away to work with the scroll > range.... any ideas? You can do that but it will be at least a minor nuisance. You'll need to use the place geometry manager and do the communication with the scrollbar yourself. The essence of the scrolling is that you can give the place geometry manager negative offsets. Here's a tiny example that shows what I mean: >>> from Tkinter import * >>> r=Tk() >>> t=Text(r) >>> t.place(x=0,y=0,relheight=1,relwidth=1) >>> t.insert(END,"Wibble") >>> t.place(y=-5,relheight=1,height=5) >>> t.place(y=-10,relheight=1,height=10) The height option is added after the relheight option is taken into account so you're stretching the Text widget while you're allowing its top to move "above" the window. Regards, Matt From gustav at morpheus.demon.co.uk Tue Mar 18 14:31:46 2003 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: Tue, 18 Mar 2003 19:31:46 +0000 Subject: LDAP server in Python References: <3cllelqc.fsf@morpheus.demon.co.uk> Message-ID: <7kaw5v4t.fsf@morpheus.demon.co.uk> Gerhard H?ring writes: > * Paul Moore [2003-03-17 21:17 +0000]: >> The background is that Oracle are moving their database naming service >> from a proprietary protocol (Oracle Names) to LDAP. [...] > > This sounds like tremendous overkill. Oh wait, it's Oracle ... :-) That's exactly why I want to try out LDAP - to confirm my instincts that it's massive overkill, and get some evidence to prove it to the people I work with who think I'm just cynical :-) Paul. -- This signature intentionally left blank From grzegorz at ee.ualberta.ca Thu Mar 27 21:12:22 2003 From: grzegorz at ee.ualberta.ca (Grzegorz Dostatni) Date: Thu, 27 Mar 2003 19:12:22 -0700 Subject: Python USB interface. Message-ID: Hi. I will be playing with a digital camera: Mustek Gsm at rt Mini 3. Unfortunately it comes with drivers for windows only... and I'd prefer to use it under linux. Is there an interface in python to the USB? Python interactive mode could be perfect way to figure out how to interface to this gadget. Greg "It is a tale told by an idiot, full of sound and fury, signifying nothing." - William Shakespeare From news at spam.trap.uk Tue Mar 4 19:07:56 2003 From: news at spam.trap.uk (ddoc) Date: Wed, 5 Mar 2003 00:07:56 +0000 Subject: Creating an excel spreadsheet References: <3E63C251.6070401@motorola.com> Message-ID: Stephen Boulet wrote: > I'd like to take some tab-delimited strings and put them in an Excel > workbook, each on its own worksheet tab. Out of curiosity - has anyone done this with Star Office/OpenOffice.org, and is it possible to make code to do that cross-platform at least for Linux and Windows? -- A From aleax at aleax.it Fri Mar 28 05:58:50 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 28 Mar 2003 10:58:50 GMT Subject: generic class for everything? References: Message-ID: Rob Brown-Bayliss wrote: ... > I had though of a class that has: > > unique identifier > name > description > stuff > > where stuff is basically a large text field so item might be: > > 1234 > "No Gas" > "The fule tank has run dry" > "fule(0) fule_light(on) power_out(-100%) electrical_out(-100%) lights(0) > " > > and then parse the stuff field modifying the parent class. > > The only other option I can think of is having the class have avariable > for every single thing that can happen, but that seems to be a night > mare > > Any thoughts? Python's dynamism can serve you well here -- different instances can easily have different subsets of the attributes, and a "template method" can easily introspect "self" to find out. For example (a small enhancement is possible to this in 2.3, using sets, but I'll code to 2.2 levels as it's not much of a difference anyway): import warnings class Happenstances: parent_components = ("fuel fuel_light power_out brakes engine" "electrical_out lights theft_alarm tires spare_tire").split() parent_components = dict(zip(parent_components,parent_components)) def __init__(self, name, description, parent=None, **stuff): self.uid = getuid() self.name = name self.description = description self.parent = parent for comp, value in stuff.iteritems(): if comp in parent_components: setattr(self, comp, value) else: msg = "Unk component %s ignored in %s" % (comp, name) warnings.warn(msg) def makeitso(self, parent=None): parent = parent or self.parent if parent is None: msg = "Happenstance %s can't happen to None" % self.name warnings.warn(msg) return for comp in parent_components: value = getattr(self, comp, None) if value is None: continue setattr(parent, comp. value) Alex From max at cNOvSisiPonAtecMh.com Thu Mar 27 15:59:01 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Thu, 27 Mar 2003 20:59:01 GMT Subject: OT: Re: Prime number algo... what's wrong? References: <1MudnTyOEK1mauGjXTWcqg@speakeasy.net> <_iJga.16$Xf4.13@twister.nyc.rr.com> <3E836408.72F35838@engcorp.com> Message-ID: Here is the land of sensless warmongering we prefer our first names be used in a friendly/intellectual discussion :). -- ======================================== Max Khesin, software developer - max at cNvOiSsPiAoMntech.com [check out our image compression software at www.cvisiontech.com, JBIG2-PDF compression @ www.cvisiontech.com/cvistapdf.html] "Peter Hansen" wrote in message news:3E836408.72F35838 at engcorp.com... > Max Khesin wrote: > > > > David, I would prefer that my first name be used instead of treating me as a > > schoolboy. > > Just an FYI: this is perhaps more a cultural difference, than a sign of > impoliteness. > > In North America, it is common in, for example, journalism to refer > to an individual by last name throughout an article, after introducing > the full name the first time it is used. Sort of like using an acronym > but expanding it in parentheses the first time. (And the attribution line > with the full name seems to suffice in this particular case.) > > So maybe David intended to be impolite (though I doubt it), and Max read > it that way, but it's not certain anyone else saw it that way. ;-) > > -Peter > > P.S.: Perhaps as many people would be offended by the use of their first > name by someone unfamiliar with them.... but then using their full name > might also be perceived as unfriendly by some. You just can't win here... From shagshag13 at yahoo.fr Tue Mar 11 05:40:18 2003 From: shagshag13 at yahoo.fr (shagshag13) Date: Tue, 11 Mar 2003 11:40:18 +0100 Subject: is there a nmore pythonic way ? Message-ID: <3e6dbc5e$0$2688$626a54ce@news.free.fr> hello, i need to use module.function passed from command line, by now i use : if __name__ == '__main__': args = sys.argv[1:] if len(args) == 0: ## print help information and exit: usage() sys.exit(2) im = '.'.join(sys.argv[1].split('.')[:-1]) func = sys.argv[1].split('.')[-1:][0] exec("from %s import %s" % (im, func)) -> and then func() is there a more correct way to do it ? thanks, s13. From pan-newsreader at thomas-guettler.de Thu Mar 13 13:01:55 2003 From: pan-newsreader at thomas-guettler.de (Thomas Guettler) Date: Thu, 13 Mar 2003 19:01:55 +0100 Subject: Keep Python Beautiful References: <2635252.1047490747@dbforums.com> Message-ID: On Thu, 13 Mar 2003 05:37:56 +0100, Greg Krohn wrote: > "Tetsuo" wrote in message > news:2635252.1047490747 at dbforums.com... > Basically, instead of: > > if cond: > a = tval > else: > a = fval > > You can do: > > a = cond ? tval : fval That's one reason why I love python. The syntax is easy. Evey newbie should be able to read my code. Do you like ugly girls? Most persons prefere nice partners. I don't like lamda, too. You can always define a function: def mycmp(a, b): return cmp(a.myatt, b.myatt) mylist.sort(mycmp) I hope Python will stay a beautiful programming language. thomas -- Thomas Guettler http://www.thomas-guettler.de From gustav at morpheus.demon.co.uk Sun Mar 23 15:29:32 2003 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: Sun, 23 Mar 2003 20:29:32 +0000 Subject: Incomparable abominations References: Message-ID: Niki Spahiev writes: > 3/23/2003, 6:17:08, Tim Peters wrote: > > TP> Yes, but what of it? Do you actually sort lists containing > TP> complex numbers? If so, I do believe you'll be the first to > TP> claim such a hobby. > > I do. It's easiest way to get point on the convex hull of point set. > (point === complex). Why not point === tuple of 2 co-ordinates? What do complex numbers gain you (given that they don't give you sorting properties...) Paul. -- This signature intentionally left blank From max at cNOvSisiPonAtecMh.com Fri Mar 28 10:21:43 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Fri, 28 Mar 2003 15:21:43 GMT Subject: OT: Re: Prime number algo... what's wrong? References: <1MudnTyOEK1mauGjXTWcqg@speakeasy.net> <_iJga.16$Xf4.13@twister.nyc.rr.com> <3E836408.72F35838@engcorp.com> <3QWga.32114$i26.828378@news2.tin.it> Message-ID: I stand corrected on the last name thing - David wrote to me and it is very clear that no insult was intended there. Really I would not pay any attention to it if not for the 'implicit warmongering' comment. I respect the opinion of those opposed to war, especially since this was definitely a judgement call. On the other hand I do not respect ascribing shallow psychological motivations to anyone who supports the war, like, (almost) all of Eastern Europe, where I come from. And I also do not like being manipulated by shocking pictures which Phil decided to greet us (US-based IPs) with - any intelligent person knows that there are plenty of pictures the other side could show here, too. Thoughtless Imperialist Oil-thirsty Warmonger. (BTW, I got your book last nite - looks very good! Thanks) max. -- ======================================== Max Khesin, software developer - max at cNvOiSsPiAoMntech.com [check out our image compression software at www.cvisiontech.com, JBIG2-PDF compression @ www.cvisiontech.com/cvistapdf.html] "Alex Martelli" wrote in message news:3QWga.32114$i26.828378 at news2.tin.it... > Peter Hansen wrote: > > > Max Khesin wrote: > >> > >> David, I would prefer that my first name be used instead of treating me > >> as a schoolboy. > > > > Just an FYI: this is perhaps more a cultural difference, than a sign of > > impoliteness. > > > > In North America, it is common in, for example, journalism to refer > > to an individual by last name throughout an article, after introducing > > the full name the first time it is used. Sort of like using an acronym > > That's the normal journalistic convention in Italy, too. Using the > first name instead would imply personal familiarity, "mock" familiarity > (common with stars of the movie/TV/music worlds), or that you're speaking > of the Pope, another sovereign (e.g. you might say 'Napoleon' instead > of 'Bonaparte'), or one of the relatively few historical figures who > ARE conventionally identified by their first names (e.g. 'Michelangelo' > for 'Michelangelo Buonarroti', but NOT for 'Michelangelo Merisi', who is > invariably referred to by his nickname of 'Caravaggio' instead -- no REAL > reason, just the way tradition happened to develop, just as e.g. many > use Dante for "Dante Alighieri" but NOBODY uses Francesco for "Francesco > Petrarca", who's invariably referred to by his surname Petrarca instead). > > I don't think it's reasonable to say that e.g. Horatio Nelson is "treated > as a schoolboy" because he's invariably referred to by his surname while > for Napoleone Bonaparte both first name and surname are often used. > > > Alex > From richardd at hmgcc.gov.uk Mon Mar 31 10:12:20 2003 From: richardd at hmgcc.gov.uk (Richard) Date: Mon, 31 Mar 2003 16:12:20 +0100 Subject: Breaking out of a while loop with a key press? Message-ID: <3e885ad5@mail.hmgcc.gov.uk> Hi, Can anyone suggest a simple way of detecting a key press and existing the program? I have a program which at the moment uses a while True: statement. However this is not ideal as I have to close down the console window to exist the program. Can anyone tell me the proper way of doing this? So that a CTRL-C, for example, can quit the program correctly? Cheers Richard From sholden at holdenweb.com Mon Mar 10 08:14:52 2003 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 10 Mar 2003 13:14:52 GMT Subject: Socket connection References: <8llqj-af3.ln1@beastie.ix.netcom.com> Message-ID: "Dennis Lee Bieber" insisted that the penguins eat the following fish: > Steve Holden fed this fish to the penguins on Saturday 08 March 2003 > 11:43 am: > > > That may be so, but it needs to be better explained. After the > > statements > > > > a = [2, 3, 4] > > b = a > > > > where exactly are the Post-Its for "a" and "b" stuck? Does the Post-It > > represent the name or the contents of the memory cell? etc., etc. > > > I usually do go down the level lower... A and B a what are written on > the Post-It notes (one each), and said notes are stuck on whatever > container holds the list object (memory cell, bucket on hanging from > the ceiling... > OK. The problem with this as a teaching aid is that it implies the whole object space has to be searched to find out where a particular name exists, and doesn't really reflect the distinction between namespaces and values in any kind of helpful way. Your example allowed me to realise exactly what it was about the Post-It analogy I didn't like, so thank you. > In a really silly simily (sp?)... in classical languages > [simile] > a = 2br apartment > b = a > a = 3br apartment > > would say a is the mailing address of some specific 2br apartment, and > that a new 2br apartment (an identical copy of the one at a) is built > at address b; shortly thereafter, the 2br apartment at a is torn down > and a 3br is built in its place > Indeed, Python and Icon are the only two languages I have used extensively that support such reference-based assignment. I find it much more natural natural than languages with typed values and copy-based assignment. > In Python, a is the name of the person living in some 2br apartment > (the address of said apartment is not fixed), and then b moves in to > share the same apartment; finally a moves out of the 2br and into a 3br > apartment that exists somewhere else. > Indeed. But the interpreter doesn't look at the data to find its name, (and indeed we have to regularly point out in c.l.py that objects don't, in fact "have" names, they are simply "bound to" one or more names). In truth we give the interpreter a name and it uses that as a reference to the data. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Register for PyCon now! http://www.python.org/pycon/reg.html From rganesan at myrealbox.com Tue Mar 18 07:46:56 2003 From: rganesan at myrealbox.com (Ganesan R) Date: 18 Mar 2003 18:16:56 +0530 Subject: LDAP server in Python References: <3cllelqc.fsf@morpheus.demon.co.uk> Message-ID: >>>>> "Paul" == Paul Moore writes: > Michael Str?der writes: >> >> Do you plan to develop an LDAP-enabled application? > No, not really. >> Then I'd recommend to run OpenLDAP 2.1.16 as test server because >> it's the most strict LDAP server around. You will definitely learn >> the right things. I'd still recommend that you install OpenLDAP 2.1.16. It's easy enough to install and there is an excellent python API available for it (See http://python-ldap.sourceforge.net/). Actually, the API should work with any LDAP v2/v3 compliant server, but it uses the OpenLDAP client library. > Hmm. I'm not sure "strict" is what I want. The background is that > Oracle are moving their database naming service from a proprietary > protocol (Oracle Names) to LDAP. The trouble is that (as is usual with > Oracle) the documentation is a bit opaque, so I'd rather try it out > and experiment. Believe me, strict is what you want. If you write to a "strict" version, the application should easily port to a more lenient implementation. The other way around is not necessarily true. > But Oracle's LDAP server takes a bit of setting up (specifically, it > needs a server machine bigger than my laptop :-() so I thought I'd try > something smaller and simpler for experimenting with. OpenLDAP is fairly light on resources. If you want something simple to experiment with; that is the way to go. > Oracle Names is basically a fairly trivial name->value mapping, > whereas LDAP looks far more complex. I'm not sure if I can justify the > extra complexity. On the other hand, I may be able to do useful extra > things with LDAP, such as storing extra data for other clients. At the > moment, none of the "overview" documents on LDAP which I've seen have > given me a feel for how to make "trivial" use of it (understandably, > they focus on the richness of the structure, which is precisely what > I'm not interested in...) The python-ldap mapping is not all that complex. Here's a trivial use of it; assuming the object you're interested in is "o=oraclenames". All you need to do is ------ import ldap l = ldap.init("yourhostname") l.protocol_vesrion = 3 # not mandatory res = l.search_s("o=oraclenames", ldap.SCOPE_BASE, "objectclass=*") for dn, entry in res: print "dn: ", dn print "entry: ", entry ------ That's all. The dn is not relevant in this example (it will be "o=oraclenames"). The entry is a dictionary of key, value pairs. Since LDAP allows multiple values for attributes, the "value" may be a list. HTH. Ganesan -- Ganesan R From sholden at holdenweb.com Mon Mar 17 16:30:53 2003 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 17 Mar 2003 21:30:53 GMT Subject: Has anyone created a simple POP3 and SMTP server using TWISTED? References: <0001HW.BA9660EB0012EC36F0407600@netnews.attbi.com> <1047616632.623178@yasure> Message-ID: "Donn Cave" wrote in message news:1047616632.623178 at yasure... > Quoth Zoo Keeper : > | I thought I'd be looking more along the lines of pop3d and smtpd in that > | case. BeOS is not rich with server code that is free. There is a version of > | Enamel that works, but is flaky. I could also wait for Zeta to be released, > | which might solve some of my problems, especially if they implement a full > | network api as the various unix's have. > > Might, or might be a mixed blessing if that new network implementation > has some rough edges. I can't think of any feature missing from 5.0 > that would rule out a basic TCP server like SMTP or POP3 (well, you > know that because you have one.) I can't say it's extremely robust, > sure not the best thing about BeOS, but it does implement the basics. > I think that part of the thread is based on a misunderstanding. Some of us assumed that the OP wanted to build the mail servers to provide otherwise-missing functionality from common environments. If it's either a) a fun project or b) to provide something that doesn't yet exist in the OP's environment then it's perfectly acceptable to write such servers in Python. I, for one, was trying to avoid the need for the OP to invent a wheel that's been rolling for decades now. > But there are some limitations. One that comes to mind is that an > open socket doesn't survive across a fork, so you may want to start If this is so, how does inetd work? > with a single-threaded server that deals with each connection one > by one. That should work for POP and SMTP, though probably will need > a select with timeout in front of all reads, so the occasional stuck > client doesn't jam the works. > I'm not sure I can agree with this. Are you suggesting that it isn't possible to concurrently handle multiple connections to the same server port, or am I misunderstanding? regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Register for PyCon now! http://www.python.org/pycon/reg.html From max at cNOvSisiPonAtecMh.com Thu Mar 27 14:35:43 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Thu, 27 Mar 2003 19:35:43 GMT Subject: OT: Re: Prime number algo... what's wrong? References: <1MudnTyOEK1mauGjXTWcqg@speakeasy.net> Message-ID: > > Since you're from Canada, you should be able to get through (as should > > people from France, Germany, Belgium); the guy is blocking off access > > from the US and all countries supporting the attack on Iraq, which > > includes Italy, so I can't check myself. I wonder how he would like all the US sites providing useful information to block access to him. It should only be fair according to his logic. From wesc at fuzzyorange.com Tue Mar 11 17:23:27 2003 From: wesc at fuzzyorange.com (Wesley Chun) Date: Tue, 11 Mar 2003 14:23:27 -0800 (PST) Subject: ANN: BayPIGgies mtg Wed Mar 12 7:30pm In-Reply-To: Message-ID: BayPIGgies: Silicon Valley-San Francisco Bay Area Python Users Group When: March 12, 2002 @ 7:30pm Where: Stanford University, Palo Alto, CA Agenda: PyChecker and Friends Speaker: Phil Lindsay "PyChecker and friends: Easing the transition from ad hoc scripts to stable, maintainable Python applications" PyChecker can be thought of as "Lint" for Python, and is a tool for finding bugs in Python source code. This talk will introduce PyChecker, show some of its functionality and discuss some of the lessons learned from its use in a commercial software development environment. The presentation will be from the perspective of a happy user & interested hacker. Some of the future goals of the project's authors will also be described. If time permits, the speaker will demonstrate a couple of small tools he has developed to also help in the creation of stable, maintainable applications. # Call For Talks: We are actively seeking speakers for BayPIGgies! If you would like to give a talk at one of our 2003 meetings (any Python related topic), contact us to coordinate! more info including directions: http://www.baypiggies.net hope 2 c u tomorrow nite! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, ? 2001 http://starship.python.net/crew/wesc/cpp/ Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies) http://baypiggies.net wesley.j.chun :: wesc at deirdre.org or wesc at fuzzyorange.com cyberweb.consulting : henderson, nv : cyberweb at rocketmail.com http://www.roadkill.com/~wesc/cyberweb/ From syver-en+usenet at online.no Thu Mar 20 08:40:03 2003 From: syver-en+usenet at online.no (Syver Enstad) Date: 20 Mar 2003 14:40:03 +0100 Subject: help with filling a struct for use in win32api.SendMessage() References: Message-ID: Roger Erens writes: > Hello, > > I'd like to make an MS windows application show up and present me some > data. > > I ought to use the windows API-calls FindWindow and SendMessage, but I > don't > > really know how to create the arguments needed for the latter call. > Could someone give me some directions about how to construct the 'xxx' > in > > the code fragment below? Should I use something like ctypes or > Pyrex? Check out array and struct in the standard library, play a bit around with them. They are quite nice for low-level argument massaging. -- Vennlig hilsen Syver Enstad From rc127 at yandex.ru Sat Mar 29 23:14:49 2003 From: rc127 at yandex.ru (Egor Bolonev) Date: Sun, 30 Mar 2003 15:14:49 +1100 Subject: how to hide text window when in GUI Message-ID: <4955503599.20030330151449@yandex.ru> Tkinter,windowsXP From tim.one at comcast.net Sat Mar 15 23:20:46 2003 From: tim.one at comcast.net (Tim Peters) Date: Sat, 15 Mar 2003 23:20:46 -0500 Subject: generators and exceptions In-Reply-To: <20030315212905.GA3656@doublegemini.com> Message-ID: [Clark C. Evans] > Hello, I'm playing with 2.2 generators, and it seems > that they don't like exceptions... They play with exceptions as defined in the "Specification: Generators and Exception Propagation" section of the generator PEP: http://www.python.org/peps/pep-0255.html > from __future__ import generators > class MyExc(Exception): pass > def mygen(val): > while val > 0: > if val % 2: raise MyExc > yield val > val =- 1 Presumably this last line was meant to be val -= 1 instead? > iterator = iter(mygen(4)) > while 1: > try: > val = iterator.next() > print val > except MyExc: pass > except StopIteration: break > > > Anyway, this _only_ prints out 4, instead of 4, 2 > as I expected. Read the PEP and your expectations will change . The code exactly as you gave should obviously produce only 4 (val is set to -1 and so the loop exits). With the suggested guess at what was intended, it should still produce only 4, but due to raising an exception within the generator when val is 3 (instead of falling off the end because val is -1). > I expect 4, 2 beacuse an equivalent iterator would produce 4, 2. Unclear what that means ("equivalent iterator") -- if you raise an exception within *any* function, and don't catch it within that function, the function's useful life ends. Generator functions aren't an exception to this, and neither are functions implementing any other kind of iterator. > It seems that generators die on the first exception... is there a way > around this? No. > I'm asking beacuse I'm using generators in a non-blocking database > system, where I want to raise WouldBlock in my generator, but still be > able to call the generator at a later time when it may not block... Resuming a generator that has raised a (any) exception results in StopIteration getting raised immediately, so, no, you can't do that directly. From sholden at holdenweb.com Fri Mar 7 08:57:19 2003 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 07 Mar 2003 13:57:19 GMT Subject: c = {x: '' for x in a} References: Message-ID: <3z1aa.209265$zL6.95656@news2.central.cox.net> "Aurelio Martin Massoni" ... > > "Hilbert" escribi? en el mensaje > news:v6gp1841qlpr51 at corp.supernews.com... > > Ok. > > This works: > > > > a = [1,2,3] > > b = [x for x in a] > > > > What's wrong with this one though? It would totally make sense to > me... > > > > a = [1,2,3] > > c = {x: '' for x in a} > > Try this one : > > c = dict( [ ( x, '' ) for x in a ] ) > and, in Python 2.3 c = sets.Set([1,2,3]) depending-of-course-on-your-requirements-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Register for PyCon now! http://www.python.org/pycon/reg.html From glc at well.com Sat Mar 1 12:21:49 2003 From: glc at well.com (Greg Chapman) Date: Sat, 01 Mar 2003 17:21:49 GMT Subject: Why does 2.3a2 change "slots" in complex? References: Message-ID: <21r16vcekdieusqfufjtiteflvst8p5m3a@4ax.com> On Sat, 01 Mar 2003 17:00:17 GMT, Greg Chapman wrote: >I believe the correct fix would be to change this test: > > if (PyComplex_CheckExact(r) && i == NULL) > >to this: > > if (PyComplex_CheckExact(r) && i == NULL && PyComplex_CheckExact(type)) Make that change to: if (PyComplex_CheckExact(r) && i == NULL && type == &PyComplex_Type) --- Greg Chapman From aahz at pythoncraft.com Sat Mar 1 14:17:55 2003 From: aahz at pythoncraft.com (Aahz) Date: 1 Mar 2003 14:17:55 -0500 Subject: My CTO is learning Python.... References: Message-ID: In article , Bjorn Pettersen wrote: > >...time to run screeming from the building . His problem, is that >"There doesn't seem to be any good books on Python". Pressed a little >more, it was refined to "either the documentation assumes you've never >programmed before, and spends volumes of text introducing loop >constructs etc." (that was the commentary on the Tutorial ), "or, >the author seems to be in love with the language purely for its advanced >and obscure features" (he'd hoped 'Thinking in Python' would be like the >C++/Java equivalent...). Pressed a little bit further, he commented: >"what I'm really looking for is a quick introduction for someone that >allready knows C++ or Java". Python Essential Reference -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Register for PyCon now! http://www.python.org/pycon/reg.html From candiazoo at attbi.com Thu Mar 13 15:59:31 2003 From: candiazoo at attbi.com (Zoo Keeper) Date: Thu, 13 Mar 2003 20:59:31 GMT Subject: Has anyone created a simple POP3 and SMTP server using TWISTED? Message-ID: Or by any other means for that matter. I have two domains, one for me, one for my wife, for our web sites. I want our own mail servers because our ISP has changed names 3 times in 4 years. Right now I am using a great product (my server is BeOS, btw) but it is a trial version and the minimal license is for 50 users and costs too much. So, I figured I'd write one in Python, but I wanted to check here first to make sure it hasn't already been done so that I am not wasting time researching and writing something that already exists... Thanks! Mike From sholden at holdenweb.com Thu Mar 13 18:07:15 2003 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 13 Mar 2003 23:07:15 GMT Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <3E62778F.EED49083@alcyone.com> <3E629E93.B94F7631@alcyone.com> <0bkv6v8akrd0db5i66eu685t5pmviuf0bk@4ax.com> <4fm07vg66gr4o4c74gb7ie5v85vlom1vhf@4ax.com> Message-ID: "Alex Martelli" wrote in message news:jk_ba.71962$zo2.1877444 at news2.tin.it... > Stephen Horne wrote: [...] > > > > Correct what? > > The strange assertion that built-in function names "never start a > line". > > > > For me, the strange assertion is that "'lambda' is ... one of the few > > keywords that never starts a line". It's pretty much accurate, but I > > If you change "never" into "rarely", it becomes accurate, and you > can then also strengthen the "one of the few keywords" into "the > only keyword" -- four keywords are operators ('in' is also used as > part of 'for' syntax) and NEVER start (logical) lines, 24 begin > statements or clauses thereof and always (for compound statements > and clauses) or often (for simple statements) start a line, lambda > is the only one that CAN do so but is RARELY seen in that role as > such an expression-statement essentially serves no useful purpose. > > > don't see the relevance - especially given that other words than > > I don't see the relevance of this whole discussion to anything, either. > So stop encouraging it then! > In particular, if somebody's trying to assert something about keywords, > whether that assertion be well-founded or not, your counter-assertions > about tokens that are NOT keywords has no possible relevance that I > can see. So, I've given up on trying to understand why all of these > non-sequiturs are accumulating on this thread and just making sure that > what _DOES_ get said, whether relevant or not, is at least correct. > > > You're assertion that some built-in function names often start a line > > seems to have no relevance to either Jacks or my statements. We are > > not debating the kinds of words that *can* start a line. It has > > nothing to do with the question at hand. > > It's not a question of debating, but one of asserting, specifically > of asserting things that are false. It is NOT true that built-in > functions never start a line: they are all ALLOWED to do so (as is > lambda) [and some of them are seen in such positions frequently, > while others are seen in such positions rarely]. > > Feel free to continue this weird discussion, but don't be surprised > if I correct assertions that are false, quite apart from the issue > of the relevance of anything to anything else. > The moon is made of green cheese :-) regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Register for PyCon now! http://www.python.org/pycon/reg.html From peter at engcorp.com Fri Mar 21 00:08:55 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Mar 2003 00:08:55 -0500 Subject: Is Python the Esperanto of programming languages? References: <200303192233.30383.andy@wild-flower.co.uk> <20030319175118.A6746@localhost.localdomain> <3E7A1259.2EFFAEBE@engcorp.com> Message-ID: <3E7A9E67.3A35E826@engcorp.com> "Greg Ewing (using news.cis.dfn.de)" wrote: > > Peter Hansen wrote: > > Is a Python user anyone who uses any piece of software where even a single > > Python bytecode is executed, or is a Python user someone who writes Python > > source code, or is a Python user anyone who downloads or installs a copy of > > a Python install package or .rpm? > > I think the analog of a speaker of a natural language would > have to be a programmer, not just someone who uses a program > written in that language. > > And as for being a former but not currently active user -- > once you've discovered Python, why would you ever want > to stop? :-) I'm not sure... I can't imagine it. On the other hand, Esperantists have the colloquial term "kabeinto", meaning roughly "one who has abandoned the movement", from the name (William?) Kabe, who was apparently a very active enthusiast in the earlier years but who subsequently vanished quite suddenly from the Esperanto movement (and without explanation? it's been a while...) Are there (yet?) any "famous" ex-Pythonistas who have traded in their trusty whitespace-sensitive language for more mature or younger and sexier models? And I'm referring here to those who might have left *voluntarily*, as we've all heard of those sad cases where the PSU goons forced th From peter at engcorp.com Wed Mar 19 12:11:33 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 19 Mar 2003 12:11:33 -0500 Subject: Dialog box. References: <3E786DDB.F257CC90@emi.u-bordeaux.fr> Message-ID: <3E78A4C5.3BB22EF8@engcorp.com> denis gaultier wrote: > > Do you know which class I must use to create a dialog box ? Nope. In fact, I don't even know *which* of the many GUI frameworks you are using, so it would be fairly hard to help you without making a number of assumptions... -Peter From max at alcyone.com Wed Mar 5 18:10:27 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 05 Mar 2003 15:10:27 -0800 Subject: Waffling (was Re: single-line terinary operators considered harmful) References: <882b0a41.0303020225.3caf0334@posting.google.com> <3e6618c4$0$248$edfadb0f@dread11.news.tele.dk> Message-ID: <3E6683E3.FA9FEB29@alcyone.com> Stephen Horne wrote: > OK - I'm surprised, but can't be bothered looking up the standard, > especially as I'm probably just getting confused with the comma > operator (which is *effectively* a separator, being an infix > operator). He's definitely right. Maybe you're thinking of Pascal, in which the final semicolon could be suppressed at the end of some blocks? (I haven't touched Pascal in many, many years, so I don't remember the details.) -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ It's a man's world, and you men can have it. \__/ Katherine Anne Porter The laws list / http://www.alcyone.com/max/physics/laws/ Laws, rules, principles, effects, paradoxes, etc. in physics. From mertz at gnosis.cx Tue Mar 25 12:27:32 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Tue, 25 Mar 2003 12:27:32 -0500 Subject: Const in python? References: Message-ID: Dave Brueck wrote previously: |> ALL CAPS conventions - they look ugly, |To you, perhaps. This is a very widely used, understood, and accepted |convention - I quite like it. As if this were a democracy, I'll just chime in "I agree" :-). Brueck does a great job of explaining exactly why capitalized contstants aid comprehension. Maybe I'm tainted by having already used it in a dozen languages before Python... hmmm, do you think there is a reason those dozen languages all use the same convention? Yours, Lulu... -- mertz@ _/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: \_\_\_\_ n o gnosis _/_/ Postmodern Enterprises \_\_ .cx _/_/ \_\_ d o _/_/_/ IN A WORLD W/O WALLS, THERE WOULD BE NO GATES \_\_\_ z e From phrogeeb at hotmail.com Fri Mar 7 00:18:28 2003 From: phrogeeb at hotmail.com (Uri) Date: 6 Mar 2003 21:18:28 -0800 Subject: TextPad and Python Message-ID: <8a0bb987.0303062118.201471b8@posting.google.com> Trying to get TextPad (http://www.textpad.com) to work with Python. It has lots of neat features like a file full of syntax coloring codes and an easy key-combination that executes the file in buffer and places output in a new TextPad window. I'm running into a question that I've seen come up a couple of times with Emacs. (Is Emacs on Win better than TextPad, even if I'm just a newbie?) I can run simple files that come up just fine in the new window. However, anything including input of any sort returns an error code that looks like: Hello?Traceback (most recent call last): File "C:\test.pyw", line 1, in ? a = raw_input("Hello?") EOFError: EOF when reading a line Tool completed with exit code 1 In Emacs the answer was that you use two commands: C-c ! py-shell C-c C-c py-execute-buffer However, the win version of Python 2.3 apparently doesn't come with either of these files. Can anyone give me any suggestions? From luke at chipcity.com.au Sat Mar 15 22:51:11 2003 From: luke at chipcity.com.au (Luke) Date: Sun, 16 Mar 2003 14:21:11 +1030 Subject: idle on linux Message-ID: <3e73f4fe@duster.adelaide.on.net> Hi, I've tried to install idle in RedHat 8.0 Installed python tools, tcl, tk But when I start idle at the prompt ('/usr/bin/idle') I get the following message: Traceback (most recent call last): File "/usr/lib/python2.2/site-packages/idle/idle.py", line 3, in ? import PyShell File "/usr/lib/python2.2/site-packages/idle/PyShell.py", line 13, in ? from Tkinter import * ImportError: No module named Tkinter can anyone tell me what's wrong, and how to fix it. thanks, kind regards, Luke -- =========================================== "once you've seen your future it means you've got to live it" =========================================== From fperez528 at yahoo.com Tue Mar 25 13:34:50 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Tue, 25 Mar 2003 11:34:50 -0700 Subject: Interfacing Python & Fortran References: Message-ID: Amit Keney wrote: > Hi all > I am interested in interfacing Python & Fortran . Searching the net, > I came up with Pyfort & F2PY. > I use a MIPS pro fortran 90 compiler on an IRIX platform. Should I go > forward with Pyfort or F2PY I haven't used pyfort, but I can definitely vouch for the amazing quality of f2py. And since f2py is actively used by scipy, it won't go unmaintained. It's quite impressive, and very easy to use. cheers, f. From dkuhlman at rexx.com Wed Mar 26 16:46:49 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 26 Mar 2003 13:46:49 -0800 Subject: ANN: Generating Python FSM/REST applications for Quixote Message-ID: I'm continuing my work with FSM (finite state machines) and REST. I'm now doing a more complete job of generating an FSM/REST applications that runs on top of the Quixote Web application framework. I've implemented a harness (fsmGenerate.py) that reads an XML FSM document and, from it, generates the following: - State definition modules -- These are Python modules that implement a Quixote application. One module is generated for each state in the FSM. Each generated module contains a class that implements the state. - An __init__.py file -- This file implements the dispatcher for the application. It takes the current state name and calls the implementation of that state. - A states.py file -- This file contains a super class for the classes that implement the states in the FSM. - XML Schema files -- One file is generated for each state in the FSM. And, these XML Schema files are used to generate a python parser for each XML interchange document and Python classes that represent the XML elements in each document. - A GUI definition file -- An XML definition file for a graphical user interface. The interface definition can be edited with wxGlade graphical GUI editor. wxGlade can also generate Python code that implements the user interface. This code can be used in the implementation of client applications. wxGlade generates Python code for wxPython. I've picked FSM to work with because I feel that we need a systematic way to work with and implement complex processes in a REST-ful way. This is not finished code or a shrink-wrap, use-it-right-out-of-the-box product. I view it more as code to build upon. And, the code that it generates requires editing: for example, you will want to add application specific functionality. However, my tests show that it generates a reasonable skeleton of an application. A document describing this is available at: http://www.rexx.com/~dkuhlman/fsmGenerate_howto.html And, a file containing support code and examples is at: http://www.rexx.com/~dkuhlman/fsmGenerate_examples.zip. As usual, I am interested in comments and suggestions. And, if you would like help using this, please let me know. - Dave -- Dave Kuhlman dkuhlman at rexx.com http://www.rexx.com/~dkuhlman From timr at probo.com Wed Mar 19 01:54:24 2003 From: timr at probo.com (Tim Roberts) Date: Tue, 18 Mar 2003 22:54:24 -0800 Subject: twisted.conch example References: <3E7547AA.DB9D3B29@engcorp.com> Message-ID: Klaus Alexander Seistrup wrote: >Peter Hansen wrote: > >> This may be of little help, but it's the best I can offer: >> Twisted apparently comes with a "full" suite of unit tests, >> as [...] > >Also, twisted.conch comes with a command line ssh-client, conch, >from which you might glean something. The script, however, is >surprisingly simply -- basically two lines: > >from twisted.scripts.conch import run >run() It never ceases to amaze me that, for virtually any arbitrary Python question, the answer can generally be expressed with Twisted plus 10 lines of code. I suspect I could probably do this: from twisted.appliances.coffeemaker import perk mug = perk.espresso() I just wish the entry barrier were a little lower. The documentation is, shall we say, daunting? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From max at alcyone.com Wed Mar 5 18:05:11 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 05 Mar 2003 15:05:11 -0800 Subject: ANN: Ballot for Complementary PEP308 Ternary VOTE References: <3E656589.5A91838A@alcyone.com> Message-ID: <3E6682A7.B7864769@alcyone.com> phil hunt wrote: > I disagree. I think Condorcet is the best voting system to use for > this purpose. If the original vote had used it, there would be no > need for a second one. It's irrelevant what the best voting system would have been. The problem is that second, third, or sixth votes are not going to change anything. Only the first vote, however flawed one might feel it was, counts. If one wanted to do follow-up votes for one's own edification, it would have much been much more advisable to wait until the first vote was complete so that there would be no question of confusion or contention in an already highly contentious and fairly confused process. As it stands multiple concurrent votes -- where only one counts -- only leads to confusion. Even if you really think the one vote that counts was poorly done. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ It's a man's world, and you men can have it. \__/ Katherine Anne Porter The laws list / http://www.alcyone.com/max/physics/laws/ Laws, rules, principles, effects, paradoxes, etc. in physics. From mail at manuelmgarcia.com Sun Mar 2 21:24:14 2003 From: mail at manuelmgarcia.com (Manuel M. Garcia) Date: Mon, 03 Mar 2003 02:24:14 GMT Subject: Vote on PEP 308: Ternary Operator References: <882b0a41.0303020225.3caf0334@posting.google.com> Message-ID: On 2 Mar 2003 02:25:46 -0800, pep308vote at hotmail.com (Raymond Hettinger) wrote: (edit) >Write-out these five examples using your most preferred syntax: > x = "door" + (if quantity>1: "s" else: "") > data = (if hasattr(s, 'open'): s.readlines() else: s.split()) > z = 1.0 + (if abs(z) < .0001: 0 else: z) > t = v[index] = (if t<=0: t-1.0 else: -sigma /(t + 1.0)) > return (if len(s)<10: insertsort(s) else: quicksort(s)) I think it is too bad a nested example wasn't required. If the ternary operator is added, and Python continues relentless world domination ;-) , I will probably have to puzzle out somebody's unfortunate nested ternary operator expression... at least once in my life. This might give even the most rabid supporter pause. >SAMPLE BALLOT >------------- >C accept (if c: x else: y) >D reject c ? a : b >H reject c then a else b >John Jones >x = "door" + (if quantity>1: "s" else: "") >data = (if hasattr(s, 'open'): s.readlines() else: s.split()) >z = 1.0 + (if abs(z) < .0001: 0 else: z) >t = v[index] = (if t<=0: t-1.0 else: -sigma /(t + 1.0)) >return (if len(s)<10: linsort(s) else: qsort(s)) It is also too bad that examples of how to helpfully reject all ternary operator forms were not given. There would be 2 cases of rejecting the ternary operator: 1. Horrified, but still able to rank 3 in order of least offense. (These would be people who have been steeled by voting in recent US presidential elections...) These voters could follow the format of lines 1 through 4, but be spared typing the examples. 2. Horrified, and reduced to Lovecraftian psychic jelly by all ternary operator syntax. These voters could compose obscene ASCII art to express the full measure of their contempt and disgust. Or use the single word 'REJECT', perhaps punctuated by writing the 5 examples in proper old-fasioned Python. >Vote Early. Vote Once. Mr. Raymond Hettinger must not be from Chicago. Manuel From member16943 at dbforums.com Tue Mar 25 21:00:02 2003 From: member16943 at dbforums.com (Tetsuo) Date: Wed, 26 Mar 2003 02:00:02 +0000 Subject: Finding out the weekday References: <86adfjz286.fsf@ieee.org> Message-ID: <2684006.1048644002@dbforums.com> There's a module called calendar... -- Posted via http://dbforums.com From philh at cabalamat.org Mon Mar 10 08:55:11 2003 From: philh at cabalamat.org (phil hunt) Date: Mon, 10 Mar 2003 13:55:11 +0000 Subject: copy a list References: <6ca96053.0303092333.56aef854@posting.google.com> Message-ID: On Mon, 10 Mar 2003 08:12:18 GMT, Alex Martelli wrote: >Yuval wrote: > >> Hi, >> I have to work on a list without changing it. Specifically, in every >> iteration I have to choose an object and remove it in the end of that >> iteration, repeat it until the list is empty. However, I do not want >> to touch the list itself since I need to repeat this process many >> times (start over again once the list is empty). Therefore, in order >> to "play around" with a list A, I create a copy of it: B = A[:]. >> My problem is that it slows down my program siginificantly. Is it a > >The copy operation, whether you perform it in the usual way you have >written or in the equivalent and more readable way B = list(A), is >_EXTREMELY_ unlikely to account for any significant slice of your >program's running time. The copy itself takes time k * len(A) for >a reasonably small constant k; then after each copy you _repeatedly_ >"choose an object", then "remove it" -- an operation that's most >likely K * len(B) for some K > k -- repeatedly until len(B) goes >down to 0 -- which suggests that part must take time proportional >to the SQUARE of len(A) [sum of 1, 2, ..., N is proportional to >the square of N). This is a good point. Python comes with a profiler -- perhaps the original poster would like to use it and see what figures he comes back with. -- |*|*| Philip Hunt |*|*| |*|*| "Memes are a hoax; pass it on" |*|*| From sjmachin at lexicon.net Mon Mar 24 17:28:32 2003 From: sjmachin at lexicon.net (John Machin) Date: Mon, 24 Mar 2003 22:28:32 GMT Subject: adjacent differences with a list comprehension References: <69413f9.0303241331.62f0295f@posting.google.com> Message-ID: <3e7f8583.10777667@news.lexicon.net> On 24 Mar 2003 13:31:16 -0800, pschmidt at omnimn.com (Phil Schmidt) wrote: >Given a list of numbers, such as: > >L = [2, 5, 8, 3, 9, 1] > >I want to generate a list containing the differences between adjacent >elements, i.e., > >Ld = [3, 3, -5, 6, -8] > >I don't see how I can do this (easily/elegantly) with list >comprehensions. > >Any suggestions? Thanks! >>> L = [2, 5, 8, 3, 9, 1] >>> [L[i+1]-L[i] for i in xrange(len(L)-1)] [3, 3, -5, 6, -8] >>> Depends on your definitions of "easily" and "elegantly" :-) From aleax at aleax.it Fri Mar 21 06:06:05 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 21 Mar 2003 11:06:05 GMT Subject: sort(): Giving third argument? References: Message-ID: Thomas Guettler wrote: > Hi! > > If I have a list of IDs and a hash which maps > each ID to a name: > > ids=[1, 2, 3, 4] > > names={ > 1: "foo", > 2: "bar", > ...} > > I can't do the following: > > def mycmp(a, b): > return cmp(names[a], names[b]) > > ids.sort(mycmp) > > since "name" is unkown in mycmp. > > What's the best solution? decorate-sort-undecorate, as is almost invariably the case for sorting. decorated = [ (names[i], i) for i in ids ] decorated.sort() ids[:] = [ i for name, i in decorated ] the assignment to ids[:] in the undecorate step is only needed if you do want the sort to be in-place. DSU is most often faster and simpler than passing a comparison callable to the sort method. If you ARE keen on passing a comparison callable come hell or high water, you can do that in several ways, as is always the case when you want a callable built to keep some state. Simplest is generally a closure: def make_comparer(names): def comparer(a, b, names=names): return cmp(names[a], names[b]) return comparer and ids.sort(make_comparer(names)) the "names=names" trick is only _needed_ in very old versions of Python, by the way. Only slightly more complicated than a closure is a class whose instances are callable: class Comparer: def __init__(self, names): self.names = names def __call__(self, a, b): return cmp(self.names[a], self.names[b]) and ids.sort(Comparer(names)) But -- DO consider DSU: it's really a superior approach! Alex From hat at se-46.wpa.wtb.tue.nl Mon Mar 17 11:00:24 2003 From: hat at se-46.wpa.wtb.tue.nl (Albert Hofkamp) Date: Mon, 17 Mar 2003 16:00:24 +0000 (UTC) Subject: Serializing PyThreads without holding interpreter lock? Message-ID: Hello all, A colleague of mine has written a Python program that uses threads, one thread is used for the GUI, the other for performing computations. The latter uses an external solver, written in C. The interface to the solver has been written in C to connect it to Python. The interface also allows call-back functions written in Python to be called from the solver. The program runs fine, except when the computation thread calls the solver. At that moment, Python calls the C function which performs it computations for a minute or so. During this time, the computation thread holds the global interpreter lock, and the GUI thread cannot update the user interface. At first sight, a solution to this problem seems to be releasing the global interpreter lock, by 1) adding Py_BEGIN_UNBLOCK_THREADS and Py_BEGIN_BLOCK_THREADS around the call to the solver, and 2) adding Py_BEGIN_BLOCK_THREADS and Py_BEGIN_UNBLOCK_THREADS around the call-back interface code just before and after the Py_call_func() call. (and pass the PyThreadState around through the solver, from the solver call to the call-back code.) However, releasing the global interpreter lock makes the solver re-entrant, i.e. a second thread could call the solver while the first thread is still computing. The solver library however cannot handle this situation, and will produce senseless results (so I assume). The question is now how to prevent this from happening, i.e. how do I serialize calls to the solver without holding the global interpreter lock? A nice solution would be to block the second thread until the first thread is finished, e.g. by putting a P() and V() operation around the call to the solver. The Python C programming manuals do give a number of primitives for handling thread, but blocking threads is not part of the provided functionality. Albert -- Unlike popular belief, the .doc format is not an open publically available format. From blakeg at metalink.net Wed Mar 12 20:06:55 2003 From: blakeg at metalink.net (Blake Garretson) Date: Wed, 12 Mar 2003 20:06:55 -0500 Subject: GCD in standard library? Message-ID: Unless I've been missing something for years, I don't believe there are any functions built-in or in the standard library that find the Greatest Common Divsor (GCD) of two integers. This seems like a common enough math function that I would *think* it ought to be in the math module (and gain the advantage of being coded in C.) I guess I'm wondering why it isn't there. Was it to keep out code bloat? I realize we can't include everyone's pet function, so it's fine if it stays out. I'm just guessing it is very common for people to have to add this to their programs: def gcd(x,y): if x % y == 0: return y else: return gcd(y,x%y) I know there is a PEP for a rational number type, and I'd assume that would have a GCD method, but I don't believe that's ready for primetime. If Python comes with "batteries included", where's GCD? Just Wondering, Blake Garretson From martin at v.loewis.de Sun Mar 2 07:22:10 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 02 Mar 2003 13:22:10 +0100 Subject: I like Unicode more than I used to... References: <2nZ4a.10942$_c6.1134088@newsread2.prod.itd.earthlink.net> <15961.28266.229005.462017@montanaro.dyndns.org> Message-ID: Skip Montanaro writes: > The only obvious way to announce the encoding would be by exporting > an environment variable to the child program. On Unix, the convention is that the terminal should follow the locale's encoding; it is the user's responsibility to declare the locale so that it matches the terminal. On Win32, there is API to determine the input and output encoding of a console window (yes, they can be different), provided you have a "console handle". Regards, Martin From eric.brunel at pragmadev.com Fri Mar 21 04:25:29 2003 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Fri, 21 Mar 2003 10:25:29 +0100 Subject: Tkinter wart: returned texts are sometimes strings, sometime Unicode strings References: Message-ID: Martin v. L?wis wrote: > Eric Brunel writes: > > >>Hi all, >> >>I stepped again on a problem I had too many times, and I must ask: why >>on earth do Tkinter return plain strings when getting a text value >>using only ASCII charcaters and a Unicode string when the same text >>contains anything else? > > > Which part are you questioning? > > It returns sometimes ASCII for backwards compatibility: Applications > that were working for English in Python 1.5.2 continue to work. Sorry, but I don't think there are "applications that work for English": every application may be used by people whose native language is not english and who have funny characters directly on their keyboard that they are used to type quite often. Getting a UnicodeError or some even stranger behaviour just because they typed one of these really does not seem to be a good idea. But what I'm actually questioning is not even that. It's that getting a text from Tk does not return a consistent result: once a string, once a Unicode string. And in fact, I don't see even the point in returning a string if the text contains only plain ASCII: since Python default encoding *is* plain ASCII, what would have been the problem if the text returned was also a Unicode string? > It returns sometimes Unicode to represent all possible characters. > >>Why not return plain strings encoded as UTF-8, for example? > > That may have been an option, but are you seriously proposing to > change that now? I'd really like to have opinions from other people who use Tkinter and whose native language is not english. But IMHO, this would have been a far better idea, at least until Unicode strings can be manipulated exactly the same way plain strings are, which is not exactly the case today. Anyway, thanks for your reply. -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From staschuk at telusplanet.net Tue Mar 11 19:34:08 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 11 Mar 2003 17:34:08 -0700 Subject: clear derived list In-Reply-To: ; from jdhunter@ace.bsd.uchicago.edu on Tue, Mar 11, 2003 at 05:08:26PM -0600 References: Message-ID: <20030311173408.A8220@tibia.amotlpaa.bogus> Quoth John Hunter: [...] > class mylist(list): > def set(self, seq): > # flush the old list > [self.pop() for i in range(len(self))] > self.extend(seq) How about using slice assignment? def set(self, seq): self[:] = seq -- Steven Taschuk o- @ staschuk at telusplanet.net 7O ) " ( From gerrit at nl.linux.org Thu Mar 20 16:26:52 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 20 Mar 2003 22:26:52 +0100 Subject: Is Python the Esperanto of programming languages? In-Reply-To: <200303192233.30383.andy@wild-flower.co.uk> References: <200303192233.30383.andy@wild-flower.co.uk> Message-ID: <20030320212652.GA2739@nl.linux.org> Andy Jewell schreef op woensdag 19 maart om 23:34:50 +0000: > Hi Pythonistas, > > Just thought I'd throw the cat amongst the pigeons... I just occurred to me > that Python is designed to be elegant from the ground-up, and takes many of > the 'best' features of many other programming languages, but always with > elegance in mind, similarly to Esperanto, which is designed to be a 'regular' > (i.e. elegant) human language, and draws its vocabulary from many different > spoken languages. Well, I don't think so. All programming languages are artificial, how literary they are. Artificial human languages don't work, just as beats and other artificial, practical enhancements don't work: HANC! [HANC: Humans Are No Computers] yours, Gerrit. -- 229 If a builder build a house for some one, and does not construct it properly, and the house which he built fall in and kill its owner, then that builder shall be put to death. -- Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From max at alcyone.com Mon Mar 3 04:48:02 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 03 Mar 2003 01:48:02 -0800 Subject: Pls, help me with re References: Message-ID: <3E6324D2.7E76BCB1@alcyone.com> Lexy Zhitenev wrote: > I want to match a number if it is the only one in the string, and the > second > one, if '=' preceeds it. > > Example > > 'Course: 23,95' - matches '23,95' > '$1 = 23,95 y' - matches '23,95'. Why not a regular expression simply like [including both commas and periods]: =.*([0-9,.]+) -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Custom reconciles us to everything. \__/ Edmund Burke Computer science / http://www.alcyone.com/max/reference/compsci/ A computer science reference. From dave at boost-consulting.com Sun Mar 30 08:56:03 2003 From: dave at boost-consulting.com (David Abrahams) Date: Sun, 30 Mar 2003 08:56:03 -0500 Subject: Is Python overhyped (just like Java)? References: Message-ID: "Ajay na" writes: > Can some-one please explain why one would want to use Python? What is > wrong with C++? > > In my opinion, the problem with C++ has nothing to with the language > semantics. The problem is that when people are confronted with a > powerful language like C++, they tend to want to optimize everything > to death. That's when they get themselves in trouble. As a big fan of C++ and an acknowledged expert, I can tell you there are lots of other reasons to want to use Python: simple language rules, literal expressions for high-level objects, lambda, broad standard library, no waiting for compilation, keyword arguments, full introspection, and automatic serialization are just a few that come to mind. > Those who use Python know they are sacrificing a lot in terms of > memory and speed. But if they took the same attitude toward C++, they > can actually get a lot of flexibility, code reuse, simplicity, and all > the other benefits of OO programming at over half the cost of using > Python! The problem is that people who don't understand C++, are > afraid to use the 'virtual' features of that language because it's > too expensive'. But that's stupid...because Python's 'virtualness' is > even more expensive! > > Nope...I'm not trolling...I want someone to give a solid and > intelligent argument about why I should switch from C++ to Python! Don't switch; just recognize and exploit the strengths of each. Python and C++ are complementary languages which have much to contribute to one another. See "Building Hybrid Systems With Boost.Python" at http://www.boost.org/libs/python/doc/PyConDC_2003/bpl.html (or http://www.boost.org/libs/python/doc/PyConDC_2003/bpl.pdf for the PDF). -- Dave Abrahams Boost Consulting www.boost-consulting.com From exarkun at intarweb.us Tue Mar 18 02:42:19 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 18 Mar 2003 02:42:19 -0500 Subject: Has anyone created a simple POP3 and SMTP server using TWISTED? In-Reply-To: <1047969967.296700@yasure> References: <0001HW.BA9660EB0012EC36F0407600@netnews.attbi.com> <1047616632.623178@yasure> <1047969967.296700@yasure> Message-ID: <20030318074219.GA29076@meson.dyndns.org> On Tue, Mar 18, 2003 at 06:46:08AM -0000, Donn Cave wrote: > Quoth Jp Calderone : > | > | [snip - inetd works, no it doesn't, yes it does, etc] > | > > Perhaps we're not talking about UNIX, but rather BeOS, which neither > supports the functionality required for inetd, nor is in any way intended > to be used as a network server. So, yes, something like that. > > To recapitulate, the original poster thought it might be nice to have > an SMTP and POP3 service for his site, which hosts himself, his spouse > and one or two children, on BeOS. He has experimented with commercial > software, but for whatever reason thought it might be interesting to > try a Python implementation. Before setting out to write it himself, > he asked - precipitating the most ridiculous thread you ever saw - > whether anyone had already done so. I suppose you've got me. I forgot the original thread was about BeOS, and I never knew that the inetd approach didn't work there. ;) > > | > | [snip - Threads can be bad] > | > | Or is this wrong, too? > > Only in this particular context, where forked processes don't inherit > sockets and the development effort targets a 3 user site. I suffer > from a multiple personality disorder, in which one personality programs > on BeOS and finds threads acceptable and natural, and the other programs > on UNIX and avoids threads like the plague. Personality 2 agrees > emphatically with everything stated above. > Ahh. Some of the interesting stories about threading on BeOS come back to me, now. I suppose it is a very different landscape. As for myself, I rarely find myself programming outside of UNIX, so I tend to get locked into the UNIX mindset... Thank you for reminding me that some things are different (and not in a necessarily "broken" way, like that other OS) on other platforms. Jp -- http://catandgirl.com/view.cgi?90 -- up 14 days, 23:59, 6 users, load average: 0.00, 0.02, 0.00 From ark at gmx.net Tue Mar 11 07:28:22 2003 From: ark at gmx.net (Arne Koewing) Date: Tue, 11 Mar 2003 13:28:22 +0100 Subject: os.startfile() on Linux ? References: Message-ID: "Harald Schneider" writes: > Hi, > > is there a way to call a file with it's corresponding application, like > os.startfile() on Win32 does ? > E.g. os.startfile('page.html') brings up this document in the default web > browser. > for the browser there is the webbrowser module: import webbrowser webbrowser.open('page.html') that's portable between win/linux/osX ... if you need support for other files two there is the mailcap module import mailcap mailcap.findmatch(mailcap.getcaps(),'text/html') ("/usr/bin/mozilla '/dev/null'", {'test': 'test -n "$DISPLAY"', 'nametemplate': '%s.html', 'description': 'HTML Text', 'view': "/usr/bin/mozilla '%s'"}) take a look at http://www.python.org/doc/current/lib/module-mailcap.html or http://www.python.org/doc/current/lib/module-webbrowser.html Arne From tebeka at cs.bgu.ac.il Sun Mar 23 04:55:29 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 23 Mar 2003 01:55:29 -0800 Subject: Understanding sockets? References: Message-ID: <33803989.0303230155.54bf30f6@posting.google.com> Hello G, > Still i would like to know what the problem is with the original code? > I'm trying to learn about sockets. > If anyone has any suggestions, i would really appreciate it. My guess (apart from the missing imports) is that you get both pickle objects in the same string and pickle gets only the first. Try: class Server(SocketServer.BaseRequestHandler): def parse_data(self, data): for i in range(1, len(data) + 1): try: obj = pickle.loads(data[:i]) return obj, data[i:] except: pass raise ValueError def handle(self): msg = '' while 1: data = self.request.recv(1024) if not data: break msg += data while 1: try: obj, msg = self.parse_data(msg) print obj except ValueError: break if msg: print pickle.loads(msg) HTH. Miki From benoit.besse at club-internet.fr Tue Mar 11 19:03:18 2003 From: benoit.besse at club-internet.fr (Benoit BESSE) Date: Wed, 12 Mar 2003 01:03:18 +0100 Subject: Convert a C pgm References: <3e6e5746$0$14733$7a628cd7@news.club-internet.fr> <3E6E5BEC.34CB1666@engcorp.com> <3e6e64e5$0$14739$7a628cd7@news.club-internet.fr> Message-ID: <3e6e7945$0$14734$7a628cd7@news.club-internet.fr> It's for multicast visioconferencing on the web. If you want un example see http://www.vrvs.org/. The source file I want to convert in Pyhton is Websd. Your can donwload the source files here : ftp://ftp.enst.fr/pub/network/multicast/websd/websd.tar.gz SDP describe the information session, the used tools and other information SAP annonce the session to all multicast group listeners SIP is an invitation for a conf?rence All this protocol are use for multicast. There is implementation to IP Voice, H323, and other. I think it will be intresting. I want to develop such a web site with Zope, Python, MySQL, RSS and XML. A bient?t. "Gerhard H?ring" a ?crit dans le message de news: slrnb6spv4.nd1.gh at lilith.my-fqdn.de... > Benoit BESSE wrote: > > You're right, this is just a par of Application that list multicast > > directory session. > > The module have to parsed Session Description Protocol (RFC 2327). > > This is the main () > > Thi is still not complete. The .h file you posted earlier referenced > other header files in the same project. > > I'll second Peter's suggestion of rewriting the whole thing from > scratch using the spec with unit tests. > > As I personally have no need for a "Session Description Protocol" for > Multimedia apps (RFC 2327), it's unlikely I'd find the motivation to > create an implementation. Especially as I've a bunch of other more > interesting (to me) open-source projects to work on. > > I have no idea what SDP is good for. A quick Google search suggests it > has some relation with SIP (Session Initiation Protocol), which I've > at least heard of before, but still don't know what it's all about ... > > Gerhard > -- > mail: gh at ghaering.de > web: http://ghaering.de/ From i.linkweiler at web.de Fri Mar 14 05:46:53 2003 From: i.linkweiler at web.de (Ingo Linkweiler) Date: Fri, 14 Mar 2003 11:46:53 +0100 Subject: A fun tool for demonstrating or teaching python? References: <9s7ba.2698$4q6.305236@news20.bellglobal.com> <3E71B1CE.6080608@web.de> Message-ID: <3E71B31D.2010800@web.de> > look at my diploma software: > http://www.ingo-linkweiler.de/diplom/index_en.htm "Of pens and mice" is german only, perhaps I will translate it in future. PyNassi 1.2 ist english and german. From mac at die.spammer.die.dgp.toronto.edu Wed Mar 26 13:28:26 2003 From: mac at die.spammer.die.dgp.toronto.edu (Maciej Kalisiak) Date: Wed, 26 Mar 2003 18:28:26 GMT Subject: using C's "assert" macro in extension code Message-ID: I tend to litter my experimental code with a healthy dose of "assert" statements, and writing Python extensions is no exception. I've recently noticed that my asserts are not being executed, which led me to realize that the Makefile created by "make -f Makefile.pre.in boot" always uses "-DNDEBUG", which disables the assert macro. Does this mean that using C's asserts in extension code is frowned upon? I know it's not as clean as properly handling the problem and letting the Python interpreter know about it, but sometimes when writing one-off code you don't really want/need to bother being robust. If asserts are undesirable for some reason, what is the accepted way of doing the equivalent? From staschuk at telusplanet.net Tue Mar 4 20:43:34 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 4 Mar 2003 18:43:34 -0700 Subject: Converting SQL Server data types. In-Reply-To: <3E65098B.7000601@gmx.de>; from gerhard.haering@gmx.de on Tue, Mar 04, 2003 at 09:16:11PM +0100 References: <3E65098B.7000601@gmx.de> Message-ID: <20030304184334.B2899@tibia.amotlpaa.bogus> Quoth Gerhard H?ring: > sismex01 at hebmex.com wrote: [...] > > (0, 1364570710) [...] > > when it should in fact read as: > > > > 136457.0710 [...] > If t is the tuple, t[1] * 10000.0 will work for this particular sample > tuple. Er, t[1] / 10000.0, surely. -- Steven Taschuk staschuk at telusplanet.net "I may be wrong but I'm positive." -- _Friday_, Robert A. Heinlein From gb at cs.unc.edu Sun Mar 23 13:23:30 2003 From: gb at cs.unc.edu (Gary Bishop) Date: 23 Mar 2003 13:23:30 -0500 Subject: How can I use an existing COM object pointer with win32com? References: Message-ID: <3e7dfba2_2@news.unc.edu> Gary Bishop wrote: > Thanks. I'll certainly do step 2 in my python code. > I assume I have to link with some library to define > PyCom_PyObjectFromIUnknown. Do I need to build from the sources to get > it? > gb For future generations of Googler's I'll answer my own question. First, to get access to Mark's function, I used "explicit linking" to the dll rather than building the library from source. The code in my SWIG interface file to link to the dll is: ---------------------- %wrapper %{ /* get the function we need from the win32com package using explicit linking */ typedef PyObject* (*PYCOM_PYOBJECTFROMIUNKNOWN)(IUnknown *punk, REFIID riid, BOOL bAddRef = FALSE); PYCOM_PYOBJECTFROMIUNKNOWN PyCom_PyObjectFromIUnknown = NULL; void GetPythoncomDLL() { /* this should use the version of figure out the name */ HINSTANCE hDLL = LoadLibrary("pythoncom22"); if (hDLL != NULL) { PyCom_PyObjectFromIUnknown = (PYCOM_PYOBJECTFROMIUNKNOWN) GetProcAddress(hDLL, "PyCom_PyObjectFromIUnknown"); } if (hDLL == NULL || PyCom_PyObjectFromIUnknown == NULL) { fprintf(stderr, "Explicit link to pythoncom22.dll failed\n"); } } %} %init %{ GetPythoncomDLL(); %} ------------------ Then to convert from my COM pointer to an object accessible with win32com I mimicked Mark's code like: ------------------ // wrap it for use by Mark Hammond's win32com package PyObject* result = PyCom_PyObjectFromIUnknown(pUnk, IID_IDispatch); ------------------ Finally in the Python wrapper for the C extension, I complete the job with: ------------------ com = CComObject(self.ia, clsid) # convert it using Mark Hammdond's code com = WrapDispatch(com) if EventClass: com = DispatchWithEvents(com, EventClass) return com ------------------ I got access to those functions from Mark's module with: ------------------ import win32com.client from win32com.client import DispatchWithEvents WrapDispatch = win32com.client.__WrapDispatch ------------------ Thanks to Mark for the fine code! gb From tim_one at email.msn.com Mon Mar 24 22:58:05 2003 From: tim_one at email.msn.com (Tim Peters) Date: Mon, 24 Mar 2003 22:58:05 -0500 Subject: Incomparable abominations In-Reply-To: Message-ID: [David Mertz, Ph.D.] > ... > But the current list sorting behavior is BY FAR the most surprising > thing in Python! I would have a big challenge explaining it to a new > user... heck, I can hardly remember the border cases myself. > > The examples I gave in my first post for this thread show how surprising > the exceptions are. I really think that more than half of highly > experienced Python programmers would have gotten at least one of them > wrong in their intuition (not you, not Alex... maybe not Guido :-)... > but past that, mistakes). I expect I would have gotten most of them wrong, and I confess I wasn't interested enough to guess at what would happen. Why would I? I asked last time what your use case is: for what purpose do you think you need to be able to sort lists with a mix of element types for which Python can't dream up a better ordering than comparing the objects' memory addresses? If you don't have a real use case, I don't care about this. > I guess part of what goes into this is different intuitions about the > meaning of sorting. I put sorting a list into a different conceptual > category than comparing individual items (while knowing, of course, the > underlying relatedness of the concepts). Sorting, to me, just means a > stable (but arbitrary) ordering. Comparison with "<" and friends > implie, to me, a "natural" ordering. I wouldn't mind if "<" stopped > comparing anything without an obviously correct answer. What's your use case? > Even then, no matter how you cut it, the relation "1j < 2j" is > self-evident and natural. How can I explain to anyone why that is an > error rather than a True result?! It's like faith: if they know anything about complex numbers, no explanation is necessary; if they don't know anything about complex numbers, not only is no explanation possible, but they don't have a use case for it either so it's not a real problem for them <0.5 wink>. Since the members of a complex numbers are floats, then if 1j < 2j is self-evident, what's the self-evident result for 1e-300+1j < 2j? Is one self-evident and the other arbitrary? Etc. There are *useful* orderings on complex numbers, but no "most useful" ordering, and no ordering at all is conventionally defined on them. From marklists at mceahern.com Tue Mar 4 13:45:08 2003 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 4 Mar 2003 12:45:08 -0600 Subject: About getting the name of the running script In-Reply-To: Message-ID: [Lexy Zhitenev] > Why __file__ attribute isn't defined for top-level module (the > one I start)? Beats me. However, this is fixed in Python 2.3. > I have seen a method to do it, and I haven't found any exceptions from it: > > import sys, os.path > print os.path.abspath(sys.argv[0]) Yeah, but that won't work if you're importing the module, eh? ;-) So you could do (untested, off the top of my head): def myname(): try: name = __file__ except NameError: if __name__ == '__main__': import sys name = sys.argv[0] else: raise DontKnowWhatTheHellTheNameIs return os.path.abspath(name) Cheers, // m - From adalke at mindspring.com Sun Mar 30 19:41:27 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 30 Mar 2003 17:41:27 -0700 Subject: A bug I found in Python References: Message-ID: Jp Calderone: > Here is an example of this surprising behavior: > > def biffle_buffle_bam(x, y): > z = 10 > print 'Hello world' > return anotherFunctionIWrote(x, y) > > print biffle_bam_baffle(10, -10) > > As you can clearly see, when this is run, 0 is printed out! Uncle Tim: > Yes, it's clearly a bug in Python. What's happening is that it saw the 0 in > "10", and the zero in "-10", and figured 0 was the most popular digit. As > is so often the case, Python sacrificed accuracy for popularity. I think you're simplify things to much. Both 0 and 1 are equally popular. The tie-breaking algorithm (which I thought you added?) sees that the 0 is also the most recently used digit. User studies even back to the ABC days show that the more recently typed digits are the most readily recalled, so that choice makes sense. You can see this if you try the following code def biffle_buffle_bam(x, y): z = 10 print 'Hello world' return anotherFunctionIWrote(x, y) print biffle_bam_baffle(10, -10) This will print 1, because I typed the '1's *after* I typed the '0's. Python simply looks at the timestamps for each character to determine which was typed most recently. Andrew dalke at dalkescientific.com From BPettersen at NAREX.com Mon Mar 17 14:45:51 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Mon, 17 Mar 2003 12:45:51 -0700 Subject: OT: Aspergers link Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192022DDAAB@admin56.narex.com> > From: Carl Banks [mailto:imbosol-1047922240 at aerojockey.com] > > Chris Gonnerman wrote: > > ----- Original Message ----- > > From: "Carl Banks" > > > > > >> Chris Gonnerman wrote: > >> > There are probably a lot of us on this list who suffer from > >> > Asperger's... it pretty much defines nerdiness. > >> > >> Blegh. > >> > >> I think people with Asperger's "syndrome" just violated someone's > >> arbitrary and very narrow idea of what they think is normal. > > > > I never knew how I was different, only that I was; until I was > > married to someone with "normal" social instincts for over ten > > years (still am, thankfully). My wife has shown me a lot that > > I could never see on my own. > > I'm happy for you. None of that means Asperger's "syndrome" is real. [..] Sorry Carl, but you're being an ass. What you go on saying would be like telling a bipolar person that "I too go through periods of sadness and happiness", therefore their diagnosis is not only incorrect, but non-existant. For your sake I hope you never discover the difference, but at least take some time and study the literature (including case studies)... -- bjorn From staschuk at telusplanet.net Sat Mar 22 15:54:06 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Sat, 22 Mar 2003 13:54:06 -0700 Subject: Is Python the Esperanto of programming languages? In-Reply-To: ; from imbosol-1048277707@aerojockey.com on Sat, Mar 22, 2003 at 04:39:50AM +0000 References: <7i65qe953z.fsf@enark.csis.hku.hk> <3oyea.61654$68.41484@nwrdny01.gnilink.net> Message-ID: <20030322135406.E421@tibia.amotlpaa.bogus> Quoth Carl Banks: > Steven Taschuk wrote: > > I don't, however, think that these add up to the morpheme "saying > > nothing". > > Ok, let's say it means nothing in the same sense that sin x = x. How > about that? When I first read this, I was truly baffled; now I'm just unsure what you mean. My best guess is that you mean "it means nothing" has an implicit free variable indicating the context, i.e., "it means nothing in context X", and that by not specifying that variable when you said simply that the morpheme means nothing, you intended an implicit quantifier "in most contexts X". If that's accurate, I think we agree on the substantial points and are just using the words differently. (I'd prefer to say "adds no information in context X".) > > In my personal theory of meaning (idiosemantics?), it > > always means "third person singular", and its absence always means > > "not third person singular"; this explains why > > 1. The man goes to the store. is good, > > 2. *The man go to the store. is bad, and [...] > I don't agree with the reasoning here. Things that are paradoxical or > nonsensical don't always sound bad, and things that sound bad are not > always nonsensical or paradoxical. Well, no. I hadn't intended to imply so general a rule. However, I don't see any bright line between "sounding bad" and "semantically incoherent". For example: 4a. The man goes to the store. b. *The man go to the store. 5a. John ceased to have fits of anger. b. *John ceased to have a fit of anger. 6a. That sentence is false. b. *This sentence is false. (4b) sounds bad, and is unacceptable for that reason whether the meaning is clear or not. (6b) sounds fine, and is unacceptable only for high-level semantic reasons. I borrow (5) from McCawley, who analyzes (5b) (and other examples) as unacceptable because "cease to" can be applied only to things which "can be interpreted as denoting a state" as opposed to an event -- a semantic restriction. But (5b) causes (in me) a mental hiccup that feels very similar to the one caused by (4b). I also consider rejecting (5b) as part of language competence, while rejecting (6b) is not; thus I want a theory of English to account for the former, but not the latter. This is so whether or not the theory includes a model of language processing, and if it does, whether that model is stated in terms of pattern matching or inference or other mechanisms. (Indeed, it seems possible to me that all inference actually occurs by pattern matching.) My sketch of a model can be extended naturally to cover (5); I think it could be restrained from covering (6) by restricting the types of inferences the model allows. I don't claim that this sketch of a model is a faithful representation of how language is actually processed; I have no idea how it's processed. Your fascinating example of the little French expatriate shows that it is possible to be competent enough in a language to reject things like (4b) but not so competent as to reject things like (5b) (I assume she wouldn't); this might, as you suggest, reflect the operation of two distinct faculties, but it might just be a weird level of competence, or, say, a preservation due to her unusual circumstances of a state that all children pass through before they are able to speak. -- Steven Taschuk staschuk at telusplanet.net "Telekinesis would be worth patenting." -- James Gleick From jgoerzen at complete.org Fri Mar 7 17:39:25 2003 From: jgoerzen at complete.org (John Goerzen) Date: Fri, 07 Mar 2003 16:39:25 -0600 Subject: Fixes to zipfile.py [PATCH] Message-ID: <87heae244i.fsf@christoph.complete.org> Hello, I have an instance where I need to use zipfile.py for reading large (50,000-file, 500MB or larger) ZIP files. Unfortunately, it is rather poorly suited to this. For one, it allocates tens of thousands of ZipInfo objects on open of the ZIP file, taking 10-30 seconds and eating close to 100MB of RAM. For another, it provides no way to extract a file in a ZIP archive directly to a file. This means that extracting a 100MB file requires 100MB RAM. What I have done is written a ZipReader class dedicated to reading files. Some of this scanning that ZipFile does is necessary to help with writing or updating, but not for reading. My modifications have reduced the runtime of one torture test case from over 100 seconds to about 20, and another from over 200 seconds to 80. The basic idea is that, on opening, we scan the central directory noting solely the location of the start of each file. This gets saved in a hash of filenames. This approach saves huge amounts of time on open, and makes access to any individual file fairly quick as well. Also, as part of this scanning, we note the names of directories encountered, to make it easier for software that needs to basically do a version of os.listdir() on a ZIP file directory. In general, this approach will be much faster when accessing one or two files from a large ZIP file, about the same when dealing with a small ZIP file, and a little slower when accessing many files from a large ZIP file. I believe it's a net gain. Another nifty hack: reuse some code from socket.py to provide a file-like object capable of doing readline() and readlines() directly on data being read from a compressed file. It would be nice to see this socket.py code generalized to support any class that provides a read(). I have used this code in PyGopherd to provide seamless serving of Gopher and Web sites directly from ZIP files. Here is the patch against the zipfile.py in CVS: --- /home/jgoerzen/zipfile.py 2003-03-06 21:22:29.000000000 -0600 +++ zipfile.py 2003-03-07 16:22:13.000000000 -0600 @@ -2,8 +2,14 @@ # Written by James C. Ahlstrom jim at interet.com # All rights transferred to CNRI pursuant to the Python contribution agreement -import struct, os, time +import struct, os, time, types import binascii +from StringIO import StringIO +from socket import _fileobject as BaseFileSimulator + +_STRING_TYPES = (types.StringType,) +if hasattr(types, "UnicodeType"): + _STRING_TYPES = _STRING_TYPES + (types.UnicodeType,) try: import zlib # We may need its compression method @@ -167,6 +173,304 @@ def _normpath(path): return path +class FileSimulator(BaseFileSimulator): + def close(self): + pass + +class ZipDecompressor: + def __init__(self, fd, zinfo): + self.fp = fd + self.zinfo = zinfo + self.buffer = '' + self.bytesread = 0 + self.byteswritten = 0 # Used for deflation only + self.crc = binascii.crc32("") + self.filepos = self.fp.tell() + + if zinfo.compress_type == ZIP_STORED: + self.read = self.read_stored + elif zinfo.compress_type == ZIP_DEFLATED: + self.read = self.read_deflated + self.dc = zlib.decompressobj(-15) + self.recv = self.read + + def copyto(self, destfd, size = -1): + copied = 0 + if size < 1: + size = self.zinfo.file_size + while copied < size: + data = self.read(min(4096, size - copied)) + destfd.write(data) + copied += len(data) + + def _finalize(self): + if self.crc != self.zinfo.CRC: + raise BadZipfile, "Bad CRC-32 for file %s" % self.zinfo.filename + + def flush(self): + while self.byteswritten < self.zinfo.file_size: + self.read(min(4096, self.zinfo.file_size - self.byteswritten)) + self._finalize() + + def close(self): + pass + + def read_stored(self, count = -1): + if count < 1 or count > self.zinfo.compress_size - self.bytesread: + count = self.zinfo.compress_size - self.bytesread + if count < 1: + return '' + + count = count + self.bytesread + self.fp.seek(self.zinfo.file_offset + self.bytesread) + retval = '' + while self.bytesread < count: + data = self.fp.read(min(4096, count - self.bytesread)) + retval += data + self.bytesread += len(data) + self.byteswritten = self.bytesread + self.crc = binascii.crc32(retval, self.crc) + if self.bytesread == self.zinfo.compress_size: + self._finalize() + return retval + + def read_deflated(self, count = -1): + if count < 1 or count > self.zinfo.file_size - self.byteswritten: + count = self.zinfo.file_size - self.byteswritten + if count < 1: + return '' + + count = count + self.fp.seek(self.zinfo.file_offset + self.bytesread) + + # First, fill up the buffer. + while len(self.buffer) < count: + bytes = self.fp.read(min(self.zinfo.compress_size - self.bytesread, 4096)) + self.bytesread += len(bytes) + result = self.dc.decompress(bytes) + if len(result): + self.buffer += result + self.crc = binascii.crc32(result, self.crc) + + if self.bytesread == self.zinfo.compress_size: + bytes = self.dc.decompress('Z') + self.dc.flush() + if len(bytes): + self.buffer += bytes + self.crc = binascii.crc32(bytes, self.crc) + self._finalize() + + retval = self.buffer[:count] + self.byteswritten += len(retval) + self.buffer = self.buffer[count:] + return retval + +########################################################################### +########################################################################### +########################################################################### +# New ZipReader class + + +class ZipReader: + """ Class with methods to open, read, close, list zip files. + + z = ZipFile(file) + + file: Either the path to the file, or a file-like object. + If it is a path, the file will be opened and closed by ZipFile. + """ + + fp = None # Set here since __del__ checks it + + def __init__(self, file): + """Open the ZIP file with mode read "r", write "w" or append "a".""" + self.debug = 0 # Level of printing: 0 through 3 + self.locationmap = {'': -1} # Map to location of central dir header + + # Check if we were passed a file-like object + if type(file) in _STRING_TYPES: + self._filePassed = 0 + self.filename = file + self.fp = open(file, 'rb') + else: + self._filePassed = 1 + self.fp = file + self.filename = getattr(file, 'name', None) + + + self._GetContents() + + def _GetContents(self): + """Read the directory, making sure we close the file if the format + is bad.""" + try: + self._RealGetContents() + except BadZipfile: + if not self._filePassed: + self.fp.close() + self.fp = None + raise + + def _RealGetContents(self): + """Read in the table of contents for the ZIP file.""" + fp = self.fp + endrec = _EndRecData(fp) + if not endrec: + raise BadZipfile, "File is not a zip file" + if self.debug > 1: + print endrec + size_cd = endrec[5] # bytes in central directory + offset_cd = endrec[6] # offset of central directory + self.comment = endrec[8] # archive comment + # endrec[9] is the offset of the "End of Central Dir" record + x = endrec[9] - size_cd + # "concat" is zero, unless zip was concatenated to another file + concat = x - offset_cd + self.concat = concat + if self.debug > 2: + print "given, inferred, offset", offset_cd, x, concat + # self.start_dir: Position of start of central directory + self.start_dir = offset_cd + concat + fp.seek(self.start_dir, 0) + total = 0 + while total < size_cd: + centdir = self._getcentdir() # Reads 46 bytes + filename = fp.read(centdir[_CD_FILENAME_LENGTH]) + + self.locationmap[filename] = self.start_dir + total + components = filename.split('/') + self.locationmap['/'.join(filename.split('/')[:-1])] = -1 + # Skip past the other stuff. + total = (total + 46 + centdir[_CD_FILENAME_LENGTH] + + centdir[_CD_EXTRA_FIELD_LENGTH] + + centdir[_CD_COMMENT_LENGTH]) + fp.seek(self.start_dir + total, 0) + + def namelist(self): + """Return a list of file names in the archive.""" + return self.locationmap.keys() + + def namelistiter(self): + return self.locationmap.iterkeys() + + def hasfile(self, name): + return self.locationmap.has_key(name) + + def infolist(self): + """Return a list of class ZipInfo instances for files in the + archive.""" + return [self.getinfo(x) for x in self.locationmap.iterkeys()] + + def printdir(self): + """Print a table of contents for the zip file.""" + print "%-46s %19s %12s" % ("File Name", "Modified ", "Size") + for name in self.locationmap.iterkeys(): + zinfo = self.getinfo(name) + date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time + print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size) + + def testzip(self): + """Read all the files and check the CRC.""" + for name in self.locationmap.iterkeys(): + try: + self.read(name) # Check CRC-32 + except: + return name + + def getinfo(self, name): + """Return the instance of ZipInfo given 'name'.""" + return self._getinfofrompos(self.locationmap[name]) + + def _getcentdir(self): + """Read central directory info from an ALREADY-SEEKED fp!""" + centdir = self.fp.read(46) + if centdir[0:4] != stringCentralDir: + raise BadZipfile, "Bad magic number for central directory" + centdir = struct.unpack(structCentralDir, centdir) + if self.debug > 2: + print centdir + return centdir + + def _getinfofrompos(self, location): + if location < 0: + raise KeyError, "Attempt to get information from non-file" + fp = self.fp + fp.seek(location, 0) + centdir = self._getcentdir() + filename = fp.read(centdir[_CD_FILENAME_LENGTH]) + # Create ZipInfo instance to store file information + x = ZipInfo(filename) + x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH]) + x.comment = fp.read(centdir[_CD_COMMENT_LENGTH]) + x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET] + self.concat + # file_offset must be computed below... + (x.create_version, x.create_system, x.extract_version, x.reserved, + x.flag_bits, x.compress_type, t, d, + x.CRC, x.compress_size, x.file_size) = centdir[1:12] + x.volume, x.internal_attr, x.external_attr = centdir[15:18] + # Convert date/time code to (year, month, day, hour, min, sec) + x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F, + t>>11, (t>>5)&0x3F, (t&0x1F) * 2 ) + + # And now, read the info from the file's header. + + data = x + fp.seek(data.header_offset, 0) + fheader = fp.read(30) + if fheader[0:4] != stringFileHeader: + raise BadZipfile, "Bad magic number for file header" + fheader = struct.unpack(structFileHeader, fheader) + # file_offset is computed here, since the extra field for + # the central directory and for the local file header + # refer to different fields, and they can have different + # lengths + data.file_offset = (data.header_offset + 30 + + fheader[_FH_FILENAME_LENGTH] + + fheader[_FH_EXTRA_FIELD_LENGTH]) + fname = fp.read(fheader[_FH_FILENAME_LENGTH]) + if fname != data.filename: + raise RuntimeError, \ + 'File name in directory "%s" and header "%s" differ.' % ( + data.filename, fname) + + return data + + def read(self, name): + fd = StringIO() + fd = self.copyto(name, fd) + return fd.getvalue() + + def _open_zinfo(self, zi): + return FileSimulator(ZipDecompressor(self.fp, zi), None, -1) + + def open(self, name): + if not self.fp: + raise RuntimeError, \ + "Attempt to read ZIP archive that was already closed" + return self._open_zinfo(self.getinfo(name)) + + def copyto(self, name, fd): + """Copy the contents of the named file to the given descriptor.""" + self.open(name).copyto(fd) + + def __del__(self): + """Call the "close()" method in case the user forgot.""" + self.close() + + def close(self): + """Close the file, and for mode "w" and "a" write the ending + records.""" + if self.fp is None: + return + if not self._filePassed: + self.fp.close() + self.fp = None + + +########################################################################### +########################################################################### +########################################################################### +# Old ZipFile class + class ZipFile: """ Class with methods to open, read, write, close, list zip files. From david.bear at asu.edu Tue Mar 11 16:38:12 2003 From: david.bear at asu.edu (David Bear) Date: Tue, 11 Mar 2003 14:38:12 -0700 Subject: lambda question Message-ID: I was hoping to use lambda to create some quick string transforming functions. So I did : name = "a title" title = lambda s: " % " % s print title(name) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in I don't understand this. Is lambda not a good way to do this? I was hoping to avoid function overhead by creating some anonymous functions, but I guess I don't understand how to use them.. any comments? From camel at oasis.com Wed Mar 19 21:39:05 2003 From: camel at oasis.com (dromedary) Date: Wed, 19 Mar 2003 21:39:05 -0500 Subject: Combinations and recursion, from an ASPN snippet References: <180320032212546765%camel@oasis.com> Message-ID: <190320032139055172%camel@oasis.com> > The statement: > > return printList(blist) > > will cause termination of the recursion because the *return* statement causes > control to go back to the previous context. As printList() does not > (explicitly) return anything, it in fact returns None, so both the > Combinations() functions will return None, eventually, but this value is not > used (Python allows you to politely ignore return values). Aha! The return statement. I get it. Thanks for that and the rest of the reply. Very helpful. Jon From news at scphillips.com Wed Mar 12 15:59:45 2003 From: news at scphillips.com (Stephen C Phillips) Date: Wed, 12 Mar 2003 20:59:45 +0000 Subject: deepcopy problem with new-style classes in Python 2.3a2 References: <3VKba.46563$pG1.1102880@news1.tin.it> Message-ID: <3E6F9FC1.3080205@scphillips.com> Alex Martelli wrote: > Stephen C Phillips wrote: > > >>Hi, >>I am having a problem using deepcopy on a complex data structure. I >>think it can be distilled down to a basic difficulty shown below (thanks >>to Jp Calderone). >>With Python 2.3a2 (or Python 2.2.2) I get this: >> >> >>>>>class Foo(object): >>>> >>... pass >>... >> >>>>>f = Foo() >>>>>f.foo = f >>>>>g = copy.deepcopy(f) >>>>>g is not f >>>> >>True >> >>>>>f is f.foo >>>> >>True >> >>>>>g is g.foo >>>> >>False >> >>Obviously I would like "g.foo is foo" to be True. >>g.foo is not f either, it is some other empty object. >>With old-style classes I get the desired behaviour. Can anyone explain >>what the problem is? > > > Module copy is currently not able to install a "proper" deep-copier function > that works automatically and correctly for instances of new-style classes, > in good part because it has no way to identify "instances of new-style > classes" as such (as opposed to, e.g., instances of subclasses of list, or > dict, etc -- they're all much the same thing, but need very different > approaches to deep-copying). > > I suggest you submit this as a bug, and if you need a workaround you can > ensure your new-style classes contain a __deepcopy__ that satisfies your > needs, such as: > > def __deepcopy__(self, memo): > x = Foo.__new__(Foo) > memo[id(self)] = x > for n, v in self.__dict__.iteritems(): > setattr(x, n, copy.deepcopy(v, memo)) > return x > > for new-style classes whose instances hold all of their state in __dict__, > and so on. Thank you. I thought it might be a bug, but I am not any where near expert enough to know. My problem is not as simple as that described above, so I think that your work-around will not be sufficient. I have a class with several sub-classes (and sub-classes of those). Some of these classes may use __getstate__ and __setstate__ to remove some attributes from the copying process (and I would like the __getstate__ of the subclass to be in addition to the behaviour of its parent's __getstate__). I think I can see how to begin modifying your work-around to cope with this (but cannot try code out from this computer!). Would something like this be a good start? def __deepcopy__(self, memo): x = self.__class__.__new__(self.__class__) memo[id(self)] = x dict = {} for n, v in self.__getstate__.iteritems(): dict[n] = copy.deepcopy(v, memo) x.__setstate__(dict) return x Thanks again. Stephen. From martin.vonloewis at hpi.uni-potsdam.de Mon Mar 24 08:48:04 2003 From: martin.vonloewis at hpi.uni-potsdam.de (Martin v. Löwis) Date: Mon, 24 Mar 2003 14:48:04 +0100 Subject: Understanding Python Source code References: Message-ID: > I am trying to understand Python's inner workings. I would like to know if some > of you has a good starting point (either Book or URL) to Python's C source code. You should have read the "Extending and Embedding" tutorial, and the C API reference. From there, you can start right with reading the Python source code, if you are interested in the objects and the modules. For reading the compiler and interpreter, you should read the documentation of the dis module first. Regards, Martin From skip at pobox.com Wed Mar 12 20:20:58 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 12 Mar 2003 19:20:58 -0600 Subject: GCD in standard library? In-Reply-To: References: Message-ID: <15983.56570.349810.8509@montanaro.dyndns.org> Blake> I'm just guessing it is very common for people to have to add Blake> this to their programs: Blake> def gcd(x,y): Blake> if x % y == 0: return y Blake> else: return gcd(y,x%y) Depends on what field you're in. I have been programming in Python for nine or ten years and have never once had the need for a gcd function. As for adding it to the math module, that goes against the typical grain of Python's core extension modules. They generally expose functions in a corresponding Unix C library. Since there's no gcd in the Unix math (-lm) library, there's no gcd() in the math module. Skip From hoel at gl-group.com Mon Mar 17 10:38:44 2003 From: hoel at gl-group.com (Berthold =?iso-8859-15?q?H=F6llmann?=) Date: 17 Mar 2003 16:38:44 +0100 Subject: Installer and Mixing Numeric and numarray Message-ID: Hello, I am trying to freeze a program using the McMillan Installer version 5, alpha 1 which has to use Numeric and numarray in parallell. But the generated executable just gives a segmentation fault. Here' what I get: >cat aa.py import Numeric as N print "AA" import numarray as n print "BB" print N.arange(19) print n.arange(19) >python -OO ~/work/Installer/Makespec.py --name aaa aa.py ... >python -OO ~/work/Installer/Build.py aaa.spec ... >./distaaa/aaa Adding parser accelerators ... Done. AA Segmentation fault (core dumped) >python aa.py Adding parser accelerators ... Done. AA BB [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18] [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18] [23388 refs] gdb gives: >gdb distaaa/aaa core GNU gdb 5.2.1 Copyright 2002 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i686-pc-linux-gnu"... Core was generated by `./distaaa/aaa'. Program terminated with signal 11, Segmentation fault. Reading symbols from /lib/libdl.so.2...done. Loaded symbols for /lib/libdl.so.2 Reading symbols from /lib/libpthread.so.0...done. Loaded symbols for /lib/libpthread.so.0 Reading symbols from /lib/libutil.so.1...done. Loaded symbols for /lib/libutil.so.1 Reading symbols from /lib/libm.so.6...done. Loaded symbols for /lib/libm.so.6 Reading symbols from /lib/libz.so.1...done. Loaded symbols for /lib/libz.so.1 Reading symbols from /lib/libc.so.6...done. Loaded symbols for /lib/libc.so.6 Reading symbols from /lib/ld-linux.so.2...done. Loaded symbols for /lib/ld-linux.so.2 Reading symbols from ./distaaa/struct.so...done. Loaded symbols for ./distaaa/struct.so Reading symbols from ./distaaa/zlib.so...done. Loaded symbols for ./distaaa/zlib.so Reading symbols from ./distaaa/_codecs.so...done. Loaded symbols for ./distaaa/_codecs.so Reading symbols from ./distaaa/multiarray.so...done. Loaded symbols for ./distaaa/multiarray.so Reading symbols from ./distaaa/_numpy.so...done. Loaded symbols for ./distaaa/_numpy.so Reading symbols from ./distaaa/umath.so...done. Loaded symbols for ./distaaa/umath.so Reading symbols from ./distaaa/strop.so...done. Loaded symbols for ./distaaa/strop.so Reading symbols from ./distaaa/math.so...done. Loaded symbols for ./distaaa/math.so Reading symbols from ./distaaa/cStringIO.so...done. Loaded symbols for ./distaaa/cStringIO.so Reading symbols from ./distaaa/memory.so...done. Loaded symbols for ./distaaa/memory.so Reading symbols from ./distaaa/operator.so...done. Loaded symbols for ./distaaa/operator.so Reading symbols from ./distaaa/_conv.so...done. Loaded symbols for ./distaaa/_conv.so #0 0x402656ea in init_funcDict () at Src/_convmodule.c:2337 ---Type to continue, or q to quit--- 2337 NA_add_cfunc(dict, "('Bool', 'asPyValue')", (void *) &BoolasPyValue_descr); I get this with Python 2.2.1, Numeric 21.0, numarray 0.4 as well as with Python 2.2.2, Numeric 22.0, numarray 0.4, both under Linux. Is there any fix or workarround? Thanks Berthold -- Dipl.-Ing. Berthold H?llmann __ Address: hoel at GL-Group.com G / \ L Germanischer Lloyd phone: +49-40-36149-7374 -+----+- Vorsetzen 32/35 P.O.Box 111606 fax : +49-40-36149-7320 \__/ D-20459 Hamburg D-20416 Hamburg From peter at engcorp.com Tue Mar 18 15:22:00 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Mar 2003 15:22:00 -0500 Subject: Rudeness (was: Re: OT: Aspergers link) References: <5.2.0.9.0.20030317140220.03820670@172.19.8.21> Message-ID: <3E777FE8.2B44CB29@engcorp.com> Bengt Richter wrote: > > We all got dealt a few odd cards, most likely. I'd never > heard of Asperger's Syndrome before this thread. Ah, that's Mordecai's Disorder, of course: you're one of those unhappy souls who has most certainty heard of Asperger's Syndrome before, but you suppressed the memory of it out of fear that you might actually once have been an unknowing victim yet have now fully recovered without ever having reaped the benefits of the sympathy of your peers. ;-) IANAVGC. -Peter From skip at pobox.com Wed Mar 19 17:19:36 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 19 Mar 2003 16:19:36 -0600 Subject: Does Python do try: except: finally: ? In-Reply-To: <1048108451.2357.6.camel@jwilhelm.ofsloans.com> References: <20030319135147.A1830@ash.int.ca.pason.com> <1048108451.2357.6.camel@jwilhelm.ofsloans.com> Message-ID: <15992.60664.196022.130799@montanaro.dyndns.org> >> Does Python do a block like: >> >> try: >> do_something() >> except: >> do_something_else() >> finally: >> do_cleanup() >> >>> try: ... print "Foo" ... except: ... print "Oof" ... else: ... print "Bar" ... Foo Bar >>> Joseph> That what you need? Maybe, but that's not what try/finally does. Try/finally says, "Execute the code in the try block, and irregardless of any exceptions which might get raised, execute the code in the finally block when finished." Try/except/else says, "Execute the code in the try block. If an exception is raised, execute the code in the except block, otherwise execute the code in the else block." It's tempting to think of try/except and try/finally as more closely related than they really are. What they have most in common is the "try" keyword. Skip From gerrit at nl.linux.org Sun Mar 2 16:58:02 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 2 Mar 2003 22:58:02 +0100 Subject: PyGTK-2 Full-Screen mode. In-Reply-To: <14bd1399.0303021258.67171d44@posting.google.com> References: <14bd1399.0303021258.67171d44@posting.google.com> Message-ID: <20030302215802.GA15646@nl.linux.org> kkennedy schreef op zondag 2 maart om 22:02:01 +0000: > Does anyone know how to make a window "full-screen" with PyGTK-2? By > full-screen, I mean no decoration and no task bar or panel visible, > and preferably the ability to disable the alt-tab functionality. This > would be the eqivalent of the "full-screen-exclusive-mode" in Java SDK > 1.4. > > Here is my problem: I am writing a simple childrens game (in Python), > and I would like them to be able to play it when I'm not around. The > problem is that they can really mess up icons, menus, and whatever > else can be randomly clicked on. I am using Redhat 8.0. If anyone > knows another (better) way of solving this problem, your comments are > welcome. Pygame (pygame.org) has a fullscreen mode, and IIRC it can be used with WxPython. You can grab all control (except for ctrl-alt-backspace). Just FYI. yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From member16943 at dbforums.com Wed Mar 26 21:17:15 2003 From: member16943 at dbforums.com (Tetsuo) Date: Thu, 27 Mar 2003 02:17:15 +0000 Subject: Integer arithmetic References: Message-ID: <2688988.1048731435@dbforums.com> Like... Well, first of all, I don't have enough clue what you people are talking about to ask specific questions... But how can you make a pointer in Python? Is it a real pointer to memory, or just an item in, say, a dictionary or an array? -- Posted via http://dbforums.com From boud at valdyas.org Thu Mar 20 09:45:13 2003 From: boud at valdyas.org (Boudewijn Rempt) Date: Thu, 20 Mar 2003 15:45:13 +0100 Subject: Question regarding a recent article on informit.com References: Message-ID: <3e79d55f$0$121$e4fe514c@dreader4.news.xs4all.nl> Cameron Laird wrote: > I think Boudewijn should have written that "such functional > constructs as lambda have been deprecated in favor of pro- > cedural and alternative functional expressions including > list comprehensions" (approximately). Indubitably. -- Boudewijn Rempt | http://www.valdyas.org From zhitenev at cs.vsu.ru Tue Mar 18 11:08:15 2003 From: zhitenev at cs.vsu.ru (Lexy Zhitenev) Date: Tue, 18 Mar 2003 19:08:15 +0300 Subject: file objects choices? References: Message-ID: "e y suzuki" wrote in message: news:mailman.1047931167.5356.python-list at python.org... > > are there any existing python file i/o types that can be represented > by file objects other than: > -direct files (regular, directories) specified for the open function > -stdin, stdout, stderr streams via sys module > -input from piped commands of output from program executed by os/ > another program I also widely use StringIO - represent strings as file-like objects. It is useful to unzip files just downloaded. I mean, when I download a relatively short zip file, I place its contents in a StringIO object and feed it to zip module to extract the real contents. Lexy. From theller at python.net Thu Mar 6 16:14:12 2003 From: theller at python.net (Thomas Heller) Date: 06 Mar 2003 22:14:12 +0100 Subject: Observer pattern thoughts References: <20030306154232.7eb31309.gry@ll.mit.edu> Message-ID: george young writes: > I'm using an observer pattern as part of a > model-view-presenter/controller GUI app. I had simply grabbed > someone's source file with observer/observable classes and crunched > along, inheriting from these classes and using register, notify, etc. > But it seems to me that the classic Observable (adapted from type-anal > C++): [...] > is unnecessarily restrictive and inflexible for python code. Patrick O'Brian (sp?) has a nice recipe in the ActiveState Python cookbook called dispatcher.py, which I'm using with great success. Newer sources are maintained as part of PyCrust, which is now part of wxPython. Thomas From gerhard.haering at opus-gmbh.net Thu Mar 6 06:37:42 2003 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 6 Mar 2003 11:37:42 GMT Subject: Concerns about performance w/Python, Pysco on Pentiums References: <3E660EB3.4065D81F@engcorp.com> <3E66B6AE.2AAAAEC5@engcorp.com> Message-ID: Peter Hansen wrote: > Gerhard H?ring wrote: >> Peter Hansen wrote: >> > [hardware simulator in Python] >> It may well be that the real bottleneck of your simulator is memory access >> and not CPU. [...] > Not knowing that much about Linux I'd be at a loss to do this on my > own. Any suggestions for where to look? A quick googling shows that there are several performance counter patches out there. But maybe you can get the information you need out of the standard profiling information from /proc/profile using readprofile(1). You'll need to add a kernel commandline option in your bootloader (GRUB/LILO). This is an important part of the man page: """ To enable profiling, the kernel must be rebooted, because no profiling module is available, and it wouldn't be easy to build. To enable profiling, you can specify "profile=2" (or another number) on the kernel commandline. The number you specify is the two-exponent used as profiling step. """ I've never done anything of the above myself, though ;-) -- Gerhard From sjmachin at lexicon.net Sun Mar 30 08:56:34 2003 From: sjmachin at lexicon.net (John Machin) Date: 30 Mar 2003 05:56:34 -0800 Subject: A bug I found in Python References: <20030329174134.GA21226@meson.dyndns.org> <200303291104.05791.tjg@craigelachie.org> Message-ID: Gerhard H?ring wrote in message news:... > > Perhaps this was a parody of some sort. If that is so, I don't get it. > Gerhard, That was only a tiny harbinger of things to come. On Tuesday you shouldn't access any news groups or read your e-mail, lest there be so many ungettables that your circuits fry and you remain in stunned mullet mode in perpetuity. HTH, John From lucio at movilogic.com Wed Mar 26 16:01:19 2003 From: lucio at movilogic.com (lucio) Date: Wed, 26 Mar 2003 18:01:19 -0300 Subject: Some basic questions In-Reply-To: References: Message-ID: <3E82151F.70509@movilogic.com> Hi, Brian Christopher Robinson wrote: >I just began writing Python today and have a few basic questions: > >How can I read a single character from the standard input without consuming >any more input? > > sys.stdin.read(1)? http://www.python.org/doc/current/lib/bltin-file-objects.html http://www.python.org/doc/current/lib/module-sys.html or maybe, if you want it unbuffered: http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.074.htp >Is there any way to write a boolean function? I wanted to write a simple >is_alpha function (which may be in the standard library but I'm leanring), >and this is what I came up with: > >def is_alpha(c) : > letters = re.compile("[a-zA-Z]") > return letters.match(c) > >Instead of checking for true or false I check to see if None is returned, >but that seems a little kludgy. > Actually, None evaluates to false. So you can just do: if is_alpha("c"): print "of coz" but you could change the return line to something like: return not not letters.match(c) or return not (letters.match(c) == None) So you have a [1|0] return value. You could also use the ternary operator if we had one :) See: http://www.python.org/doc/current/lib/truth.html http://www.python.org/doc/current/ref/customization.html (see __nonzero__) > >How can I print to standard out without printing a newline? It seems that >the print statement always adds a newline and I haven't found any other >outputting functions yet. > Use a coma (,) after the print. print "Hello, ", print "World" Hello, World. http://www.python.org/doc/current/ref/print.html Lucio. From tim.one at comcast.net Fri Mar 7 17:32:45 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 07 Mar 2003 17:32:45 -0500 Subject: Concerns about performance w/Python, Pysco on Pentiums In-Reply-To: Message-ID: [Tim] > Note that the eval loop special-cases list, but not tuple, > subscripts, in the BINARY_SUBSCR opcode. list[i] is done inline, tuple[i] > ends up going thru the generic PyObject_GetItem. If there's a surprise > here, then, it's that tuple[i] isn't a *lot* slower than list[i]. [A. Lloyd Flanagan] > Mostly out of curiousity, is there a reason for that difference, or > did it sort of 'just work out that way'? I'm not sure what you're asking. BINARY_SUBSCR is generated in response to any subexpression that looks like expression1[expression2] and all such subexpressions can be evaluated by PyObject_GetItem(). The special case for when expression1 turns out (at runtime) to be a list, and expression2 turns out (at runtime) to be an int, is (of course) deliberately aimed at speeding list indexing. Tuple indexing is surely much rarer, and every special case slows down all cases it doesn't apply to (e.g., the special case for list indexing slows down tuple indexing, by the amount of time it takes to determine that it's not the special case of list indexing). From mis6 at pitt.edu Tue Mar 4 13:23:04 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 4 Mar 2003 10:23:04 -0800 Subject: Can __iter__ be used as a classmethod? References: <3e649aa3_4@news.bluewin.ch> Message-ID: <2259b0e2.0303041023.43e8b81f@posting.google.com> "Samuele Pedroni" wrote in message news:<3e649aa3_4 at news.bluewin.ch>... > "Alex Martelli" ha scritto nel messaggio > news:dv%8a.2507$pG1.64267 at news1.tin.it... > > > > In Python 2.2 and later (excepting, for backwards compatibility, > > 'classic classes') an operation always looks up the special methods > > of interest on the CLASS (aka type) of the object being operated on. > > > > this is true (only exception is partially the static special method > __new__), OTOH looking at what the OP was trying to do it is seems that: > > - the support for both classmethods (ignored wrt to special methods) and > metatypes with their methods can be confusing > Is there any good reason for supporting classmethods in Python ? Looking at Guido's essay it seems they have been introduced by mistake (trying to implement __new__ as a classmethod). It seems to me I could always use a regular method instead of a classmethod, by accessing the class trough self.__class__ or type(self), therefore classmethods only provide a very small amount of syntactical sugar. Actually they seems to me an unessential complication to the language, expecially because they are easily confused with the methods in the metaclass. On the other hand, I like very much static methods. However, I noticed that >>> isinstance(object.__new__,staticmethod) False Therefore if I try to retrieve all the staticmethods from a class I will miss __new__. That's unfortunate, even if I understand this is done in order to avoid to write __new__=staticmethod(__new__) each time I redefine __new__. In a sense, __new__ is an "implicit" static method. explicit-is-better-than-implicit-and-no-special-case-is-special-enough-ly yours, Michele From gstaniak at inka.zagiel.pl Mon Mar 3 03:54:22 2003 From: gstaniak at inka.zagiel.pl (Grzegorz Staniak) Date: Mon, 3 Mar 2003 08:54:22 +0000 (UTC) Subject: My CTO is learning Python.... References: Message-ID: On Sat, 1 Mar 2003 03:30:55 -0700, Bjorn Pettersen wrote: > ...time to run screeming from the building . His problem, is that > "There doesn't seem to be any good books on Python". Pressed a little > more, it was refined to "either the documentation assumes you've never > programmed before, and spends volumes of text introducing loop > constructs etc." (that was the commentary on the Tutorial ), "or, > the author seems to be in love with the language purely for its advanced > and obscure features" (he'd hoped 'Thinking in Python' would be like the > C++/Java equivalent...). Pressed a little bit further, he commented: > "what I'm really looking for is a quick introduction for someone that > allready knows C++ or Java". As a Python newbie I won't even try to comment on the remainder of your letter, but as far as reading material is concerned, have you shown him "Dive into Python" (http://diveintopython.org/)? I think that's exactly what he needs, judging from my own experience. I was in the same position and expressed my needs in the same tone. [---] > -- bjorn -- Grzegorz Staniak From snarflemike at yahoo.com Wed Mar 12 01:52:38 2003 From: snarflemike at yahoo.com (Mike Silva) Date: 11 Mar 2003 22:52:38 -0800 Subject: Flying With Python (Strong versus Weak Typing) References: <37a869bc.0303102102.4533973@posting.google.com> <20619edc.0303111308.62d6a8e2@posting.google.com> <3E6E5EEF.F128744B@engcorp.com> Message-ID: <20619edc.0303112252.2238d1f9@posting.google.com> Peter Hansen wrote in message news:<3E6E5EEF.F128744B at engcorp.com>... > Mike Silva wrote: > > > > Alex Martelli wrote in message news:... > > > ....isn't it obvious that it's totally > > > irrelevant to the system's overall safety whether the compiler has > > > performed the further smattering of semantically puny "verifications" > > > allowed by mandatory-declaration, stating-typing languages? > > > > > > Static typing makes it easier for the compiler to generate fast > > > code, and (depending also on other issues) may slightly enhance > > > programmer productivity by catching a small percentage of errors > > > a bit earlier than testing would catch them -- that's all. It has > > > no real bearing on safety issues for life-critical software. > > > > Is a factor of 100 difference in error rates of certified, fielded > > aviation software relevant? > > > > http://www.sparkada.com/downloads/Mar2002Amey.pdf > > > > (2nd page, 3rd column, re UK MoD analysis of DO-178B Level A software) > > > > Language (including, but not limited to, static typing) definitely > > makes a difference. > > I don't think Alex was arguing that *language* does not matter at all, > just that the minimal extra verification provided by statically typed > languages does not much matter. Well, he did write: "The issue of what programming language[s] has/have been used in developing the control software is largely irrelevant to the issue of system safety, which depends instead on the process used for the development and the proper mindset on the part of the development team." > > Anyway, the article doens't necessarily support the conclusion you > appear to be claiming (that static typing produced a factor of 100 > improvement in error rates). My only claim was that "Language (including, but not limited to, static typing) definitely makes a difference." > > For one thing, it is comparing the SPARK results to common results > with Ada, which are then compared with common C results. C is > hardly on a par with Python as far as weak and strong typing goes > (though it is somewhat statically typed... when you avoid casting). But *all* the code was certified to DO-178B Level A (the highest [most safety-critical] level). It's probably just about as close as you can get to an oranges vs. oranges comparison. Neither the SPARK code, nor the Ada code, nor the C code, was in any way "common." > > For another thing, the results came from not just a language, but the > approach used, including "semi-formal specifications", "thin-slice > prototyping of high risk areas" (i.e. "testing"), a "template-driven > approach" for boilerplate types of code, plus the static analysis > to which you appear to give all the credit. Arrgh!!! :-] I don't give "all the credit" to static analysis (I think you mean static typing here?) I am simply arguing against the claim that "The issue of what programming language[s] has/have been used in developing the control software is largely irrelevant." It's a claim I hear a lot, and I just don't believe it. Neither, apparently, does the author of the paper. > > Perhaps this quote summarizes it best: "Lockheed succeeded because > they had a strong process with an emphasis on requirements capture > and accurate specifications." Then by implication all of the other code, which had also been certified to Level A, was developed *without* a strong process, etc? > > In other words, exactly what we've been saying. But not what the paper says. > > (Disclaimer: I'm just rushing off to a meeting and having read the > whole thing, so I risk looking foolish for overlooking something > key to that article.) (Disclaimer: I often look foolish even when I'm not rushing, so I can empathize!) Mike From bokr at oz.net Tue Mar 25 17:56:26 2003 From: bokr at oz.net (Bengt Richter) Date: 25 Mar 2003 22:56:26 GMT Subject: Conjugate gradients minimizer References: Message-ID: On 25 Mar 2003 15:43:37 GMT, Andrew Walkingshaw wrote: >Hi. Ages since I last posted to c.l.p, and this is a long shot, but here >goes. > >Does anyone have a conjugate-gradients minimization routine (failing >that, even a line-search-using-gradients algorithm would be extremely >useful): > >a) in "pure" python (NumPy is *just about* OK for my purposes; C >extensions aren't); > >b) under the Python/2-clause BSD/X11/public-domain/similar license. > >(this is as part of work I'm doing into a problem in materials physics, >and I intend to release the code I'm working on under a Free Software >license at some point[1] - but depending on your perception, it could be >construed to be linking to non-free software, and I have neither the time >or inclination to get into a license war right now. Commercial >exploitation, however, is right out.) > >... which I could either adapt or even just *read*? I've looked at >Numerical Methods in C, and though it makes the algorithms pretty clear, >it's so unPythonic it sets my teeth on edge. > >Many thanks, >Andrew > >(The subject email address *is* real, but is read infrequently. Trim >the obvious extension for quicker replies...) > >[1] http://www.lexical.org.uk/created/anarcryst-latest.tar.gz is some >of my other code: it won't be interesting unless you really need >autogenerated disordered crystalline structures, but it *is* GPL. :) > http://www.google.com/search?hl=en&lr=&ie=ISO-8859-1&q=python+conjugate+gradient Regards, Bengt Richter From intentionally at blank.co.uk Tue Mar 11 06:39:03 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 11 Mar 2003 11:39:03 +0000 Subject: Summary of PEP 308 Vote for a Ternary Operator References: Message-ID: On Tue, 11 Mar 2003 04:51:18 GMT, Tim Hochberg wrote: >Again, I'd disagree. The results seems to slightly leaning toward some >ternary syntax, but no change seems to be preferred almost 2:1 (or 1.5:1 >if you toss the fuzzy votes) over any particular syntax. I certainly >wouldn't characterize that as leaning towards accepting the PEP as proposed. Over any *particular* syntax, yes - Raymonds choice of words may have been imprecise. However... 1. Overall, more people are pro-some-change than against-any-change. 2. Of those who are pro-some-change, the current PEP308 syntax seems to be the first choice overall. It seems that the vote has the worst possible type of outcome - it could be interpreted as favoring either factions opinion. Either it supports no change (as the no-change vote is more popular than any single syntax) or it supports making a change (as, if the particular syntax is considered a less important detail, the total votes for change outweigh the total votes against). Thankfully, we have a BDFL. The alternative might have involved suicide bombers :-( From hjwidmaier at web.de Thu Mar 20 13:58:30 2003 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: Thu, 20 Mar 2003 19:58:30 +0100 Subject: Working with binary data, S-records (long) Message-ID: We have a program to download (Flash-)Eprom images to an embedded device. It reads the image data from a file in Motorola S-record format, augments the image with some device specific data and sends the thing via a serial port to the device, usually after downloading a small piece of software, a second-stage bootloader, first, in the same manner. This program is currently written in C and runs under Linux and in a DOS shell under older Windows versions. Over the years said program accumulated a lot of cruft and grew command line options like weed. Now my boss asked me to make a new version which offers a GUI and runs under Windows 2000, XP as well. Which is perfectly fine with me, 'cause after finding pyserial that'll be more like a fun job (I've already written a similar thing in Python that reads an ELF program file and downloads the needed section to another device - it worked in a few hours; a C version would have taken weeks to write and debug). Time to get to the topic. Reading S-records in Python is not all that much fun (ok, it's neither in C). I've thought about doing it in C and returning a string, but that would lose the address information. And creating more complex python data types in C is something I've never done. And I don't want to compile under Windows. Thus I wrote a pure Python reader, which looks like (this is the whole class so far): -------------------------- import operator class SRecord: def __init__(self, init=0xff, checkcs=True): self.udata = [] self.data = [] self.tail = {} self.offset = 0 self.size = 0 self.start = None self.comm = [] self.init = init self.check = checkcs def readrecord(self, line): """Lese eine Zeile als S-Record und gebe Adresse, Daten und Pr?fsumme zur?ck.""" type = line[:2] data = [int(line[i:i + 2], 16) for i in range(2, len(line), 2)] cs = (reduce(operator.add, data) + 1) & 0xff # Mu? 0 ergeben if type in ('S1', 'S9'): adr = (data[1] << 8) + data[2] fd = 3 elif type in ('S2', 'S8'): adr = (data[1] << 16) + (data[2] << 8) + data[3] fd = 4 elif type in ('S3', 'S7'): adr = (long(data[0]) << 24) + (data[2] << 16) + (data[3] << 8) + data[4] fd = 5 elif type == 'S0': # Kommentar return 'C', 0, data[3:-1], cs else: raise ValueError, "Kein g?ltiger S-Record" if type > 'S6': # Startadresse type = 'S' else: # Daten type = 'D' return type, adr, data[fd:-1], cs def readrecords(self, records): """Eine Liste (Zeilen) von S-Records lesen.""" recno = -1 for line in records: recno += 1 line = line.rstrip() type, adr, data, cs = self.readrecord(line) if cs and self.checkcs: raise ValueError, "Pr?fsummenfehler in Record %d" % recno if type == 'D': self.udata.append((adr, data)) elif type == 'S': self.start = adr else: self.comm.append("".join(map(chr, data))) if not self.udata: return self.udata.sort() loadr = self.udata[0][0] hiadr = self.udata[-1][0] + len(self.udata[-1][1]) size = hiadr - loadr self.data = [self.init] * size for adr, data in self.udata: dlen = len(data) adr -= loadr self.data[adr:adr + dlen] = data self.offset = loadr self.size = size ----------------------- On my development machine (1.7 GHz) it's reasonably fast with a file worth 100 KB. But I'm afraid it'll suck on our production machines, which run at 166 MHz (give or take some). I thought about using array, but it's lacking a method to create a big array without creating a list or string first. Anyway, does anyone see a way to speed this up? I'm not going to inline readrecord(), as I don't care about 10 %. I'm asking if you see a real flaw in my algorithm. Whenever I play with binary data in Python, a dream of a mutable string data type crops up. Doing byte fiddling with strings is quite ok as long as the data is comparably small. But when the thing gets largish, the slicing, copying and reassembling are getting increasingly inelegant, not to say "un-pythonic." Even if that hypothetical mutable string type wouldn't be returned by read() and wouldn't be accepted by write(), conversion from and to normal immutable strings should be cheap. Hope you're not distracted by the german comments, and just presuming you know what S-records are, Hans-Joachim From ajsiegel at optonline.net Sun Mar 30 11:39:50 2003 From: ajsiegel at optonline.net (Arthur) Date: Sun, 30 Mar 2003 11:39:50 -0500 Subject: A bug I found in Python Message-ID: <000501c2f6da$fc2e9590$0c02a8c0@Arts> Tim explains ->Yes, it's clearly a bug in Python. What's happening is that it saw the 0 in >"10", and the zero in "-10", and figured 0 was the most popular digit. As >is so often the case, Python sacrificed accuracy for popularity. Thanks for the clairification. My guess had been that it had something to do with the "lo" in "Hello" being mangled with the "10" in 10. Similar to the kind of issues one runs into entering the license keys for the commercial version of Python. I happen to be designing a more expensive version of Python, where O and 0, and l and 1 are not distinguished. I expect it to become *the* language for entering license keys. Art From vijay at accellion.com Mon Mar 10 00:48:04 2003 From: vijay at accellion.com (Vijay Rao) Date: Mon, 10 Mar 2003 11:18:04 +0530 Subject: bsddb crashes on windows In-Reply-To: <15976.48315.332783.60778@montanaro.dyndns.org> References: <15976.47138.80321.755378@montanaro.dyndns.org> <20030307020101.12244.35865.Mailman@mail.python.org> <5.1.0.14.0.20030307105920.01a36010@131.103.204.244> <15976.47138.80321.755378@montanaro.dyndns.org> Message-ID: <5.1.0.14.0.20030310110131.00bc4680@131.103.204.244> At 09:37 07/03/2003 -0600, you wrote: > Vijay> Does this mean that if I use bsddb3 with Python 2.2 I wont have > Vijay> to make any change when I use the same code base with Python 2.3. > > Skip> Correct. You can still call bsddb.hashopen(...) to open a > Skip> database file. > >My mistake. I read a bit too fast and missed the "3". If you want to use >code in the distribution you'll have to change your imports at least. On >the other hand, if you installed PyBSDDB (aka bsddb3) separately, just >reinstall it using Python 2.3 and you should be okay. You'll have two >versions of the same package installed, but it shouldn't be a problem unless >there's a name clash at the C level. I tried using bsddb3-4.1.0.win32-py2.2.exe on WinXP with Python 2.2.1. Iterating through a btree seems to be resulting a in open Handles ( viewable in processes , Windows Task Manager ). About 1 handle per 20 entries in the database is added and it is not freed even when the db is closed. The same code ( below ) does not result in any such handles for the bsddb module that is part of python. def getTreeSize(type_db3,tree_path) : if type_db3 : tree_handle = bsddb3.btopen(tree_path) else : tree_handle = bsddb.btopen(tree_path) size = 0 try : try : entry = tree_handle.first() except : traceback.print_exc() return 0 else : size += 1 while 1: try : tree_handle.next() except : traceback.print_exc() break else : size += 1 except : traceback.print_exc() tree_handle.close() return size Could this be memory leak somewhere ? vr From sSPAMMENOTmarrocco at gtninc.com Sun Mar 16 14:54:09 2003 From: sSPAMMENOTmarrocco at gtninc.com (Sam Marrocco) Date: Sun, 16 Mar 2003 19:54:09 GMT Subject: Pmw and Python setup In-Reply-To: References: <4_2da.31582$s75.11393282@twister.columbus.rr.com> Message-ID: Bob X wrote: > There is also a great book by Manning: > > Python and Tkinter Programming by John Grayson > > It deals with Pmw as well. > > I picked it up recently....it's a good reference book, but a little skimpy on examples. -- ================================================================== Sam J. Marrocco Sr. Visual Effects Artist/R&D Travelling Pictures/GTN Inferno, Flame, Houdini, Maya, All that cool stuff! "The fact that no one understands you doesn't make you an artist." ================================================================== From graham__fawcett at hotmail.com Sat Mar 1 18:55:41 2003 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 1 Mar 2003 15:55:41 -0800 Subject: Borg - is that a singleton? References: <3d799735.0302281853.2f2784a5@posting.google.com> Message-ID: Alex Martelli wrote in message news:... > > Too much work! Just: > > class Foo(Borg): _shared_state = {} > > > class Bar: > > __shared_state = {} > > def __init__(self): > > self.__dict__ = self.__shared_state > > Ditto: just > > class Bar(Borg): _shared_state = {} Beautiful! -- Graham From imbosol-1047873617 at aerojockey.com Mon Mar 17 01:15:40 2003 From: imbosol-1047873617 at aerojockey.com (Carl Banks) Date: Mon, 17 Mar 2003 06:15:40 GMT Subject: a simple question about string object References: Message-ID: Frank Zheng wrote: > Hi, all: > >>>> s = '12345' >>>> s[2] = 'x' > Traceback (most recent call last): > File "", line 1, in ? > TypeError: object doesn't support item assignment > > i know the string object is immutable, so if i want to do 'item assignment', > i should do: >>>> new_s = s[0:1] + 'x' + s[2:] > ( i think it's ugly) > > Is there other ways to do this? > should i define a function to do this? Is there any modules existing can do > this? The array module has arrays of characters, which you can use as a kind of mutable string: from array import array s = array('c', '12345') s[2] = 'x' print s.tostring() Problem is, most string operations don't work on character arrays. -- CARL BANKS From marklists at mceahern.com Mon Mar 10 13:55:59 2003 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 10 Mar 2003 12:55:59 -0600 Subject: Testing for a list In-Reply-To: <000d01c2e735$a68e6cf0$0d01a8c0@Antun> Message-ID: [Antun Karlovac [mailto:antun at antunkarlovac.com]] > Python doesn't have a builtin method for doing this then, right? Short answer: No. Teasing out a longer answer gets you into long pointless philosophical debates about static vs. dynamic typing. Those usually bore me to tears, but I'm sure that's because I'm too dumb to understand them much less read them. Cheers, // m - From cnetzer at mail.arc.nasa.gov Thu Mar 13 15:34:56 2003 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: 13 Mar 2003 12:34:56 -0800 Subject: Tkinter callback problem In-Reply-To: <20030313175826.GC3471@unpythonic.net> References: <5b6217b0.0303130918.5409b763@posting.google.com> <20030313175826.GC3471@unpythonic.net> Message-ID: <1047587695.661.42.camel@sayge.arc.nasa.gov> On Thu, 2003-03-13 at 09:58, Jeff Epler wrote: > It's likely to be relevant which version of Tk you are using. > Historically not all fields applied to all events, but Tk would still > cheerfully substitute a meaningless decimal for all fields anyway. If > they've tightened this up, it's a pity, because it will add complicated > logic to Tkinter. I just got burned with this when upgrading to Tk 8.4.2 on Debian. Apparantly, many more of the fields now return "??" rather than an int string (during the _substitute() call in Tkinter). Downgrading back to Tk 8.4.1 fixed the problem for me. If this change in Tk is not considered a bug, and will remain, than Tkinter must be fixed to operate with the most recent Tk (as usual). So, Ian, in the meantime, can you install Tk 8.4.1 instead (assuming you are using 8.4.2)? -- Bay Area Python Interest Group - http://www.baypiggies.net/ Chad Netzer (any opinion expressed is my own and not NASA's or my employer's) From xtian at toysinabag.com Sun Mar 16 22:40:12 2003 From: xtian at toysinabag.com (xtian) Date: 16 Mar 2003 19:40:12 -0800 Subject: Strange rounding problem References: <4378fa6f.0303141540.de857b8@posting.google.com> <3E736D6A.42C9355A@engcorp.com> <20030315185608.GB14733@meson.dyndns.org> Message-ID: danb_83 at yahoo.com (Dan Bishop) wrote in message news:... > Imho, 6 would be better than either 10 or 14, because for any > sufficiently large finite range of integers, there are more multiples > of 3 than multiples of 5 and 7. > > If we define the utility of a number base as proportional to the > number of its factors (excluding itself), and inversely proportional > to the magnitude of those factors (and use the Python script at the > end of this message to calculate those factors), we find that the best > bases are 12 (1.562), 6 (1.500), and 24 (1.361), and that bases 14, > 21, 22, 25-28, and 32-35 are worse than the prime bases. > OT (although arguably no more than the other stuff immediately before in the thread ;)- I found this discussion of the benefits of number systems based on what the author terms versatile numbers very interesting: http://www.earth360.com/math-versatile.html cheers, xtian From ddougan at telus.net Mon Mar 24 23:17:02 2003 From: ddougan at telus.net (Des Dougan) Date: Tue, 25 Mar 2003 04:17:02 GMT Subject: Problems build 2.1.3 RPM on Mitel SME Server Message-ID: <2LQfa.54725$wW.5350304@news2.telusplanet.net> I'm attempting, for the first time, to build an RPM for Python 2.1.3 on the Mitel SME Server Linux distribution. My test box has all the relevant compile tools and source RPMs, as far as I can tell. When I run the rpm --rebuild command, it processes for a good 10 minutes or so, before failing with the following: Processing files: python2.1-2.1.3-1 Executing(%doc): /bin/sh -e /var/tmp/rpm-tmp.23129 + umask 022 + cd /usr/src/redhat/BUILD + cd Python-2.1.3 + DOCDIR=/var/tmp/python2.1-2.1.3-root/usr/share/doc/python2.1-2.1.3 + export DOCDIR + rm -rf /var/tmp/python2.1-2.1.3-root/usr/share/doc/python2.1-2.1.3 + /bin/mkdir -p /var/tmp/python2.1-2.1.3-root/usr/share/doc/python2.1-2.1.3 + cp -pr Misc/README Misc/HYPE Misc/cheatsheet Misc/unicode.txt Misc/Porting /var/tmp/python2.1-2.1.3-root/usr/share/doc/python2.1-2.1.3 + cp -pr LICENSE Misc/ACKS Misc/BLURB.LUTZ Misc/BLURB.WINDOWS Misc/HISTORY Misc/NEWS /var/tmp/python2.1-2.1.3-root/usr/share/doc/python2.1-2.1.3 + exit 0 Finding Provides: (using /usr/lib/rpm/find-provides)... Finding Requires: (using /usr/lib/rpm/find-requires)... error: line 328: Dependency tokens must begin with alpha-numeric, '_' or '/': %defattr(-,root,root) error: Failed to find Requires: Provides: _codecs.so _curses.so _curses_panel.so _locale.so _socket.so _symtable.so _testcapi.so _weakref.so array.so audioop.so binascii.so bsddb.so cPickle.so cStringIO.so cmath.so crypt.so dbm.so errno.so fcntl.so fpectl.so gdbm.so grp.so imageop.so linuxaudiodev.so math.so md5.so mmap.so new.so nis.so operator.so parser.so pcre.so pwd.so pyexpat.so regex.so resource.so rgbimg.so rotor.so select.so sha.so strop.so struct.so syslog.so termios.so time.so timing.so unicodedata.so xreadlines.so zlib.so PreReq: rpmlib(PayloadFilesHavePrefix) <= 4.0-1 rpmlib(CompressedFileNames) <= 3.0.4-1 Requires(rpmlib): rpmlib(PayloadFilesHavePrefix) <= 4.0-1 rpmlib(CompressedFileNames) <= 3.0.4-1 Requires: ld-linux.so.2 libc.so.6 libdl.so.2 libm.so.6 libpthread.so.0 libutil.so.1 libcrypt.so.1 libexpat.so.0 libgdbm.so.2 libncurses.so.5 libnsl.so.1 libpanel.so.5 libz.so.1 Processing files: python2.1-devel-2.1.3-1 Finding Provides: (using /usr/lib/rpm/find-provides)... Finding Requires: (using /usr/lib/rpm/find-requires)... PreReq: rpmlib(PayloadFilesHavePrefix) <= 4.0-1 rpmlib(CompressedFileNames) <= 3.0.4-1 Requires(rpmlib): rpmlib(PayloadFilesHavePrefix) <= 4.0-1 rpmlib(CompressedFileNames) <= 3.0.4-1 Requires: python2.1 = 2.1.3 /bin/sh Processing files: python2.1-tkinter-2.1.3-1 error: File not found by glob: /var/tmp/python2.1-2.1.3-root/usr/lib/python2.1/lib-dynload/_tkinter.so* Requires: python2.1 = 2.1.3-1 Processing files: python2.1-tools-2.1.3-1 Finding Provides: (using /usr/lib/rpm/find-provides)... Finding Requires: (using /usr/lib/rpm/find-requires)... error: line 328: Dependency tokens must begin with alpha-numeric, '_' or '/': %defattr(-,root,root) error: Failed to find Requires: PreReq: rpmlib(PayloadFilesHavePrefix) <= 4.0-1 rpmlib(CompressedFileNames) <= 3.0.4-1 Requires(rpmlib): rpmlib(PayloadFilesHavePrefix) <= 4.0-1 rpmlib(CompressedFileNames) <= 3.0.4-1 Requires: python2.1 = 2.1.3-1 RPM build errors: line 328: Dependency tokens must begin with alpha-numeric, '_' or '/': %defattr(-,root,root) Failed to find Requires: File not found by glob: /var/tmp/python2.1-2.1.3-root/usr/lib/python2.1/lib-dynload/_tkinter.so* line 328: Dependency tokens must begin with alpha-numeric, '_' or '/': %defattr(-,root,root) Failed to find Requires: I want 2.1.3, as I plan to test Plone, which currently does not support Python 2.2. I'd be grateful for any feedback anyone can provide. Des Dougan From troy at gci.net Wed Mar 5 18:30:13 2003 From: troy at gci.net (Troy Melhase) Date: Wed, 05 Mar 2003 23:30:13 +0000 Subject: "len()" gives a curious error References: Message-ID: err...? i don't think my original note was in any way chastening. if i had called you a knuckle head, then yes, that would have been chastening. but since i've done the same thing you did (many more times than i care to admit), i felt somewhat restrained from calling names. :) Mike McKernan wrote: > Thanks, I'm appropriately chastened. I promise my next question > won't be about the same bit of foolishness. From eddie at holyrood.ed.ac.uk Thu Mar 13 12:34:07 2003 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Thu, 13 Mar 2003 17:34:07 +0000 (UTC) Subject: little programming probleme References: <3e6fab9d$0$83883$ba620e4c@news.skynet.be> Message-ID: Jonas Geiregat writes: >I have a string and I want to delete all comments , comments start with a # >here is my code >conf is my string where I want to delete comments I think the probleme >is that if he finds a comment he delete's the element of the list but >then he can't loop true that element anymore so I should break the loop >and start the first one again but I don't know how if it could be any >help I added my error code un the code >chunk = string.split(conf,"\n") > for i in range(len(chunk)): > for x in range(len(chunk[i])): > if chunk[i][x] == "#": > print chunk[i] conf = '\n'.join([x.split('#')[0].strip() for x in conf.split('\n')]) Will remove all comments and reconstruct whole string. This assumes comments can start anywhere on the line. Since your code doesn't seem to match what you say you're trying to do I'm guessing that's what you want. In essence, it's easier to build a new string by extracting the bits you want from the old string and joining them rather than deleting substrings from the original. Also when iterating over a list you can just use: for item in list: do something with item rather than: for i in range(len(list)): do something with list[i] So the longer version of above is: tmp_string = '' for line in conf.split('\n'): tmp_string += line.split('#')[0].strip() conf = tmp_string where line.split('#')[0] extracts the portion before the '#' or the whole string if there is none. Eddie From b.hall at irl.cri.nz Tue Mar 11 21:52:08 2003 From: b.hall at irl.cri.nz (Blair Hall) Date: Wed, 12 Mar 2003 15:52:08 +1300 Subject: assigning to matrix elements in NumPy Message-ID: <3E6EA0D7.CD6FBAA1@irl.cri.nz> I have just upgraded from NumPy 21 to NumPy 23 and was surprised to find that my matrix assignment doesn't work like it used to. For example: >>> from Matrix import * >>> m = Matrix( [[1,2],[3,4]]) >>> m[1,1] 4 >>> m[1,1] = 2 Traceback (most recent call last): File "", line 1, in ? File "C:\PYTHON22\lib\site-packages\Numeric\Matrix.py", line 183, in __setitem__ value = value[0,0] IndexError: invalid index >>> Apparently, I should have written >>> m[1,1] = Matrix( 2 ) Is this really indended, or am I confused? From skip at pobox.com Thu Mar 6 11:25:54 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 6 Mar 2003 10:25:54 -0600 Subject: C-h f equivalent In-Reply-To: <15975.29744.37453.196156@montanaro.dyndns.org> References: <87adg8fwpj.fsf@millingtons.org> <15975.29744.37453.196156@montanaro.dyndns.org> Message-ID: <15975.30354.351361.954133@montanaro.dyndns.org> Skip> e.g. string.find or sock.gethostbyaddr. Make that sock*et*. S From jnix at medi.physik.uni-oldenburg.de Wed Mar 19 05:43:36 2003 From: jnix at medi.physik.uni-oldenburg.de (Johannes Nix) Date: 19 Mar 2003 11:43:36 +0100 Subject: multidimensional take Message-ID: <673cljzlev.fsf@achernar.i-did-not-set--mail-host-address--so-shoot-me> I have an interesting task which may be of general interest (for number-crunchers, the rest might crunch what it likes). I am working with the Numeric module (aka Numerical Python) on large statistical datasets. What I want to do is a _fast_ multidimensional "take" operation. Numeric.take is defined so that >>> a array([[140, 455, 325, 360, 498], [372, 647, 636, 365, 462], [893, 141, 776, 238, 259]]) >>> b = [0, 3, 4] >>> take(a, b, 1) array([[140, 360, 498], [372, 365, 462], [893, 238, 259]]) >>> c = [[0, 3, 4], [0, 1, 4]] >>> take(a, c, 1) array([[[140, 360, 498], [140, 455, 498]], [[372, 365, 462], [372, 647, 462]], [[893, 238, 259], [893, 141, 259]]]) That is, for each element i in c, a[:,i] is returned, wether a[:,i] might be a single element or a submatrix. The lookup is done on the second axis because of the axis parameter, but I'll neglect this in the following. Now I want to have a function defined as following: def mtake(a, ind): ind = array(ind) if len(ind.shape) <= 2: return array([ a[i] for i in ind]) # (1) else: return array([ mtake(a, i) for i in ind]) That means that the result of mtake(a, ind[.., NewAxis]) would be equal to take(a, ind) If the last dimesion has more than one element, it would perform a coordinate lookup with the coordinates being the elements on the last dimension of ind, as in mtake(a, [[1, 0], [ 1, 1], [2, 4]]) array([372, 647, 259]) Now I want to have this function defined by using take for the lookup done in (1), because it's much faster - take is implemented in C . Any suggestions ? Johannes From carel.fellinger at chello.nl Tue Mar 4 10:27:47 2003 From: carel.fellinger at chello.nl (Carel Fellinger) Date: Tue, 4 Mar 2003 16:27:47 +0100 Subject: Towards a more Pythonic "Ternary Operator" In-Reply-To: <20030304130602.GA54772@doublegemini.com> References: <882b0a41.0303020225.3caf0334@posting.google.com> <20030304130602.GA54772@doublegemini.com> Message-ID: <20030304152747.GA5797@mail.felnet> On Tue, Mar 04, 2003 at 01:06:02PM +0000, Clark C. Evans wrote: > I was thinking, perhaps if people first agreed on the problem > finding a solution could become more of a detail. Here is a > stab at the 'terinary operator' problem. ... > (a) someone reading the code has to scan the whole > structure and determine that there is a parallel > structure, where the variable is assigned a value > in either case of the condition; and > > (b) someone writing/editing the code has to make sure > that the variable is the same in both places or > else the parallel structure is broken. > ... I think you missed (c) it takes up too much precious screen estate otherwise I agree, and I think a general switch expression might be more interesting, but as you propose the beast it only deals with straight comparision. What about enhancing it like: b = (if a : on X: Q on Y: R else: S) being equivalent to: if a Y: b = R else: b = S And a possible shortening syntactic sugaring could produce: b = (if a ; on X: Q; on Y: R; else: S) The semicolon being used to allow to put on one line what otherwise needs two, like with multiple statements on a single line. The parens being required to allow nesting and making scope explicit. And leaving finding proper names for if (select) and on (case) for later to decide. I think something along these lines has been proposed during the recent ternary operator tempest, but I lost track. Anyway, by now it looks so troublesome that I rather not have it in:) -- groetjes, carel From djn at daimi.au.dk Thu Mar 27 06:34:57 2003 From: djn at daimi.au.dk (Daniel Nielsen) Date: Thu, 27 Mar 2003 11:34:57 +0000 (UTC) Subject: signal module? In-Reply-To: <20030327092336.GB17524@daimi.au.dk> References: <20030327092336.GB17524@daimi.au.dk> Message-ID: <20030327113455.GE17524@daimi.au.dk> On 27/03-03 09.23, Daniel Nielsen wrote: [snip] I've been examining the situation more. It seems that I allowed the main thread to exit, but this is not good when you need that to handle the SIGINT. However, when SIGINT is caught, sys.exit() only exits the main thread... How do you terminate the whole program? /Daniel -- There are no great men, only great challenges that ordinary men are forced by circumstances to meet. -- Admiral William Halsey From philh at cabalamat.org Sun Mar 30 01:01:57 2003 From: philh at cabalamat.org (phil hunt) Date: Sun, 30 Mar 2003 07:01:57 +0100 Subject: Easibox 0.1.5 released Message-ID: Easibox is a utility for making tar files, zip files and other archive files, designed to be particularly useful when making releases of open source projects. Easibox was written to solve a problem I had when releasing open source software packages, such as my Leafwa program. The technique I was using was manually creating a directory with the required filename (such as "leafwa-0.6.1"), copying those files to be archived into the directory, and then cd'ing to that directory's parent and running tar to create the tarball. I found this process time-consuming and error-prone. So I decided there must be a better way... My solution was this program ``easibox'' which decides what files it will put in the archive, what sort of archive files will be created, and other parameters, based on the contents of a configuration file in the project directory. The configuration file is read in by the Python interpreter; this means that it uses Python syntax (so you don't have to learn another file type) and that you can put Python program statements in it. Easibox is written in Python and licensed under the GNU General Public License; see file COPYING (which comes with the distribution) for details. Easibox is available on the web at: -- Philip Hunt Interested in adventure holidays in Spain? Look at: From garycramblitt_NOSPAM at comcast.net Sun Mar 9 11:58:03 2003 From: garycramblitt_NOSPAM at comcast.net (Gary Cramblitt) Date: Sun, 09 Mar 2003 11:58:03 -0500 Subject: GUI Toolkits References: Message-ID: On Sat, 08 Mar 2003 12:15:56 +0000, Thomas G. Willis wrote: > I wanted to know if there are any reccomended GUI toolkits for python. wxPython is an excellent option. www.wxPython.org. Together with the Boa-constructor IDE you get a nice cross-platform RAD development environment with built-in debugging etc. From gerrit at nl.linux.org Sun Mar 16 16:23:08 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 16 Mar 2003 22:23:08 +0100 Subject: Is " a is b " and " id(a) == id(b) " the same? In-Reply-To: References: Message-ID: <20030316212308.GA3941@nl.linux.org> Aahz schreef op zondag 16 maart om 22:11:47 +0000: > s/__getattr__/__getattribute__/ I take it you mean: s.replace('__getattr__', '__getattribute__') ;) yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From gerard.breiner at ias.u-psud.fr Mon Mar 17 08:59:27 2003 From: gerard.breiner at ias.u-psud.fr (Gerard Breiner) Date: Mon, 17 Mar 2003 14:59:27 +0100 Subject: how to send a form html by email ? References: Message-ID: I try "PythonHandler tmail". the result provide the same error. Gerard "Gerhard H?ring" a ?crit dans le message de news: slrnb7bgcf.1ho.gerhard.haering at haering.opus-gmbh.net... > Gerard Breiner wrote: > > My form is a html form. My server apache is configured with > > mod-python and here is a part of my http.conf : > > ------------------------------ > > Alias /python "C:/Program Files/Apache Group/Apache/htdocs/python" > > > > AddHandler python-program .py > > PythonHandler email > > PythonDebug on > > > > --------------------------------- > > and here is my email.py file that i am trying to test. > > -------------------------------- > > import smtplib > > > > # Import the email modules we'll need > > from email.MIMEText import MIMEText > > [...] > > Try using a different module name, *not* email. 'email' is already the > name of the 'email' package that you're trying to import, so it's > likely that there's a name collission that's causing your problems. > > HTH, > > -- Gerhard From a.schmolck at gmx.net Mon Mar 3 08:41:50 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 03 Mar 2003 13:41:50 +0000 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <58q36vgv1ga8ovde5ftub9t8ugaa2pnum5@4ax.com> <7k366vonlu82mq7ve83bmq7ijfhrv03hpf@4ax.com> Message-ID: Stephen Horne writes: > On 02 Mar 2003 23:16:53 +0000, Alexander Schmolck > wrote: > > >Stephen Horne writes: > > > >> Actually, I've always thought that having separate 'def' and 'lambda' > >> syntaxes is a bit redundant. In lisp (and a few others) you'd use the > >> 'lambda' form to do both jobs, rather like (in current Python) > >> writing... > >> > >> sum = lambda a, b : a + b > > > >Not true, I think. Apart from scheme (which's lispness is often disputed in > >both lisp and scheme circles). > > Wierd - I've hardly used scheme, but I have looked at it much more > recently than lisp (not used properly in more than a decade). Still, I > appologise for the confusion. To clarify, in scheme, there is only one namespace: > (define a-var 1) > (define a-function (lambda () 1)) > a-var 1 > (a-function) 1 in (common) lisp, which has a separate namespace for functions: > (defvar a-var 1) > (defvar a-function (lambda () 1)) > a-var 1 > (a-function) Error: the function a-function is undefined > (funcall a-function) 1 > ;; this doesn't affect the variable value of a-function > (defun a-function () 'result) > (a-function) 'result > ;; still the same variable > (funcall a-function) 1 alex From PEP308reply at telus.net Wed Mar 12 02:08:01 2003 From: PEP308reply at telus.net (Lenard Lindstrom) Date: Wed, 12 Mar 2003 07:08:01 GMT Subject: Overloading operators for currying, a PEP309 suggestion References: Message-ID: "Stephen Horne" wrote in message news:bmjr6vgc7efto3qqqfbmkri9u68l54k78c at 4ax.com... > > You may be onto something, but I'm not keen on your '|' version in > particular. > I chose the '|' bitwise or and '<<' left shift operators because of a superficial simularity between currying a parameter list and manipulating a string of bits. Doing an 'or' allows you to selectively set arguments; doing a 'shift' allows you to remove arguments sequencially. However, there are many operators to choose from. > I would prefer defining the __len__, __getitem__, __setitem__ and > __delitem__ methods to allow direct manipulation (and creation and > deletion) of the closure. Though probably the function object should > be immutable. > Yes, I think the curried function object should be immutable. This leaves out __setitem__. But is it needed? > How about... > > [ | ] -> > . -> >... or [ | | ] Using my '<<' grammer, positional assignment might be done like this: fn << {:, ...} eg: fn1 = fn << {1:'a'} # the key is an integer posn rather than an arg. name. >... > << > Return a new function/closure with the selected fields from the > old one added or modified. > Maybe this is where __call__ comes in. (, ...) In addition to the currying operators one can add a 'curry' method that behaves like the curry function proposed for the functional module. > That would mean, for a function... > > def fn (a, b, c, d) : > pass > > ...you could write... > > fn2 = fn [0] << "x" # Curry first parameter > fn2 = fn [-1] << "x" # Curry last parameter > fn2 = fn[0]("x") fn2 = fn[-1]("x") > fn2 = fn.b << "x" # Curry keyword parameter > fn2 = fn["b"]("x") > fn2 = fn [1:2] << (1, 2) # Curry a slice > fn2 = fn[1:2](1, 2) >... > fn2.a.value () # Get value currently assigned to a > fn2["a"].value () fn2["a"] # Hmmm. fn2.getargval("a") # ? Having to use some method or property like 'value' is awkward. What other ways are there? If an argument already has a value, this could be returned instead of a . Then a 'has_arg' method would be needed for argument testing. This needs more thought. Anyways, implementing value retrieval would require additional data be kept around if Python closures are used to save the argument values. How important is it? >... > One advantage - it should be possible to write this as a library > without any language changes. I think. > from functional import curryfunction def fn(): fn = curryfunction(fn) At some point class 'function' will be rewritten to allow subclassing. At that time curry operation methods could be added. At the very least the def statement could be extended to provide a way to specify a function class like the class statement and metaclasses. Then a subclass of 'function' could define the curry operators. Lenard Lindstrom "<%s%s.%s>" % ("len-l.", 'telus', 'net') From aleax at aleax.it Mon Mar 24 05:24:41 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 24 Mar 2003 10:24:41 GMT Subject: pass objects to exec References: <7d728336.0303210515.219f63ef@posting.google.com> <7d728336.0303232359.344b2022@posting.google.com> Message-ID: zunbeltz wrote: ... > Tanks for answer. Group class need a second argument, it is a string > similar to that in the dictionary key. Can I use something like that > d = {} > for i in range(len(MemberList)): > d['GroupA-%c' % (i + ord('A'))] = > Group(MemberList[i],'GroupA-%c' %(i+ ?rd('A'))) Yes, this is quite correct code (apart from one too-long line getting broken). But I would recommend never repeating code of any complexity, such as the expression computing the string -- computer it ONCE then use it, i.e.: d = {} for i in range(len(MemberList)): gname = 'GroupA-%c' % (i + ord('A')) d[gname] = Group(MemberList[i], gname) Python 2.3 lets you code this a tad more elegantly, IMHO: d = {} for i, igroup in enumerate(MemberList): gname = 'GroupA-%c' % (i + ord('A')) d[gname] = Group(igroup, gname) and an alternative that also works with earlier Python version is: import string d = {} for c, igroup in zip(string.uppercase, MemberList): gname = 'GroupA-%c' % c d[gname] = Group(igroup, gname) Alex From tomchance at gmx.net Sun Mar 16 17:56:13 2003 From: tomchance at gmx.net (Tom Chance) Date: Sun, 16 Mar 2003 22:56:13 +0000 Subject: Finding child pids Message-ID: Hello again, I've got some code that opens a pipe using popen2.Popen3, and reads data from the pipe. I need to be able to kill the process at any time, and at present I can do this: --- # To open the pipe self.pipe = popen2.Popen3(command) # To kill it (seperate section of the program) self.pid = self.pipe.pid + 1 os.kill(self.pid, 9) os.waitpid(self.pipe.pid, os.WNOHANG) --- The problem here is in the line where I have to add 1 to the pid of the child process. When I open the pipe, python opens the command with sh, and so the first child process is sh, and sh then makes the command its child process. SO... if I kill the pipe (sh), it just then leaves the command to detach and work on its own. So I have to increment the pid by one to kill the command instead. But this seems like a nasty hack to me. How can I get the pid of the command, and not just sh? Tom From max at cNOvSisiPonAtecMh.com Tue Mar 25 17:35:24 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Tue, 25 Mar 2003 22:35:24 GMT Subject: closure References: <3XNfa.9332$iE4.3141991@twister.nyc.rr.com> <2259b0e2.0303250733.2b5445e1@posting.google.com> Message-ID: How is the book coming along? Is there a tentetive publication date? thnks, -- ======================================== Max Khesin, software developer - max at cNvOiSsPiAoMntech.com [check out our image compression software at www.cvisiontech.com, JBIG2-PDF compression @ www.cvisiontech.com/cvistapdf.html] "David Mertz" wrote in message news:mailman.1048622995.13838.python-list at python.org... > "Max Khesin" wrote previously: > |Thanks - my whole research started out from reading your articles on FP :). > |Q-n: what would the "closure" keyword add that a nested scope cannot > |accomplish? > > I think its proponents think that having some special form for closures > would help emphasize the intention of the code to a later programmer. I > don't think anyone claimed that it would make something possible that > was impossible before (but that's true of lots of things: listcomps, > nested scopes themselves, yield/generators, etc). > > I don't advocate the idea myself (but neither am I particularly opposed > to it). Search google groups or the list archive for lots more > discussion, or take a look at the related PEP 309. > > Yours, David... > > -- > _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/ > _/_/ ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~ _/_/ > _/_/ The opinions expressed here must be those of my employer... _/_/ > _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/ > > From wayne at mishre.com Tue Mar 4 20:52:58 2003 From: wayne at mishre.com (Wayne Pierce) Date: 4 Mar 2003 17:52:58 -0800 Subject: help! advocacy resources needed fast References: Message-ID: <2a897f11.0303041752.6da6cf68@posting.google.com> Geoff Gerrietts wrote in message news:... > I didn't think I was going to need to do this, but it looks like I > might. > > Within the next couple days, the firm I work for is likely to be > meeting to decide what we're doing in terms of technology change. > We've been using Python, ILU, and Zope for a long time as the > backbone of our business. We're now talking about changing that, but > we're trying to decide to what. > > The problem is, we're drowning under traffic, and we have very strong > plans/deals/whatever going into place that will multiply that traffic. > We need to start building now for that day. > > One of the guys who's been with the organization for a long time wants > to go to a Java-based approach. The long term viability, he maintains, > is better, and the short term boost in performance per box in the cage > is also better. > > I could be persuaded to let Zope go -- it's nice, but it's not really > a very good fit for our organization. And I welcome the day ILU is no > longer part of our technology framework. But I quail at the thought of > losing Python. > > So I'm hunting for options, and hard facts (preferably with numbers > attached). > > My current read is that Webware + Twisted, or mod_python + Twisted, > would be the "fastest" web server platform python supports. Does > anyone else have better numbers? Solid comparisons of any kind? I've > got lots of anecdotal evidence I can point at, but very little in the > way of hard numbers. > > Thanks, > --G. If you have to use Java, look into Jython...then you can use the existing Python code as well as the new Java code. -W From cnd at ecn.purdue.edu Thu Mar 13 09:22:39 2003 From: cnd at ecn.purdue.edu (Christopher N. Deckard) Date: Thu, 13 Mar 2003 09:22:39 -0500 Subject: reportlab lineplots and very large numbers Message-ID: <20030313092239.5ada1670.cnd@ecn.purdue.edu> Hello, I'm using reportlab to create a line plot of scientific data. Some of our data is for things like Frequency (in Hz) and can get to be really huge numbers. Is there a way to make the plot so that the tick marks get printed out as exponents instead of numbers like 100000000, 200000000, etc.? This would also apply to very small numbers where I'd want to see 9.814e-05 instead of .00009814. I could patch reportlab to do it, but I'd rather do it when setting up the plot. Thanks, -Chris From fonso at aturuxo.net Fri Mar 21 04:08:38 2003 From: fonso at aturuxo.net (=?iso-8859-1?Q?Afonso_Fern=E1ndez_Nogueira?=) Date: Fri, 21 Mar 2003 10:08:38 +0100 Subject: Time<->Weather (Re: A suggestion for a possible Python module ) References: Message-ID: <00f201c2ef89$76257700$0201a8c0@colesterol> ----- Original Message ----- From: "Dave Brueck" > On Wed, 19 Mar 2003 sismex01 at hebmex.com wrote: > > > > From: Andres Rosado [mailto:arosado at softhome.net] > > > Sent: Tuesday, March 18, 2003 6:43 PM > > > > > > > > Italian is even farther from English in terminology (e.g., in > > > > > common speech we do not distinguish between 'time' and 'weather', > > > > > using the same word, 'tempo', for both > > > > > > The same happens in Spanish (tiempo). > > > > > > > Not always; the most correct form is "clima". > > What is most correct varies by region - in some (many?) S.A. countries > "clima" is used pretty much the same way as the American English use of > "climate". You'd get funny looks if you asked about the weather using > "clima". :) > > -Dave Definitely, you never use "clima" in such colloquial, elevator-talk expressions in Spain. fonso From imbosol-1047243733 at aerojockey.com Sun Mar 9 16:03:43 2003 From: imbosol-1047243733 at aerojockey.com (Carl Banks) Date: Sun, 09 Mar 2003 21:03:43 GMT Subject: tuples from lists References: Message-ID: Bob Roberts wrote: > I have a list of lists of lists. How can I turn that into a tuple of > tuples of tuples? Mathematica has a function that can do this kind of thing: MapAll. Maybe this would be a good candidate for the proposed functional module? -- CARL BANKS From david at no.westcontrol.spam.com Wed Mar 26 04:24:25 2003 From: david at no.westcontrol.spam.com (David Brown) Date: Wed, 26 Mar 2003 10:24:25 +0100 Subject: Const in python? References: Message-ID: "Lulu of the Lotus-Eaters" wrote in message news:mailman.1048613681.19759.python-list at python.org... > Dave Brueck wrote previously: > |> ALL CAPS conventions - they look ugly, > > |To you, perhaps. This is a very widely used, understood, and accepted > |convention - I quite like it. > > As if this were a democracy, I'll just chime in "I agree" :-). Brueck > does a great job of explaining exactly why capitalized contstants aid > comprehension. He did indeed give a good explaination. I don't like all caps personally, but I fully realise that I'm in the minority. > > Maybe I'm tainted by having already used it in a dozen languages before > Python... hmmm, do you think there is a reason those dozen languages all > use the same convention? > Perhaps because it's conventional? People are used to it, so there is no point in changing it without good reason. The use of all caps in programming stems back to the days when caps were all you had. I feel that it looks ugly, and I am not going to use it just to be traditional. If people (such as Dave Brueck) feel it improves the readability of their programs, then that's great. I think it is important to emphasis readability in programming, and that readability is more important than writing code just like your grandfather wrote it, so I dislike the idea of using all caps just because it has been done in dozens of other langauges (after all, curly brackets and begin-ends are used to show scope in dozens of other languages - that doesn't make it the only way to do it :-). But I have no problem with using all caps because you feel it really is a better way to do it. David. > Yours, Lulu... > > -- > mertz@ _/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: \_\_\_\_ n o > gnosis _/_/ Postmodern Enterprises \_\_ > .cx _/_/ \_\_ d o > _/_/_/ IN A WORLD W/O WALLS, THERE WOULD BE NO GATES \_\_\_ z e > > From marco.bari at vene.ws Thu Mar 13 06:12:36 2003 From: marco.bari at vene.ws (Marco Barisione) Date: Thu, 13 Mar 2003 12:12:36 +0100 Subject: list to dict? References: <8fc3c459.0303111859.7ebbd60a@posting.google.com> Message-ID: <1w8qyweow57d$.dlg@marco.barisione> On Wed, 12 Mar 2003 04:00:57 GMT, Raymond Hettinger wrote: >>>> d = {} >>>> for pair in s: > key, value = pair.split("=") "pair.split('=', 1)" is better as it works even if there are two "=" in the string. -- Marco Barisione http://spazioinwind.libero.it/marcobari/ From rnd at onego.ru Thu Mar 6 14:25:48 2003 From: rnd at onego.ru (Roman Suzi) Date: Thu, 6 Mar 2003 22:25:48 +0300 (MSK) Subject: Speed *triples* by changing 'apply(f, args)' to 'f(*args)' In-Reply-To: <3e6679b2$0$49113$e4fe514c@news.xs4all.nl> Message-ID: On Wed, 5 Mar 2003, Irmen de Jong wrote: >Roman Suzi wrote: >>>>>def tomorrow(fff): print fff() >> ... >>>>>tomorrow(:len('123')) >> 3 > >What's that? Didn't you forget a "lambda" before the colon? >I get a SyntaxError as written. I was joking. Laugh. It was intended to demonstrate implicit lambda is not that outlandish. (PEP 312) >Irmen > > Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by Linux RedHat 7.3 From salvatore at wanadoo.fr Mon Mar 31 17:22:44 2003 From: salvatore at wanadoo.fr (Salvatore) Date: Tue, 01 Apr 2003 00:22:44 +0200 Subject: changing icon to a Tkinter gui program In-Reply-To: References: Message-ID: Federico wrote: > How can I change the icon of the windows of a Tkinter Gui program? > Thanks > > http://effbot.org/downloads/tkicon-0.9-19980218.zip Regards Salvatore From glc at well.com Sat Mar 1 12:00:17 2003 From: glc at well.com (Greg Chapman) Date: Sat, 01 Mar 2003 17:00:17 GMT Subject: Why does 2.3a2 change "slots" in complex? References: Message-ID: On Fri, 28 Feb 2003 22:03:45 -0500, mertz at gnosis.cx (David Mertz) wrote: >One of the unit tests involves adding extra attributes to descendents of >standard data types. It turns out, that test breaks with Python 2.3a2, >because of a change in the implementation of complex. > >Here is a brief test case that shows the behavior. I am interested in >why this change was made. Is it a bug or a feature? If a feature, what >benefit does this have? If a bug... well, I guess that's the point of >an alpha version. If you check the type of c in your example, you'll find that it is complex under 2.3a2 (rather than __main__.Complex). I believe this is definitely a bug. It appears this problem was introduced by a change which causes the complex constructor (complex_new) to return its argument if it is of the exact type complex (rather than creating a new complex instance). Instead, I believe complex_new should also check to see if the type being constructed (i.e., the type parameter) is in fact exactly complex; if not, then it should try to create the new instance no matter what arguments it gets. I believe the correct fix would be to change this test: if (PyComplex_CheckExact(r) && i == NULL) to this: if (PyComplex_CheckExact(r) && i == NULL && PyComplex_CheckExact(type)) I'll file a bug report. --- Greg Chapman From aleax at aleax.it Sat Mar 22 04:09:03 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 22 Mar 2003 09:09:03 GMT Subject: Exception in multiple use of xml.dom.minidom.parse() References: Message-ID: Martin L?thi wrote: > Dear Pythonistas > > An exception is trown when I try to parse a several xml files. For the > first file everything works out as described in the docs (for Python 2.2), > using > > Python 2.2.2 (#1, Oct 17 2002, 08:48:02) > [GCC 2.95.3 20010315 (SuSE)] on linux2 > > python-docs-2.2p1/lib/module-xml.dom.minidom.html > >>>> from xml.dom.minidom import parse > >>>> dom1 = parse('/my/data1.xml') # parse an XML file by name > > When I try to access an other file > >>>> dom2 = parse('/my/data2.xml') > > I get the following exception > > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/local/lib/python2.2/site-packages/_xmlplus/dom/minidom.py", > line 962, in parse > return _doparse(pulldom.parse, args, kwargs) > File "/usr/local/lib/python2.2/site-packages/_xmlplus/dom/minidom.py", > line 953, in _doparse > events = apply(func, args, kwargs) > File "/usr/local/lib/python2.2/site-packages/_xmlplus/dom/pulldom.py", > line 338, in parse > parser = xml.sax.make_parser() > File "/usr/local/lib/python2.2/site-packages/_xmlplus/sax/sax2exts.py", > line 37, in make_parser > return XMLParserFactory.make_parser(parser_list) > File "/usr/local/lib/python2.2/site-packages/_xmlplus/sax/saxexts.py", > line 64, in make_parser > return self._create_parser(parser_name) > File "/usr/local/lib/python2.2/site-packages/_xmlplus/sax/saxexts.py", > line 43, in _create_parser > return drv_module.create_parser() > File "/usr/local/lib/python2.2/site-packages/_xmlplus/sax/saxexts.py", > line 74, in _create_parser > raise _exceptions.SAXReaderNotAvailable > TypeError: __init__() takes at least 2 arguments (1 given) > > Is this the expected behaviour? Absolutely not, and indeed that traceback is totally weird -- it points to a raise of SAXReaderNotAvailable but then it gives you a TypeError instead...!!! I suspect you may be running afoul of some installation problem compounded with / hidden by _xmlplus' import tricks. I am unable to reproduce your problem with my Python 2.2.2 installation, on which I seem to have xml 0.5.2 installed in _xmlplus (just reading the _checkversion.py file in that directory). Perhaps removing and reinstalling a stable version of _xmlplus might help you...? Alex From snail at objmedia.demon.co.uk Thu Mar 13 08:59:37 2003 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Thu, 13 Mar 2003 13:59:37 +0000 Subject: [ANNOUNCE] New Python Software Tools on Win32 Message-ID: Software Verification are pleased to announce the release of Performance and Coverage Software tools for Python into public beta. If you would like to take part in the beta test, please visit. http://www.softwareverify.com/publicBeta.html and go to the bottom of the page for details of the Python tools. We also do tools for C++ and Java. Stephen -- Stephen Kellett Software Verification Limited http://www.softwareverify.com Memory Validator From student00 at angelfire.com Sun Mar 30 17:49:06 2003 From: student00 at angelfire.com (student) Date: 30 Mar 2003 14:49:06 -0800 Subject: simulating keyboard events Message-ID: is there an easy way to simulate a keyboard event in python.. i need to send a 'Delete' key event to a text widget (at the current cursor position/selection) thanks From mwm at mired.org Fri Mar 21 11:55:31 2003 From: mwm at mired.org (Mike Meyer) Date: Fri, 21 Mar 2003 16:55:31 GMT Subject: Unittests and external data.... References: <3E79C4E5.FB0C16D0@engcorp.com> Message-ID: Peter Hansen writes: > Mike Meyer wrote: > > While I'm really fond of unit tests, I keep running into problems of > > their needing more framework than can easily be captured in the > > unittest module. > > > > For instance, I'm working on a project to interface a data source to > > an SQL database. Doing unit tests properly means I need to have > > multiple different versions of the source around, or I need to modify > > it on the fly. Neither of those is really very practical. > Why do you think changing it on the fly is not "very practical"? Because the data the test is using is generated on a different - and very limited - platform than the one the test is running on. To change it on the fly requires going back to the other platform, changing it, and then rerunning the export process. This isn't practical for automated testing. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From me at privacy.net Mon Mar 24 17:44:27 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 25 Mar 2003 10:44:27 +1200 Subject: type function does not subtype In-Reply-To: References: <3E7E81EF.1992BFD4@alcyone.com> Message-ID: Martin v. L?wis wrote: > That won't work. If you create a function through the def statement, > it will be of type function, not of a subclass thereof. Maybe something like the __metaclass__ syntax is called for: def myfunction(args): __functionclass__ = myspecialfunc ... (I know that looks like a local variable assignment, but it wouldn't be. As Guido once said about something else, "It's a double-underscore name -- I can give it whatever semantics I want!") -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From tim_one at email.msn.com Fri Mar 14 00:48:24 2003 From: tim_one at email.msn.com (Tim Peters) Date: Fri, 14 Mar 2003 00:48:24 -0500 Subject: GCD in standard library? In-Reply-To: Message-ID: [lynx] > i suppose it's pointless to ask for python to become a properly > tail-recursive language then? That depends on the point you'd like to make. If the point is for Python to become that, yup, it's pointless, at least until someone capable of doing it cares enough to implement it. 10 years plus & counting, and it's not at the top of anyone's list. properly-tail-recursive-sounds-like-a-chaste-lap-dance-ly y'rs - tim From dcengija_remove_ at inet.hr Wed Mar 19 05:58:37 2003 From: dcengija_remove_ at inet.hr (Davor Cengija) Date: Wed, 19 Mar 2003 11:58:37 +0100 Subject: Setting http proxy programmatically Message-ID: <13615821.zngrY5C3n6@lothar.cengija.com> I read about urllib2.Request and urllib2.ProxyHandler, but being really new in Python, I don't know how to use it (btw, an example in the documentation would be really helpful). Basically, I need to set http proxy within my program. I use urllib2.urlopen(url, data) to submit some form data and it works fine when having no proxy, or when http_proxy environment variable is set, but the program will be run behind a firewall which forces proxy. Here's what I have now (simplified): def addEmail(self, emailValue): """Adds the email which will be submitted to the form""" log(("Adding", emailValue)) self.data[self.emailField] = emailValue self.params = urllib.urlencode(self.data) # GET method def doSubmit(self, email): self.addEmail(email) preparedUrl = self.url + "?%s" % self.params log(preparedUrl) return urllib2.urlopen(preparedUrl).info() # POST method def doSubmit(self, email): self.addEmail(email) log((self.url, self.params)) return urllib2.urlopen(self.url, self.params).info() self.data is a simple dictionary object, and self.params is that dictionary, but urlencoded. Where I should instantiate ProxyHandler and/or Request and how can I force urllib2.urlopen() to use it? Thanks. -- Davor Cengija, dcengija_remove_ at inet.hr From mike at bindkey.com Fri Mar 28 19:50:35 2003 From: mike at bindkey.com (Mike Rovner) Date: Fri, 28 Mar 2003 16:50:35 -0800 Subject: Determining if program executing in shell background? References: Message-ID: "Donn Cave" wrote in message news:b62mau$2aoi$1 at nntp6.u.washington.edu... From amartin at traza-si.com Fri Mar 7 05:41:40 2003 From: amartin at traza-si.com (Aurelio Martin Massoni) Date: Fri, 7 Mar 2003 11:41:40 +0100 Subject: c = {x: '' for x in a} References: Message-ID: "Hilbert" escribi? en el mensaje news:v6gp1841qlpr51 at corp.supernews.com... > Ok. > This works: > > a = [1,2,3] > b = [x for x in a] > > What's wrong with this one though? It would totally make sense to me... > > a = [1,2,3] > c = {x: '' for x in a} Try this one : c = dict( [ ( x, '' ) for x in a ] ) From mwh at python.net Thu Mar 27 06:58:05 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 27 Mar 2003 11:58:05 GMT Subject: signal module? References: <20030327092336.GB17524@daimi.au.dk> Message-ID: <7h3ptodm377.fsf@pc150.maths.bris.ac.uk> Daniel Nielsen writes: > I'm currently working on some code that uses the signal module... But > I doesnt seem to work proberly. > > I'm using threads, You are in trouble already. > so I'd like ctrl-c to actually terminate the program. If my memory > serves me, ctrl-c is SIGINT, so in my code, in the main thread, I > write: > > signal.signal(signal.SIGINT, gp.handler); > > where gp is a module and handler looks like: > > def handler(signum, frame): > print "Handling signal: " + signum; > sys.exit(2); > > But ctrl-c doesnt do anything! > > If I write: > signal.signal(signal.SIGINT, signal.SIG_DFL); > instead, ctrl-c actually terminates the program... > Have I misunderstood something? I'd expect this to work, but that it doesn't fails to surprise. What OS (+version, probably) are you on? Any chance of a complete code sample? Cheers, M. -- Monte Carlo sampling is no way to understand code. -- Gordon McMillan, comp.lang.python From jack at performancedrivers.com Mon Mar 17 13:14:12 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 17 Mar 2003 13:14:12 -0500 Subject: Programmatic HTML? In-Reply-To: <173c7vkboomefme64r0hjqqvn4507h5emh@4ax.com>; from abelikov72@hotmail.com on Mon, Mar 17, 2003 at 05:57:38PM +0000 References: <173c7vkboomefme64r0hjqqvn4507h5emh@4ax.com> Message-ID: <20030317131412.B1129@localhost.localdomain> On Mon, Mar 17, 2003 at 05:57:38PM +0000, Afanasiy wrote: > I have a use for a Python module which would allow > me to call functions which generate common HTML. > > A simple example of which might be : > > html.link('http://example.com','Example Website') I use this, and it works. It follows the HTML standard and will carp if you try to add properties not in the standard. Other than that, it works pretty well (it seems to generate superfluous whitespace, but not enough that that I've bothered to hack on it). http://dustman.net/andy/python/HyperText/ ex/ print HTML.A('Click here to read about us', href = "about_us.html") Click here to read about us -jackdied From staschuk at telusplanet.net Sun Mar 9 23:31:43 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Sun, 9 Mar 2003 21:31:43 -0700 Subject: pep 308: why doing (almost) nothing suffices In-Reply-To: ; from edream@tds.net on Mon, Mar 10, 2003 at 12:24:24AM +0000 References: Message-ID: <20030309213143.A785@tibia.amotlpaa.bogus> Quoth Edward K. Ream: [...] > def choose_eval(cond, a, b): # warning: evals all arguments > > if cond: return eval(a) > else: return eval(b) > > Heavy duty stuff by my present bathtub standards. So to "delay" the > evaluation of an argument, just quote it. Wow--just like lithp. Example: > > choose_eval(a < b,"foo(a)","spam(b)") Hm. What about this little problem? >>> def optional_reverse(s, reverse=0): ... return choose_eval(reverse, 's.reverse()', 's') ... >>> optional_reverse('foo', 1) [...] NameError: name 's' is not defined I suppose choose_eval could be special-cased to take implicit arguments of the locals and globals of the calling context... [...] > P.P.S. All criticisms of this brilliant proposal are obviously impertinent, > even if valid. I am ashamed. Forgive me! -- Steven Taschuk o- @ staschuk at telusplanet.net 7O ) " ( From aleax at aleax.it Tue Mar 4 05:41:06 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 04 Mar 2003 10:41:06 GMT Subject: list in list of objects References: <29415857.0303040152.282448ec@posting.google.com> Message-ID: <6p%8a.2792$zo2.94628@news2.tin.it> strachon wrote: > try this (in python 2.2.2): > >>>> class a: > u = 0 > v = [] OK: to start with (i.e. until you explicitly rebind either attribute), all instances of a share the class's u and v attributes. OK so far, right? >>>> x = [] >>>> x.append(a()) >>>> x.append(a()) So you now have two instances of a (sharing the class's attributes, since there has been no rebinding). Again, OK so far, right? >>>> print x[0].u, x[0].v, x[1].u, x[1].v > returns: 0 [] 0 [] > > now make some changes in properties of the first object: Careful with that phrase "changes in properties". There is no 'property' object involved here (in Python 2.2, 'property' is a built-in -- look it up). There are two attributes, named u and v. And "changes" is also very ambiguous: >>>> x[0].u = 1 this is BINDING name u in object x[0] to a new value. Whatever was previously bound to that NAME in that object doesn't matter -- re-binding a name (unless you intervene to alter its semantics, e.g. by __setattr__) just re-binds that name to a new object, period. So now x[0] has a per-instance attribute named 'u', while x[1] doesn't (it still shares the class attribute of that name). >>>> x[0].v.append(1) this does no rebinding at all -- it MUTATES the object to which x[0].v refers. The object itself has mutated; obviously, therefore, all references to that same object will from now on access the mutated object. >>>> print x[0].u, x[0].v, x[1].u, x[1].v > returns: 1 [1] 0 [1] And indeed, we see that the two ways used here to refer to the attribute 'v' of class 'a' do access the same object -- the same list object, now mutated by having appended a 1 to it. > i think it is wrong, the last item should be empty Nope, it's perfectly right. assert x[0].v is x[1].v is a.v these are three ways to refer to the SAME object (a list object). > i expected something like this: 1 [1] 0 [] Then your understanding of object and references is imperfect. Why would you expect x[0].v and x[1].v to suddenly start referring to DIFFERENT objects when you haven't re-bound either? > now append another object to the list 'x': >>>> x.append(a()) >>>> print x[0].u, x[0].v, x[1].u, x[1].v, x[2].u, x[2].v > returns: 1 [1] 0 [1] 0 [1] > > it is strange, the last item should be empty again Nope, x[2].v is, again , the same object as a.v -- and you mutated that earlier. > is it a bug? if not, how can i get the right behavior? No bug in Python, and you ARE getting the right behavior -- not what you WANT, apparently, but it's a bit difficult to guess what IT is you want. If you want different instances of a class to have attributes with the same name that refer to separate object, you must bind those names to those objects somewhere -- it will never happen "by black magic", but only by explicit binding. The most usual place in which to initialize an instance's attributes is the __init__ method of the class. For example: class a: def __init__(self): self.u = 0 self.v = [] here, class a does not have u and v attributes, but each INSTANCE of class a does -- all separate, since we're binding attributes of the INSTANCE, self, NOT of the whole class. Such a "class a" would produce exactly the behavior you say you expect. It's of course not the only way to obtain such behavior, but it's quite typical. Alex From lance-ladamage at rogers.com Tue Mar 4 17:31:55 2003 From: lance-ladamage at rogers.com (Lance LaDamage) Date: Tue, 04 Mar 2003 22:31:55 GMT Subject: Sorry ... References: Message-ID: Thanks for the suggestion :-) I'll take a look at it! -- Lance From rballard_99 at yahoo.com Tue Mar 4 12:28:06 2003 From: rballard_99 at yahoo.com (Bob Ballard) Date: Tue, 4 Mar 2003 11:28:06 -0600 Subject: md5 for large files Message-ID: Can someone provide me with a snippet or pointer to usinging Python to verify the md5 value for a large file? All examples I've seen are for a small string. I'm not yet using GPG for NT and I need to verify or generate md5 values for file xfers. Bob From abpillai at lycos.com Tue Mar 25 01:52:17 2003 From: abpillai at lycos.com (Anand B Pillai) Date: 24 Mar 2003 22:52:17 -0800 Subject: Center new windows References: Message-ID: It is not clear from the post which python GUI you are talking about. Is it tkinter/wxPython/PythonWin ? I think anyone can help you only if you provide that information :) Regardsm Anand Pillai "richard.a.charts.1" wrote in message news:... > Hi, > I have a fairly quick question that I haven't been able find the answer > for. When opening a new window, how can I force it to open in the center > of the screen? > > I have searched through old messages but most are over 2 years old and I > am wondering if there has been changes for the better? > > > > On a small side note: > How does geometry work with a given widget? Whenever I try to use it, > Python says that some class has no instance of geometry or withdraw or > others for that matter. > Thanks From mcfletch at rogers.com Mon Mar 24 00:17:32 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 24 Mar 2003 00:17:32 -0500 Subject: type function does not subtype In-Reply-To: <3E7E81EF.1992BFD4@alcyone.com> References: <3E7E81EF.1992BFD4@alcyone.com> Message-ID: <3E7E94EC.5090203@rogers.com> Why would you want to sub-class a function object? * To provide methods on the object allowing OO-style API's for introspection? o retrieving arguments and/or variable names, defaults, presence of * or ** argument-sets o retrieving text of the function from source files o retrieving formatted "parameter" help text, or more detailed run-time help-text o retrieving "raised exception" information and/or caught-exception information * Experimenting with meta-programming mechanisms o automatically generating pre and/or post-condition checks + argument and/or return value types/interfaces/values + system-status checks (there is an open database connection, there is a TCP/IP stack, or whatever) o providing a "restart" API for extremely long-running functions which have encountered exceptions o providing enhanced "cleanup" functionality for an entire class of functions which a framework may call if the function fails * To provide, for instance, a "script" function object defined in such a way that the function object stores the source code, provides pickling support, and is generally a first-class content object, but is a simple function object as far as the system is concerned (with no overhead for its call method, standard support in IDE's and documentation systems etceteras) You can certainly do that stuff using wrapping, and it's certainly easier to do it that way today (given that the subclassing is impossible). The question then becomes, is it appropriate to allow the sub-classing approach? Recent changes in Python (i.e. 2.2+) have made the type-class split considerably less visible, with a trend toward using sub-classing of core objects as an acceptable and useful idiom. Consistency and the principle of least surprise would suggest that having all of the primitive types sub-classable, where it doesn't negatively impact performance, is a good thing. (It's also nice to allow systems such as the generic introspection systems to deal with the objects without needing explicit modification to support them (i.e., your functions still show up as functions in your IDE, you don't have them showing up as data attributes)). Which comes back to Tim's post, suggesting that a volunteer creating a sub-classable version of the function object would be sufficient to introduce such a thing to the core. Enjoy, Mike Erik Max Francis wrote: >Lenard Lindstrom wrote: > > > >>Would someone please explain why subtyping of type 'function' is not >>permitted in Python 2.3? >> >> > >That would probably be best done by asking a counter question: Why >would you want to? > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From tdelaney at avaya.com Thu Mar 13 02:55:50 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 13 Mar 2003 18:55:50 +1100 Subject: "is" and "==" Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE2E78E8@au3010avexu1.global.avaya.com> > From: Dagur P?ll Ammendrup [mailto:dagurp at heimsnet.is] > > Ah ok, I wish it was the same as ==, it just looks nicer :-) If they did the same thing, there would be no point having two operators. 'is' and '==' test for different things. '==' should be a superset of 'is' - if two names refer to the same object then they should[1] compare equal. OTOH, just because two objects compare equal does not mean that they are the same object. [1] It is technically possible to make an object compare unequal to itself, but there is almost never any sane reason to do this. Tim Delaney From aleax at aleax.it Tue Mar 25 04:29:07 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 25 Mar 2003 09:29:07 GMT Subject: Integer arithmetic References: Message-ID: Daniel Timothy Bentley wrote: > I am currently embarking on the utterly futile and mildly recursive task > of implementing a C interpreter in python (Jython specifically). > > Right now, I'm trying to think about integer ops. > > I want to add two integers, e.g., and have the result be an integer. The And what do you want to happen when the two integers you're adding yield a result too large to be represented as an integer? You do no specify what behavior you want for that (and I believe the C standard doesn't, either, though I'm not familiar with the 1999 version, only the older one). Basically what you need is a function makeint that will return the int of its single argument -- if that overflows, then you may want to e.g. truncate that to 32 bits, or whatever. Since most cases won't overflow you're best off with an "easier to ask forgiveness than permission" structure, e.g.: def mask(x, themask = 0x7FFFFFFF): return int(x & themask) def makeint(x): try: return int(x) except OverflowError: if x < 0: return -mask(-x) else: return mask(x) > naive way: > > foo = bar + baz > > Doesn't work because of automatic promotion to bignum. so you code foo = makeint(bar + baz) with some makeint function such as the above one. Alex From rmunn at pobox.com Fri Mar 21 11:58:30 2003 From: rmunn at pobox.com (Robin Munn) Date: Fri, 21 Mar 2003 16:58:30 GMT Subject: a couple of newbie questions References: <20030321.081510.2111331352.12265@localhost.localdomain> Message-ID: Joseph Paish wrote: > i am in the process of converting a perl script to python and have a > couple of questions : > > --- 1. is there a way to comment out a large block of code in python? > the reason i ask is that i would like to comment out the entire perl > script and convert it piece by piece into python, uncommenting each > function as it is converted so i can test if it does what i want. You could enclose blocks of code in triple-quote characters: """ like this... def foo(bar): return bar+1 """ Triple-quotes quote everything, including newlines, until the next triple-quote. Note that triple-quotes can be used with both the quote character (") and the apostrophe ('). So if you already have triple-quotes of the """ style in the function you're trying to comment out, then you can enclose it in '''-style triple quotes. See http://www.python.org/doc/current/ref/strings.html for all the formal syntax details of triple-quoted strings. The other alternative for commenting out large blocks of code is to make an editor macro to insert # at the start of every line, but for what you want to do, triple-quoting would be more efficient. > > --- 2. is there a way to read a datafile whose records are space > separated so that the second field becomes the key to a dictionary and > the value portion is the entire record. for example, > > 01/01/2003 abc 1234.56 789.98 12332.98 <<< the original record > > the key would be : abc > the value would be : 01/01/2003 abc 1234.56 > 789.98 12332.98 > > i have managed to read the datafile into a list of lists and would > like to loop through this collection of records and convert it to a > list of dictionaries keyed on the second field. i have already looked > everywhere i can think of, but i haven't had any luck finding how to > convert a list of lists into dictionaries. > > an alternative would be to bypass the list of lists altogether and > populate the dictionary as i read each record. this would be even > simpler. > > suggestions? Read about the dict() built-in: http://www.python.org/doc/current/lib/built-in-funcs.html Basically, you pass it a list of lists, where the inner list has two element: first element is the key, second element is the value. Or, even better, use something like the following approach: datadict = {} # Make a new, empty dictionary inputfile = file('inputdata.txt', 'r') for line in inputfile: # Works in Python 2.2 or later fields = line.split() datadict[fields[1]] = line # Voila, you're done! That is by far the simplest way of doing what you're trying to do. Notice especially the "fields = line.split()" line. If you're coming from Perl, your instinct will probably be to call a function (like split), passing it the string as a parameter. You can do things that way in Python if you really want to; most of the functions you'll need are found in the string module. But the Pythonic way of doing string operations is to call methods of string objects. In Python, strings are objects just like everything else, and can have methods (and attributes, if you're feeling insane). So most functions in the string module are deprecated, and you should be using methods of string objects to do your string-processing work. See here for the string methods available: http://www.python.org/doc/current/lib/string-methods.html I hope this helps. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From gerhard.haering at opus-gmbh.net Mon Mar 17 09:40:18 2003 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 17 Mar 2003 14:40:18 GMT Subject: how to send a form html by email ? References: Message-ID: Gerard Breiner wrote: > I try "PythonHandler tmail". the result provide the same error. Did you delete all email.py[co] in the directory where you have your mod_python handlers? -- Gerhard From donn at u.washington.edu Mon Mar 3 12:11:54 2003 From: donn at u.washington.edu (Donn Cave) Date: 3 Mar 2003 17:11:54 GMT Subject: How to get IP address References: <2a897f11.0303011133.3acdfc8@posting.google.com> Message-ID: Quoth Nagy_Lszl_Zsolt : ... | Sorry, but this does not help me. I want to determine the IP address | because I want to send my external | IP address to a dynamic DNS provider (in an A record). I get my IP | address with DHCP and I'm ... What I have done in this case is connect to a remote service and use getsockname() to return the actual IP. (getsockname is a method of the socket object.) I use the DNS service that's configured in my TCP setup - not because this has anything to do with DNS, it's just the most basic IP address I know from first principles. If that doesn't work, then I'm a goner anyway. This is still mildly platform dependent, as there is no standard way to determine this TCP configuration parameter, but at worst you can solve this by hand per installation. Donn Cave, donn at u.washington.edu From jkpangtang at yahoo.com Wed Mar 5 21:02:21 2003 From: jkpangtang at yahoo.com (JW) Date: 5 Mar 2003 18:02:21 -0800 Subject: embedding python - PyImport_ImportModule returns null Message-ID: <3607e8e4.0303051802.7ddf1dfd@posting.google.com> I am trying to embed python within a c program, but I can't get PyImport_ImportModule() command to load my module. Please let me know what I'm doing wrong. -- #file func.py def func1(): print "inside func1()" -- //main.c int main() { PyObject *pFunc, *pModule; Py_Initialize(); pModule=PyImport_ImportModule("func"); //fileread.py if(pModule==NULL) { PyErr_Print(); fprintf(stderr,"Failed to load \"%s\"\n","func"); } //etc.... } --- Both main.c and func.py are in the same directory. I run main and get the error Failed to load "func", meaning that PyImport_ImportModule returns NULL. What am i doing wrong? Thanks in advance for the help From sjmachin at lexicon.net Sat Mar 22 20:33:26 2003 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2003 01:33:26 GMT Subject: Newbie question about reference References: Message-ID: <3e7d0864.9585593@news.lexicon.net> On Sat, 22 Mar 2003 22:50:35 +0100, Gerhard =?iso-8859-1?Q?H=E4ring?= wrote: >* Tim Smith [2003-03-22 13:10 -0800]: >> Something that this beginner does not understand about Python. Why >> does the following-- >> >> > python >> Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on >> win32 >> Type "help", "copyright", "credits" or "license" for more >> information. >> >>> x = 1 >> >>> y = 2 >> >>> z = 3 >> >>> list = [x, y, z] >> >>> list >> [1, 2, 3] >> >>> y = 0 >> >>> list >> [1, 2, 3] >> >>> >> >> do what it does? > >Immutable vs. mutable types. ints, floats, strings, tuples are immutable. lists >and dictionaries are mutable (there are more types than these, so this is a >nonexclusive list). Que? > >So if, instead of an int, you use a dictionary, you get the effect you >looked for: > >#v+ >Python 2.2.2 (#1, Jan 18 2003, 10:18:59) >[GCC 3.2.2 20030109 (Debian prerelease)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> x, y, z = 1, {"key": 5}, -2 >>>> lst = [x, y, z] >>>> lst >[1, {'key': 5}, -2] >>>> y["key"] = 6 >>>> lst >[1, {'key': 6}, -2] >>>> y["key2"] = 7 >>>> lst >[1, {'key2': 7, 'key': 6}, -2] If you use a dictionary instead of an int in Tim's example, i.e. one of the "variables" is bound to a new object, you get **exactly** the same effect. See below. Nothing to do with mutability of the original oject. Concurring with Terry: funny, this is expected behaviour in most languages, shouldn't need doco. However if the original object is a mutable container, you can meddle with the *contents* of that object and the meddling is then of course visible through all references to that object.. Can be surprising, is a FAQ, needs doco, has doco(?) -- to lazy to look :-) >>> x, y, z = 1, {"key":5}, 42 >>> lst = [x, y, z] >>> lst [1, {'key': 5}, 42] >>> y = {"another":"dict"} >>> lst [1, {'key': 5}, 42] >>> From maney at pobox.com Sun Mar 30 18:34:18 2003 From: maney at pobox.com (Martin Maney) Date: Sun, 30 Mar 2003 23:34:18 +0000 (UTC) Subject: Is Python overhyped (just like Java)? References: Message-ID: Ajay na wrote: > Can some-one please explain why one would want to use Python? Because I find it both much more productive and much more enjoyable than other languages I have used, including C++. > What is wrong with C++? What do you think might be less than perfect about C++ that you are inquiring about Python? > Nope...I'm not trolling...I want someone to give a solid and intelligent > argument about why I should switch from C++ to Python! But I don't want to argue with you. If you're happy with C++, then why should I expend time and effort trying to make you unhappy? Contrarily, if you are unhappy with C++, why don't you look at Python and tell us what you like better, or less, about it? [this is the point at which the tongue goes into the cheek; I repeat, we have achieved cheeked tongue] If Zen Koans were reborn as jokes, I think many of them would choose to come back as lightbulb jokes. Which doesn't so much bring us to the next bit as provide a point from which a leap might be made in its general direction. How many C++ programmers does it take to switch to Python? Only one, but he has to really want to change. From none at of.your.business Tue Mar 11 11:50:22 2003 From: none at of.your.business (lynx) Date: Tue, 11 Mar 2003 11:50:22 -0500 Subject: os.startfile() on Linux ? References: Message-ID: On Tue, 11 Mar 2003 12:35:51 +0100, Harald Schneider wrote: > is there a way to call a file with it's corresponding application, like > os.startfile() on Win32 does ? the problem is that then you have to know what the "corresponding application" for some given file is, and on unix, that's a not quite trivial problem. if you're willing to tie your program to a specific desktop environment, then KDE and Gnome each have their own ways of resolving such correspondences, and Gnome at least has reputedly-good python bindings; but "barebones unix", posix that is, has no such mechanism. -- PGP/GnuPG key (ID 1024D/3AC87BD1) available from keyservers everywhere Key fingerprint = FA8D 5EA4 E7DC 84B3 64BC 410C 7AEE 54CD 3AC8 7BD1 "...if you can fill the unforgiving minute with sixty seconds' worth of distance run..." From max at alcyone.com Sat Mar 22 17:11:49 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 22 Mar 2003 14:11:49 -0800 Subject: Is Python the Esperanto of programming languages? References: <7i65qe953z.fsf@enark.csis.hku.hk> <3oyea.61654$68.41484@nwrdny01.gnilink.net> <3E7ABD93.7DFBCFB@alcyone.com> <3E7BA475.2A0B41C6@alcyone.com> Message-ID: <3E7CDFA5.7FED4917@alcyone.com> Carl Banks wrote: > "The man go" is NOT ambiguous because the ending on the verb is > superfluous (when the number of the subject is known, as it is here). > No native English speaker will interpret "the man go" as possibly > meaning "the men go." But, as I said, how about interpreting it as "The man went" or "The man will go"? It may not be ambiguous in number, but it's ambiguous in tense. > Even your list of other possibilities for the meaning of "the man go" > didn't include "the men go." You only listed different tenses. That > you would even doubt the tense is, I say, an intellectual reaction to > the sentence sounding bad. What difference does it make precisely what reason the sentence is ambiguous? If it's ambiguous because it uses grammar improperly, resulting in someone who understands the grammar to become confused, how's that any less ambiguous? -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Nobody can reach me, nobody can touch me; it's a wonderful feeling. \__/ Aaliyah Official Omega page / http://www.alcyone.com/max/projects/omega/ The official distribution page for the popular Roguelike, Omega. From marshall at spamhole.com Mon Mar 10 21:53:25 2003 From: marshall at spamhole.com (marshall) Date: 10 Mar 2003 18:53:25 -0800 Subject: Pygame and Tk References: Message-ID: <4017400e.0303101853.624de814@posting.google.com> "Eric Mattes" wrote in message news:... > Hi everyone. > > I'd like to know if Pygame and Tk can be used for the same window. Can I > have a pygame window with a Tk GUI surrounding it? > > If not, is it difficult to create a mouse-driven GUI in pygame? anyone know > of a good example/tutorial? > > Thank you so much!!! > -Eric Eric, There is at least one GUI toolkit that uses pygame as a renderer: http://pyui.sourceforge.net/ Marshall From member16943 at dbforums.com Wed Mar 12 01:00:54 2003 From: member16943 at dbforums.com (Tetsuo) Date: Wed, 12 Mar 2003 06:00:54 +0000 Subject: Long integers: to L or not to L? Message-ID: <2632446.1047448854@dbforums.com> I have a function that uses longs, and also of the length of their equivalent strings. I thought that longs have an L at the end, so I suntracted 2 instead of 1 from the length. The program gave wrong results. I put print statements in. The value returned by function long(n) was a plain integer, with no L. I checked the type of that return value. Long. So why no L? Also, why does this raise an error? (numbers in front of lines indicate levels of indentation) def h(): 1 i = 0 1 def h1(): 3 i = i + 1 3 print 1, i 3 if i == 5: 4 return i 3 else: 4 i = h1() 4 return i 1 i = h1() 1 print 2, i Posting code is annoying... -- Posted via http://dbforums.com From h_schneider at marketmix.com Fri Mar 21 16:10:10 2003 From: h_schneider at marketmix.com (Harald Schneider) Date: Fri, 21 Mar 2003 22:10:10 +0100 Subject: httplib with SSL support for Python 2.1 ? References: Message-ID: They all point to Robin Dunn's drop in replacement. But this one raises the "missing sendall atttrib" exception ... :-/ --Harald "Gerhard H?ring" schrieb im Newsbeitrag news:mailman.1048276977.14121.python-list at python.org... > * Harald Schneider [2003-03-21 19:53 +0100]: > > does there exist a httplib with SSL support for Python 2.1? [...] > > Yes. I presume your only problem was finding the right keywords for > Google: > > http://www.google.de/search?q=_socket.pyd+ssl+2.1 > > Gerhard > -- > mail: gh at ghaering.de > web: http://ghaering.de/ > From imbosol-1048652275 at aerojockey.com Tue Mar 25 23:34:04 2003 From: imbosol-1048652275 at aerojockey.com (Carl Banks) Date: Wed, 26 Mar 2003 04:34:04 GMT Subject: Conjugate gradients minimizer References: <3K9ga.7304$kU.2710@nwrdny01.gnilink.net> Message-ID: <05aga.24391$SX.4167@nwrdny03.gnilink.net> Carl Banks wrote: > So, unless you have reason to believe conjugate-gradient is specially > suited to this problem (indeed, I have heard of an atomic structure > problem that was like that), or if you plan to scale up to DNA > crystals someday, use the BGFS method instead. > > BGFS is far more efficient than conjugate gradient for most systems. > The only thing is, it requires inverting a matrix at every step, which > you really don't want to do in Python. It's also much more > complicated. But it solves almost everything faster. Sorry, that should be BFGS. Makes a difference when Googling. -- CARL BANKS From sismex01 at hebmex.com Wed Mar 26 09:55:45 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 26 Mar 2003 08:55:45 -0600 Subject: writing to file very slow Message-ID: I kinda skimmed over your code, and the problem isn't the DB adaptor, it's the way you're building up your data: you're concatenating a huge string and then dumping it to the file, that's very slow. Instead of concatenating strings like this (which is used extensively): stringvar += something_else use a list to accumulate data until you want to dump it to the file, like this: listvar.append(something_else) When you're ready to dump the data to the file, you can either create a huge string ONCE and write that: filevar.write(''.join(listvar)) OR, you can iterate through the listvar and write every individual string inside: for I in listvar: filevar.write(I) HTH! -gustavo From ulope at gmx.de Tue Mar 25 08:37:14 2003 From: ulope at gmx.de (Ulrich Petri) Date: Tue, 25 Mar 2003 14:37:14 +0100 Subject: A bit fun with Python References: Message-ID: "Ulrich Petri" schrieb im Newsbeitrag news:b5nvo6$2aio1s$1 at ID-67890.news.dfncis.de... > a little riddle: > > how does this script: > ------------------ > re.fork("this works") > print sys.compile > ------------------ > produce that output: > > ------------------ > this works > posix > ------------------ > ok it was a bit unfair... here's the complete script: ------------------- import os, sys, re os.fork = sys.stdout.write re.compile = os.name sys = re re = os re.fork("this works") print sys.compile ------------------ Ciao From tjreedy at udel.edu Fri Mar 7 11:09:19 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 7 Mar 2003 11:09:19 -0500 Subject: Vote on PEP 308: Ternary Operator References: <882b0a41.0303020225.3caf0334@posting.google.com> <_U59a.311281$SD6.15810@sccrnsc03> Message-ID: "Jack D. Hammer" wrote in message news:AP2aa.351249$2H6.6408 at sccrnsc04... > > I don't like them for readability. I rarely use them in other languages. So, > I just don't see the need. Other people do, but that's fine. > One of the good things that I see about python is its readability. Agreed. > I think that this decreases the readability. A vote for NO CHANGE is a vote for no change, for the status quo, for limiting choices for conditional selection expresssions to what is currently available -- such as 'C and a or b', among others. Anyone who thinks that 'C then a or b' (for instance, and my favorite), etc, is less readable should indeed vote for NO CHANGE. TJR From me at privacy.net Thu Mar 20 20:44:48 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Fri, 21 Mar 2003 13:44:48 +1200 Subject: Combinations and recursion, from an ASPN snippet In-Reply-To: References: <180320032212546765%camel@oasis.com> Message-ID: Andy Jewell wrote: > I like to think of recursion as 'nesting' calls to the function, one inside > the other: > > 1 > \ > 2 > \ > 3 > \ > 4 > \ > : > / > 4 > / > 3 > / > 2 > / > 1 > > Bear in mind, though, that it won't usually be as 'tidy' as this! Indeed. If your call graph is just a straight line down to the bottom and back up, you're probably better off using a loop -- it'll be faster, use much less stack space, and probably be just as clear. Recursion really comes into its own when the call graph is some sort of tree structure. Then you get n recursive calls for only log(n) worth of stack space, and the use of recursion can tremendously simplify the program logic, since you're really making use of the stack-ness of the stack. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From spam at magnetic-ink.dk Wed Mar 12 16:01:12 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Wed, 12 Mar 2003 21:01:12 +0000 (UTC) Subject: ReportLab, PDF and Latin-1 characters References: Message-ID: <7c961ad4-6f23-4704-9647-3637e988093c@news.szn.dk> Svenne Krap wrote: > > from reportlab.pdfgen import canvas > c = canvas.Canvas("C:\\mypdf.pdf") > c.setFont('Arial',12) > c.setFont('Helvetica',12) > c.drawString(10,10,'???') > > > but then, I get : > > > UnicodeError: ASCII encoding error: ordinal not in range(128) > How about #v+ >>> utf8 = lambda s: unicode(s, 'iso-8859-1').encode('utf-8') >>> c.drawString(10, 10, utf8('fr?kke fr?l?r') #v- (substitute your input charset for 'iso-8859-1')? // Klaus -- ><> vandag, m?re, altyd saam From mwh at python.net Wed Mar 19 08:44:50 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 19 Mar 2003 13:44:50 GMT Subject: resource module References: Message-ID: <7h37kavii7i.fsf@pc150.maths.bris.ac.uk> Jp Calderone writes: > I've looked at this module several times over the years. It seems to have > been in a perpetual state of undocumented brokeness. What makes you say that? It might well behave a bit erratically x-platform, but it's a just thin wrapper of the underlying library calls... Cheers, M. -- I really hope there's a catastrophic bug insome future e-mail program where if you try and send an attachment it cancels your ISP account, deletes your harddrive, and pisses in your coffee -- Adam Rixey From leazen at uol.com.ar Wed Mar 19 21:35:27 2003 From: leazen at uol.com.ar (Leazen) Date: Wed, 19 Mar 2003 23:35:27 -0300 Subject: BOA and non-ascii characters In-Reply-To: References: Message-ID: <3E7928EF.9060208@uol.com.ar> Are you using the unicode build of wxPython? Tracker wrote: > I found, BOA cannot use non-ascii characters in source code. It is a > nonsense. :( > > I found even bigger problem with non-ascii characters. I created the > example application (according to manual). Despite of the fact that > help manual does not correspond to the layout of the latest BOA > version and despite of the fact, that wxTextCtrl widget has no all its > attributes in Inspector window (there is no Style attribute mentioned > by manual!) I cannot write any non-ascii (cp1250) characters to > wxTextCtrl content (Value attribute). It seems exTextCtrl can display > ONLY ISO-8859-1 characters. It is a nonsense once again. :( > From me at privacy.net Mon Mar 10 21:24:51 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 11 Mar 2003 15:24:51 +1300 Subject: PEP 308 original proposal "used" already in Python Documentation In-Reply-To: References: Message-ID: Jon Perez wrote: > Now how would we express setdefault() using the ternary > operator though? No problem, we just indulge in a bit of listcomp-abuse: a[k] if k in a else [y for y in x if operator.setitem(a, k, y) or 1][0] :-) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From donn at drizzle.com Fri Mar 7 22:50:31 2003 From: donn at drizzle.com (Donn Cave) Date: Sat, 08 Mar 2003 03:50:31 -0000 Subject: Socket connection References: <3e6a4b62.41009638@news.dsl.pipex.com> Message-ID: <1047095429.617329@yasure> Quoth simon at uggs.demon.co.uk (Simon Foster): [someone with an assumed name said ...] |> Could somebody point me to the documentation on this? | | Here is the documentation: | | "In Python, everything is a reference" If references are at all featured in the official documentation, I believe that would be a new development. The party line a couple years back seemed to be that you shouldn't have to think about things like that, it should just work. ``Computer programming for everyone'' was a big deal at Python headquarters at the time, references were too geeky. Donn Cave, donn at drizzle.com From gerrit at nl.linux.org Mon Mar 17 14:48:30 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 17 Mar 2003 20:48:30 +0100 Subject: Aspergers link In-Reply-To: References: <4fm07vg66gr4o4c74gb7ie5v85vlom1vhf@4ax.com> <0vv17v4vn4khffgr2io0otrnni8sc6rug7@4ax.com> <%dica.80722$zo2.2065641@news2.tin.it> <7f2b571b.0303161642.320e0997@posting.google.com> Message-ID: <20030317194830.GB2639@nl.linux.org> Hi, I feel I must objects strongly to the tone in this discussion. Carl Banks schreef op maandag 17 maart om 08:12:13 +0000: > > There are probably a lot of us on this list who suffer from > > Asperger's... it pretty much defines nerdiness. "A lot" would be relative, maybe three times as much as outside, which still means one or two. It is *not* nerdiness! It is something *different*! It is a form of *autism*! It is a *syndrome*! > I think people with Asperger's "syndrome" just violated someone's > arbitrary and very narrow idea of what they think is normal. Please go meet Aspergers. Please visit schools with a lot of Aspergers, please don't talk about something you don't know something about. > Here's my advice: forget all this crap about Asperger's syndrome. Please don't say this, you may insult people. > Instead, go read about Myers-Briggs personality typing. _Please > Understand Me_, by David Kiersey, is a good reference. Kiersey would > probably dismiss Asperger's "syndrome" as nothing but a strong > introverted and thinking personality. Well, he is wrong than. > Frankly, it sickens me that there are people out there who consider > traits such as introversion, and reliance on thought instead of > feeling, to be "diseases." Well, please don't dismiss Asperger's syndrome as something simple or as something meaning introvertion. Please, people, go talk about lambda's but not about subjects you haven't got any knowledge about! I feel really strongly about this! Please. yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From ulope at gmx.de Wed Mar 19 19:01:47 2003 From: ulope at gmx.de (Ulrich Petri) Date: Thu, 20 Mar 2003 01:01:47 +0100 Subject: Does Python do try: except: finally: ? References: <20030319135147.A1830@ash.int.ca.pason.com> <1048108451.2357.6.camel@jwilhelm.ofsloans.com> Message-ID: "Skip Montanaro" schrieb im Newsbeitrag news:mailman.1048112434.6123.python-list at python.org... > > Maybe, but that's not what try/finally does. Try/finally says, "Execute the > code in the try block, and irregardless of any exceptions which might get > raised, execute the code in the finally block when finished." > Try/except/else says, "Execute the code in the try block. If an exception > is raised, execute the code in the except block, otherwise execute the code > in the else block." > I allways asked myself of what practical use finally (except the syntactical "clearness of code") is? I can simply write like: try: do_this() except: print "error" #now here is what will be executed next, so what for i do need finally? Ciao Ulrich From peter at engcorp.com Tue Mar 11 22:48:30 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Mar 2003 22:48:30 -0500 Subject: Flying With Python (Strong versus Weak Typing) References: <37a869bc.0303102102.4533973@posting.google.com> Message-ID: <3E6EAE0E.F0F4C789@engcorp.com> W D Tate wrote: > > IMHO, some of the posts thus far would precipitate the equivalent of > WWIII of flamewars on boards such as comp.lang.eiffel, comp.lang.ada > and a few others I can think of. With good reason. My god, everyone in that industry is still using the Waterfall process for Pete's sake. Talk about archaic! When they open their minds enough to start considering some newer approaches and how that might impact on the *perceived* value of static typing (since, of course, Python *has* strong typing already so "static" must be what you meant), then they might get some visits from outsiders interested in rational discussion. Until then, they have to be guests *here*, and we have certain conventions about behaviour that they must follow. No "WWIII flamewars", for example. Except when discussing ternary ops. ;-) -Peter From marshall at spamhole.com Sun Mar 16 23:08:00 2003 From: marshall at spamhole.com (marshall) Date: 16 Mar 2003 20:08:00 -0800 Subject: Strange rounding problem References: <4378fa6f.0303141540.de857b8@posting.google.com> <3E736D6A.42C9355A@engcorp.com> <3E739138.DF7E129E@alcyone.com> Message-ID: <4017400e.0303162008.1b062083@posting.google.com> Erik Max Francis wrote in message news:<3E739138.DF7E129E at alcyone.com>... > Jp Calderone wrote: > > > 15 is the next best base after 10, and 30 after that. Of course, no > > base > > can exactly represent any fraction, and this doesn't even take into > > consideration bases which are, themselves, fractional ;) > > The traditional "next best" base after 10 will be 12. That's why our > clocks divide time into 12-hour chunks (well, two of them, so it's 24), > etc. Next after that is 60, for equally obvious reasons. Actually the division of day and night into 12 hours dates back to the Babylonians who had a base 60 system. 12 was probably chosen as a factor of 60 and 12 was special becuase of the division of the year into roughly 12 lunar months and the demarcation of the night by twelve constellations. Marshall From sjmachin at lexicon.net Thu Mar 27 06:09:56 2003 From: sjmachin at lexicon.net (John Machin) Date: 27 Mar 2003 03:09:56 -0800 Subject: doing hundreds of re.subs efficiently on large strings References: <3E80CE1D.1000200@NOmyrealCAPSbox.com> <3e818b47$0$31942$edfadb0f@dread12.news.tele.dk> <3E82911D.3030807@NOmyrealCAPSbox.com> Message-ID: nihilo wrote in message news:<3E82911D.3030807 at NOmyrealCAPSbox.com>... > > I am sorry but I am still not sure how you are suggesting the > replacement occur. After I have the iterator, what would I do with each > of the match objects in the iterator? Below is an example of what Anders was talking about. HTH, John === file raboof.by === import re from_str = ["foo", "bar", "zot"] to_str = ["oofay", "arbay", "otzay"] pat = "|".join(["(" + x + ")" for x in from_str]) print pat text_in = "fee fie foo and bar or zot then foo again" asm = [] asmap = asm.append lpos = 0 for m in re.finditer(pat, text_in): spos, epos = m.span() grpnum = m.lastindex print spos, epos, grpnum asmap(text_in[lpos:spos]) asmap(to_str[grpnum-1]) lpos = epos asmap(text_in[lpos:]) text_out = "".join(asm) print text_in print text_out === results === C:\junk>python raboof.py (foo)|(bar)|(zot) 8 11 1 16 19 2 23 26 3 32 35 1 fee fie foo and bar or zot then foo again fee fie oofay and arbay or otzay then oofay again C:\junk> ================== From bobx at linuxmail.org Sun Mar 16 12:34:45 2003 From: bobx at linuxmail.org (Bob X) Date: Sun, 16 Mar 2003 17:34:45 GMT Subject: Pmw and Python setup References: Message-ID: "Sam Marrocco" wrote in message news:EFRca.27858$s75.10861845 at twister.columbus.rr.com... > I've got Python running/installed on a Windows XP and SGI/Irix box.... > I want to install Pmw onto both of these machines. What locations should > I place the Pmw directory into on each of these machines? > -- http://pmw.sourceforge.net/doc/starting.html From cartermark46 at ukmail.com Tue Mar 25 08:40:35 2003 From: cartermark46 at ukmail.com (Mark Carter) Date: 25 Mar 2003 05:40:35 -0800 Subject: urllib and persistence References: <_Pffa.104805$pG1.2227390@news1.tin.it> Message-ID: > > http://wwwsearch.sourceforge.net/ClientCookie/ may thus > > prove of help. > > As will wget, if you want a non-python solution. Alas, the site requires logging in, but not in a strict account/password way - it wants to know your surname, for example. So I don't think that wget will help. I must admit that I'm a bit lacking in understanding how urllib2 and/or ClientCookie are supposed to work. Does ClientCookie work with Internet Explorer cookies, or not? My problem is as follows: If I use Internet Explorer, and type in the URL I'm interested in, then I get the page. It's obviously picking up a cookie that I've stored, and letting me access the page. However, if I use urlib() from python on the same URL, I get a page to the effect that I haven't logged in, and need to supply my name and a few other details. So I somehow need to respond to that request in order to get the real page I'm interested in. I tried one of the ClientCookie examples, but it didn't help. One of my main problems is a lack of understanding about the basic concepts of what's going on (OK, I understand what a Cookie is, but I don't understand how the server is picking it up from Internet Explorer, and how I can replicate the behaviour in Python). I don't even mind hard-coding some of the information, if it makes things easier. From vze4rx4y at verizon.net Fri Mar 14 01:01:38 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Fri, 14 Mar 2003 06:01:38 GMT Subject: GCD in standard library? References: Message-ID: <6feca.51557$gi1.37364@nwrdny02.gnilink.net> > On Wed, 12 Mar 2003 20:08:18 +0000, Steven Taschuk wrote: > > Quoth Blake Garretson: > > >> def gcd(x,y): > >> if x % y == 0: return y > >> else: return gcd(y,x%y) > > > I for one haven't needed this in Python yet, but if I did I'd do > > it this way: > > def gcd(a, b): > > while b: > > a, b = b, a % b > > return abs(a) > > which (1) avoids the unnecessary recursion, > > i suppose it's pointless to ask for python to become a properly > tail-recursive language then? Depends on who you ask. http://www.stackless.com Raymond Hettinger From sjmachin at lexicon.net Fri Mar 21 20:35:49 2003 From: sjmachin at lexicon.net (John Machin) Date: 21 Mar 2003 17:35:49 -0800 Subject: open() in binary vs. text mode References: <3E7A80F3.3030303@yahoo.com> Message-ID: Hal Wine wrote in message news:<3E7A80F3.3030303 at yahoo.com>... > > P.S. if you know the file is a text file (but perhaps from > another platform), you can normalize the input string thusly: > contents = open( "foo", "rb").read() > contents.replace( '\x0d\x0a', '\n' ) > contents.replace( '\r', '\n' ) Or just [no pun intended] use the new (in Python 2.3) "rU" (universal text format) ... > Now contents looks like a native platform text string. (I _think_ > all the platforms that used LFCR as a separator are long dead now...) What platforms used LFCR? I had to deal once upon a time with a data source that provided files that used LFCR but I just assumed that they were crazy ... From exarkun at intarweb.us Tue Mar 18 12:33:20 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 18 Mar 2003 12:33:20 -0500 Subject: Serving a file through HTTP In-Reply-To: <3E772B80.5010504@ghaering.de> References: <3e770934$0$1129$4d4ebb8e@news.nl.uu.net> <3E770BB1.2080803@ghaering.de> <21266.213.53.122.6.1047991508.squirrel@looze.net> <3E771434.3090301@ghaering.de> <22456.213.53.122.6.1047995704.squirrel@looze.net> <3E772B80.5010504@ghaering.de> Message-ID: <20030318173320.GA29926@meson.dyndns.org> On Tue, Mar 18, 2003 at 03:21:52PM +0100, Gerhard H?ring wrote: > [snip] > def do_GET(self): > """Serve a GET request.""" > self.send_header("Content-Type", "audio/mp3") > self.end_headers() > > my_mp3_file = open("Metallica - Nothing Else Matters.mp3", "rb") > > # Reading the entire file at once is probably not that great a > # strategy. > self.wfile.write(my_mp3_file.read()) A cheap improvement on the above line is shutil.copyfileobj() Jp -- Where a calculator on the ENIAC is equipped with 18,000 vacuum tubes and weighs 30 tons, computers in the future may have only 1,000 vacuum tubes and weigh only 1.5 tons. -- Popular Mechanics, March 1949 -- up 15 days, 10:00, 2 users, load average: 0.00, 0.00, 0.00 From aleaxit at yahoo.com Fri Mar 7 09:03:15 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Mar 2003 15:03:15 +0100 Subject: Books Database In-Reply-To: <20030307130946.GA1182@rulix> References: <200303061741.26327.aleaxit@yahoo.com> <20030307130946.GA1182@rulix> Message-ID: <200303071503.15242.aleaxit@yahoo.com> On Friday 07 March 2003 02:09 pm, Eliran Gonen wrote: > Alex Martelli : > > thefile = open('X','r+') > > lines = thefile.readlines() > > del lines[X] > > thefile.seek(0) > > thefile.writelines(lines) > > thefile.close() > > The code is: > > infile = open(database, 'r+') > lines = infile.readlines() > del lines[0] > infile.seek(0) > infile.writelines(lines) > infile.close() > > Now the database is like that : > > sample|none|1924|nobody > stuff|two|1934|tree > > Now executing the above code results in: > > stuff|two|1934|tree > ody > stuff|two|1934|tree > > Bizarre. Ah, yes, sorry -- you need to add a call to thefile.truncate() right before you close the file, to ensure the file on disk reflects any shortening that may have happened since the last write. Alex From aleax at aleax.it Thu Mar 6 17:23:30 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 06 Mar 2003 22:23:30 GMT Subject: Can __iter__ be used as a classmethod? References: <60FB8BB7F0EFC7409B75EEEC13E20192022DD8D3@admin56.narex.com> <2259b0e2.0303050740.52a92487@posting.google.com> <89G9a.12708$pG1.332485@news1.tin.it> <2259b0e2.0303061331.2b0b2028@posting.google.com> Message-ID: Michele Simionato wrote: ... > Alternatively, one could have classmethods defined in a module of the > standard library (and I would like that). > I don't like the fact that they are in the language. Well, they're in-between -- they ARE defined in a module of the standard library... it's just that said module is __builtin__, is all. > Of course, now there is nothing to do: they are in Python and they will > stay there. I also use them. I do not discuss that they have some > convenience, I am saying that their convenience is little. I posted these Personally I think they're more useful than several other built-ins, such as (say) apply, buffer, coerce, intern, oct, reduce -- all names I'd rather have in _other_ library modules and not in __builtin__. > C++), nevertheless I am disturbed by the confusion between "metamethods" > (regular methods in the metaclass) and classmethods. If Samuele is I just don't see that confusion. > I also was confused by the *syntactic* similarity between staticmethods > and classmethods: at the beginning I was induced to think that they > were similar concepts, but actually they are completely different They're perfectly polymorphic -- they're called in exactly the same ways, so, in terms of interface a certain class offers to its users, they ARE extremely similar concepts... the class need not even document whether a given name is a staticmethod or classmethod -- unless it's specifically designed to support being inherited from with that method being overridden and called-upwards, a very specific set of circumstances. If I want client code to be able to call X.foo() and X().foo(), it's strictly a matter for ME, as the implementer of class X, if I want to make foo a staticmethod or a classmethod -- I'll use the latter if I want foo's code to know what exact class (possibly a subclass of X, rather than X itself) it's being called on. That doesn't constituite "completely different" for me -- they're VERY close in most things that matter (which DOESN'T include calling type(...) on them and the like -- what Pythonically matters is essentially signature-based polymorphism). Alex From djn at daimi.au.dk Thu Mar 27 08:20:13 2003 From: djn at daimi.au.dk (Daniel Nielsen) Date: Thu, 27 Mar 2003 13:20:13 +0000 (UTC) Subject: signal module? In-Reply-To: <7h3ptodm377.fsf@pc150.maths.bris.ac.uk> References: <20030327092336.GB17524@daimi.au.dk> <7h3ptodm377.fsf@pc150.maths.bris.ac.uk> Message-ID: <20030327132010.GA440@daimi.au.dk> On 27/03-03 11.58, Michael Hudson wrote: > Daniel Nielsen writes: > > > I'm currently working on some code that uses the signal module... But > > I doesnt seem to work proberly. > > > > I'm using threads, > > You are in trouble already. That I am beginning to realize :) > > so I'd like ctrl-c to actually terminate the program. If my memory > > serves me, ctrl-c is SIGINT, so in my code, in the main thread, I > > write: > > > > signal.signal(signal.SIGINT, gp.handler); > > > > where gp is a module and handler looks like: > > > > def handler(signum, frame): > > print "Handling signal: " + signum; > > sys.exit(2); > > > > But ctrl-c doesnt do anything! > > > > If I write: > > signal.signal(signal.SIGINT, signal.SIG_DFL); > > instead, ctrl-c actually terminates the program... > > Have I misunderstood something? > > I'd expect this to work, but that it doesn't fails to surprise. What > OS (+version, probably) are you on? Any chance of a complete code > sample? Well, I'm running it on the computers that belong to the University where I study. They are heavily modified RH7.3. I have compiled and installed python 2.2.2 as a local user. I seem to have figured out what is going on: 1) When you use the signal module with your OWN handlers (e.g. not signal.SIG_DFL or signal.SIG_IGN), it is required that the main thread does not exit. The it works like a charm. 2) IF the mainthread exits, then then all handlers defined by signal module is ignored. UNLESS it is signal.SIG_DFL, and signal.SIG_IGN. So, I have solved the problem by not letting the main thread exit... Seems funny though... As for complete source, I have atttached the current version of the two files. (it is a VERY work in progress, and I'm learning python along the way). It's supposed to be a genetic programming project, and I'm in charge of providing a skeleton distributed implementation. Note, I'm using latest pyro from pyro.sourceforge.net (14. march) /Daniel -- There are no great men, only great challenges that ordinary men are forced by circumstances to meet. -- Admiral William Halsey -------------- next part -------------- import threading, Pyro.naming, sys; #A class, representing a individual class Myre: def __init__(self, name): self.name=name; def output(self): print "Name: " + self.name; class Population: def __init__(self): self.pop = []; def __len__(self): return len(self.pop); def append(self, myre): if isinstance(myre,Myre): self.pop.append(myre); else: raise TypeError; def output(self): i = 0; for m in self.pop: print "Myre " + str(i) + ": "; m.output(); i += 1; class Server: def __init__(self): print "Bringing up server..."; def startNS(self): print "Starting the nameserver..." self.ns = NSstart(); #Making the application exit when onlye daemon threads are left self.ns.setDaemon(True); self.ns.start(); class NSstart(threading.Thread): def __init__(self): threading.Thread.__init__(self,name="ns"); def run(self): self.ns = Pyro.naming.NameServerStarter(); self.ns.start(); #fkt for signal handling def handler(signum, frame): print "Handling signal:", signum; sys.exit(2); -------------- next part -------------- #!/usr/bin/env python import os, sys, gp, getopt, signal; CLIENTS=['meltdown','magneto','cyclops','blink']; def nice(): #Set this proces nice value... eq. 10 - we are behaving! current = os.nice(0); inc = 10 - current; print "Current niceness is " + str(current) + " adding "+ str(inc); os.nice(inc); def usage(): print "Usage: "+sys.argv[0]+" -c|--client -s|server"; def main(): nice(); try: opt, args = getopt.getopt(sys.argv[1:],"cs",['client','server']); except getopt.GetoptError: usage(); sys.exit(2); doClient = False; doServer = False; for o,a in opt: if o in ("-c","--client"): #Client time! doClient = True; if o in ("-s","--server"): #Server Time! doServer = True; if doServer: #getting around crtl+c and threads... signal.signal(signal.SIGINT, gp.handler); server = gp.Server(); server.startNS(); print "Creating population..."; myrerne = gp.Population(); myrerne.append(gp.Myre("FirkAnt")); myrerne.append(gp.Myre("Legions")); myrerne.append(gp.Myre("Militant")); #ugly hack, not allowing main thread to exit. Should prob'ly sleep while True: pass; elif doClient: print "Doing client..."; #making script run... could be importet ya know... if __name__ == "__main__": main(); From aleax at aleax.it Sun Mar 16 02:15:29 2003 From: aleax at aleax.it (Alex Martelli) Date: Sun, 16 Mar 2003 07:15:29 GMT Subject: dict.popitem(key) ??? References: Message-ID: Raymond Hettinger wrote: > "Justin Shaw" >> Why doesn't popitem take a key argument that defaults to None? Or how >> should I pop a particular item out of a dict? > > In Py2.3, dict.pop can take an optional default argument: > > avalue = mydict(possiblekey, default) > > It can also just search for a specified key and return an > exception if not found: > > avalue = mydict(possiblekey) Just to clarify (I think a ".pop" just failed to appear here): Python 2.3a2+ (#10, Mar 16 2003, 08:10:57) [GCC 3.2 (Mandrake Linux 9.0 3.2-1mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> ad=dict.fromkeys('ciao') >>> ad {'i': None, 'a': None, 'c': None, 'o': None} >>> ad.pop('z') Traceback (most recent call last): File "", line 1, in ? KeyError: 'z' >>> ad.pop('z',23) 23 >>> ad.pop('a',23) >>> ad {'i': None, 'c': None, 'o': None} >>> If you can't use 2.3 (still in alpha stage), then as somebody else suggested you can still do the job, albeit in two steps: >>> ad.get('o',42) >>> del ad['o'] >>> ad {'i': None, 'c': None} >>> Alex From zhitenev at cs.vsu.ru Tue Mar 18 12:35:25 2003 From: zhitenev at cs.vsu.ru (Lexy Zhitenev) Date: Tue, 18 Mar 2003 20:35:25 +0300 Subject: What is PyInt_Fini? Message-ID: All I have found out it is something from C part of Python API and it is from Stackless. Actually I don't need detailed specifications, it's just curiosity. If the answer can't be short please mail me or give a link. Lexy. From lennart at regebro.nu Wed Mar 5 09:18:10 2003 From: lennart at regebro.nu (Lennart Regebro) Date: 5 Mar 2003 06:18:10 -0800 Subject: single-line terinary operators considered harmful References: <882b0a41.0303020225.3caf0334@posting.google.com> Message-ID: <6a6a10bd.0303050618.77cc01e0@posting.google.com> "Clark C. Evans" wrote in message news:... > Getting it to fit on a single line is just an unnecessary > distraction, and, IMHO, one that is bogging down the whole > discussion down... and preventing a good mechanism to > express conditional logic within an expression. Yup. That said, I don't mind a x = conditional(c, a, b), becuase it looks like a function. If people neseecarily have to make if-then-else statements like this on one line, create that function. Heck, here it is: conditional.py: def conditional(c, a, b): if c: return a else: return b Done! Look, I even tested it for you! :) >>> from conditional import conditional >>> >>> x = conditional(1, 'True', 'False') >>> print x True So there. No, go and vote "I reject all options". There is no point in adding ugluness to a pretty language if that uglyness doesn't have a real value, and this hasn't. If you want one line conditionals, now you have them. :) From fcibin at thesis.deis.unibo.it Thu Mar 6 11:01:17 2003 From: fcibin at thesis.deis.unibo.it (Fabio Cibin) Date: Thu, 6 Mar 2003 16:01:17 -0000 Subject: Python on iPAQ Message-ID: <200303061601.RAA29679@promet2.deis.unibo.it> Hi all, I want to install Python on my iPAQ H3970 because I want to create a User Interface for my program (writes in C). Is it Python a right choice ? Could you give me some link where I can find some useful information ? Thanks a lot in advanced. Fabio From mcherm at mcherm.com Tue Mar 25 09:37:39 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Tue, 25 Mar 2003 06:37:39 -0800 Subject: The ternary operator: more than one way to do it? Message-ID: <1048603059.3e8069b389f37@mcherm.com> Erik Max Francis writes: > Any language feature can be abused. The writer of the abuse is to blame > for such misuses, not the language. Thomas Wouters responds: > Then why is Python any better than C, C++, Java, Perl, *LISP, etc ? Why are > we using indentation for blocks, if we can trust the writer not to mis-use > indentation ? Many people will answer to the first by explaining Python is > small, simple, easy to learn. Some may say (as they have in the past) 'it > fits your brain'. Where does adding features from other languages stop ? I think you're missing the point. Erik said that the fact that a language feature can be abused is not necessarily a flaw in the feature. He didn't say that no feature is ever useful. For instance, the basic if *statement* can be abused by nesting if's dozens of levels deep so you can't easily tell which if lines up with which else. But that doesn't make the if statement a bad idea. As for your example, you say "why are we using indentation for blocks if we can trust the writer not to mis-use indentation?" The use of indentation for blocks has little to do with programmers failing to line up thier braces, it is there so coders and compilers will be using the SAME cues. I understand your wish to have Python "fit your brain" -- and we all have different brain sizes and shapes. For me, a feature like metaclasses gives me lots of difficulty, distinguishing between __slots__ and __dict__ is a major problem, but adding another expression form like conditional expressions hardly makes a difference. Not that I'd give up metaclasses (they're powerful enough to be worth it (I think)), but not all features add equally to the "mental size" of a language. -- Michael Chermside From username at ilt.fhg.de Thu Mar 13 17:13:54 2003 From: username at ilt.fhg.de (username) Date: Thu, 13 Mar 2003 23:13:54 +0100 Subject: function get_class_name() Message-ID: <3E7102A2.2C2D754E@ilt.fhg.de> Hi, I need something (<>) for a class i.e. class Hello: . . def get_class_name(self): <> that does this >>>World=Hello() >>>World.get_class_name() "World" Thanks Marco -- ------------------------------------------------------------ # Dipl. Phys. Marco Hoefer # Fraunhofer Institut f. Lasertechnik # Steinbachstr. 15, D-52074 Aachen, Germany. # Tel: + 49 (0) 241 8906 128, Fax: +49 (0) 241 8906 121 # EMail: hoefer at ilt.fraunhofer.de, WWW: http://www.ilt.fhg.de From pschmidt at omnimn.com Mon Mar 24 16:31:16 2003 From: pschmidt at omnimn.com (Phil Schmidt) Date: 24 Mar 2003 13:31:16 -0800 Subject: adjacent differences with a list comprehension Message-ID: <69413f9.0303241331.62f0295f@posting.google.com> Given a list of numbers, such as: L = [2, 5, 8, 3, 9, 1] I want to generate a list containing the differences between adjacent elements, i.e., Ld = [3, 3, -5, 6, -8] I don't see how I can do this (easily/elegantly) with list comprehensions. Any suggestions? Thanks! From mwh at python.net Tue Mar 4 10:39:48 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 4 Mar 2003 15:39:48 GMT Subject: code coverage tool References: <7h3n0kbjpnk.fsf@pc150.maths.bris.ac.uk> <7h3el5njnqv.fsf@pc150.maths.bris.ac.uk> Message-ID: <7h33cm3jg9b.fsf@pc150.maths.bris.ac.uk> "John Roth" writes: > "Michael Hudson" wrote in message > news:7h3el5njnqv.fsf at pc150.maths.bris.ac.uk... > > The overhead is probably somewhat higher because of the way line trace > > events are generated in 2.3 is what I meant. Fallout from the removal > > of SET_LINENO. > > > > I haven't actually tried it, so I might be hopelessly wrong... > > That shouldn't affect the profiler, but it might affect the > debugger, and hence pyCover. Well, sys.settrace vs. sys.setprofile, sure. But the hotshot profiler uses the trace interface in some circumstances. Calling it a debugger is a touch bogus :-) > I really should fire up 2.3 and give it a test. Don't hold your > breath, though. Don't worry, I won't. Cheers, M. -- 93. When someone says "I want a programming language in which I need only say what I wish done," give him a lollipop. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From exarkun at intarweb.us Fri Mar 21 13:23:37 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 21 Mar 2003 13:23:37 -0500 Subject: Incomparable abominations (was: python-dev Summary) In-Reply-To: References: <698f09f8.0303201041.6b69619d@posting.google.com> <698f09f8.0303202158.511534e8@posting.google.com> Message-ID: <20030321182337.GC7819@meson.dyndns.org> On Fri, Mar 21, 2003 at 08:29:34AM -0500, John Roth wrote: > > "Jeremy Fincher" wrote in message > news:698f09f8.0303202158.511534e8 at posting.google.com... > > "John Roth" wrote in message > news:... > > > "Jeremy Fincher" wrote in message > > > news:698f09f8.0303201041.6b69619d at posting.google.com... > > > > If something like this was added, so there was a total ordering on > > > > Python objects during sorts, I'd be completely happy with the > > > > comparison operators /<=/>= being changed to only work between > > > > consistent types. In fact, I'd prefer it that way. > > > > > > > > Of course, == and != would still work between inconsistent types. > > > > > > I think that's probably the way is *should* have been from the > > > beginning. However, I'd be against changing it at this point; it > would > > > break programs. Save the change for Python 3000. > > > > If the sort() method on lists was changed to use this total ordering > > on Python objects (using before()), then changing the relational > > operators to raise exceptions on type-invalid code wouldn't break any > > of *my* code, so I'd be fine with the change :) > > > > (And what code it did break, mine or not, would almost certainly be > > either a bug or a place that would need to use before() instead of <; > > I can't imagine the latter case occuring all that often.) > > But that's not the issue. Suggested changes to Python won't happen if > there's any likelihood of breaking people's code. Incompatible changes > need a lot of justification and quite a bit of work to show that the error > cases are unlikely. Assertions don't do it; actual surveys of working code > are needed. Nah. All that's needed is a BDFL pronouncement. PEP 238, for example. > > Even then it would have to be transitioned in over several releases, with > warning messages for illegal usage. That much is certain. Jp -- Examinations are formidable even to the best prepared, for even the greatest fool may ask more the the wisest man can answer. -- C.C. Colton -- up 1 day, 13:58, 2 users, load average: 0.18, 0.34, 0.36 From wsonna at attglobal.net Fri Mar 14 18:16:50 2003 From: wsonna at attglobal.net (William Sonna) Date: Fri, 14 Mar 2003 17:16:50 -0600 Subject: No Do while/repeat until looping construct in python? References: Message-ID: On Fri, 14 Mar 2003 11:32:27 -0600, sismex0 wrote: >> From: William Sonna [mailto:wsonna at attglobal.net] Sent: Friday, March >> 14, 2003 10:30 AM >> >> On Thu, 13 Mar 2003 09:27:07 -0600, sismex0 wrote: >> >> > Troll? Flamebait? Or just uninformed? >> >> None of the above. Legitmate criticism of questionable design >> decisions made. Either respond to the issues raised or look foolish- >> your choice. >> >> > "Questionable design". That's a pretty subjective qualification, > because it's "questionable" from your point of view, using your scale of > what's important and what's not. > > EVERY design decision in the world is subject to question, therefore questionable. That is an OBJECTIVE fact. > There is no absolutely perfect language, because absolute perfection > does not exist. Python is "perfect" in it's own niche, which means it's > "relatively perfect". You might disagree, certainly you're entitled to > it; but don't go spouting off pseudo-data and pseudo- knowledge, > implying that we *have* to agree with you. > > > First two sentences of paragraph - I agree. Third sentence - YOU are the one throwing flames here, not me. I have backed up EVERYTHING I have said with facts. What "pseudo-data" and "pseudo-knowledge", are you referring to, anyway? As for the "implication" that I care whether you or anyone else agrees with me, you haven't backed that up either. [snip] >> > repeat ... until (condition) >> > >> > is exactly the same thing; only that the language places the >> > responsability of choosing the condition's location and exit point on >> > the programmer, not the other way around. >> > >> > For bonus points, can you point out the advantage of Python's >> > approach and the disadvantage of language X's? >> > >> Item 1 - one-or-more is *not* the same as zero-or-more. It is >> mathematically incorrect to make that claim. >> >> > Where did I say that [0..n] == [1..n] ?? > > > What does "exactly the same thing" mean, then? You can score some of your own "bonus points" if you can explain that one. > Exactly, no where. If you wish to code a "zero or more" construct in > Python, you do it. If you wish for a "one or more" construct, you can > also do it. > > The correct word for what you describe is "approximately", or "functionally", not "exactly". > Except that, there's no syntax sugar to sweeten your day, you have to > pick when and where. Whether you like the freedom it gives you, or > resent the responsability of having to think carefully your algorithms, > is your issue, not the language's. > > Its not a question of freedom or responsibility. It is a question of having to recode standard (and often classic) algorithms for Python's quirky omission. [snip] >> The argument is NOT whether its already there (it isn't), or whether it >> would be nice to have (it would), but whether it is sufficiently >> important to justify its existence. >> >> The general concensus is that it is not. A substantial number >> disagree. >> >> > In that case, "a substantial number" may fork Python and add it, it's > perfectly doable. > > Ahh... but you don't want to do it yourself, and you wish for approval > by the masses, and also a little checkmark which says "Approved by > Guido". I don't think you can have it both ways. > > When did I ask for "approval by the masses" or "Approved by Guido"? More false claims. Do you really consider false claims to be a valid argument in favor of the design decisions that I was attempting to discuss with you? >> >> The workaround for "self" is to assign a local variable and use it >> >> instead. >> >> >> >> >> > Really... >> > >> > "self", in an instance method, *IS* a local variable. You can call >> > it whatever you want: "me", "self", "this", "_", "obj", "instance", >> > "here", "etc", ... >> > >> > And, having it explicit and not implicit keeps the instance's >> > namespace apart from the local namespace. >> > >> > >> You've just contradicted yourself, (which is OK; it illustrates the >> problem). Why would a local variable need to be qualified to keep it >> separate from the local namespace? That's the *conceptual* problem with >> "self". >> >> > I really, try as hard as I might, can't see exactly where I contradicted > myself. > > "self" is a local variable, referencing the instance which is "active". > Local variables are in the local namespace. Instance namespace is > inside "self", and accessed as attributes. > > Where's the contradiction? > > When you state it clearly like that, of course there is none. Instance variables are in the namespace of the local variable "self", but they are never local despite the fact that they occur in an instance method of the same instance of the same class. I find it very confusing, and while I can parrot the rules, I don't think I'll EVER understand the rationale (unless someone can explain it). [snip] > Well, that just demonstrates that common sense is the least common of > senses. Instance variables are inside self.__dict__ (where applicable), > and local variables are visible through local(). > > >> It MAY be consistent with Python's general tendency to favor least-type >> (both as in class, and as in typewriter), it DOESN'T help get the job >> done. >> >> > Get *what* job done? > > The job of generating correct code quickly. >> Now, as for your personal attacks ("troll", "flaimbait", etc.), I have >> taken the time to post legitimate criticism substatiated with facts. >> >> > You're oversensitivity to criticism to your own comments, while > attacking others who disagree with you, truly make you out as a troll. > Many won't take your comments seriously and will simply ignore you > because of it. > > Who's throwing flames here? YOU just said I am a troll. And I haven't insulted you once! tu MADRE, cabron! All kidding aside - my response? - I am NOT a troll, but you APPEAR to be a very poor debater. The true test of poor-debaterhood is substitution of facts and logic for unsubstantiated claims and personal attacks. [snip] > I already explained why I find it advantageous; you're entitled to not > like mi reasons, but they're mine, and I'm my own user. Is not my point > of view as a user valid? > > > You haven't explained why this is advantageous, you have merely re-stated the rules. If you have more to say about this, tell me something new. For example: why is the current design better than, say, having instance variables unqualified and qualifying local variables with "local"? Or better than not needing to qualify local or instance variables at all - with well-defined rules for precedence between local and instance variables? If you can answer these questions without making false claims about me or my motives or resorting to insults or personal attacks, there's hope for you yet. From cnetzer at mail.arc.nasa.gov Thu Mar 6 14:27:53 2003 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: 06 Mar 2003 11:27:53 -0800 Subject: C-h f equivalent In-Reply-To: <87adg8fwpj.fsf@millingtons.org> References: <87adg8fwpj.fsf@millingtons.org> Message-ID: <1046978873.712.18.camel@sayge.arc.nasa.gov> On Thu, 2003-03-06 at 05:31, Glyn Millington wrote: > Now when I want to put something together in elisp, in Xemacs all I have > to do is C-h f and then feed in the function name and I get the goods on > a particular function. C-h v does the same for variables. Is there > anything quite as handy as this in python which will tell me about > functions, built-in variable etc I HIGHLY recommend 'IPython' for this type of thing. It greatly extends the python interactive shell (among other things), to allow easy introspection of objects, tab completion of attribute names, replay of commands, etc. http://www-hep.colorado.edu/~fperez/ipython/ -- Bay Area Python Interest Group - http://www.baypiggies.net/ Chad Netzer (any opinion expressed is my own and not NASA's or my employer's) From mwm at mired.org Wed Mar 19 12:17:20 2003 From: mwm at mired.org (Mike Meyer) Date: Wed, 19 Mar 2003 17:17:20 GMT Subject: username cgi References: Message-ID: Ben Hutchings writes: > In article , Anthony Paul wrote: > > I am writing a forum on intranet using python. I don't want my users > > have to enter their username when they will add a message, so I need to > > read the %username% environment variable of the workstations (they're > > running win2k). > > Is it possible ? > > I found a solution about REMOTE_USER but it needs web > > authentification... > It's possible, as long as the server is IIS and the browser is IE. > Just configure IIS to use Integrated Windows Authentication, and the > username should show up in REMOTE_USER. If you're using standard web > software then I think you're out of luck. There's also REMOTE_IDENT. You need the other end to be running an authd - see RFC 1413 - server for that to work. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From danb_83 at yahoo.com Mon Mar 24 16:53:06 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 24 Mar 2003 13:53:06 -0800 Subject: Python 2.3 True = False References: <3E7EB0C1.FB2A76EB@alcyone.com> Message-ID: Rene Pijlman wrote in message news:... > Martin v. L?wis: > >At one point, there was a patch to restrict assignments to True and False > >for 2.3. This patch wasn't implemented as too much code actually did > >assign to True and False. > > You have got to be kidding :-D > > What did it assign True and False to? And why? I've written some code that makes assignments to True and False. Namely, True = 0 == 0 False = not True This makes True and False have type bool in Python 2.3 and int in Python 2.2. From exarkun at intarweb.us Thu Mar 6 14:23:10 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 6 Mar 2003 14:23:10 -0500 Subject: unsigned integers In-Reply-To: References: Message-ID: <20030306192310.GA31276@meson.dyndns.org> On Thu, Mar 06, 2003 at 02:35:13PM +0000, Giovanni Bajo wrote: > Hello, > > I have some troubles with signed/unsigned integers, probably because it is > still not clear to me how Python works with respect to this. Especially: > Python doesn't have unsigned ints builtin. > 1) How can I force 0xFFFFFFFF to be 4294967295 instead of -1? My problem is > that I'm converting some C code like a = b*c where the result needs to be > wrapped within 32-bit limits. If I bit-and the result with 4294967295 > everything is ok, but if I use 0xFFFFFFFF the number does not mask > correctly, because 0xFFFFFFFF is seen as -1. Why should it ever consider a > hex literal as negative, by the way? Is there any real-world case where this > is needed? > Python ints (on 32 bit platforms) use 31 bits for value and one bit for sign, so you can't have 2**32-1 as an int, you'll need a long. This is easy - 0xFFFFFFFFL or long('FFFFFFFF', 16) (and in 2.3, int('FFFFFFFF', 16) will work, too). That said, -1 and 0xFFFFFFFF are really the same thing. The bits of -1 are all set so, if I understand what you're trying to do, using -1 will work fine. > 2) binascii.crc32() returns a signed integer representing the CRC. I call it > signed because if I print the result it displays a signed number. Now, what > if I need the unsigned representation of it (as in, the unsigned number > which is machine-represented with the same 32 bits)? I need to multiply it > by another integer, but I need an unsigned multiplication, not a signed one. > This works: >>> import struct >>> struct.unpack('!L', struct.pack('!l', -3)) (4294967293L,) See the struct module docs for why. Jp -- up 3 days, 11:58, 7 users, load average: 0.12, 0.20, 0.18 From martin at v.loewis.de Thu Mar 6 01:13:00 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 06 Mar 2003 07:13:00 +0100 Subject: embedding python - PyImport_ImportModule returns null In-Reply-To: <3607e8e4.0303051802.7ddf1dfd@posting.google.com> References: <3607e8e4.0303051802.7ddf1dfd@posting.google.com> Message-ID: JW wrote: > pModule=PyImport_ImportModule("func"); //fileread.py Why do you try to load func, when the module is called fileread.py? > PyErr_Print(); > fprintf(stderr,"Failed to load \"%s\"\n","func"); [...] > What am i doing wrong? You are not telling us what the Python exception was that you got. Regards, Martin From vze4rx4y at verizon.net Sat Mar 8 22:21:55 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 09 Mar 2003 03:21:55 GMT Subject: xls to txt References: Message-ID: > > How easy is it/would it be to have Python Automatically convert them > > from .xls? > > If you are on Windows, you can use the Python COM extensions to invoke > Excel automatically. Here is an example: http://users.rcn.com/python/download/quoter.pyw Raymond Hettinger From matt.gerrans at hp.com Fri Mar 14 20:03:08 2003 From: matt.gerrans at hp.com (Matt Gerrans) Date: Fri, 14 Mar 2003 17:03:08 -0800 Subject: calling a method using a variable name? References: <3E724077.1020003@nowhere.com> Message-ID: <3e727ba6$1_2@hpb10302.boi.hp.com> > > class X: > > def method(): > > pass Shouldn't that be: class X: def method(self): pass From max at alcyone.com Sun Mar 16 02:44:03 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 15 Mar 2003 23:44:03 -0800 Subject: Is " a is b " and " id(a) == id(b) " the same? References: <3E7418A1.25346E61@alcyone.com> Message-ID: <3E742B43.2F4111A3@alcyone.com> Alex Martelli wrote: > Not when they exist at the same time. I think you failed to notice > the crucial aspect in explaining the anomaly found by the original > poster: that the method objects are being generated on the fly and > go away at once, so the "exist at the same time" doesn't apply -- > their id can get recycled. Ah, interesting. Learn something new every day. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ But since when can wounded eyes see / If we weren't who we were \__/ Joi Blackgirl International / http://www.blackgirl.org/ The Internet resource for black women. From zopestoller at thomas-guettler.de Thu Mar 13 09:27:10 2003 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Thu, 13 Mar 2003 15:27:10 +0100 Subject: Grail source code? References: Message-ID: Anthony Baxter schrieb: >>>>Thomas Guettler wrote >>> >>grail is far from a browser. But wxPython has a HTML widget, Python has >>a httplib. I thought about making a small browser like this, too. >> >>But of course wxHTML does not support JavaScript, but it would be enough >>for simple pages. > > > Another approach would be to use PyKDE and KParts and use the KHTML widget > (I assume this is supported by PyKDE - be surprised if it wasn't). Is KHTML supported on win32? thomas From morden at shadows.net Thu Mar 27 21:46:09 2003 From: morden at shadows.net (morden) Date: Thu, 27 Mar 2003 18:46:09 -0800 Subject: 2.2.1 crashes on Linux (RH7.3) trying to load python shared library timemodule.so Message-ID: My app embedding statically linked libpython 2.2.1 .a crashes with the following stack trace: #0 0x081217f7 in _dl_lookup_symbol () #1 0x08123cf6 in _dl_relocate_object () #2 0x081049cf in dl_open_worker () #3 0x08104017 in _dl_catch_error () #4 0x08104bc3 in _dl_open () #5 0x080cd85b in dlopen_doit () #6 0x08104017 in _dl_catch_error () #7 0x080cda76 in _dlerror_run () #8 0x080cd829 in dlopen () #9 0x080ac08c in _PyImport_GetDynLoadFunc (fqname=0xbfffde34 "time", shortname=0xbfffde34 "time", pathname=0xbfffd9a4 "/usr/lib/python2.2/lib-dynload/timemodule.so", fp=0x81e2180) at Python/dynload_shlib.c:90 #10 0x080a36f7 in _PyImport_LoadDynamicModule (name=0xbfffde34 "time", pathname=0xbfffd9a4 "/usr/lib/python2.2/lib-dynload/timemodule.so", fp=0x81e2180) at ./Python/importdl.c:42 #11 0x080a171e in load_module (name=0xbfffde34 "time", fp=0x81e2180, buf=0xbfffd9a4 "/usr/lib/python2.2/lib-dynload/timemodule.so", type=3) at Python/import.c:1365 #12 0x080a2353 in import_submodule (mod=0x816757c, subname=0xbfffde34 "time", fullname=0xbfffde34 "time") at Python/import.c:1895 #13 0x080a1f0d in load_next (mod=0x816757c, altmod=0x816757c, p_name=0xbfffe240, buf=0xbfffde34 "time", p_buflen=0xbfffde30) at Python/import.c:1751 #14 0x080a1b6b in import_module_ex (name=0x0, globals=0x8216fac, locals=0x8216fac, fromlist=0x816757c) at Python/import.c:1602 #15 0x080a3064 in PyImport_ImportModuleEx (name=0x820f88c "time", globals=0x8216fac, locals=0x8216fac, fromlist=0x816757c) at Python/import.c:1643 #16 0x080c5f48 in builtin___import__ (self=0x0, args=0x81cade4) at Python/bltinmodule.c:40 #17 0x0806b114 in PyCFunction_Call (func=0x81c7d28, arg=0x81cade4, kw=0x0) at Objects/methodobject.c:80 #18 0x080551e0 in PyObject_Call (func=0x81c7d28, arg=0x81cade4, kw=0x0) at Objects/abstract.c:1684 #19 0x0808df0f in PyEval_CallObjectWithKeywords (func=0x81c7d28, arg=0x81cade4, kw=0x0) at Python/ceval.c:3049 #20 0x0808c312 in eval_frame (f=0x81db1bc) at Python/ceval.c:1839 #21 0x0808d72d in PyEval_EvalCodeEx (co=0x81daa10, globals=0x8216fac, locals=0x8216fac, args=0x0, argcount=0, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2585 #22 0x0808f729 in PyEval_EvalCode (co=0x81daa10, globals=0x8216fac, locals=0x8216fac) at Python/ceval.c:483 #23 0x080a09f9 in PyImport_ExecCodeModuleEx (name=0xbfffedd4 "foo", co=0x81daa10, pathname=0xbfffe4d4 "/tmp/sched/modem/foo.pyc") ... Where foo is my actual module name and pathname is something valid My questions are: 1. Why does 2.2.1 goes looking for timemodule.so in /usr/lib/python2.2/lib-dynload/ even though I've built it statically with prefix /u/local Btw timemodule.so was not built: Python-2.2.1]$ find . -name *timemodule* -print ./build/temp.linux-i686-2.2/timemodule.o ./Modules/timemodule.c 2. How could I tell configure that I want modules statically linked with libpython.a? I don't want to rely on the garbage compiled with 2.96 supplied by RedHat. Thank you! From theller at python.net Thu Mar 6 09:58:34 2003 From: theller at python.net (Thomas Heller) Date: 06 Mar 2003 15:58:34 +0100 Subject: C-h f equivalent References: <87adg8fwpj.fsf@millingtons.org> Message-ID: Gerhard H?ring writes: > Glyn Millington wrote: > > [...] Now when I want to put something together in elisp, in Xemacs > > all I have to do is C-h f and then feed in the function name and I > > get the goods on a particular function. C-h v does the same for > > variables. [...] > > Check out the help and dir builtin functions. > > #v+ > >>> import os > >>> help(os.rename) > Help on built-in function rename: > > rename(...) > rename(old, new) -> None > Rename a file or directory. > > >>> x = {} > >>> dir(x) > ['__class__', '__cmp__', '__contains__', ... , 'setdefault', 'update', > 'values'] > >>> > #v- > > There may be a shortcut that does just from Emacs' Python mode. Recent versions of python-mode.el bind the F1 key to the help function: Pressing F1 on the word 'dir' show this in a help-buffer: Help on built-in function dir: dir(...) dir([object]) -> list of strings Return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it: No argument: the names in the current scope. Module object: the module attributes. Type or class object: its attributes, and recursively the attributes of its bases. Otherwise: its attributes, its class's attributes, and recursively the attributes of its class's base classes. I have python-mode.el version 4.29, you may have to get it by CVS if there are still older versions bundled with Xemacs. Thomas From reply.in at the.newsgroup Sat Mar 8 11:00:34 2003 From: reply.in at the.newsgroup (Rene Pijlman) Date: Sat, 08 Mar 2003 17:00:34 +0100 Subject: CGI ZIP References: Message-ID: Simon Faulkner: >Can the zipfile module only write to a file system? It can write to any file-like object. "class ZipFile(file[, mode[, compression]]) Open a ZIP file, where file can be either a path to a file (a string) or a file-like object." http://www.python.org/doc/current/lib/zipfile-objects.html -- Ren? Pijlman From mertz at gnosis.cx Thu Mar 13 00:22:03 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Thu, 13 Mar 2003 00:22:03 -0500 Subject: Tuples, what are they: read-only lists or heterogeneous data arrays? Message-ID: <7VBc+kKkXwVb092yn@gnosis.cx> googlegroups at tekNico.net (Nicola Larosa) wrote previously: |Date: 2001-02-15 05:49 Sender: gvanrossum |"Why bother? I like the fact that when you want to do list-ish |things you have to use lists. Use list(t).count(x) if you really |want this for a tuple. |"I'm rejecting this in the name of all those users who want Python |to be small." |Guido, can't we settle this once and for all? Sure looks to me like it HAS BEEN settled once and for all :-). Tuples don't have an .count() method... so it is written, and so shall it be (unless it changes in a later version). Yours, David... -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad ---[ Postmodern Enterprises ]-------------------------- From mwh at python.net Wed Mar 12 10:09:26 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 12 Mar 2003 15:09:26 GMT Subject: Curses - Win/dos References: <3e6e62b7$1@nntp01.splitrock.net> <3e6e6614$0$51897$a1866201@newsreader.visi.com> <3e6e68dc$0$52910$a1866201@newsreader.visi.com> <3e6e90b2@news.mt.net.mk> Message-ID: <7h3k7f4mxju.fsf@pc150.maths.bris.ac.uk> ?????? ?.

writes: > While we are at the ncurses topic... does python support the ncursesw > libaries. As of ncurses-5.3 there is a compile-time option to produce > wide-ncurses libraries. These libraries have greatly improved Unicode nad > UTF-8 handling. > > So, can Python's curses module be made to work with ncursesw? Almost certainly :-) More helpfully: http://python.org/sf/700921 I'm sure cben wouldn't mind some help. CHeers, M. -- Unfortunately, nigh the whole world is now duped into thinking that silly fill-in forms on web pages is the way to do user interfaces. -- Erik Naggum, comp.lang.lisp From sholden at holdenweb.com Mon Mar 17 20:43:55 2003 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 18 Mar 2003 01:43:55 GMT Subject: Rudeness (was: Re: OT: Aspergers link) References: Message-ID: "Eric Stechmann" wrote in message news:mailman.1047941909.27272.python-list at python.org... > At 04:34 PM 3/17/03 -0500, you wrote: > >And it appears that with the massive 21 or so lines of useless cruft that > >makes > >up your signature, your own signal-to-noise ratio is even less impressive. > > Yes, ugly, isn't it? > > Much of the cruft is beyond my control. I don't like it > either, but I'm stuck with it. > > >Carl we know: he _adds_ content. > > Perhaps. However, the "content" in this particular thread > seemed unnecessarily nasty and I decided to say so. > > >Who are you? > > Who am I? Just a lurker on the threshold. A lurker who > rarely sees any reason to post, but was bothered enough > to do so this time. > > However, I apologize for taking up bandwidth with my "cruft." > I should have e-mailed Mr Banks directly rather than posting > to the group. That would no doubt have been better for all > parties concerned. A lesson learned. > > > > Eric Stechmann > > > > > -------------------------------------------------------------------------- > Eric Stechmann Direct: +1 (651) 234-1217 > Domestic Feline Wrangler Fax: +1 (651) 490-1484 > Advanced Respiratory, Inc. E-mail: estechmann at advresp.com > 1020 West County Road F URL: www.thevest.com > St.Paul MN 55126 > > > ______________________________________________________________ > Information contained in this e-mail message may be legally privileged and confidential information intended only for the use of the individual(s) named above. If the reader of this message is not the intended recipient, you are hereby notified that any use, dissemination, distribution, or copying of this e-mail is strictly prohibited. If e-mailed messages include MEDICAL RECORDS, these records ARE PRIVILEGED AND CONFIDENTIAL and may be released only upon written permission of the patient. If you have received this e-mail in error, please immediately notify the sender by telephone at 1-800-426-4224 and delete this e-mail. Thank you! > ______________________________________________________________ > > Eric: Normally when I reply to a post I trim the signatures from the original poster as a courtesy to other readers. In this case I have left them intact. Merely to underline Peter's remarks about your "signal-to-noise ratio". I don't think anybody takes issue with your right to say what you think. It's simply that companies like your employer, forcing you as they apparently do to add large amounts of information (irrelevant in this context) at the end of each post, drown your opinions in a sea of irrelevant verbiage. That said, I'm glad you took the trouble to reply to Peter (despite the somewhat petulant tone :-) and didn't take your own advice. You're just as entitled to your say as me or anyone else. And I'm sure Peter has no beef with your reply either (right, Peter?) regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Register for PyCon now! http://www.python.org/pycon/reg.html From exarkun at intarweb.us Sat Mar 15 11:41:33 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sat, 15 Mar 2003 11:41:33 -0500 Subject: High performance IO on non-blocking sockets In-Reply-To: References: Message-ID: <20030315164133.GA14733@meson.dyndns.org> On Sat, Mar 15, 2003 at 12:33:57PM +0100, Troels Walsted Hansen wrote: > Jp Calderone wrote: > >> send_buffer = buffer(self.data, self.offset) > >> sent = self.socket.send(send_buffer) > >> self.buffer_offset += sent > > Have you timed this, vs the original, naive code? > > I have to admit that I haven't timed it. I've only looked at the Python > source and based my statements on that. > > > Slicing a string shouldn't copy any bytes, only create a new string > > object with a modified starting pointer and length. > > I believe this is wrong, at least for Python 2.2.2 which I'm working > with. Only if the string slice is the same as the original string do you > get an optimized slice without any copying. See source snippet below. > > The buffer object is the one that implements read-only slices in the > manner that you describe. > > static PyObject * > string_slice(register PyStringObject *a, register int i, register int j) > { > [...] > if (i == 0 && j == a->ob_size && PyString_CheckExact(a)) { > /* It's the same as a */ > Py_INCREF(a); > return (PyObject *)a; > } > [...] > return PyString_FromStringAndSize(a->ob_sval + i, (int) (j-i)); > Woops, I misinterpreted this code. > > This seems as if it would be about as expensive as creating a new buffer > > object, but has the advantage of running more of the work in C, rather > > than Python (no name lookup for buffer, for example). > > > > I ask because I can't seem to squeeze any speedup out of Twisted by > > making this change (in fact, I find a significant slowdown, 12309.8 KB/s > > using the original "buf = buf[sent:]" code to 9408.2 KB/s using the > > buffer() approach). > > > > I'm hoping I've just screwed something up, of course, and would love to > > hear that the buffer() approach is, in fact, much faster :) > > Your numbers are surprising and very interesting. Would you care to test > a modified send loop with the Twisted framework for me? > > if self.offset: > sent = self.socket.send(buffer(self.data, self.offset)) > else: > sent = self.socket.send(self.data) > self.offset += sent > > The idea here is to avoid the cost of creating a buffer object for short > sends that fit into the kernel's socket buffer. > Good call. This approach does show a speedup. With the same settings as the previous numbers, the throughput rate rises to 12750 KB/s. > How large is self.data in your test? I tried using three different file sizes (0.5MB, 10MB, 100MB), but since I used the standard Twisted.web server, these got chunked up into 65KB pieces. I thought that this limited buffer size would reduce the effectiveness of this optimization, so in addition to the change you suggested above, I benchmarked the server with a ~4MB chunk size instead. This only showed a very minor speedup, 12778 KB/s, possibly one inside the error range for the benchmark applied. For my edification, what are common sizes for kernel socket buffers, or does it vary too widely to answer for anything but specific systems? Jp -- "One World, one Web, one Program." - Microsoft(R) promotional ad "Ein Volk, ein Reich, ein Fuhrer." - Adolf Hitler -- up 12 days, 7:59, 8 users, load average: 0.12, 0.17, 0.24 From jbarham at jbarham.com Tue Mar 11 14:16:52 2003 From: jbarham at jbarham.com (John E. Barham) Date: Tue, 11 Mar 2003 19:16:52 GMT Subject: Need some basics References: Message-ID: "L. B." wrote: > I'm quite a newbie in programming and i'm soon getting tired of the VB > crap (and that's why i'm learning Python)... i'd like, someday, to > define myself a programmer, but i feel i'm missing some valuable > basics of computer science: algorithms, data-structures, software > engeenering... and when thinking about making even a simple game (like > tic-tac-toe) i found myself screaming just for thinking how it should > be done. > > So here is the question... assuming that i'm too old (26) for going > back to college and study something else that Politics and Economics > which doesn't seem to be anything computer-related ;-) which book > should i study, which books shouldn't miss from a serious programmer's > bookshelf? I'd suggest becoming familiar with the Standard C++ STL ("Standard Template Library") to get a handle on the most common and important data structures and algorithms. The STL also specifies runtime complexity guarantees. The SGI STL implementation (http://www.sgi.com/tech/stl/) was developed in part by Alex Stepanov, the inventor of the STL, and includes excellent documentation. Note that the STL vector and (not yet standard) hash_map containers are roughly equivalent to Python lists and dictionaries, respectively. John From jblazi at hotmail.com Thu Mar 6 16:53:26 2003 From: jblazi at hotmail.com (Janos Blazi) Date: Thu, 06 Mar 2003 22:53:26 +0100 Subject: Problem finding modules References: <3E67BC35.F54C9C17@engcorp.com> Message-ID: On Thu, 06 Mar 2003 16:23:01 -0500, Peter Hansen wrote: > Try running python interactively, then type "import sys" and then > "sys.path". What you see listed is what Python thinks the path > should be for finding files, including site-packages. If it's > really bizarre, either post it or deduce what went wrong... Yes, you are right. The values point to drive d: but they point to drive c:. How can I change that? PYTHONHOME ist not defined at all, PYTHONPATH could be all right but it only contains another directory (which I do not need at the moment). It is strange that the Windows installer does not set this. JB -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From dave at boost-consulting.com Mon Mar 31 16:32:22 2003 From: dave at boost-consulting.com (David Abrahams) Date: Mon, 31 Mar 2003 16:32:22 -0500 Subject: Is Python overhyped (just like Java)? References: Message-ID: Alex Martelli writes: > Ajay na wrote: > >> Can some-one please explain why one would want to use Python? > > One word: *PRODUCTIVITY*. > >> What is wrong with C++? > > One word: *COMPLEXITY*. > > >> In my opinion, the problem with C++ has nothing to with the language >> semantics. The problem is that when people are confronted with a >> powerful language like C++, they tend to want to optimize everything >> to death. That's when they get themselves in trouble. > > You're over-generalizing. Not all users of C++ are so naive as to > have failed to read Knuth -- "Premature optimization is the root of > all evil in programming". But the point is -- by choosing a lower > level language, like C++, at the start of your project, rather than a > higher level one, like Python, you ARE optimizing WAY prematurely. In my experience, it may be even more powerful to begin with hybrid development from the ground up. On one project, when I tried to start with Python and push time-critical code into C++, I found that although algorithm prototyping had been fast, the Python interface I had developed for those critical components was not well-suited to the C++ world. In my application it was easy to predict where the bulk of the time would be spent, and had I written the core engine in C++ early on I might have saved myself a redesign effort. Another effect of this approach is that you end up with a well-designed core C++ library that can be used by C++-only applications, instead of something that really only works well with the Python wrapper. > One example I give is a task for which C++ is quite suited, with its > standard library -- reading a text file, breaking it into > whitespace-separated 'words', building an index from each word to > the line numbers on which it appears, and showing the index with > words in alphabetical order, one per line, each followed by the line > numbers on which it appears. Boy, that sure sounds like a job for Python to me. On the other hand, I can't think of any C++-ish job that Python wouldn't be good for as long as you're willing to spend some more cycles. > Thanks to the excellent support given for these tasks by the standard > library, the C++ source is ONLY twice as big as the Python source for > the same job (a more usual ratio is around 5:1). This holds for both > the simplest versions, and the slightly more complicated ones with > somewhat better optimization. The runtimes on my box (Linux Mandrake > 9.0, gcc 3.1, Python 2.3) are, when the programs are run on the 4.4 MB > of the "King James Bible" in plain ASCII text: 17.4 seconds for the > simplest C++, going down to 15 with optimizations; 11.2 seconds for > the simplest Python, going down to 8.1 with optimizations (CPU times > are in very similar ratios). Of course, this basically reflects the > excellence of Python's intrinsics (dictionaries, lists, strings) > versus the lesser quality of C++'s library implementation (maps, > vectors, strings) -- with different implementations, you may see > different ratios. Really? Are you sure that time wasn't sunk into I/O? "Read all the lines from a file" is a primitive in Python, but not in C++. Also, it's only fair to point out that C++ doesn't have one library implementation -- each compiler comes with its own. Which implementation(s) were you testing? Oh, I see it was probably libstdc++ that comes with gcc 3.1. Well, IIRC GCC-3.1 was well known to optimize poorly (it took them some time to figure out how to integrate all the new optimizations that came in with GCC-3, and they actually made things slower for a while), and I wouldn't exactly say that libstdc++ is the fastest implementation. In other words, there's nothing intrinsic about C++ which says that it has to be twice as slow as Python at this job. I don't think it's fair to talk about "the lesser quality of C++'s library implementation." Aren't you glad I'm asking these questions now, instead of at your talk in Oxford? ;-) > The simplest and most flexible C++ you can write is still way > bigger, more complicated, and less flexible than the most refined > and optimized Python code it may make sense to write -- it's as > simple as this. I think when you're comparing the use of the core language I have to agree. However, when it comes to functionality provided by libraries, it really depends on the quality and availability of the library interface. That said, I think Python still has way more useful libraries than C++ does. > For tasks to which Python is extremely well suited (text processing > of all kinds, including XML parsing, for example), you may ALSO get > better running time than C++ with the standard library would give > you -- in general, C++ lets you develop faster code, but oh what a > price in terms of productivity you pay for that! > > And the funniest thing is, there IS no need to pay that price -- 90% > of your program's runtime is likely to be taken up by 10% of your > program's source code, or some such ratio. By writing Python first, > you'll often get an application with acceptable performance; if not, > you profile it, find out the hot-spots, optimize those in Python > terms, and if that's still not enough, it's EASY to recode the > hot-spots in faster ways while still leaving MOST of your application > in Python. There are many ways to do such recoding (even without > counting the still experimental 'psyco' selective just-in-time > optimizer), and among them are ways to integrate C++, such as SciPy's > "weave" and the Boost Python Library (if you don't know Boost, DO give > it a look -- it WILL increase your C++ productivity, and not just by > easing integration of C++ to Python, either). > >> people who don't understand C++, are afraid to use the 'virtual' >> features of that language because it's 'too expensive'. But that's >> stupid...because Python's 'virtualness' is even more expensive! > > It's quite inconsiderate of you to imply that Python users are "people > who don't understand C++", when among those users are people like > Andrew Koenig (author of "Ruminations on C++" and other great C++ > books, as well as a towering figure of C++ development -- the > algorithm for name lookup in the C++ language is called "Koenig > lookup" because HE developed it...!), Bruce Eckel (author of > best-sellers "Thinking in C++" and "Thinking in Java"), and so many > others whose C++ competence is in all likelihood AT LEAST as good as > yours. > > >> Nope...I'm not trolling...I want someone to give a solid and >> intelligent argument about why I should switch from C++ to Python! > > You shouldn't *SWITCH*! If you hadn't already made the huge investment > to master all the complexity of C++, it might be best to avoid it -- > but, if you HAVE made it, count it as a "sunk cost", as I do, and see > how best to leverage it. Learn Python (a trivial investment compared > to learning C++), and use BOTH Python and C++ in your development. > You'll find that Python gives you extremely high productivity and > flexibility, letting you prototype, experiment, refactor whole > architectures from the inside out and back again -- even if you knew > the final product MUST be delivered in C++ due to contractual > requirements, you'd STILL be better off doing the early phases in > Python ANYWAY. Once the program is working, benchmark it; most often, > you'll find you're done -- in a FRACTION of the time. If the > performance isn't satisfactory, profile it, and start optimizing -- > including recoding parts in C++, e.g. with weave or the Boost Python > Library. In the end, you'll use both Python and C++ in the same > program, *each for what it does best*: Python for most of the code, C++ > for the bottlenecks. It's as simple as this, really! > > And your programming productivity will soar... > > > Alex > -- Dave Abrahams Boost Consulting www.boost-consulting.com From aleax at aleax.it Sun Mar 16 02:34:03 2003 From: aleax at aleax.it (Alex Martelli) Date: Sun, 16 Mar 2003 07:34:03 GMT Subject: Is " a is b " and " id(a) == id(b) " the same? References: Message-ID: Chen wrote: > Some one said that " a is b " is the same as " id(a) == id(b) ". But it > seems not always true from the following codes: Your observation is correct, and shows this common assertion needs one extra qualification: "provided objects a and b are alive while the whole operation is taking place". This in turn comes from two Python characteristics: 1. as soon as there is no reference extant to an object, Python is allowed to destroy that object (and classic Python does so at once, while other versions such as Jython may choose to delay); 2, id(x) is only guaranteed to be unique as long as x is alive -- as soon as x goes away, Python is allowed to "recycle" (i.e., reuse) the id. The operation of "fetching an attribute", be it on a class a or on an instance b of a, generates a new object on the fly when the attribute being fetched is a function -- the object is a method, unbound or bound, that wraps the function. As soon as there are no more references to that method-object (i.e. as soon as the call to id(themethod) returns, unless other references have also been bound to the method-object) it goes away and its id can be recycled. So, in your example: >>>> class a: > ... def f(self): > ... pass > ... g=f > >>>> b=a() >>>> print id(a.f), id(b.f), id(a.g), id(b.g) > 6759528 6759528 6759528 6759528 all id's are the same just because each of the four method object has gone away as soon as its only reference did, and Python recycled the same id four times. To show this, bind another reference to the object being generated on the fly: >>> froma = a.f >>> fromb = b.f >>> id(froma), id(fromb) (1076642836, 1076643516) >>> id(a.f), id(b.f) (1076643476, 1076643476) >>> as we see, froma (one reference bound to a particular call to a.f) and fromb (ditto but for b.f) differ -- indeed when we fetch a.f again it gets ANOTHER id, because it's a new and separate method object being built on the fly. Another way to look at this is to add another class: >>> class c: ... def h(self): pass ... >>> id(a.f), id(c.h) (1076643476, 1076643476) >>> while a and c have nothing to do with each other, the same "recycling effect" occurs -- a.f goes away and its id is immediately recycled for c.h. >>>> print a.f is b.f > False >>>> print a.f is a.g > False >>>> print b.f is b.g > False >>>> print a.g is b.f > False In all of these cases, the 'is' operator is keeping alive its left operand until it's done executing, so there is no "recycling effect" -- but each access to e.g. b.g and b.f is generating a new separate method object, so the 'is' ain't satisfied and returns False. > Then, how to understand this example and the relationship of id() and > 'is'? By understanding the magic of method-objects -- which are built on the fly. If you use for attributes objects that aren't functions, there is no transmogrification of their types when you access them as attributes, no generation on the fly, no "going away at once" of the generated objects, and no occurrence of this fascinating anomaly you've found. > I'm using 2.3a2 on win98, if it affects. In this case it doesn't, but kudos for specifying this, as often you see people failing to give this crucial info in cases where it DOES matter. I'm using 2.3 from CVS on Linux, btw. Alex From boethius at techie.com Fri Mar 28 07:11:49 2003 From: boethius at techie.com (Boethius) Date: 28 Mar 2003 04:11:49 -0800 Subject: Recurring Timer Message-ID: <67446a0a.0303280411.79dac66f@posting.google.com> Hi, I checked out the Threading.Timer and it executes _once_ after x seconds. I need something similar: a Timer that executes every x seconds until explicitely stoped. How can I do this? O:-) TIA From sandorlevi at yahoo.com Sun Mar 2 16:52:28 2003 From: sandorlevi at yahoo.com (Levente Sandor) Date: 2 Mar 2003 13:52:28 -0800 Subject: How to get IP address References: <2a897f11.0303011133.3acdfc8@posting.google.com> Message-ID: <8b5e42a6.0303021352.4b60c@posting.google.com> If you want to determine your external IP, AFAIK, you must ask a machine that's external to your network. The simplest way is to visit http://www.showmyip.com/ ---- levi Nagy L?szl? Zsolt wrote in message news:... > > > > > >Nagy L=E1szl=F3 Zsolt wrote in message news: an.1046487302.8558.python-list at python.org>... > > =20 > > > >>I'm trying to get all inet addresses of a machine in python. Is there a= > =20 > >>way to do it using > >>the standard library? I found a solution on Google and in Python=20 > >>CookBook but they > >>are platform dependent. I need a platform-independent solution. Thank=20 > >>you in advance. > >> > >> Laci 1.0 > >> =20 > >> > > > >How about this? I only have one IP on my box so I do not know if this > >will work for you.. > > > >socket.gethostbyaddr(socket.gethostname()) > > > >You could probably use the loopback as the parameter, like: > > > >socket.gethostbyaddr('localhost') > > > >Both of these will return a tuple in the form of (hostname, aliaslist, > >ipaddrlist). This is in 7.2 of the Python docs if you need to check > >other variations. > > > Sorry, but this does not help me. I want to determine the IP address=20 > because I want to send my external > IP address to a dynamic DNS provider (in an A record). I get my IP=20 > address with DHCP and I'm > writting a program that assigns a DNS name to a given IP address. So my=20 > hostname may have a bad IP address > assigned at the time when I need the IP address. IP address is a lower=20 > level than DNS name. I can have an IP > address without hostname. Can you tell me a solution in the case when I=20 > have no valid DNS name? > Thanks. > > Laci 1.0 > > > > -- From johnroth at ameritech.net Tue Mar 4 06:46:00 2003 From: johnroth at ameritech.net (John Roth) Date: Tue, 4 Mar 2003 06:46:00 -0500 Subject: Towards a more Pythonic "Ternary Operator" References: <882b0a41.0303020225.3caf0334@posting.google.com> Message-ID: Interesting. I'm not sure what to make of it, but it has one huge advantage over the current flameage: you're actually thinking! Good work. John Roth "Clark C. Evans" wrote in message news:mailman.1046774818.32264.python-list at python.org... > After looking over my code some, I found that where > I thought I needed a terinary operator, I ended > up taking one of two paths: > > exit = { 0: 'no exit', > 1: 'a door' }.get(quantity, > '%s doors' % quantity) > > Or, the more 'obvious' ... > > if 0 == quantity: exit = 'no exit' > elif 1 == quantity: exit = 'a door' > else: exit = '%s doors' % quantity > > The first construct has two advantages over the more 'obvious' > solution: > > 1. It's clear that I'm making an assignment to exit > 2. I don't have to duplicate the ugly '== quantity' > each time. > > However, the first construct brings with it two problems: > > 1. The 'else' case is kinda ugly. > 2. It doesn't short-circut cleanly, to have the short-circut > behavior you need to use lambda's as the mapping values > and then invoke the result... > > So, if you asked me, what I'd like is a hybrid of the two options > above, a nicer-looking short-circuting in-line mapping: > > exit = select quantity > case 0: 'no exit' > case 1: 'a door' > else: '%s doors' % quantity > > #NOTE: new lines/indentation is mandatory in this proposal > > IMHO, the other options in the survey are quite clean > when you look at it this way: > > data = select hasattr(s,'open') > case true: s.readlines() > else: s.split() > > z = 1.0 + select abs(z) < .0001 > case true: 0 > else: z > > t = v[index] = select t <= 0 > case true: (t-1.0) > else: -sigma / (t + 1.0) > > return select len(s) < 10 > case true: linsort(s) > else: qsort(s) > > ... > > The other advantage of this mechanism is that the > semantics could be made a bit more flexible by requiring > the case item to be a predicate -- a boolean function > with one argument, the item being selected upon. Thus, > > z = 1.0 + select abs(z) > case lt(.0001): 0 > case gt(.5): .5 > else: -sigma / (t + 1.0) > > score = select die > case 1: -2 > case 2: -1 > case between(3,4): 0 > case 5: +1 > case 6: +2 > else: > raise "invalid die roll %d " % roll > > Since the items 1,2,5,6 arn't predicates, then the > "equal" predicate is assumed. > > Now... _this_ I would really find useful. > > Best, > > Clark > From wilk-spamout at flibuste.net Fri Mar 14 10:48:30 2003 From: wilk-spamout at flibuste.net (Wilk) Date: 14 Mar 2003 16:48:30 +0100 Subject: python as a web glue ? References: <3e7190c2$0$236$626a54ce@news.free.fr> <3e719b4a$0$15897$79c14f64@nan-newsreader-02.noos.net> <3e71aade$0$2728$626a54ce@news.free.fr> <3e71e919$0$7891$626a54ce@news.free.fr> Message-ID: <87el5aeypd.fsf@flibuste.net> "shagshag13" writes: > Nikolaus Wagner wrote: > > um, whaddya mean? > > Just setup your apache webserver and use mod_python with that. > > well i'm reading things about zope, isn't it more adapted than using apache > + mod-python ? if your programs need to communicate with others, maybe with other protocols ? maybe in asyncronous way ?... Look at twistedmatrix.com -- William Dode - http://flibuste.net From aahz at pythoncraft.com Wed Mar 19 16:19:18 2003 From: aahz at pythoncraft.com (Aahz) Date: 19 Mar 2003 16:19:18 -0500 Subject: Multiple simultaneous Python interpreters References: <3E78C112.48015ABE@engcorp.com> Message-ID: In article , White Flame \(aka David Holz\) wrote: >"Peter Hansen" wrote in message >news:3E78C112.48015ABE at engcorp.com... >> >> Perhaps you're overestimating your need for independence in the multiple >> instances? Have you considered whether that's absolutely necessary for >> your design? > >Yes, it is absolutely necessary. Independence is crucial for the >ability to kill off and clean up a runaway script (ie, one that is >adding elements to a dictionary in an infinite loop) without taking >down the application or other simultaneously running scripts. Plus, >various interpreters should have different import functionality >available to them, giving various "sandbox" models. These are 2 >fundamental points to the design. Then you definitely want multiple processes. It's too easy to hang a Python interpreter with unsafe code. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Register for PyCon now! http://www.python.org/pycon/reg.html From yngwiie at developer.bg Sat Mar 22 20:13:09 2003 From: yngwiie at developer.bg (Ivan Georgiev) Date: Sun, 23 Mar 2003 03:13:09 +0200 Subject: String to int newbie question In-Reply-To: References: Message-ID: <200303230313.09900.yngwiie@developer.bg> Hallo Luka, I am a newbie as well, but still here is my view of the probl= em. I do not know what you are trying to do exactly, but if you know the max. number you are going ot get, then you know how many zeros you are going to have to add in the back conversion to string. if max is. 99999 then every other number would have to have that many zer as to conatin 5 chars. 00009 00099 00999 etc. So you can simply add as many zeros as you need in the back conversion. Regards: Ivan > On Sat, 22 Mar 2003 14:44:55 +0100, Rene Pijlman wrote: > > Boris Genz: > >>I want to convert a number string ( '3211' for example ) to a number, ( > >>actually integer ) preserving the original number > > > > Is there any other way? > > > >>( the exact number being string and integer ) > > > > Que? > > > >>but if my number string starts with one or more zeroes, then the numbers > >>won't be same... > > > > Yes they will. '0027' and '027' both convert to 27. > > > >>For example, if I have string = '0027' then int(string) would give 27. > >>How can I add leading zeroes to that number? > > > > By not converting it to an integer. It already had leading zeroes before > > you converted it :-) > > > > 0027 == 027 == 27 > > Ok, I proabably haven't been clear enough. Here is what I really want to > do: I have a list of strings ( the content of strings are actually > numbers ), for example I have the following list: ['4312', '7599', > '0724', '0003']. The things I need to do is to change the strings inside > the list to integers and then write the list to a file ( I know how to do > the latter:). The problem is, if I change it with > int(my_string_inside_the_list) I won't get the same numbers, and I need > to have the content of the string and integer the same. So, after the > conversion of that list, what I want to have is: [4312, 7599, 0724, 0003] > and NOT [4312, 7599, 724, 3]. > Can you solve my problem? > Your help will be appreciated. > Thank you From jorgencederberg at hotmail.com Thu Mar 20 02:25:13 2003 From: jorgencederberg at hotmail.com (=?ISO-8859-1?Q?J=F8rgen_Cederberg?=) Date: Thu, 20 Mar 2003 08:25:13 +0100 Subject: Novice needs help with py2exe References: Message-ID: <3E796CD9.30106@hotmail.com> Matthew wrote: > Been there, done that, and didn't understand it. Please remember, I am a > total novice. On Hellers page for example he says run > python setup.py py2exe.py --help and I received the error stated below > in my original post. There *is no* setup.py in the py2exe diectory. A > few simple guidelines would be greatly appreciated. Thanks, matthew. Go to http://starship.python.net/crew/theller/py2exe/ once again. Scroll down to the "Using py2exe" section. This basically says that you must create a setup.py file to put in the directory of your _own_ module. First off, create a setup.py file similar to the one mentioned in the section. Assuming your paths are setup correctly you should be able to something like: d:\matthew\apps\python setup.py py2xe (where d:\matthew\apps is the path to your application) The resulting exe file is placed in the directory d:\matthew\apps\dist\applicationname You should distribute the complete directory. Hope this helps. J?rgen Cederberg From Kasper.Souren at ircam.fr Mon Mar 3 21:32:59 2003 From: Kasper.Souren at ircam.fr (Kasper Souren) Date: Tue, 4 Mar 2003 03:32:59 +0100 Subject: embedding Python in Python Message-ID: <200303040332.59660.Kasper.Souren@ircam.fr> Hi, Maybe this has been done or asked before, but with Google I couldn't find anything about it. I want to make an interface from TeXmacs to Python (and later IPython). I translated the C++ example (mycas.cc) into mycas.py and it works fine. But now I want to embed (..or call it what you like..) a Python interpreter in mycas.py. Thus I would like to be able to write something like: py_interpreter_instance = Python_Embedded_Interpreter() output_string = py_interpreter_instance.execute(command_string) or py_stdout, py_stderr = py_interpreter instance.execute(command_string) I took a look at IPython's code, which implements something similar. It works by trapping the stdout and stderr, but I hope that there is a nicer way to do this... I wouldn't mind writing the Python_Embedded_Interpreter class myself. I played with the idea of simply using eval() but eval("print") doesn't even work as expected. bye, Kasper From 'tert at pncen.hf'.decode Thu Mar 6 20:35:02 2003 From: 'tert at pncen.hf'.decode (Greg Krohn ('rot-13')) Date: Thu, 6 Mar 2003 19:35:02 -0600 Subject: Parsing Search Criteria References: Message-ID: "Alex Martelli" wrote in message news:veQ9a.22161$zo2.646805 at news2.tin.it... > >>>> parse_criteria('parrot "I like Python." ternary operator trouble') > > ['I like Python.', 'parrot', 'ternary', 'operator', 'trouble'] > > I'm confused by the strange ordering you specify in this example. > Without strange reordering, here's how I'd do it: The order has no significance. It's that way, only because I pulled the quoted words out first, then dealt with the other words. > import tokenize, cStringIO > def parse_criteria(criteria): > rl = cStringIO.StringIO(criteria).readline > return [ t[1] for t in tokenize.generate_tokens(rl) if t[0] ] Perfect! Now I just need to go read the tokenize docs. Thank you, greg From jonparkinson at hotmail.com Sat Mar 22 03:07:34 2003 From: jonparkinson at hotmail.com (Jon) Date: 22 Mar 2003 00:07:34 -0800 Subject: Erratic import behavior Message-ID: I've been butting my head against this one all day. I'm learning how to use COM in Python and all the examples I've seen look something like: from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") This has worked great for me in PythonWin, but when I run the exact same program from command prompt I get a python.exe Application Error. I've figured out another way of doing it that works for both: import win32com, win32com.client xlApp = win32com.client.Dispatch("Excel.Application") What I would like to know is why is there a difference in behavior between running my code in PythonWin and running it from the command prompt? Any help would be much appreciated. I'm just starting out on a big project and hate to have doubts about how everything is working (or not working) right at the beginning. From staschuk at telusplanet.net Tue Mar 11 14:25:02 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 11 Mar 2003 12:25:02 -0700 Subject: A possible lazy evaluation system? In-Reply-To: <7h3d6kynhp6.fsf@pc150.maths.bris.ac.uk>; from mwh@python.net on Tue, Mar 11, 2003 at 01:46:03PM +0000 References: <7h3d6kynhp6.fsf@pc150.maths.bris.ac.uk> Message-ID: <20030311122502.C2401@tibia.amotlpaa.bogus> Quoth Michael Hudson: [...] > Two problems spring to mind: at compile you don't know whether the > callable evaluates all it arguments or not. I can't really see a sane > implementation strategy, though where there's a will there's no doubt > a way. Perhaps not what you'd call sane, but you could have all arguments to all callables passed as lambdas; the generated code for normal functions would immediately call them and proceed as before. Unfortunately this makes the weird case possible at the expense of the normal case. -- Steven Taschuk "The world will end if you get this wrong." staschuk at telusplanet.net (Brian Kernighan and Lorrinda Cherry, "Typesetting Mathematics -- User's Guide") From tjreedy at udel.edu Fri Mar 28 16:07:47 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Mar 2003 16:07:47 -0500 Subject: Metaphors and politics (was: Prime number algo...) References: <1MudnTyOEK1mauGjXTWcqg@speakeasy.net> <3E835DC2.3678BD7F@engcorp.com> Message-ID: "Lulu of the Lotus-Eaters" wrote in message news:mailman.1048875737.24642.python-list at python.org... > As a rule, the anti-war folks--as well as being generally better > educated on geography, history, and the like You mean like the 'anti-war' leaders who praise the thugs ruling North Korea? Perhaps you should visit Iraq and talk to the people like certain ex-anti-war folks did " In a dispatch from Amman, Jordan, distributed by UPI and published in the Washington Times on March 23, veteran foreign correspondent Arnaud de Borchgrave reported that a group of Americans who had joined a delegation of Japanese "human shields" in Iraq had changed their minds and fled the country with 14 hours of videotaped interviews with Iraqis who hoped the Coalition forces would be their liberators. The spokesman for the group, the Rev. Kenneth Joseph, a pastor of the Assyrian Church of the East, an ancient Christian church that has a substantial membership in the United States, told de Borchgrave that his trip to Iraq "had shocked me back to reality." He said that his talks with Iraqis convinced him that Saddam is "a monster the likes of which the world had not seen since Stalin and Hitler. He and his sons are sick sadists. Their tales of slow torture and killing made me ill, such as people put in a huge shredder for plastic products, feet first so [the torture masters] could hear their screams as bodies got chewed up from foot to head." He told de Borchgrave that some of the Iraqis he had interviewed on camera told him they would commit suicide if the American bombing didn 't start and that they were willing to see their homes destroyed if it would free them from Saddam's bloody tyranny. The Rev. Joseph and his group were not the only would-be human shields who changed their minds after hearing what Iraqi civilians had to say about Saddam. Daniel Pepper, a 23-year-old Jewish American living in London who had traveled in the Middle East as a student and a photographer for Newsweek, went to Iraq on Jan. 25 with a group that intended to serve as human shields to call attention to the anti-war movement. He wrote about his experience in the London Telegraph on March 23. He said, "The human shields appealed to my anti-war stance, but by the time I had left Baghdad five weeks later my views had changed drastically. I wouldn't say that I was exactly pro-war. No, I am ambivalent, but I have a strong desire to see Saddam removed. I was shocked when I first met a pro-war Iraqi in Baghdad - a taxi driver taking me back to my hotel late at night. I explained that I was American and said, as we shields always did, 'Bush bad, war bad, Iraq good.' He looked at me with an expression of incredulity. "He slowed down and started to speak in broken English about the evils of Saddam's regime. Until then I had only heard the president spoken of with respect, but now this guy was telling me how all of Iraq's oil money went into Saddam's pocket and that if you opposed him politically he would kill your whole family. It scared the hell out of me. ... I had read reports that Iraqis hated Saddam Hussein, but this was the real thing. Someone had explained it to me face to face. ... I became increasingly concerned about the way the Iraqi regime was restricting the movement of the shields, so a few days later I left Baghdad for Jordan by taxi with five others." Safely over the border, they asked the driver "what he felt about the regime and the threat of an aerial bombardment." He surprised them, saying: "The Americans don't want to bomb civilians. They want to bomb the government and Saddam's palaces. We want America to bomb Saddam. All Iraqi people want this war." He was convinced that Saddam had paid them to come to Iraq. Pepper concluded his article saying, "Anyone with half a brain must see that Saddam has to be taken out. It is extraordinarily ironic that the anti-war protesters are marching to defend a government which stops people from exercising that freedom " Or perhaps we should stick to Python and leave geopolitical disagreements aside. Terry J. Reedy From sismex01 at hebmex.com Tue Mar 4 15:15:23 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 4 Mar 2003 14:15:23 -0600 Subject: Converting SQL Server data types. Message-ID: > From: Gerhard H?ring [mailto:gerhard.haering at gmx.de] > Sent: Tuesday, March 04, 2003 2:16 PM > > sismex01 at hebmex.com wrote: > > Hello yalls :-) > > > > I've a problem. When running some database queries and > > formatting results, I found that some columns are type > > "money", and these arrive as a tuple of integers, > > as this: > > > > (0, 1364570710) > > Strange. Which database module is this that you're using? > > > > > when it should in fact read as: > > > > 136457.0710 > > > > So... how do I convert from type MONEY to type FLOAT, > > inside python? I wouldn't want to have to modify the > > dbase side, but if there's no other way I'll do it > > (rather than do 200+ reports by hand, again...) > > If t is the tuple, t[1] * 10000.0 will work for this > particular sample > tuple. > > -- Gerhard argh... another victim of not seeing the trees for the leaves... :-P I'm accessing the database directly v?a win32com.client.Dispatch using ADODB.Connection objects. Hmmm... it seems that I need to check my results better... and get eyeglasses, maybe. :-) Thanks Gerhard. -gustavo From bdesth at removethis.free.fr Fri Mar 7 23:04:14 2003 From: bdesth at removethis.free.fr (laotseu) Date: Fri, 07 Mar 2003 23:04:14 -0500 Subject: How does Python compare with RealBasic? References: Message-ID: <3E696BBE.10109@removethis.free.fr> Markus Winter wrote: > Hi all, > > I've just started programming in RealBasic and now came across Python > (mainly because a molecular visualisation app I'm interested in is using > Python as it's script language). I intend to write my first program (a DNA > sequence analysis program) and wondered how Python compares to RB ... > > Thanks for any advice. > > Best Regards > > Markus > RealBasic is real cool tool for fast GUI apps (really...). But the language by itself is a bit limited compared to Python - limited OO support, lack of dynamism, no functionnal possibility... Well, it's a pretty good basic, but still a basic !-) I don't know much about DNA sequence analysis, but I guess you'll find Python a better choice for this kind of stuff. my 2 cents... Laotseu From mis6 at pitt.edu Tue Mar 11 15:03:46 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 11 Mar 2003 12:03:46 -0800 Subject: Can __iter__ be used as a classmethod? References: <3e649aa3_4@news.bluewin.ch> <2259b0e2.0303041023.43e8b81f@posting.google.com> <4B89a.6715$zo2.218162@news2.tin.it> Message-ID: <2259b0e2.0303111203.3b8147ae@posting.google.com> Thomas Heller wrote in message news:.. > > Maybe 'classmethod' is as weird as what some people aks for in this > forum (and they are overly happy if I point out that it is indeed > possible, while the 'right' answer would probably be 'you don't want to > desing your program in this way'): Have a method that binds to the class > if called from the class, and binds to the instance if called from an > instance. > > > > > > And _having_ to write a custom metaclass as the > > > only way to get classmethods would be somewhat of an overkill. > > While Guido doesn't like this notation, I actually find it nice: > > class MyClass(object): > > class __metaclass__(type): > > def my_class_methods(cls): > ..... > > def my_normal_method(self): > .... > > (Donald Beaudry had a similar notation in his objectmodule.c, which > also provided class methods). > > Thomas I have used that trick few days ago to define Frozen classes: def frozen(self,name,value): if hasattr(self,name): object.__setattr__(self,name,value) # standard __setattr__ else: raise AttributeError("You cannot add attributes to %s" % self) class Frozen(object): """Subclasses of Frozen are frozen, i.e. it is impossible to add new attributes to them and their instances, except via inheritance""" __setattr__ = frozen class __metaclass__(type): __setattr__ = frozen This kills Python dynamism. Also, it become impossible to use the self.var=something idiom, and one is forced to write code as in a static compiled language. It protects your code against run-time modifications (unless one overrides __setattr__). Michele From ark at gmx.net Sun Mar 16 03:17:02 2003 From: ark at gmx.net (Arne Koewing) Date: Sun, 16 Mar 2003 09:17:02 +0100 Subject: generators and exceptions References: Message-ID: "Clark C. Evans" writes: > Anyway, this _only_ prints out 4, instead of 4, 2 > as I expected. I expect 4, 2 beacuse an equivalent > iterator would produce 4, 2. It seems that generators > die on the first exception... is there a way around > this? I'm asking beacuse I'm using generators in a > non-blocking database system, where I want to raise > WouldBlock in my generator, but still be able to > call the generator at a later time when it may > not block... you may build your own object handling the iterator protocol, that wraps up your generator: from __future__ import generators class MyExc(Exception): pass def mygen(val): while val >= 0: if val % 2: yield MyExc() #yield it don't raise else: yield val val = val - 1 class handler: def __init__(self,itr): self.iterator=itr def __getitem__(self,index): val=self.iterator.next() if isinstance(val,Exception): raise val return val iterator = iter(handler(mygen(4))) while 1: try: val = iterator.next() print val except MyExc: print 'catched' except StopIteration: break From me at privacy.net Tue Mar 11 16:59:17 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Wed, 12 Mar 2003 10:59:17 +1300 Subject: IndentationError: two many levels of indentation In-Reply-To: References: <3E685D44.FDD5A810@alcyone.com> Message-ID: Alex Martelli wrote: > Removing the limit altogether ... might be > achieved by turning those arrays into dynamically resized ones, Use a Python list object! Probably the reason it doesn't already do that is because Guido wrote the tokeniser before any of the rest of Python existed. Hmmm... isn't someone working on rewriting parts of the core in Python? That might make the problem go away, too. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From member16943 at dbforums.com Fri Mar 7 01:14:33 2003 From: member16943 at dbforums.com (Tetsuo) Date: Fri, 07 Mar 2003 06:14:33 +0000 Subject: This sucks. Message-ID: <2614138.1047017673@dbforums.com> No matter how much I look at my code, I can't see how 0>=10. I fixed a few things today, but the program still beyond fails. Here's a link to the program: http://hoverboarder.tripod.com/base.txt Here's the algorithm I used: http://www.ca-osi.com/article.php?sid=429 -- Posted via http://dbforums.com From me at privacy.net Mon Mar 24 18:30:00 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 25 Mar 2003 11:30:00 +1200 Subject: A bit fun with Python In-Reply-To: References: Message-ID: Ulrich Petri wrote: > how does this script: > ------------------ > re.fork("this works") > print sys.compile > ------------------ > produce that output: > > ------------------ > this works > posix > ------------------ Um... it doesn't, for me -- it produces Traceback (most recent call last): File "foo.py", line 1, in ? re.fork("this works") NameError: name 're' is not defined If I add some import statements, it produces Traceback (most recent call last): File "foo2.py", line 2, in ? re.fork("this works") AttributeError: 'module' object has no attribute 'fork' Are you sure you ran it using the Python interpreter, and not something else? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From me at privacy.net Wed Mar 12 17:41:33 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Thu, 13 Mar 2003 11:41:33 +1300 Subject: Can __iter__ be used as a classmethod? In-Reply-To: References: <3e649aa3_4@news.bluewin.ch> <2259b0e2.0303041023.43e8b81f@posting.google.com> <4B89a.6715$zo2.218162@news2.tin.it> Message-ID: Alex Martelli wrote: > what happens if you're multiply inheriting from > a class C and a class D and both have class methods? Should > we have a FURTHER custom metaclass generated then? Magic > gets blacker and blacker... Hmmm, I hadn't considered that. You're right, it could get messy. (Smalltalk avoids this problem by not having multiple inheritance. :-) > What do you find so horrible with classmethod as it stands > that would come close to justifying such an excursion into > exhoterism in order to get rid of it? I don't find them horrible, I was just exploring whether it was redundant or nearly so, given the metaclass mechanism. It seemed as though the only extra thing it gave you was the ability to call class methods through an instance, which didn't seem startlingly useful to me. But I can see now that it is better behaved in the face of multiple inheritance, which is probably a pretty good justification! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From max at alcyone.com Thu Mar 6 02:52:26 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 05 Mar 2003 23:52:26 -0800 Subject: range References: Message-ID: <3E66FE3A.CAFD4D0C@alcyone.com> Hilbert wrote: > Why does range(1,4,1) return [1,2,3]? > It does not make sense at all. > It should return [1,2,3,4]. help(range) It counts up to but not including the stop number. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ The only way to get rid of a temptation is to yield to it. \__/ Oscar Wilde Alcyone Systems / http://www.alcyone.com/ Alcyone Systems, San Jose, California. From max at alcyone.com Wed Mar 19 17:23:29 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 19 Mar 2003 14:23:29 -0800 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 17) References: Message-ID: <3E78EDE1.961DEAF5@alcyone.com> mcherm at mcherm.com wrote: > I agree that normality is usually considered a property of irrational > numbers (which I think the original poster may NOT have realized) but > if we DO extend it to the rational realm, then I had assumed that all > rationals would be non-normal in all bases. But it turns out that it's > not quite so easy, since some rational numbers have multiple valid > decimal expansions. But I think it's safe to say that when that happens, none of those valid base-b expansions will be normal. They'll still be terminating or repeating, which by definition means they can't be normal. It seems like I'm just being anal, but normality is intimately tied with the notion of irrationality. The definition of b-normality states that for a decimal expansion in base b, every b-digit sequence of length k will appear with the expected frequency. This can't possibly be the case for an expansion which terminates or repeats, because even if the repeating portion is very long, there must be some (in fact, an infinite number) of sequences that don't appear anywhere at all in the expansion. This can be seen by trying to construct such a number; the logical result is to create Champernowne's constant in base b (C_b), which is irrational. If it repeats, then some sequences _must_ be left out. (Furthermore, there is some K such that no sequences of length k >= K appear _anywhere_ in the expansion.) > If you define normality by including all the > digits > of all the valid decimal expansions, then integers are normal in base > 2. I doubt that's a USEFUL result, but it's certainly a curious one. But in mathematics, when you're talking about something, even if it's not unique, you don't consider all the different non-unique forms simultaneously; you don't treat them as a superposition of states, you treat each state individually. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Patriotism is the virtue of the vicious. \__/ Oscar Wilde Bosskey.net: Counter-Strike / http://www.bosskey.net/cs/ A personal guide to Counter-Strike. From evan at 4-am.com Fri Mar 7 16:06:59 2003 From: evan at 4-am.com (Evan Simpson) Date: Fri, 07 Mar 2003 15:06:59 -0600 Subject: tal template engine in python out of zope In-Reply-To: References: Message-ID: <3E6909F3.1040705@4-am.com> Antonio.P wrote: > I am looking for an implemetation of the zope "tal" template engine but out > of zope. One of the following may do what you want: http://savannah.nongnu.org/projects/opental/ http://www.owlfish.com/software/simpleTAL/ It is possible to separate the Zope implementation of Page Templates from the rest of Zope, but not trivial (see the Zope mailing list). Cheers, Evan @ 4-am From peter at engcorp.com Sat Mar 29 07:59:21 2003 From: peter at engcorp.com (Peter) Date: Sat, 29 Mar 2003 07:59:21 -0500 Subject: looking for 'coding standard rules' for Python References: Message-ID: <3E8598A9.F800178E@engcorp.com> "Martin v. L?wis" wrote: > > skalpp at wanadoo.fr (skalpinet) writes: > > > Industrial applications need to be written with standard rules. > > By this way, code is more explicit, and changes become easier. > > I think that's a good way to learn a new langage, too. > > I have to teach Python and write a 'coding guideline' for it. > > > > If you understand my bad english, any help is welcome... > > You may want to look at PEP 8, > > http://www.python.org/peps/pep-0008.html And after reading that, consider some aspects of Twisted's coding standard at http://www.twistedmatrix.com/documents/howto/coding-standard -Peter From peter at engcorp.com Thu Mar 20 08:40:53 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Mar 2003 08:40:53 -0500 Subject: Unittests and external data.... References: Message-ID: <3E79C4E5.FB0C16D0@engcorp.com> Mike Meyer wrote: > > While I'm really fond of unit tests, I keep running into problems of > their needing more framework than can easily be captured in the > unittest module. > > For instance, I'm working on a project to interface a data source to > an SQL database. Doing unit tests properly means I need to have > multiple different versions of the source around, or I need to modify > it on the fly. Neither of those is really very practical. Why do you think changing it on the fly is not "very practical"? In Python, it's eminently practical, and extremely easy and effective. We do it all the time (not with SQL databases mind you, but with much hairier beasts) and don't have a problem with it. Multiple versions of source could be "practical", but it's a Very Bad Idea as far as unit-testing and TDD go... far too high a risk that you aren't testing the right thing, or that the manual maintenance that's required will produce out-of-sync versions. Don't go there. > Dealing with the SQL side of things is possible, so long as I start > with an empty database for the suite. I recall a number of threads in the testdrivendevelopment mailing list John Roth referred to which talked about just this point. They generally considered it the Right Thing to do to start with an empty database. The test setUp() would populate the database with the necessary data and the test would run with it, then it would be torn down for the next test. If this is possible for you, why not just go with what works? > Anyone have any thoughts on how I might better deal with things like > the source being external to the program? The mock object suggestions are good as well, although it's always a good idea to consider whether you can easily avoid them, for obvious reasons. If you go that route though, Python makes it so easy to do that I'm still pleasantly surprised every time we do it... -Peter From erez at actona.com Tue Mar 4 04:01:02 2003 From: erez at actona.com (erez) Date: 4 Mar 2003 01:01:02 -0800 Subject: Expect on window (from python script) References: Message-ID: eddie at holyrood.ed.ac.uk (Eddie Corns) wrote in message news:... > eddie at holyrood.ed.ac.uk (Eddie Corns) writes: > > >enough and maybe sending 'tester\n' might work. I think a telnet client is > Duh, I meant 'tester\r' of course, the CR vs LF vs CRLF issue. > >Eddie I tried to do so (sending the \r OR \n OR \r\n ) but it did not work, So what i can get till now is that i need to give up for the Expect module for python ??? (it's pitty, because the pexpect module, seams to me like very comfortable Expect implementation) Thanks, Erez From jepler at unpythonic.net Thu Mar 13 12:58:26 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 13 Mar 2003 11:58:26 -0600 Subject: Tkinter callback problem In-Reply-To: <5b6217b0.0303130918.5409b763@posting.google.com> References: <5b6217b0.0303130918.5409b763@posting.google.com> Message-ID: <20030313175826.GC3471@unpythonic.net> It's likely to be relevant which version of Tk you are using. Historically not all fields applied to all events, but Tk would still cheerfully substitute a meaningless decimal for all fields anyway. If they've tightened this up, it's a pity, because it will add complicated logic to Tkinter. Jeff From max at alcyone.com Thu Mar 20 18:49:13 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 20 Mar 2003 15:49:13 -0800 Subject: Is Python the Esperanto of programming languages? References: <200303192233.30383.andy@wild-flower.co.uk> <3E7908A7.CCEF27E8@alcyone.com> <20030319194019.B6746@localhost.localdomain> Message-ID: <3E7A5379.187C8CC6@alcyone.com> Andy Jewell wrote: > 2) What film was that? Really - I didn't know there *was* a film > which > featured Esperanto. That's probably because it starred William > Shatner... It was a movie made in 1965 called _Incubus_. The film has a Web site: http://www.incubusthefilm.com/ It's a black-and-white horror movie, and all the dialogue is in Esperanto, although the pronunciation is atrocious. The prints were thought lost, but evidently a copy was found playing in French theatres in a Rocky Horror Picture Show style showing. It was cleaned up and released on VHS and DVD. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Morality is a weakness of the mind. \__/ Arthur Rimbaud Blackgirl International / http://www.blackgirl.org/ The Internet resource for black women. From durdn at yahoo.it.oops!.invalid Sat Mar 22 07:19:53 2003 From: durdn at yahoo.it.oops!.invalid (Nicola Paolucci) Date: Sat, 22 Mar 2003 12:19:53 GMT Subject: a regular expression question In-Reply-To: References: <577e43a1.0303212331.5eaf93e5@posting.google.com> Message-ID: All, Nicola Paolucci wrote: >> If I use re2, it works, but obviously only gets the odds since there >> is no overlapping. Is there a way to modify re1 to get the text, or >> is there a way to overlap with python's re engine somehow? >> > This worked for me: > >>> re1 = re.compile("]+>([0-9]+?)([^<]*)") > >>> print re.findall(re1,text) > [('1', ' abc '), ('2', ' def '), ('3', ' ghi '), ('4', ' jkl')] I deeply apologyze for the multiple posts. My Mozilla just went crazy ... ciao, Nick From member16943 at dbforums.com Wed Mar 12 12:39:07 2003 From: member16943 at dbforums.com (Tetsuo) Date: Wed, 12 Mar 2003 17:39:07 +0000 Subject: I don't understand PEP 308. Message-ID: <2635252.1047490747@dbforums.com> I saw there's a debate over it, and decided to read it. I didn't read much, but what I can understand is that it proposes an if-then statement. So how is it different from what's there already? You know... if a == abs(g): ...print "a = abs(" + str(g) + ")" else: ...print zlib.compress(str(locals()) -- Posted via http://dbforums.com From alex_nanou at pochtamt.ru Sat Mar 8 18:20:32 2003 From: alex_nanou at pochtamt.ru (Alex A. Naanou) Date: 8 Mar 2003 15:20:32 -0800 Subject: Bug or wart? You make the call. References: <2e363c08.0303051256.58c94b08@posting.google.com> <20030307180524.GF9018@siliconimage.com> <6uacncnXWbVfu_ejXTWcpQ@comcast.com> Message-ID: I stand corrected (that was a bit hasty of me :) ) Thanks Terry. here is the *error free* version of the code from my last post: ---cut--- class X(object): def meth(self):pass x = X() # the ways to go in the current state: # proposed above: X.__dict__['meth'].attr1 = 1 # another way that works: x.meth.__setattr__('attr2', 2) X.meth.__setattr__('attr3', 3) print x.meth.attr0, x.meth.attr1, x.meth.attr2, x.meth.attr3 # will print "0 1 2 3" # so why not make this work as well: ## x.meth.attr4 = 4 ---uncut--- Best Regards... Alex. From mertz at gnosis.cx Sat Mar 22 21:17:23 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sat, 22 Mar 2003 21:17:23 -0500 Subject: Incomparable abominations References: Message-ID: "Tim Peters" wrote previously: |Python's comparison sometimes resorts to comparing objects' memory |addresses. The most notorious case of that is instances of a common |class I have no particular desire to have sorting work identically between platforms, versions, or even different interpreter runs. As I wrote before, I just want it consistent *within* an interpreter run. That is to say, I want the following function always to return True: def WantTrue(*l): m = list(l) n = list(l) m.sort() n.sort() return m == n My desire was fulfilled for Python 1.5.2 and every earlier version, btw (the only caveat I can think of is if the builtin 'list' was overridden). Python 2.0 broke the desideratum for the new Unicode objects (sometimes)[*]. Python 2.1 broke it worse for complex numbers. Yours, Lulu... [*] I'm not positive whether 1.6 has Unicode, actually. I don't have that version installed on my current system (only 1.5.1, 1.5.2, 2.0, 2.0-stackless, 2.1, 2.2.0, 2.2.2, 2.3a2, and Jython 2.0 :-)). -- mertz@ _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i gnosis _/_/ Postmodern Enterprises _/_/ s r .cx _/_/ MAKERS OF CHAOS.... _/_/ i u _/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/ g s From johanfo at ohman.no Mon Mar 10 11:03:11 2003 From: johanfo at ohman.no (Johan Fredrik Øhman) Date: Mon, 10 Mar 2003 17:03:11 +0100 Subject: SOAP problems References: <8jbe6v8r3o6k2sme0e4uja2r4n9fac56pj@4ax.com> <23891c90.0303060959.232c591a@posting.google.com> <7d6p6v4ukrgbkeh3p7misd9cs4pqf815jt@4ax.com> Message-ID: Be sure you need to use the soap protocol. The hours I spent with soap convinced me that is it quite a 'bloat'. Try to transfer a long array (i.e. 2000 entries) and you are in for an unpleasant surprise. It is extremely slow and inefficient. Check http://pyro.sourceforge.net/ for a much better alternative for Python - Python communication. -- JF? "Svenne Krap" wrote in message news:7d6p6v4ukrgbkeh3p7misd9cs4pqf815jt at 4ax.com... > How is this changed (ie. which files). > > I have soap.py, soap.pyc and soap.pyo ? > Isn't there something like libs should be compiled (I am on Windows) ? > > Futher help appriciated :) > > Svenne > > On 6 Mar 2003 09:59:55 -0800, paul at boddie.net (Paul Boddie) wrote: > > >Svenne Krap wrote in message news:<8jbe6v8r3o6k2sme0e4uja2r4n9fac56pj at 4ax.com>... > >> > >> I have installed PyXML and Soapy ( http://soapy.sf.net ) . > > > >[...] > > > >> File "C:\PROGRA~1\py222\soap.py", line 248, in load_namespaces > >> self.targetns = node.getAttributeNS('','targetNamespace') > > > >[...] > > > >> NamespaceErr: Use None instead of '' for empty namespace > >> > >> > >> What does I do wrong ? Is there any way to fix it ? > > > >I can imagine that Soapy was written to use the old convention of an > >empty string meaning "empty namespace", but in more recent releases of > >PyXML the convention is to use None for that purpose. As you can see > >from the error and from the line in the traceback that I've quoted, > >usage of '' with getAttributeNS (and probably other ...NS methods) is > >the cause. > > > >To fix it, I would suggest doing a search for calls of methods whose > >names end with NS and where the first argument is the empty string ('' > >and possibly ""). After testing, you might want to submit patches to > >the Soapy project on SourceForge, or the Python Web Services project > >if that's more appropriate. > > > >Good luck! > > > >Paul > > > >P.S. You could, of course, downgrade to an old PyXML release, but I > >wouldn't recommend that. > From andersjm at inbound.dk Sun Mar 2 18:42:16 2003 From: andersjm at inbound.dk (Anders J. Munch) Date: Mon, 3 Mar 2003 00:42:16 +0100 Subject: Why no RE match of A AND B? References: <3E6270DC.3060904@tiscali.co.uk> Message-ID: <_Fw8a.106840$Hl6.9851028@news010.worldonline.dk> "Rene Pijlman" wrote: > I take it this means: > > match(r1&r2,s) <==> match(r1,s) and match(r2,s) > > > I assume (without a formal prove at this point) that r1&r2 can > always be reformulated as a simpler expression, BIMBW. It can always be reformulated as an expression without an intersection ('&') operator. But not necessarily a simpler one. BIMBW? I've never understood either why the intersection operator is usually missing from regular expression implementations. Tradition? - Anders From tomchance at gmx.net Sun Mar 16 17:35:12 2003 From: tomchance at gmx.net (Tom Chance) Date: Sun, 16 Mar 2003 22:35:12 +0000 Subject: Closing pipes References: <1047787460.506561@yasure> <7k1da.66281$pG1.1537117@news1.tin.it> Message-ID: > Ah, brilliant, I've got Popen3 working, and I can get the pid. But for > some reason I can't kill the process! I've tried doing "kill(pid, > signal.SIGKILL)" and "kill(pid, 0)", but neither work. I've tried closing > the pipe first with "child.fromchild.close()", and then killing, and that > doesn't work either. Kill just fails to kill the process. > > Is there any reason/solution for this? Oh no, ignore me, it was killing the processes, and just leaving zombies in the process table which I've cleanedup with os.waitpid() :) Tom From peter at engcorp.com Thu Mar 20 06:45:17 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Mar 2003 06:45:17 -0500 Subject: comparing lists References: Message-ID: <3E79A9CD.8E8EE8EF@engcorp.com> Martin Franklin wrote: > > Enrique Palomo wrote: > > Hello all > > > > I must compare the contained of several directories in several pcs. Each > > directory must contain about 17000 files. > > > > Do you know any special method to compare the lists of listdir quickly? > > Enrique, > > Lists can be tested for equality with == but I suspect this is too > simplistic. > So my question is what exactly do you want to compare? Or perhaps, "what do you expect to happen as a result of the comparison"? I suspect he wants some kind of "diff" happening here... From bmunroe at tribador.nu Fri Mar 21 21:06:24 2003 From: bmunroe at tribador.nu (Brian Munroe) Date: Fri, 21 Mar 2003 18:06:24 -0800 Subject: minimum python for distribution on Windows In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org On Behalf Of Thomas Heller > > It should be added that for a minimum Python distribution, site should > probably be *not* imported. Apart from setting up some additional, site > specific sys.path entries, it adds stuff like pydoc (which includes > HTTPServer, IIRC). See the -S flag to Python. > > (I always wondered why freezing 'print "hello"' script needed the > HTTPServer stuff). > Ok, I give up! I thoroughly investigated the -S option for myself, verified, that yes (while running verbose) that -S really does work. BUT, if I run freeze on my program, I STILL see it freezing httplib, pydoc, etc. I've tried it by putting into the beginning of the script I want to freeze: #!/usr/bin/python -S I've tried it while running the freeze.py script: $ python /usr/local/lib/python2.2/Tools/freeze/freeze.py ../test.py Neither of those seem to have any effect. Any suggestions, or just get the cvs version of freeze? TIA, -- brian From sonicbit at hotmail.com Sat Mar 29 19:34:55 2003 From: sonicbit at hotmail.com (sonicbit) Date: 29 Mar 2003 16:34:55 -0800 Subject: use for jython? References: Message-ID: "William Sonna" wrote in message news:... > On Sat, 29 Mar 2003 13:59:36 +0100, A Nilsson wrote: > > > I am just curious: is there anyone using jython for a "real" project or > > is it just useful for quick-and-dirty java tests? > > > > Regards > > Anders Nilsson > > I don't do any "real" projects, I just write scripts. I also abstain from > Java vs. Python advocacy. They're apples and oranges as far as I'm > concerned. > > Nonetheless, I can assure you that Jython is not just a toy. It is a > well-written superset of Python that permits access to the Java libraries > with Python syntax. > > Whether it is more appropriate for Java or Python development is a question > you can only answer for yourself. There are commercial software companies that Jython in production software releases. One that comes to mind immediately is Intraspect (www.intraspect.com). Their complete API is writtin in Jython. From godoy at metalab.unc.edu Tue Mar 25 14:16:09 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Tue, 25 Mar 2003 16:16:09 -0300 Subject: Finding out the weekday Message-ID: <86adfjz286.fsf@ieee.org> Hi! Is there any Python module that given a particular date it returns me the day of the week? I'm needing it for some special calculations involving dates... See you, -- Godoy. From johnroth at ameritech.net Tue Mar 4 06:57:40 2003 From: johnroth at ameritech.net (John Roth) Date: Tue, 4 Mar 2003 06:57:40 -0500 Subject: code coverage tool References: Message-ID: "Alex Martelli" wrote in message news:HvZ8a.1938$pG1.51847 at news1.tin.it... > John Roth wrote: > ... > > My experiance with pyCover is that it is about a factor of three slower > > than running without it, so I'd expect the same slowdown, or somewhat > > more, > > for a threaded approach. For a coverage analyzer, that's not a > > significant > > problem for me. If you're trying to do volume testing, it could be > > prohibitive. > > Haven't tried pyCover, but I _have_ noticed the hotshot "profiler" has > all the hooks one needs to use it in a simple statement-coverage mode, > and it seems to have very low overhead when used that way; it's just a > question of interpreting its log files correctly, and, while not well > documented, there's even a module in the standard library to help out > with that task. Hmmm.... Actually, it doesn't. pyCover uses the debugger, not the profiler. The profiler only gives you function entry and exit, it doesn't allow you to check for things like not taking one path of a branch. This is rather obviously needed for statement (and branch) coverage tests. Also notice that neither one does threads automatically, which is what the OP wanted. John Roth > > > Alex > From roy at panix.com Sat Mar 29 20:34:12 2003 From: roy at panix.com (Roy Smith) Date: Sat, 29 Mar 2003 20:34:12 -0500 Subject: Best way to embed Python in a C++ app? Message-ID: I'm toying with the idea of embedding Python in an existing C++ application. As far as I can tell, there are three possible paths I could take. There's the raw API, there's SWIG, and there's boost.python. I've played with the first two a little over the years, but don't really know anything about boost beyond what little I've learned from reading the boost web site. It looks like I'm going to need to pass objects back and forth from C++ to Python, and (at least on the surface) boost looks like it can handle a lot of the messy details of this. On the other hand, I'm a little worried that it's still a bit of a work in progress. Anybody with experience in all three willing to offer a comparitive evaluation? Also, are there any alternatives that I've missed? From grante at visi.com Sat Mar 15 12:55:33 2003 From: grante at visi.com (Grant Edwards) Date: 15 Mar 2003 17:55:33 GMT Subject: Strange rounding problem References: <4378fa6f.0303141540.de857b8@posting.google.com> Message-ID: In article , Marc wrote: > But I didn't make a calculation to achieve this number. I entered it to be > an exact value. [...] > By I know that binary digits aren't incapable of holding exact numbers. Wrong. Partly. Some numbers that are exactly representable in base 10 are not exactly representble in base 2. For example, the number 0.1 (base 10) can't be exactly represented in base 2. Just like 0.1 (base 3) can't be exactly represented as a decimal value in base 10: it's 0.33333 (repeats forever). > If that were true, there wouldn't be an accurate computer in the world. There arent. When dealing with floating point, you must assume that _no_value_is_exact_. > So I still don't understand that if I enter a number to be an exact value of > .00000096, why it can't be stored as 9.60000000e-007? Becausing you entered it in base 10, and it's stored in base 2. Just because it's an exact value in base 10 it doesn't mean it can be represented exactly in base 2. -- Grant Edwards grante Yow! There's enough money at here to buy 5000 cans of visi.com Noodle-Roni! From ark at research.att.com Wed Mar 19 17:18:57 2003 From: ark at research.att.com (Andrew Koenig) Date: Wed, 19 Mar 2003 22:18:57 GMT Subject: Incomparable abominations (was: python-dev Summary) References: Message-ID: David> I completely DO NOT BUY Guido's point in the thread. The David> failure of The argument is sometimes made that it is a David> programming mistake to try to compare items of incomensurable David> types. Actually, the problem is somewhat worse than that, because at present, comparison between long integers and floating-point numbers is done by converting the integer to floating-point and comparing the converted result. One problem with this approach is that the conversion might fail. So, for example, [0.0,1L<<10000].sort() typically causes a run-time error. More subtle problems can occur because of loss of information in conversions. For example: >>> x = 10000000000000000000000000000000000 >>> y = x+1 >>> z = float(x) >>> x == z 1 >>> y == z 1 >>> x == y 0 See SF bug report #513866 for more detail. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From basu at mahiti.org Thu Mar 27 02:38:25 2003 From: basu at mahiti.org (Basalingamma) Date: Thu, 27 Mar 2003 13:08:25 +0530 (IST) Subject: xml and python Message-ID: <35474.192.168.0.232.1048750705.squirrel@192.168.0.254> hai, -- How can I generate xml by extracting Zope's ZCLASS instances properties using python. - ------------------------ Basalingamma, Volunteer, Mahiti Infotech Private Limited 314/1, Vijay Kiran, II Floor, 7th Cross, Domlur Layout, Domlur, Bangalore - 560 071 From Kyler at news.Lairds.org Thu Mar 27 09:23:03 2003 From: Kyler at news.Lairds.org (Kyler Laird) Date: Thu, 27 Mar 2003 14:23:03 GMT Subject: tuning our site (was: help! advocacy resources needed fast) References: <6igij-8sl.ln1@news.lairds.org> Message-ID: claird at lairds.com (Cameron Laird) writes: >Also, I don't believe *at >all* arguments about how Web designers need to work in >DTML; it would interest me a great deal to try to thrash >that out with someone who sees it differently. Are you baiting me? Yes, I still use DTML for forms that I know are going to be maintained by other people. With enough of the right "dtml-let" statements, it's usable. I could do just as well in Python using """ blocks. That would also allow me to avoid having to make a break to Python when the functionality required gets too much. So...I'm no longer willing to argue for DTML. I use it for historical reasons only. --kyler From imbosol-1048717795 at aerojockey.com Wed Mar 26 17:44:26 2003 From: imbosol-1048717795 at aerojockey.com (Carl Banks) Date: Wed, 26 Mar 2003 22:44:26 GMT Subject: Some basic questions References: Message-ID: Brian Christopher Robinson wrote: > Is there any way to write a boolean function? I wanted to write a simple > is_alpha function (which may be in the standard library but I'm leanring), > and this is what I came up with: > > def is_alpha(c) : > letters = re.compile("[a-zA-Z]") > return letters.match(c) > > Instead of checking for true or false I check to see if None is returned, > but that seems a little kludgy. The truth function from the operator module will do what you are asking for. Begining with Python 2.3, you can also use the bool builtin. Note that this is all unnecessary. The function will work as advertised without any such function, and without explicitly testing against None. This will work: if is_alpha(c): print "c is a letter!" else: print "c is not a letter." -- CARL BANKS From pmott at comp.leeds.ac.uk Thu Mar 13 08:20:44 2003 From: pmott at comp.leeds.ac.uk (Peter Mott) Date: Thu, 13 Mar 2003 13:20:44 GMT Subject: Upload of binary files References: <8b5e42a6.0303121653.6d452403@posting.google.com> <3e7050b4$0$49113$e4fe514c@news.xs4all.nl> Message-ID: OK - I've changed the code so it is now: #! C:/python22/python.exe import cgi import cgitb; cgitb.enable() form = cgi.FieldStorage() if form.has_key("Data"): fileinfo=form["Data"] read_in=0 iteration=0 while 1: chunk = fileinfo.file.read() if len(chunk) == 0: break read_in += len(chunk) iteration += 1 print "Content-type: text/plain\n\n" print "Bytes read:",read_in print "Read iterations",iteration With my Apache httpd.conf file I get: Bytes read: 36175 Read iterations 1 With a 3K gra.png file I get: Bytes read: 4 Read iterations 1 With a 66K JPEG file I get: Bytes read: 164 Read iterations 1 So plainly it is _not_ a question of chunked reads. The data is not being delivered. This experiment was with XP professional rather than W2K on a different machine. Python 2.3a2 behaves in the same way. Using Netscape 7 instead of IE6 makes no difference. I tried just using standard input: import sys read_in=0 iteration=0 while 1: chunk = sys.stdin.read() if len(chunk) == 0: break read_in += len(chunk) iteration += 1 print "Content-type: text/plain\n\n" print "Bytes read:",read_in print "Read iterations",iteration but the behaviour is exactly the same. The only thing that I have not tried is using a 'real' network rather than looping back with 127.0.0.1 which is about all I can think of. Running out of ideas .. Peter "Irmen de Jong" wrote in message news:3e7050b4$0$49113$e4fe514c at news.xs4all.nl... > Peter Mott wrote: > > if form.has_key("Data"): > > fileinfo=form["Data"] > > data = fileinfo.file.read() > > This won't do. It is not guaranteed that a single read() returns > all of your data. Rather, it is likely to return a chunk at a > time. So what you probably have to do is extract the Content-Length > and loop over a read() (appending the results) until you've > got a result that is the correct length. > > Irmen. > From BrenBarn at aol.com Mon Mar 10 11:33:41 2003 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 10 Mar 2003 16:33:41 GMT Subject: single-line terinary operators considered harmful References: <882b0a41.0303020225.3caf0334@posting.google.com> Message-ID: Clark C. Evans wrote: > After the select/case option presented previously, my second > best option would be something like... > > var = (if 1 == x: 'yes' > else: 'no') > > Where the 'else' must be in the same column as the > corresponding if. Personally I find this frightening. I don't like the idea of an indent level being defined by non-whitespace characters. Here, the "var = (" is defining the indent level for the else. This is, to me, a bad thing, because, if you just look at this line: var = (if 1 == x: 'yes' . . . it's not immediately obvious what the "correct" column is for the else. -- --OKB (not okblacke) "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From python at dylanreinhardt.com Wed Mar 12 18:09:35 2003 From: python at dylanreinhardt.com (Dylan Reinhardt) Date: Wed, 12 Mar 2003 15:09:35 -0800 Subject: Getting return value of another script (resolved) In-Reply-To: <5.1.1.6.0.20030312140452.02cf6828@pop3.spa.norton.antiviru s> References: <3E6F16FE.34F14EDC@engcorp.com> Message-ID: <5.1.1.6.0.20030312150740.01eabe30@pop3.spa.norton.antivirus> It's a proven fact... nothing helps you find the documentation you're looking for than admitting to a list that you can't find it. Just after I posted this question, I found popen3, which is exactly what I was looking for. Thanks, Dylan At 02:45 PM 3/12/2003, Dylan Reinhardt wrote: >Hi all, > >I'm trying to launch a shell script from Python, but I want to get the >actual output of the script, not just the shell's exit status. Unless I'm >missing something, it doesn't appear that os.exec* or os.spawn* return >anything but the exit status. > >I'm running this with Python 2.1.3 on Gentoo Linux. > >Thanks in advance for any tips, > >Dylan > > >-- >http://mail.python.org/mailman/listinfo/python-list > From dagurp at heimsnet.is Sat Mar 1 18:47:53 2003 From: dagurp at heimsnet.is (=?ISO-8859-1?Q?Dagur_P=E1ll_Ammendrup?=) Date: Sat, 01 Mar 2003 23:47:53 +0000 Subject: Code speedup tips In-Reply-To: References: Message-ID: <3E6146A9.30607@heimsnet.is> Hi If you haven't already, I recommend reading this: http://manatee.mojam.com/~skip/python/fastpython.html -Dagur From tismer at tismer.com Mon Mar 31 20:29:40 2003 From: tismer at tismer.com (Christian Tismer) Date: Tue, 01 Apr 2003 03:29:40 +0200 Subject: Ann: Stackless Perl 4.0 Message-ID: <3E88EB84.7090708@tismer.com> Dear Python/Perl Community, Insiders have known this from the beginning, and they were waiting for this to happen for much too long time: Stackless 3.0 has been dead-born from the beginning. The new live language is Stsckless Perl 5.0! This is not due to the nature of Stackless, it is due to the nature of Python. There is a better language than Python, and its name is PERL! Python has always been a recursively implemented language. Perl has been stackless from the very early days. My brain has always been thinking the Python way. But my heart always was beating the Perl rhythm & $blues. Now my time has come, and there is again A BIG CHANGE OF STACKLESS: Finally, after all the years of development, it became not only natural but also consequent, to abandon the very hard way of merging the principles of Stackless Python 1.0 and 2.0 into 3.0. Instead, I invented Stackless Perl 5.0. ================================================================ Stackless Perl 5.0 The implementation was incredibly simple. I just had to drop 95 percent of my C implementation for Stackless Python 3.0, change the object model, and to invent three new Perl objects. These are: stackless::tasklet (about 20 methods) stackless::channel (about 120 methods) stackless::continuation (about 4 methods) The latter is a re-incarnation of an old idea, which was most popular in many Scheme dialects, but seems to me most appropriate in the Stackless Perl context. There are now infinitely countable ways to express new ways to express new or existing control structures by Perl continuations. This is an incredible, outstanding feature, which clearly contradicts the Python "one size fits all" paradigm. Or was it "there is only one way to do it"? (What to do, at all?) Stackless Perl has Default UNIVERSAL methods, for example: isa(tasklet) isa returns true if its object is blessed into a subclass of tasklet isa is also exportable and can be called as a sub with two arguments. This allows the ability to check what a reference points to. Example use UNIVERSAL qw(isa); if(isa($ref, 'tasklet')) { #... } can(become) can check to see if its object has a method called become, if it does then a reference to the sub is returned, if it does not then undef is returned. And so on. The number of well-formed examples is so incredible large. Isn't that just great! ? Oh, I love it so much. Such a match! Another very relevant example is the solution to *all* existing PEP308 proposals: The stackless Perl dynamic syntax parser has been extended in a way that covers every possible PEP 308 alternative to implement ternary operators in a completely individual way: Every individual is now able to spell her/his own way of understanding the myriads of possible solutions to implement the different incarnations of $if expr $elif expr $else expr $endif Perl constructs and their relatives, in any imaginable and unimaginable perlish way. This is of course due to the radical use of continuations, together with dynamic syntax rules. I have to admit that this example code took me another two days, and three days of theoretically testing every thinkable implementation possible. There is no single way to say it. Just say it. 100 Python people will just say "say what?" or "ni!". 10000 Perl people will love and support my message. Messias, you did so absolutely right, finally! Isn't that amount of love and support worth a paradigm change? I'm very happy that I became converted to this remarkable language in such a short time. It took me only two days to do the whole implementation (that is, abandoning almost all of the code). I will spend the next six months doing the debugging, and the next 10 years doing the porting: I'm now happy to tell this to all my customers and sponsors: After having ported all your code from Stackless Python 1.0 to 2.0 and almost to 3.0, I now would like to be paid for porting your whole Python application to Stackless Perl 5.0. I know you are happy with this since you knew from the beginning, that this would be most effective in the first place. Sorry for messing with Python for all the years. This was a major design flaw, that I realized a few days before. This principle of very fast design changes makes Open Source so attractive to me. Downloads are avaliable here: http://stackless.apriperl.org This was a statement about Stackless Perl 5.0, just an intermediate step towards Stackless Perl 6.0, which will make use of the outstanding feature of white space overloading with continuations. This feature will be presented on the Python/Perl Integration marathon sprint session in August 2005 in Luxemburg. Please apply early, this is a really small country. BTW., can any knowleadgeable body please give me a crash course in Perl programming? I would like to be able to produce some testing code, but I didn't have the time to RTFM, yet. :-) cheers -- chris at stackless.apriperl.org p.s.: This message was intentionally not cross-posted, since most readers will be assimilated to the Perl community anyway, the sooner or later... -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From wsonna at attglobal.net Fri Mar 14 22:25:45 2003 From: wsonna at attglobal.net (William Sonna) Date: Fri, 14 Mar 2003 21:25:45 -0600 Subject: use of "self", was "No Do while/repeat until looping construct in python?" References: Message-ID: On Fri, 14 Mar 2003 13:20:53 -0500, Chermside, Michael wrote: >> On the other hand, if you have a valid reason why "self" is >> advantageous FROM THE USER's POINT OF VIEW I would like to hear it. > > I'm not sure I really believe you (about desiring to hear a reason why > "self" is advantageous), but I'll give it a shot anyhow. > > Consider the following Java snippet (sorry, I don't know Ruby well > enough to get the syntax right). > > public class MyClass extends ParentClass { > String accessId; > public MyClass(accessId) { > this.accessId = accessId; > } > public int overlyLongFunction() { > // Here goes 162 lines of messy code > return (jiggerPercent > 100) ? 100 : jiggerPercent; > } > } > } > In the last line of overlyLongFunction, we refer to the variable > "jiggerPercent". This could be either a local variable OR an instance > variabler... and there's no way to tell which one it is. Notice how the > constructor uses a common java idiom which makes use of this ambiguity. > > Yes, the constuctor is clear as can be. The rules in Java are also clear as can be, and evey bit as clear as the self in Python - local variables or function parameters overshadow instance variables of the same name. But I am not troubled at all by the enhanced clarity that self provides. What I am sick of is getting nailed by the interpreter for forgetting to add "self" to every lousy instance variable name - or even worse - having it treat my omission as a local variable. The mandatory self is itself a source of errors, and I believe based on my own experience that it creates more errors than it prevents. Call it a feature if you will, but my guess is that its an implementation requirement that has a side benefit for those who like mandatory qualification. > In Python, it would refer to either "jiggerPercent" or to > "self.jiggerPercent", and the reader would be immediately aware of which > was intended. (Note that Python values terseness for the sake of the > READER of the code, not because the WRITER of the code has lazy > fingers.) > > Of course, Python isn't perfect in this regard... it still has three > different namespaces (local, global, built-in) where the variable might > live, but at least it distinguishes the instance-variable namespace. > > The biggest problem I have personally found with name pollution is tracking hand-me-down names from base classes I know nothing about. Unfortunately, while "self" helps a tiny bit, it doesn't really solve THAT problem. > You can argue over whether you LIKE this feature, but it IS a > commonly-mentioned advantage of the use of self. Now you said that > "common sense says the instance variables are local", but I believe this > is a very odd use of the term of "common sense", given that instance > variables are _NOT_ the same as local variables... not in Python, in > Java, or in Ruby. Doesn't mean you have to like typing "self", but it IS > one good reason (among others) for requiring it. > > Instance variables are accessed identically to local variables within mehtods in virtually every other major programming language in use today. Wouldn't you call that common? The case of a name overload is usually deemed a *special* case, and as you pointed out in your example, the syntax of Java to resolve it couldn't be clearer. But enough with my sour grapes. Truth is, Python 2.2 is a MAJOR step in the direction of making Python into a full object-oriented language. Its the best Python yet, and hopefully 2.3 will be even better. And I will continue to hope "self" at someday cease to be mandatory. In the mean time, I'll keep makng the same dumb mistake over, and over, and over, and over, and over, and over, and over, ..... From amk at amk.ca Wed Mar 5 07:44:10 2003 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 05 Mar 2003 06:44:10 -0600 Subject: help! advocacy resources needed fast References: Message-ID: On Tue, 4 Mar 2003 15:06:04 -0800, Geoff Gerrietts wrote: > My current read is that Webware + Twisted, or mod_python + Twisted, > would be the "fastest" web server platform python supports. Does This is more anecdotal evidence, but Jon Corbet reported that SCGI provided a significant boost over mod_python. See http://mail.mems-exchange.org/pipermail/quixote-users/2003-February/001243.html and http://mail.mems-exchange.org/pipermail/quixote-users/2003-February/001248.html . --amk (www.amk.ca) Be vewy, vewy quiet. We're hunting Wippers. -- Alan Moore, in "Dance of the Gull-Catchers" in FROM HELL From james.kew at btinternet.com Sun Mar 9 04:57:53 2003 From: james.kew at btinternet.com (James Kew) Date: Sun, 9 Mar 2003 09:57:53 -0000 Subject: This sucks. References: <2614138.1047017673@dbforums.com> <3e6852fe$0$5550$afc38c87@news.optusnet.com.au> <2616488.1047057454@dbforums.com> <2619860.1047102300@dbforums.com> Message-ID: "Tetsuo" wrote in message news:2619860.1047102300 at dbforums.com... > > Originally posted by Steven Taschuk > > Am I the only person who is completely baffled by this comment? > > Yes. No. You read c.l.p through dbforums.com, which appears to be some form of newsgroup-to-web-forum gateway. To the majority of us who read c.l.p with a newsreader, or have an email subscription to python-list, talk of "forums" and "padlocks" is puzzling and meaningless. -- James Kew james.kew at btinternet.com From iko at cd.chalmers.se Tue Mar 25 18:37:12 2003 From: iko at cd.chalmers.se (Anders Hammarquist) Date: 25 Mar 2003 23:37:12 GMT Subject: Integer arithmetic References: Message-ID: In article , Daniel Timothy Bentley wrote: >Unless there's a function I'm missing that returns INT_MAX (as C >pronounces it) and I'm just supposed to mod it. >>> import sys >>> hex(sys.maxint) '0x7fffffff' HTH /Anders -- -- Of course I'm crazy, but that doesn't mean I'm wrong. Anders Hammarquist | iko at cd.chalmers.se Physics student, Chalmers University of Technology, | Hem: +46 31 88 48 50 G|teborg, Sweden. RADIO: SM6XMM and N2JGL | Mob: +46 707 27 86 87 From tvassila at siac.com Mon Mar 31 10:18:38 2003 From: tvassila at siac.com (Thanos Vassilakis) Date: Mon, 31 Mar 2003 10:18:38 -0500 Subject: Simple Python web development Message-ID: try: http://sourceforge.net/projects/pso/ see pso - A Users Guide and pso - Building a web service with pso in ten minutes ----------------------------------------- This message and its attachments may contain privileged and confidential information. If you are not the intended recipient(s), you are prohibited from printing, forwarding, saving or copying this email. If you have received this e-mail in error, please immediately notify the sender and delete this e-mail and its attachments from your computer. From antun at antunkarlovac.com Thu Mar 20 13:34:21 2003 From: antun at antunkarlovac.com (Antun Karlovac) Date: 20 Mar 2003 10:34:21 -0800 Subject: How to create a CDATA XML node Message-ID: How do I implement a CDATA node in Python? I'm using dom.minidom as follows:- impl = xml.dom.minidom.getDOMImplementation() doc = impl.createDocument( None, "element", None ) root = doc.documentElement Then I want to create my CDATA node. The reason I want a CDATA node is because I want to preserve all the HTML formatting tags (i.e. the

's here) in the text node:- longDescText = '

There will be more text here.

' longDescText = longDescText longDescNode = doc.createElement( 'longdescription' ) longDescTextNode = doc.createTextNode( longDescText ) longDescNode.appendChild( longDescTextNode ) root.appendChild( longDescNode ) I can't anything in either the docs, or the Python & XML O'Reilly book. Am I blind or summat? -Antun From belred1 at yahoo.com Sat Mar 22 20:32:13 2003 From: belred1 at yahoo.com (Bryan) Date: 22 Mar 2003 17:32:13 -0800 Subject: Defining Python class methods in C References: Message-ID: i found one of my problems: i was using METH_NOARGS for get_path. when i changed to METH_VARARGS my callback got called. but the self variable in context_get_path is NULL. so i can't get to the variables i stored in the context_object from the __init__ call. bryan ----- static PyMethodDef context_methods[] = { {"__init__", context_init, METH_VARARGS, "Create context"}, {"get_path", context_get_path, METH_VARARGS, "Get the path"}, {NULL, NULL, 0, NULL} }; static PyObject* context_get_path(PyObject *self, PyObject *args) { context_object *context_obj = (context_object*)self; wgagent_provider_context *ctx = NULL; PyObject *py_str_path = NULL; printf("context_get_path:"); if (self) { printf("self is not NULL"); else printf("self is NULL"); if (context_obj) { printf("context_obj"); sscanf(context_obj->context, "%p", &ctx); if (ctx) { py_str_path = PyString_FromString("c:\\test"); } } if (py_str_path) { return py_str_path; } else { Py_INCREF(Py_None); return Py_None; } } From noway at sorry.com Tue Mar 4 13:29:24 2003 From: noway at sorry.com (Giovanni Bajo) Date: Tue, 04 Mar 2003 18:29:24 GMT Subject: Can __iter__ be used as a classmethod? References: Message-ID: <8g69a.176850$YG2.5353209@twister1.libero.it> "Alex Martelli" ha scritto nel messaggio news:b42ev802l51 at enews4.newsguy.com... > Sure, let's -- no "classic classes" in the following (and, feel free > to switch the discussion to it.comp.lang == with [Python] at the start > of the subject == if discussing this in Italian will make it easier for > you... otherwise, keeping it on c.l.py does seem preferable). Is my english that bad? :) It's ok to keep it in here, thanks anyway for the offer. Your reply was pretty clear and exhaustive. I think the main problem is that I was thinking of iter(B()) as a different way of calling B().__iter__ (usually 'inherited' from B.__iter__), and not type(B).__iter__. Everything makes more sense now. I still have a small doubt by classmethod(). Let's consider this: class A: def f(cls): pass f = classmethod(f) def g(self): pass a = A() Now, in my current understanding, the differences between A.f and A.g are: 1) A.f() is a valid call (and the function will receive class A as parameter), while A.g() will raise a runtime exception (unbound method). A.g(a) is correct because it is equivalent to a.g(). 2) a.f() is a valid call (and the function will receive class A, aka type(a), as parameter); a.g() is a valid call as well, and the function will receive a as parameter Also, both are attributes of A and not of a. They can be used on a because they are automatically looked up on type(a), but they belong to A. Another source of confusion in my mind is that type(A.g) is called "instance method", because it must be bound to an instance of the class, to become 'callable'. But it does not 'belong' to the instance, it is actually defined in A.__dict__, not in A().__dict__. > > mean that rebinding B().__iter__ has no effect since B.__iter__ is always > > looked up when iterating over instances of B(), while B().f() can be > > freely rebound? > > It's not true that rebinding name '__iter__' on an instance has NO > effect -- Yes, it should have been 'has no effect with respect to iterating over B instances'. > it does affect calls DIRECTLY to thatinstance.__iter__, AND > iterations on INSTANCES of that instance (if, of course, that instance > is usable and gets used as a type. AKA class). But it has no effect > on ITERATIONS on that instance, or calls to iter(...) with that > instance as their argument. So, if I rebind B().__iter__, Python will use the rebound function when calling "for x in B().__iter__()" (assuming that 'B()' always refers to the same instance of course) but it will not change "for x in B", which is semantically the same of "for x in iter(B)", or "for x in type(B).__iter__()" (maybe modulo obscure situations that I can ignore for now). > [snip] > This > may help explain why inheritance is not transitive AND why the > operations and built-ins access special attributes on the TYPES > of their arguments, not on their arguments themselves. Yes, I understand very well why 'inheritance' cannot be transitive. By the way, it seems that the word 'inheritance' has been abused in this context: this is not the normal inheritance as in class A(B), but something different (A() will lookup attributes from A if they have not been rebound, and A will lookup attributes from A.__metaclass__ -- more generically, A will lookup attributes in type(A)). Is there a more correct word for this? 'meta-inheritance'? :) Thanks again for your time Giovanni Bajo From pmagwene at speakeasy.net Mon Mar 17 20:55:05 2003 From: pmagwene at speakeasy.net (Paul M) Date: Mon, 17 Mar 2003 20:55:05 -0500 Subject: Recommended Linux Laptops, suppliers? In-Reply-To: <5gnda.102064$zo2.2696240@news2.tin.it> References: <3e6a571b$1_1@spamkiller.newsgroups.com> <5gnda.102064$zo2.2696240@news2.tin.it> Message-ID: Alex Martelli wrote: > > Right. *MY* criteria are a bit simpler -- I need to be able to use my > notebook "comfortably" (relatively speaking...) to write and edit text > (program code, book chapters, articles, ...) while sitting in an > economy-class seat on an airplane. This rules out PDA's (screen too > small, not to mention keyboard issues -- so far I haven't found "fold > out" keyboards satisfactory) as well as behemoths with 14" or larger > screens (I have a nice Dell Inspiron but in practice I hardly ever > take it with me on trips -- too large, too heavy). If my old 12" screen, > 1.8 Kg Acer Travelmate 345T had a better battery life (it's just about > 3 hours' worth of useful work even with the most prudent use, alas), > I'd be looking no further. As things are, I daydream about ultralight > ultrathin fuel cells far more than I do about any other laptop issue;-). > > > Alex > Alex, You might check out the Fujitsu P series notebooks: http://webshop.fujitsupc.com/fpc/Ecommerce/buildseriesbean.do?series=P2 They've got usable keyboards and nice letterbox ratio displays along with DVD/CD+RW. I get about 4.5 hrs of use (non-DVD playing, screen brightness reduced a couple of notches) on the extended battery. All in about 3.5 lbs. I've been travelling A LOT the last 6 months and everytime I get on a plane or train I know I made the right decision as far as a notebook comptuer goes! --Paul From cce at clarkevans.com Tue Mar 4 20:16:32 2003 From: cce at clarkevans.com (Clark C. Evans) Date: Wed, 5 Mar 2003 01:16:32 +0000 Subject: Vote on PEP 308: Ternary Operator In-Reply-To: References: <882b0a41.0303020225.3caf0334@posting.google.com> <1046630521.114725@yasure> Message-ID: <20030305011632.GA57458@doublegemini.com> On Sun, Mar 02, 2003 at 09:30:03PM +0000, Dennis Reinhardt wrote: | 308 represents too much cruft. Most examples look good as one-liners with | short names. They do not look so good with longer names. Here is an | example: | | z_of_useful_length = 1.0 + (if abs(z_of_useful_length) < .0001: 0 else: | z_of_useful_length) | | The above long-name can be expressed in current Python in nearly the same | number of characters as | | if abs(z_of_useful_length) < .0001: | z_of_useful_length = 1.0 | else: | z_of_useful_length += 1.0 | | ... much more readable. Agreed. But I think you are throwing out the baby with the bathwater here. What is useful about the terinary operator is that for assignments it is clear that the lhs is uniform. z_of_useful_length = select abs(z_of_useful_length) case < .0001: 1.0 else: 1.0 + z_of_useful_length In this case it is clear that you are making an assignment with two choices. This syntax also extends nicely to facilitate more than one case. Clark From reageer.in at de.nieuwsgroep Sun Mar 2 08:04:34 2003 From: reageer.in at de.nieuwsgroep (Rene Pijlman) Date: Sun, 02 Mar 2003 14:04:34 +0100 Subject: Strange regex problem References: <33803989.0303020048.10c8fc09@posting.google.com> <3E61FC67.8070705@heimsnet.is> Message-ID: Dagur P?ll Ammendrup: >This code is enough to reproduce it for me: Yes, I see it to with Python 2.2.2 in WingIDE 1.1.7. While stepping through the code in the debugger, the output is produced by the following code in method Tokenizer.parse() in sre_parse.py: if flags & SRE_FLAG_DEBUG: p.dump() So it seems you are indeed running in debug mode. I don't know why though. -- Ren? Pijlman Wat wil jij leren? http://www.leren.nl From max at alcyone.com Wed Mar 19 16:21:30 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 19 Mar 2003 13:21:30 -0800 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 17) References: <7h3bs07ii9h.fsf@pc150.maths.bris.ac.uk> Message-ID: <3E78DF5A.6213186D@alcyone.com> Robin Becker wrote: > I assume absolute normality excludes the case where one expresses the > number in itself as a base or am I being more than usually stupid. When one talks about a number being b-normal, b is an integer. It's true that pi written in base pi is 10, but that's "cheating" in the sense that integral bases are usually what is intended when one is talking about writing numbers in different bases. > Also I suppose that being non-random implies finiteness (in some > sense) > so are we just talking 'symbol' count or information. After all there > are very small symbolic representations of pi, but are they smaller in > information content etc etc. No, non-random (in terms of non-normality) simply means that a number does not terminate or repeat (thus it is irrational), but that the distribution of digits (in whatever base(s) are being discussed) are not uniform. Digit expansions (in any base) have nothing to do with a number's symbolic representation; there are probably an infinite number of different symbolic representations for any number you can name, but the digit expansion in base b is unique (or, well, at least mostly unique, for cases like 0.999... = 1). -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Of all the perversions, chastity is the strangest. \__/ Anatole France Bosskey.net: Counter-Strike / http://www.bosskey.net/cs/ A personal guide to Counter-Strike. From Vector180W at netscape.net Mon Mar 17 21:37:51 2003 From: Vector180W at netscape.net (vector) Date: Tue, 18 Mar 2003 13:37:51 +1100 Subject: Pyserial,Docs, tutorials, line terminators Message-ID: <3E76867F.3080002@netscape.net> Im having alittle trouble with pyserial and cant seem to find the normal documentation and or tutorials for this extension. Im using the windows environment. and as such once the serial port is open the readline() is missing the /r (terminating on /n) causign all sorts of greif. is there a way of making the serial port function more windows like? From cer at vtr.net Sun Mar 9 18:11:16 2003 From: cer at vtr.net (Cristian Echeverria) Date: Sun, 09 Mar 2003 19:11:16 -0400 Subject: __slots__ , private members and properties In-Reply-To: References: Message-ID: Thanks a lot!! Your reference show me that at least my code is ok with the concepts and is the raw way to use those features. Anyway, many people is trying to avoid the extra typing related with this features. Cristian Bjorn Pettersen wrote: >>From: Cristian Echeverria [mailto:cer at vtr.net] >> >>Is the atached code a good way to work with __slots__, >>private members >>and properties. >>In the examples all the members are read-only and the code works, but >>I'am not sure this is the way to work with this features. > > > Seems like an awful lot of boilerplate code. Take a look at the > __readonly__ receipe in the Python Cookbook for a better solution > (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157768). > > -- bjorn > From 2002 at weholt.org Thu Mar 13 13:33:04 2003 From: 2002 at weholt.org (Thomas Weholt) Date: Thu, 13 Mar 2003 19:33:04 +0100 Subject: MySQL : Too many connections References: Message-ID: <574ca.38057$Rc7.543778@news2.e.nsc.no> It's a application that scans a cdrom/dvd-rom and inserts records describing each file found. Then I create an index of words used in filename and paths on the media that was scanned. This process contains both inserts and selects on allready inserted records. It's a script run once a while, not a long-running process. It seems as if the opened connections are not closed after the script has finished. Why? Do I have to call close on the connections manually? This is not done in any of the examples I've seen. In "MySQL Control Center" I see more and more open connections listed as I run my code. Thomas "Jeff Bauer" wrote in message news:mailman.1047569967.24366.python-list at python.org... > Thomas, > > You haven't indicated what type of application you're > running with MySQL. For web applications, I create a > single database connection object per user session, > running as a persistent connection (a.k.a long running > process). All database queries are passed through the > database connection object. > > In other words, you should only require one database > connection per process space (or modulo # of databases, > if accessing multiple databases). > > Jeff Bauer > Rubicon Research > > > > I get an exception using MySQL, "Too many connections". I understand > > the error and why it occurrs, but how can I avoid it?? Do I close > > after each cursor.execute-call or do I close the connection?? In > > case of closing after the execute-call, how ?? > > > > What is the proper way of inserting a lot of records and during > > this process check rows allready inserted and avoid the problem > > above? > From aleax at aleax.it Fri Mar 14 04:45:59 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Mar 2003 09:45:59 GMT Subject: Recommended Linux Laptops, suppliers? I ORDERED A DELL References: <3e6a571b$1_1@spamkiller.newsgroups.com> <3e71192f$1_1@spamkiller.newsgroups.com> Message-ID: Dennis Lee Bieber wrote: ... > Probably less than you might think. As I recall, the Latitude line > is > Dell's "corporate" laptop -- the one marketed to IT departments who > would buy lots of them in one standardized configuration. It tends to > be one generation behind "state of the art". For "state of the art", > one would look at the Dell Inspiron (which is pushed toward the home > consumer). Absolutely correct in terms of "state of the art" -- the "Highlights" of the two series start, for Inspiron, with "Emphasizes newest notebook technology", for Latitude, "Emphasizes durable, proven technology" -- very sharp contrast here. Alex From mhammond at skippinet.com.au Sat Mar 29 01:05:10 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 29 Mar 2003 06:05:10 GMT Subject: win32com and MSHTML In-Reply-To: <3e8533d7_1@news.unc.edu> References: <3e8533d7_1@news.unc.edu> Message-ID: Peter Parente wrote: > Any help in solving this problem would be greatly appreciated. Reduce it down to a simple example that repeatedly reloads the same document, connecting each time. From what you describe, you will notice pythoncom._GetInterfaceCount() increasing without bound. If there is a simple win32com bug, you should be able to demonstrate this with very few lines of code. Otherwise, there may be some other circular reference buried somewhere. If you have a very new win32all, there is a "WithEvents()", which allows you to use 2 discrete objects - one for the IDispatch, and another to receive events. But in general, the source of the circular reference will still need to be tracked. Mark. From andy_todd at yahoo.com Tue Mar 11 09:48:11 2003 From: andy_todd at yahoo.com (Andy Todd) Date: 11 Mar 2003 06:48:11 -0800 Subject: Gadfly DB problem in python References: Message-ID: <8f2c2d6b.0303110648.2564d859@posting.google.com> "Lance LaDamage" wrote in message news:... > This is the traceback I get: > > C:\DATA\RY>main.py > Traceback (most recent call last): > File "C:\DATA\RY\main.py", line 27, in ? > DataPool.Startup( connection = connection ) > File "C:\Data\Ry\DataPool.py", line 35, in Startup > DataPool.instance = DataPool( init[ 'connection' ] ) > File "C:\Data\Ry\DataPool.py", line 24, in __init__ > self.cursor.execute("select * from datapool") > File "F:\Python22\Lib\site-packages\gadfly\database.py", line 372, in > execute > File "C:\Data\Python\lib\site-packages\gadfly\gadfly\semantics.py", line > 2719, > in eval > substseq = h.join(substseq) > File "C:\Data\Python\lib\site-packages\gadfly\gadfly\semantics.py", line > 149, > in join > new = t.remap(transformG) > File "F:\Python22\Lib\site-packages\gadfly\kjbuckets0.py", line 581, in > remap > File "C:\Data\Python\lib\site-packages\gadfly\gadfly\kjbuckets0.py", line > 413, > in __mul__ > raise ValueError, "kjGraph composes only with kjTable" > ValueError: kjGraph composes only with kjTable > [snip code example] > > > All this code is fine but it used to work on my old computer, but now it > won't work on this one... Lance, You haven't posted the code that actually causes the error to be raised; > File "C:\Data\Ry\DataPool.py", line 24, in __init__ > self.cursor.execute("select * from datapool") Which I believe is your obfuscated database access routine. Nevertheless I am going to start guessing. You said that this stopped working when you ported the code to your new machine. Did you copy the gadfly database files as well? Not copying the database files (they end in .gfd and .grl) is a possible cause of your error. If this isn't the case then I would suggest reducing the code to a nice simple example which illustrates your error. It will make finding the source of it much easier. To get to this position I would suggest that you try importing the DataPool module in an interactive session and examining what happens when you create objects from it and invoke their methods. HTH, Andy From sschwarzer at sschwarzer.net Mon Mar 17 16:13:07 2003 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Mon, 17 Mar 2003 22:13:07 +0100 Subject: Logging _into_ an application Message-ID: I would like to know if there's a framework available for logging into a Python application, in the same sense I can use a command line database client to query a database (e. g. psql for PostgreSQL). Example for the Python case: myhost$ start_application.py Running in background ... myhost$ application_admin.py >>> import mycache >>> mycache.cached_items_count() # number of items in the application's cache? 42 >>> import gc >>> len(gc.garbage) # how many objects weren't collected? 3 >>> ^D myhost$ Stefan From shalehperry at attbi.com Fri Mar 14 02:09:36 2003 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 13 Mar 2003 23:09:36 -0800 Subject: please comment - my first classes In-Reply-To: References: Message-ID: <200303132309.36973.shalehperry@attbi.com> On Thursday 13 March 2003 22:53, Hilbert wrote: > Hello, > > I started writing a script to keep track of my > bookmarks. > This is the first script where I'm using classes. > I wanted to ask your opinions so that I know > I'm on the right (or wrong) path > I want to turn this into a cgi script, so the input > part is just for testing. I'm not sure if this is the > correct way for setting up the groups class. > > > def Print(self): > print self.group,':',self.name,':',self.url > this is my only major issue with your class design. Depending on print limits your class's usefulness. You are better off implenting something like your asTuple() method and passing that to print: print myclass.asString() in Python a common way to accomplish this is via __str__ or __repr__: >>> class Foo: ... def __str__(self): ... return "I am foo" ... >>> f = Foo() >>> print f I am foo Now your class can be used in cgi's, GUIs, text based programs, etc. As a purely matter of style, your naming convention is reverse from what I am used to. In projects I have worked on classes/types get capital letters, methods as studlyCaps (note the first word is lower case) and variables get names_like_this. Often you will see functions declared like_this() as well. class Bookmark: def __init__(self, group, name, url): self.group = group self.name = name self.url = url def __str__(self): return '%s:%s:%s' % (self.group, self.name, self.url) def asTuple(self): return (self.group, self.name, self.url) class BookmarkGroupDb: pass From lists at ghaering.de Tue Mar 25 05:44:25 2003 From: lists at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 25 Mar 2003 11:44:25 +0100 Subject: web application with python In-Reply-To: References: Message-ID: <3E803309.2050208@ghaering.de> Amir Hadar wrote: > Hi > Do cgi module and the CGI web server support Session? No. You'll have to build your own. But CGIs suck, anyway. > Do Python has a module for the Apache something like JServ? mod_python/mod_webware/... > Do Python has a module for database connection? (like jdbc) There's a standardized API with plenty of implementations, just like JDBC. It's called the Python DB-API, version 2.0. > How about an application server for python (like python-beens)? There are such beasts. > How about support for Web-Services? XML-RPC is well supported. There are also different SOAP implementations, but none of them seems to be well supported right now. > In other words - can I build a full scale clustered web application / > service with python? Clustering is a different issue entirely. What do you want? 1) Failover? 2) Load-balancing? 3) Both? For distributed network applications, Twisted has some support. -- Gerhard You can find URLs for all of the Python frameworks mentioned above using Google. You can also explore the Python wiki, starting from http://www.python.org/cgi-bin/moinmoin/WebProgramming From matthew at newsgroups.com Wed Mar 19 22:09:05 2003 From: matthew at newsgroups.com (Matthew) Date: Thu, 20 Mar 2003 15:09:05 +1200 Subject: Novice needs help with py2exe Message-ID: Hi, I've written a simple py program which I want to run under win32 as a standalaone. the program works fine under pythonwin. Now how-to wrap it up using py2exe? I've downloaded and installed py2exe and now to be perfectly frank - What do I do now? There doesn't seem to be any documentation at all on how to use it - well not that I could understand anyway. D:\Python22\Lib\site-packages\py2exe>python py2exe.py Traceback (most recent call last): File "py2exe.py", line 3, in ? raise RuntimeError, "something's wrong" D:\Python22\Lib\site-packages\py2exe>python setup.py py2exe.py --help python: can't open file 'setup.py' ^^^^^^^^ >>> doesn't exsist in the py2exe dir So, for this novice it's currently "Game Over". Any help would be greatly appreciated. Regards, matthew. From maschio_77 at hotmail.com Mon Mar 31 16:28:34 2003 From: maschio_77 at hotmail.com (Federico) Date: Mon, 31 Mar 2003 23:28:34 +0200 Subject: changing icon to a Tkinter gui program Message-ID: How can I change the icon of the windows of a Tkinter Gui program? Thanks From logistix at zworg.com Tue Mar 25 23:05:43 2003 From: logistix at zworg.com (logistix) Date: 25 Mar 2003 20:05:43 -0800 Subject: Searching in Active Directory (also using LDAP in Windows) References: <2d0ga.6354$t_2.924@afrodite.telenet-ops.be> Message-ID: "Rudy Schockaert" wrote in message news:<2d0ga.6354$t_2.924 at afrodite.telenet-ops.be>... > Hi, > > I have a troubles accessing Active Directory. When I use Mark Hammond's > win32com extensions, I can connect and bind to the server, but when I try to > enumerate an OU, I sometimes get results back, but not always. > Also when I enumerate the first time, and it works, it won't work a second > time, unless I delete the objects and recreate them. > > I also tried to create a simple query using ADODB.RecordSets, but that > doesn't work at all. > > I also tried Python-LDAP, but no avail either. > > Has anyone been able to access or search Active Directory succesfully? I > googled till passed midnight yesterday, but couldn't find anything helpfull. > > Does anyone know of another LDAP module for Python on Windows? > > I can always send some example scripts if someone's interested. > > Thanks in advance, > > Rudy I've always just used the ADSI (Active Directory Scripting Interface) components via win32com.client.Dispatch, and have never had a problem getting the data I wanted. From godoy at metalab.unc.edu Sun Mar 9 15:20:19 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Sun, 09 Mar 2003 17:20:19 -0300 Subject: vim/linux doesn't highlight mismatched parens in scripts References: Message-ID: <86ptp05m2k.fsf@ieee.org> John J Lee writes: > How about Emacs + python-mode, with vi keybindings? I'm sure > there's a vi mode of some kind. M-x viper-mode :-) But personally I find Emacs keybinding more comfortable. -- Godoy. From sismex01 at hebmex.com Tue Mar 18 13:07:40 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 18 Mar 2003 12:07:40 -0600 Subject: OT: Recommended Linux Laptops, suppliers? Message-ID: > > Under the right circumstances, it would appear a > 1GHz G4 might do fairly well against a 2GHz Celeron. > > Skip > Make that "under most circumstances". An opcode on a G4 does more work per clock cycle than an opcode on a Celeron or a P4. The G4's pipeline is more shallow than the P4's, so it's clock speed can't go as high, but then, it doesn't get such hideous pipeline stalls every time it mispredicts a branch. -gustavo From peter at engcorp.com Sat Mar 22 18:33:45 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 22 Mar 2003 18:33:45 -0500 Subject: glob & fnmatch unable to match dirs/files containing [ ] ? References: <3e7caaac$0$21717$9b622d9e@news.freenet.de> Message-ID: <3E7CF2D9.BF1A8C3B@engcorp.com> Steven Taschuk wrote: > > Quoth Robert: > [...] > > quoting attempts don't work: > > > > >>> glob.glob( r'testsync\[2\]/*' ) # or 'testsync\\[2\\]/*' > > [] > > You can quote the '[' by putting it in a character class of its > own: > >>> glob.glob('testsync[[]2]') > ['testsync[2]'] I'm not certain, but I believe you would need to change the order to 'testsync[][2]' ... this looks like an empty class then one with a single 2 in it, but it's not. Yours would look like a single [ in a class, then a 2 and then... syntax error or something, since you've got a closing ] without a matching opening one. -Peter From max at alcyone.com Wed Mar 5 19:55:27 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 05 Mar 2003 16:55:27 -0800 Subject: Vote on PEP 308: Addenda References: Message-ID: <3E669C7F.AA083E2F@alcyone.com> John Roth wrote: > I trust Guido on something like this, which is why I'm wondering > what all the fuss is about. Probably the principle that if something's worth doing, it's worth doing _right_. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ The basis of optimism is sheer terror. \__/ Oscar Wilde HardScience.info / http://www.hardscience.info/ The best hard science Web sites that the Web has to offer. From pedronis at bluewin.ch Thu Mar 6 04:43:04 2003 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Thu, 6 Mar 2003 10:43:04 +0100 Subject: Can __iter__ be used as a classmethod? References: <3e649aa3_4@news.bluewin.ch> <2259b0e2.0303041023.43e8b81f@posting.google.com> <4B89a.6715$zo2.218162@news2.tin.it> <3e65273f$1_3@news.bluewin.ch> <2259b0e2.0303050855.1eece801@posting.google.com> Message-ID: <3e671845$1_3@news.bluewin.ch> "Michele Simionato" ha scritto nel messaggio news:2259b0e2.0303050855.1eece801 at posting.google.com... > > This can be used as an argument to have them explicitely (you can implement > > them anyway, so let's get them right once and for all) or to not have them > > (who need them can cook them up). > > In my view this is an argument against them. I sympathize. > > It is worth to notice that once you override one of them (like g in D > > overriding g in C) it is impossible to call in a clean way the parent > > version (C g) passing the derived class (D), which is what would happen in > > case of no overriding (if D would not define g, then D.g() would call g in C > > passing D), (so above C.g() obviously is calling g in C passing C). "Let's > > call this their price". > > It seems to me that > > class D(C): > def g(cls): > print 'Dg',cls > C.g.im_func(cls) Yes, but I would not count that as clean way. From kostya at mpi-magdeburg.mpg.de Wed Mar 19 09:41:32 2003 From: kostya at mpi-magdeburg.mpg.de (Kostyantyn Teplynskyy) Date: Wed, 19 Mar 2003 15:41:32 +0100 Subject: Fatal Python error: Interpreter not initialized (version mismatch?) Message-ID: <200303191541.32955.kostya@mpi-magdeburg.mpg.de> Hi, I've made Python C extension ( hafke.so ) and when I try to import it in python shell, started(Py_Main command) in main function of application (created in C++) I get fatal error. >> import _hafke >> Fatal Python error: Interpreter not initialized (version mismatch?) Maybe somebody know how to fix this problem, Thank you, Konstantin -- Best regards ! Mit freundlichem Gruss ! C ?????????? ??????????? ! ----------------------------------------- Konstanitin Teplinskiy, Mail: kostya at mpi-magdeburg.mpg.de From danb_83 at yahoo.com Sun Mar 23 02:03:07 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 22 Mar 2003 23:03:07 -0800 Subject: Newbie question about reference References: Message-ID: Tim Smith wrote in message news:... > "Terry Reedy" wrote: > >You here bind 'list' to the object [1,2,3]. (Note: DON'T use builtin > >names as vars unless you have a positive reason for so doing.) > > OK, I had thought that L = [x,y,z] was binding the list L as an > ordered set of references/pointers to the variables x, y, z. Obviously > not, as integers are, along with strings etc., immutable types. It doesn't have anything to do with mutable v. immutable types. The same thing happens with >>> x = [1] >>> y = [2] >>> z = [3] >>> lst = [x, y, z] >>> lst [[1], [2], [3]] >>> y = [0] >>> lst [[1], [2], [3]] >>> The important thing to remember is that the list created by "list = [x, y, z]" stores a pointer to the object that y points to (all variables in Python are pointers in disguise), and *not* the name or address of the variable "y". The immutable/mutable distinction matters in situations like >>> x = [1] >>> y = [2] >>> z = [3] >>> lst = [x, y, z] >>> lst [[1], [2], [3]] >>> lst[1][0] = 0 # mutates the list [2], which is also pointed to by y >>> lst [[1], [0], [3]] >>> y [0] >>> > This is not clearly explained in the material I have read so far. It's > emphasized that strings are immutable, but not ints, tho' I suppose it > should be obvious, especially to one who's thinking in implementation > terms (I don't think that way :-) It might not be obvious to those who still use buggy FORTRAN compilers :-) From brian at sweetapp.com Mon Mar 10 14:19:40 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 10 Mar 2003 11:19:40 -0800 Subject: Testing for a list In-Reply-To: <000001c2e737$d88dbba0$0d01a8c0@Antun> Message-ID: <003301c2e739$ff8cb9c0$21795418@dell1700> > Thanks Brian > > That's exactly what I needed. > > Why were people ignoring my question? What was wrong about it? It shouldn't matter to you what type something is, as long as its behavior is consistent with what you expect. But, to be quick and dirty, I'd use this construction: import types if isinstance(a, types.StringTypes): # do string code path else: # do list code path Cheers, Brian From bkc at Murkworks.com Wed Mar 19 09:29:25 2003 From: bkc at Murkworks.com (Brad Clements) Date: Wed, 19 Mar 2003 09:29:25 -0500 Subject: OT: Recommended Linux Laptops, suppliers? References: Message-ID: <3e787f66$1_1@spamkiller.newsgroups.com> Dell says my Laptop is expected to ship april 24th. Do you think this thread will still be going then? ;-) -- Novell DeveloperNet Sysop #5 From paddy3118 at tiscali.co.uk Mon Mar 3 14:26:31 2003 From: paddy3118 at tiscali.co.uk (Paddy) Date: Mon, 03 Mar 2003 19:26:31 +0000 Subject: Why no RE match of A AND B? References: <3E6270DC.3060904@tiscali.co.uk> Message-ID: <3E63AC67.5000802@tiscali.co.uk> Paddy wrote: > > Just looking through the docs to confirm it and their seems to be no > regular expression construct that matches 'A and B' - an equivalent to > the '|' character that matches A or B > To paraphrase the documentation it could be documented as: > > "&" > A&B, where A and B can be arbitrary REs, creates a regular expression > that will match both A and B in any order. An arbitrary number of REs > can be separated by the "&" in this way. This can be used inside groups > as well. REs separated by "&" are tried in arbitrary order, the > beginning of the first matching branch up to the end of the last branch > that allows the complete pattern (all branches) to match is considered > the span of the match. > > I envision it being used where a string is accepted at present if it > matches multiple REs. > The REs could be rewritten as r"&&...". > > The use of "&" could be supported by more efficient, (simultaneous?), > matching of all branches of the "&" construct - if such algorithms exist! > > Just an idea, > > Paddy. > Thanks all, for your input so far. Having thought of it, and seen the posts on if it is necessary or not, or needed or not; it seems a bit odd that we are left with one of the few places where the or 'operation' is defined, but the orthogonal and 'operation' is not ?! Paddy. From peter at engcorp.com Fri Mar 7 19:57:22 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 07 Mar 2003 19:57:22 -0500 Subject: Concerns about performance w/Python, Pysco on Pentiums References: <3E660EB3.4065D81F@engcorp.com> <3E66BA3F.7691C3B0@engcorp.com> <3e677433$0$87747$edfadb0f@dread11.news.tele.dk> <7h3bs0oh25s.fsf@pc150.maths.bris.ac.uk> <3E6784AD.E4D523BD@engcorp.com> <7h3y93sfldh.fsf@pc150.maths.bris.ac.uk> <3E67A2F2.187785EA@engcorp.com> <7h3llzrff5g.fsf@pc150.maths.bris.ac.uk> <3E691B8A.50780217@engcorp.com> Message-ID: <3E693FF2.6F56D715@engcorp.com> Skip Montanaro wrote: > > Peter> Py2.2, list, inlined: 16468, 108% > Peter> Py2.3, list, inlined: 19074, 126% > Peter> Py2.2, list, inlined, Psyco: 9963, 66% (!) > > Peter> Not sure what that last one indicates, except that under certain > Peter> circumstances (perhaps when used by someone who hasn't even read > Peter> it's documentation? :-), Psyco can produce *worse* results. > > How exactly are you using Psyco? If you let it figure out which routines to > specialize, it generally does a poor job. If you know where your hotspots > are, you can tell it to just specialize those routines. At first I tried binding all the opcode handler functions, and the Opcode class, and the Cpu class. A little experimentation showed that ditching the opcode handlers increased performance, so now I just do the two classes. Are you suggesting picking only some methods in the classes would help? At this point, actually, I need to do one thing before going any further makes sense: profile the code. And read the Psyco manual. Two things I must do before it makes sense. Profile, RTFM, and develop a _need_ for greater performance. *Three* things... there are three things I need. Oh bugger... -Peter From exarkun at intarweb.us Sun Mar 2 15:04:23 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sun, 2 Mar 2003 15:04:23 -0500 Subject: Strange regex problem In-Reply-To: <200303021111.35316.gherron@islandtraining.com> References: <200303021111.35316.gherron@islandtraining.com> Message-ID: <20030302200423.GA4085@meson.dyndns.org> On Sun, Mar 02, 2003 at 11:11:34AM -0800, Gary Herron wrote: > [snip] > > So when the value of "begin" has that particular bit set, set > SRE_FLAG_DEBUG on and so get the debug output. > > > I have just (last week) volunteered to take over maintenance of the > regular expression code, so I'll think about fixing this, but it's not > clear to me what a fix should entail. > > * Document the flag. +1 > > * Ignore the flag. -1 > > * Raise an exception for any flag bit other than the document flags. +1 Jp -- Know what I pray for? The strength to change what I can, the inability to accept what I can't and the incapacity to tell the difference. -- Calvin -- up 22 days, 0:30, 5 users, load average: 0.00, 0.00, 0.03 From antonio.p at llibero.it Fri Mar 7 15:22:51 2003 From: antonio.p at llibero.it (Antonio.P) Date: Fri, 07 Mar 2003 20:22:51 GMT Subject: tal template engine in python out of zope Message-ID: I am looking for an implemetation of the zope "tal" template engine but out of zope. I can only use python not zope, but I'd like to use a template engine like the tal of zope. Thank you From python-list at hazen.net Thu Mar 20 19:29:43 2003 From: python-list at hazen.net (John Hazen) Date: Thu, 20 Mar 2003 16:29:43 -0800 Subject: Running into problems with os.popen In-Reply-To: <3E79BBCE.3030909@motorola.com>; from Stephen Boulet on Thu, Mar 20, 2003 at 07:02:06AM -0600 References: <3E7900E9.30606@motorola.com> <3E79BBCE.3030909@motorola.com> Message-ID: <20030320162943.A12974@gate.hazen.net> On Thu, Mar 20, 2003 at 07:02:06AM -0600, Stephen Boulet wrote: > The command is: > > pth = os.path.join(curDir,self.fileName) > command = 'hdp dumpsds -c "%s"' % pth If the filename (or any of the directories on the path) has a space in it, the shell (depending on your OS) may split what you *mean* as one argument into two. If that's the kind of truncation you're talking about, try this: command = "hdp dumpsds -c '%s'" % pth Even though they're the same to python, to the shell single quotes will contain the space, while double quotes will not. HTH- John From dave at boost-consulting.com Sat Mar 22 21:04:14 2003 From: dave at boost-consulting.com (David Abrahams) Date: Sat, 22 Mar 2003 21:04:14 -0500 Subject: Boost help please References: <_fjea.3599$j5.16816@news> Message-ID: Jim writes: > Hi, > > I am switching some C++ code over to use boost ... but i am having > some problems just getting things to compile ... the compile error is > not very helpful so i'll leave it out for now ... the problem i think > is more related to the fact i need return a structure from a boost > function .... can anyone help ;-) Please post Boost.Python questions to the c++-sig: http://mail.python.org/mailman/listinfo/c++-sig > > The my attempt at a boosted function is here: > --------------------------------------------- > > struct boardInfoStruct { > double d1; > double d2; > double d3; > double d4; > double d5; > double d6; > double d7; > double d8; > long l1; > long l2; > long l3; > long l4; > }; > > boardInfoStruct BOOSTED_cosim_get_board() > { > boardInfoStruct * ret = new boardInfoStruct(); > > ret.d1 = theboard.x60_clk/1e6; > ret.d2 = theboard.pwm_clk/1e6; > ret.d3 = theboard.utx_clk/1e6; > ret.d4 = theboard.urx_clk/1e6; > ret.d5 = theboard.local_ref_clk/1e6; > ret.d6 = theboard.pcr_ref_clk/1e6; > ret.d7 = theboard.mod_ref_clk/1e6; > ret.d8 = theboard.demod_ref_clk/1e6; > > ret.l1 = theboard.mod_utopia; > ret.l2 = theboard.demod_utopia; > ret.l3 = theboard.dac_type; > ret.l4 = theboard.adc_type; > > return ret; > > } Why not just expose boardInfoStruct? class_("board_info") .def_readwrite("d1", &boardInfoStruct::d1) .def_readwrite("d2", &boardInfoStruct::d2) .def_readwrite("d3", &boardInfoStruct::d3) ... ; -- Dave Abrahams Boost Consulting www.boost-consulting.com From jdhunter at ace.bsd.uchicago.edu Tue Mar 4 09:48:41 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 04 Mar 2003 08:48:41 -0600 Subject: gtk popup window question In-Reply-To: ("Wouter van Marle"'s message of "Tue, 4 Mar 2003 14:51:54 +0800") References: Message-ID: >>>>> "Wouter" == Wouter van Marle writes: Wouter> Hi all! For my application I am trying to write a simple Wouter> module to do the following: Wouter> - open a popup window (usually error, or info) with only Wouter> an OK button. I made such a window in Glade, it is a Wouter> GtkMessageDialog (hope I am correct... can't use news at Wouter> home where I do my programming due to wacky server). - Wouter> change it for error, information, ... (there are five or Wouter> six of these options) - change the text Wouter> Even a dir() on the object didn't help me out! Wouter> What to do? There is no settext() option, or anything Wouter> similar. You don't really need to design a message dialog in glade, because there is nothing to design. gtk.MessageDialog is already designed, you just need to supply the parameters. The message text is defined at construction Try this (for pygtk-2) import gtk dialog = gtk.MessageDialog( parent = None, flags = gtk.DIALOG_DESTROY_WITH_PARENT, type = gtk.MESSAGE_INFO, buttons = gtk.BUTTONS_OK, message_format = "Your message here") dialog.set_title('Error!') dialog.connect('response', lambda dialog, response: dialog.destroy()) dialog.show() gtk.mainloop() If you use this code from within some widget, you may want to set the parent to the calling widget, which will automatically set_transient_for for you. However, that dir on the object returned nothing is suspicious. MessageDialog inherits from Dialog has many many methods. If you do dir(dialog) in the example above, you will see them. In glade, if you call gtk.glade.XML.get_widget on a nonexistent widget, it will return None. Is it possible you are working with None here? John Hunter From sismex01 at hebmex.com Tue Mar 4 10:09:52 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 4 Mar 2003 09:09:52 -0600 Subject: Towards a more Pythonic "Ternary Operator" Message-ID: > From: Clark C. Evans [mailto:cce at clarkevans.com] > Sent: Tuesday, March 04, 2003 7:06 AM > > if a == X: > b = Q > elif a == Y: > b = R > else: > b = S > > In this case, not only is 'b = ' duplicated three times, > but 'a ==' is duplicated twice. These two can be combined > into the select/case pattern: > > b = select a: > case X: Q > case Y: R > else: S > Yes, there is a lot of duplicated "text" in the first case, and the second case corrects that. But you don't need new syntax to be able to make it better, you already have dictionaries: b = { Q:X, R:Y }.get(a,S) At least to me, it's a lot more readable, doesn't involve new syntax, and can grow to a larget amount of options if needed. And it isn't limited to constant expressions inside the dictionary, as this IDLE session demonstrates: >>> a, A = "a", "Peter" >>> b, B = "b", "John" >>> c, C = "c", "Ernest" >>> default = "Spanish Inquisition" >>> def chooser(choice): global a, A, b, B, c, C, default return { a:A, b:B, c:C }.get(choice, default) >>> print chooser("a") Peter >>> print chooser("c") Ernest >>> print chooser("x") Spanish Inquisition >>> print chooser("b") John >>> print chooser("John") Spanish Inquisition >>> B = "Ironman" >>> print chooser("b") Ironman >>> A = "Raquel Welch" >>> C = "Ozzy Osbourne" >>> default = "Eric Idle" >>> print chooser("a") Raquel Welch >>> print chooser("d") Eric Idle >>> print chooser("c") Ozzy Osbourne >>> c = "zz" >>> print chooser("zz") Ozzy Osbourne >>> The "need" for a ternary operator in many occasions is created by not knowing the "correct" pythonic construction which expresses that which you need to do. Python's interactive nature helps you explore all that. Ternary operators are good to select between two (and let's keep it at two) expressions which might have (severe?) side-effects, there lies the need for short- circuiting. In the above example, imagine evaluating A, B or C could have side-effects; in that case, upon constructing the selection dictionary, all side-effects would have been triggered, so this construction would be no good. It could be adapted, by changing the function chooser() like so: >>> def chooser(option): try: return { a:lambda:A, b:lambda:B, c:lambda:C }[option]() except KeyError: return default It becomes a bit more complex, but still quite simple. -gustavo From elektroQUITA at wol.es Sun Mar 2 07:38:04 2003 From: elektroQUITA at wol.es (EleKtR0) Date: Sun, 02 Mar 2003 13:38:04 +0100 Subject: Simple question, how can i create a record? Message-ID: <1046608880.565095@seux119> Hi! i'm reading a good manual about Python to learn it. it has an example where uses a module named "record" to import a class named "record". With record class i can create records on Python, but i'm not find the record module. How can i create records on Python? I use Python 2.2 on Suse Linux 8.0 Thanks! Python manual (in spanish): http://marmota.act.uji.es/MTP/pdf/python.pdf From aleax at aleax.it Thu Mar 6 16:51:54 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 6 Mar 2003 22:51:54 +0100 Subject: embedding python - PyImport_ImportModule returns null In-Reply-To: <60FB8BB7F0EFC7409B75EEEC13E20192022DD94C@admin56.narex.com> References: <60FB8BB7F0EFC7409B75EEEC13E20192022DD94C@admin56.narex.com> Message-ID: <200303062251.54416.aleax@aleax.it> On Thursday 06 March 2003 08:44 pm, Bjorn Pettersen wrote: ... > Perhaps you would know how to import a module so that it can be used in > PyRun_String()? I've tried PyImpor_Import, PyImport_ImportModule, and > PyImport_ImportModuleEx which all imported the module but didn't make it > visible. They give you the module object; if you want any object, including that module you just imported, to be available under a name X in some other module such as __main__, you set-attribute accordingly to bind the name to the object. E.g. in the following snippet: > void main() { > Py_Initialize(); > PySys_SetPath(Py_GetPath()); > > > PyObject* mainmod = PyImport_AddModule("__main__"); > Py_INCREF(mainmod); > PyObject* ns = PyModule_GetDict(mainmod); > Py_INCREF(ns); > > PyObject* timeModule = PyImport_ImportModuleEx("time", ns, ns, > NULL); > if (!timeModule) std::cout << getTraceback() << std::endl; > std::cout << "time module imported successfully" << std::endl; you have the object timeModule and you want it to be visible in module object mainmod under the name 'time', i.e., in dictionary ns at key 'time'. So you can for example: PyModule_AddObject(mainmod, "time", timeModule); careful -- this steals a reference to timeModule, so incref it now if you need it to stick around, or else just omit decref'ing it later. Apart from this, the following code: > PyObject* timeFn = PyRun_String("time.time", Py_eval_input, ns, ns); > > if (!timeFn) std::cout << getTraceback() << std::endl; > > Py_XDECREF(timeModule); > Py_XDECREF(timeFn); > Py_DECREF(ns); > Py_DECREF(mainmod); > Py_Finalize(); > } should now work. Python statement import does implicit binding -- you can see import time as equivalent to time = __import__('time') and at the C-API level you must use this more detailed approach -- it's not QUITE as high-level as the Python statement 'import'!-) Alex From noway at sorry.com Tue Mar 4 13:46:51 2003 From: noway at sorry.com (Giovanni Bajo) Date: Tue, 04 Mar 2003 18:46:51 GMT Subject: Can __iter__ be used as a classmethod? References: <3e649aa3_4@news.bluewin.ch> <2259b0e2.0303041023.43e8b81f@posting.google.com> Message-ID: "Michele Simionato" ha scritto nel messaggio news:2259b0e2.0303041023.43e8b81f at posting.google.com... > It seems to me I could always use a regular method instead of > a classmethod, by accessing the class trough self.__class__ or > type(self), therefore classmethods only provide a very small amount > of syntactical sugar. Actually, they let you also call the method without any instance of the class (they do not need to be bound to any instance). > Actually they seems to me an unessential complication to the language, > expecially because they are easily confused with the methods in the > metaclass. Yes: class A(object): x = 10 class __metaclass__(type): def f(cls): print "Hello from", cls, ", value is", cls.x def g(cls): print "Hello from", cls, ", value is", cls.x g = classmethod(g) >>> A.g() Hello from , value is 10 >>> A.f() Hello from , value is 10 So for basic usage, you accomplished the same: you have a method in class A that you can call without any instance of A, and can work on the attributes of the class. The only difference I can see is: >>> a = A() >>> a.g() Hello from , value is 10 >>> a.f() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'A' object has no attribute 'f' This is because of the lack of transitivity in the 'inheritance' from types, as explained by Alex in another post in this thread. So, what are the other differences (if any)? Why do classmethods exist? Giovanni Bajo From peter at engcorp.com Sat Mar 29 07:54:58 2003 From: peter at engcorp.com (Peter) Date: Sat, 29 Mar 2003 07:54:58 -0500 Subject: Nice quote References: Message-ID: <3E8597A2.13FE92DE@engcorp.com> Jeremy Bowers wrote: > > On Fri, 28 Mar 2003 18:30:28 +0100, Just wrote: > > """The Python people also piped to say "everything's just > > fine here" but then they always do, I really must learn that > > language.""" > > Would somebody amplify on this please? What XML library do we have that's > easier to use then DOM or SAX for real world tasks that doesn't require > reading the whole file into memory to work? I'm fairly sure the context you omitted would show that the comment above didn't imply Python folks have some magic new library that solves the XML world's problems. It seemed to be a statement made partly in contrast to the previous statements about Perl's "a zillion ways to do it" and the difficulties that was causing XML developers using Perl, and partly in contrast to implied other difficulties with XML using other languages. Basically, he was conveying that Python people don't find processing XML to be a huge problem in any particular way, and I think that's a fair assessment. IMHO. -Peter From lsmithso at NOhare.SPAM.demon.co.uk Tue Mar 25 06:26:56 2003 From: lsmithso at NOhare.SPAM.demon.co.uk (Les Smithson) Date: 25 Mar 2003 11:26:56 +0000 Subject: I/O Serial and Parallel References: Message-ID: >>>>> "Skender" == Skender writes: Skender> distutils.errors.DistutilsPlatformError: invalid Python Skender> installation: unable to open Skender> /usr/lib/python2.2/config/Makefile (No such file or Skender> directory) Looks like a bad Python install. Does /usr/lib/python2.2/config/Makefile exist? Does distutils work for other packages? From fredrik at pythonware.com Sat Mar 29 04:45:33 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 29 Mar 2003 10:45:33 +0100 Subject: Tkinter: Listboxes, Keybindings? References: Message-ID: Jonathan McLin wrote: > A number of questions, for which I've not found the answer in my Python > books nor on the web: > > Why does the curselection method of an instance of Tkinter.Listbox return a > single element tuple rather than a scalar? since multiple items can be selected, if the listbox is configured to support that. > Why is this element a string rather than an int? a flaw in the orginal implementation, which nobody has fixed, possibly to avoid breaking existing code. see the "Listbox patterns" section in "An introduction to Tkinter" for more info: http://www.pythonware.com/library/tkinter/introduction/listbox.htm => patterns (as you've noticed, the "bug" is still there in 2.2.2) > Key bindings do not work for me: > > For my listbox: > ... > self.list=Listbox(self) # self is a subclass of Frame. > self.list.bind('<1>',self.ScrollUp) # works > self.list.bind('',self.ScrollUp) # doesn't work > self.list.bind('<2>',self.ScrollDown) # works > self.list.bind('',self.ScrollDown) # doesn't work > ... > > the bindings to <1> and <2> work (calling the bound methods on mouse > clicks), but the up and down arrow keys on the keyboard do not. What am I > doing wrong? keyboard events are sent to the widget that has the keyboard focus. if keyboard bindings don't work as expected, the usual reason is that some other widget has the focus. you can use the focus_set() method to explicitly move focus to a widget (you might want to do this in the Button-1 handler, for example). From h_schneider at marketmix.com Fri Mar 21 14:35:10 2003 From: h_schneider at marketmix.com (Harald Schneider) Date: Fri, 21 Mar 2003 20:35:10 +0100 Subject: httplib with SSL support for Python 2.1 ? References: Message-ID: Tested this one: http://alldunn.com/python/ But it crashes with: pD9531BB1.dip.t-dialin.net - - [21/Mar/2003 20:30:49] code 400, message Bad request syntax ('') ---------------------------------------- Exception happened during processing of request from ('217.83.27.177', 2413) Traceback (most recent call last): File "C:\usr\python\lib\SocketServer.py", line 221, in handle_request self.process_request(request, client_address) File "C:\usr\python\lib\SocketServer.py", line 240, in process_request self.finish_request(request, client_address) File "C:\usr\python\lib\SocketServer.py", line 253, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\usr\python\lib\SocketServer.py", line 501, in __init__ self.handle() File "C:\usr\python\lib\BaseHTTPServer.py", line 259, in handle if not self.parse_request(): # An error code has been sent, just exit File "C:\usr\python\lib\BaseHTTPServer.py", line 243, in parse_request self.send_error(400, "Bad request syntax (%s)" % `requestline`) File "C:\usr\python\lib\BaseHTTPServer.py", line 291, in send_error self.wfile.write(self.error_message_format % File "C:\usr\python\lib\socket.py", line 192, in write self.flush() File "C:\usr\python\lib\socket.py", line 179, in flush self._sock.sendall(self._wbuf) AttributeError: sendall ---------------------------------------- Exception exceptions.AttributeError: 'sendall' in ignored ------------ Any ideas ? All the best, Harald "Harald Schneider" schrieb im Newsbeitrag news:b5fo5a$ieb$03$1 at news.t-online.com... > Now it's getting interesting: > > The test for SSL in xmlrpclib is OK. The prob is socket.py: > > ----------------------------------- > if (sys.platform.lower().startswith("win") > or (hasattr(os, 'uname') and os.uname()[0] == "BeOS") > or (sys.platform=="RISCOS")): > > _realsocketcall = _socket.socket > > def socket(family, type, proto=0): > return _socketobject(_realsocketcall(family, type, proto)) > > try: > _realsslcall = _socket.ssl > except AttributeError: > pass # No ssl > ----------------------------------- > > It raises an AttributeError: socket has no attrib ssl. > Is there a version of socket.pyd with SSL support enabled out there for > Win32/Python 2.1 ? > > --Harald > > > > > > "Harald Schneider" schrieb im Newsbeitrag > news:b5fnif$hd2$04$1 at news.t-online.com... > > Sorry -- I was too fast: > > It surely has HTTPS support, but xmlrpclib claims, that it wouldn't. The > > test method of my xmlrpclib is not up to date. > > > > --Harald > > > > > > "Harald Schneider" schrieb im Newsbeitrag > > news:b5fn2u$19e$05$1 at news.t-online.com... > > > Hi, > > > > > > does there exist a httplib with SSL support for Python 2.1? > > > The one, that comes with ActiveState's distribution has no SSL support > ... > > > :-/ > > > > > > Thanks for your answers, > > > Harald > > > > > > > > > > > > From godoy at metalab.unc.edu Tue Mar 25 19:05:08 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Tue, 25 Mar 2003 21:05:08 -0300 Subject: Finding out the weekday References: Message-ID: <86znnjc7rf.fsf@ieee.org> "Mark McEahern" writes: > [Jorge Godoy] >> Is there any Python module that given a particular date it returns me >> the day of the week? I'm needing it for some special calculations >> involving dates... > > import time > weekday = time.localtime()[6] > > As help(time) says, Monday is 0. Thanks. I had found this before posting... I told in the other message that the calendar module seems more suitable for what I'm needing. I appreciated a lot your answer. -- Godoy. From exarkun at intarweb.us Mon Mar 17 14:31:20 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 17 Mar 2003 14:31:20 -0500 Subject: Programmatic HTML? In-Reply-To: <173c7vkboomefme64r0hjqqvn4507h5emh@4ax.com> References: <173c7vkboomefme64r0hjqqvn4507h5emh@4ax.com> Message-ID: <20030317193120.GA23723@meson.dyndns.org> On Mon, Mar 17, 2003 at 05:57:38PM +0000, Afanasiy wrote: > I have a use for a Python module which would allow > me to call functions which generate common HTML. > > A simple example of which might be : > > html.link('http://example.com','Example Website') > > I am of course capable of writing a module for the above example... > > But I was hoping for something conclusive and well designed, > with all sorts of neat Pythonic tricks I could not think of, > possibly especially apparent in table creation. > Check out Woven: http://twistedmatrix.com/documents/howto/woven Jp -- Lowery's Law: If it jams -- force it. If it breaks, it needed replacing anyway. -- up 14 days, 11:59, 5 users, load average: 0.01, 0.01, 0.00 From anonymous at microsoft.com Wed Mar 19 20:48:45 2003 From: anonymous at microsoft.com (Tracker) Date: Thu, 20 Mar 2003 02:48:45 +0100 Subject: Nasty launching of Python applications References: <0avh7vosq71l1vs1np4hrdfe8a9qucn0hl@4ax.com> Message-ID: On 19 Mar 2003 15:43:56 -0800, Cliff Wells wrote: >Change the name of your Python file from .py to .pyw. Alternatively, >you can associate .py files with pythonw.exe. THANX! From stda at enea.se Sun Mar 16 06:32:49 2003 From: stda at enea.se (Sten Dahlgren) Date: Sun, 16 Mar 2003 12:32:49 +0100 Subject: unicode and os.listdir References: <3E735FE6.60002@enea.se> <3E736E36.7050205@v.loewis.de> Message-ID: <3E7460E1.7070400@enea.se> Martin v. L?wis wrote: > Sten Dahlgren wrote: > >> Problem: i would like to scan through a windows volume that contains >> filenames with unicode filenames (utf16) but when i try os.listdir("y:") >> i get the result ['???'] the only file there is 3 unicode characters wide > > > I assume you are using some variant of Microsoft Windows? > yepp > In that case, you should use Python 2.3, and pass a Unicode directory > name to listdir; the resulting file names will then be Unicode objects > as well (see PEP 277). got it, i used os.listdir(unicode("y:")) thanks for taking your time it saved me! > > Regards, > Martin > From jerf at jerf.org Sun Mar 30 13:14:05 2003 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 30 Mar 2003 18:14:05 GMT Subject: Nice quote References: <3E8597A2.13FE92DE@engcorp.com> <3E871AB6.F5418D76@engcorp.com> Message-ID: On Sun, 30 Mar 2003 11:26:30 -0500, Peter Hansen wrote: > Jeremy Bowers wrote: >> You may consider XML processing not a particular pain but I think that's >> more a personal judgment then anything else, because I don't see Python >> granting a huge advantage over Perl. > > a) Of _course_ it's a personal judgment. (and from later) > (I've never understood why people think personal judgments, a.k.a. > "opinions", are such a bad thing... every has them, but nobody likes them? > :-) I don't mean to imply that it is therefore invalid or bad, sorry. What I mean is that it's not so clear an advantage that it transcends the very fuzzy line between "personal judgement" and "obvious, if not really 'objective', fact". (An example of the latter is "For most programming tasks, Python will result in shorter and easier-to-maintain programs than C++ will." You can't really *prove* it, but for most practical purposes it's true.) > b) I'm not clear why you think anyone was saying there's a "huge > advantage" over Perl. They weren't! (I suspect) Logic like this: 1. (From Tim Bray) Current programming paradigms/libraries for XML suck. 2. (From Tim Bray) Python people report it is not a problem. 3. For the purposes of discussion, assume 2 as fact. 4. 1 & 3 -> Python must have an XML programming paradigm/library that does not suck. 5. Such a library would be a "huge advantage" (my words) over Perl. The hope that I would find out what this library/paradigm was is what prompted my original post. Wasn't fruitless, as I was not as aware of gnosis as I am now. (Had previously heard of the xml.pickle module but was not aware it was part of a family of other XML tools.) > They simply were saying > they didn't see there being a big problem in Python-land. If those who > spend their time in Perl-land complain a lot more than those in > Python-land, perhaps one can start to draw some conclusions, but one of > those might simply be that Perl-folk are so stressed they need to vent > some anger, while Python-folk are pretty happy in their daily lives. :-) Once I get the data into the Python program I am happier; if that's all the Python people were getting at then I am somewhat disappointed. I suspect Tim Bray will be as well, since IMHO he was clearly complaining about libraries, and if he does learn Python hoping to find something better, IMHO he's going to end up disappointed to find out that's all the "Python people" were referring to. Ironically, I would have *expected* that the Python community would be that much more likely to try to come up with and embrace a better XML parsing solution, as the current SAX/DOM approaches are that much uglier by contrast to the rest of Python code. In Perl it fits in better with the generally cruftiness... seems the opposite has occurred and the language compensates enough for the cruft in SAX/DOM that it doesn't cross the irritation threshold. (For what it's worth, my original posting is prompted by the fact that I intend to write a program in the near future that will want to be reading effectively arbitrary document XML formats, up to and including the, shall we say, "well-marked up" contents of a Microsoft Office XML document. I'm going to need all the power I can get, because time will be money.) >> At best Python XML processing is at most a small linear improvement over >> Perl. > > That sounds very much like a personal judgment to me. But tending toward the "obvious fact" side, as described above, though not quite making it. A SAX-based parser in Perl and a SAX-based parser in Python are going to be the same basic size, to within some linear factor, if they are both doing the same thing. Post-parsing data structures may be nicer in Python, but that's a reflection of the language, not the parsing solution. A lot of people misinterpreted both of the Tim Bray pieces quite badly (see the Slashdot discussions on both articles for proof). My conclusion is that the "Python people"*, whomever they were, misinterpreted the first article as complaining about the final output of SAX/DOM approaches rather then the SAX/DOM approaches themselves, and that Python does not, with the possible exception of gnosis.xml (which I can't judge thoroughly as I haven't used it yet, though I feel confident the API is better then DOM), have any better solutions to the act of parsing XML then any other language. As always, YMMV and I'm not trying to push that conclusion down anybody's throat. ;-) And I'd like to wave my creds around as a bona-fide Python advocate; I'm not trying to dis Python, it's my favorite language, I just think that the claims someone made to Tim Bray were probably not correct, just as "Pure Python is the best solution for every programming problem" is not correct. *- A reminder that by "Python people" I mean the ones Tim Bray was referring to in his post, who reported that Python has no problems with XML. From aleax at aleax.it Mon Mar 24 13:14:03 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 24 Mar 2003 18:14:03 GMT Subject: Newbie questions References: <3e7f3dbc$1_5@news.meganetnews.com> Message-ID: Ladv?nszky K?roly wrote: > I'd like to get help with the following issues. > > 1. > Is there a faster way to allocate a list of objects than this one? > > ls=cnt*[None] > for j in range(cnt): > ls[j]=TestClass(j) Yes, but you can easily check such questions for yourself, particularly thanks to the little jewel named timeit.py that comes with Python 2.3 (but works quite well even with 2.2 -- you can download it at [one single BIG url...]: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/*checkout*/python/python/dist/src/Lib/timeit.py?rev=1.9&content-type=text/plain and then: [alex at lancelot alex]$ python timeit.py -s 'def TestClass(x): return x' \ > -s 'cnt = 1111' \ > 'ls = cnt * [None]' \ > 'for j in range(cnt): ls[j] = TestClass(j)' 1000 loops, best of 3: 900 usec per loop [alex at lancelot alex]$ python timeit.py -s 'def TestClass(x): return x' -s 'cnt = 1111' 'ls = [TestClass(j) for j in range(cnt)]' 1000 loops, best of 3: 1.22e+03 usec per loop [alex at lancelot alex]$ So, the preallocated list saves about 1220-900 = 300+ microseconds, for a list of 1111 items, vs the obvious approach (a list comprehension); BUT: [alex at lancelot alex]$ python timeit.py -s 'def TestClass(x): return x' -s 'cnt = 1111' 'ls = map(TestClass,range(cnt))' 1000 loops, best of 3: 746 usec per loop [alex at lancelot alex]$ built-in function map can slice another 150 microseconds or so (when you need no lambda nor other extra levels of call to use it). You presumably mean TestClass to be a class, not a function, but that doesn't change the timings' rankings: [alex at lancelot alex]$ python timeit.py -s 'class TestClass:' -s ' def __init__(self, j): self.j=j' -s 'cnt = 1111' 'ls = map(TestClass,range(cnt))' 100 loops, best of 3: 4.36e+03 usec per loop [alex at lancelot alex]$ python timeit.py -s 'class TestClass:' -s ' def __init__(self, j): self.j=j' -s 'cnt = 1111' 'ls = [TestClass(j) for j in range(cnt)]' 100 loops, best of 3: 5.11e+03 usec per loop [alex at lancelot alex]$ Rarely do you HAVE to wonder about such differences -- simplicity, clarity, and the like are paramount -- but when you do, timeit.py is your friend! > 2. > I understand that it's relatively easy to interface C++ DLLs to Python > code. What are the main limitations? Can Python code use C++ objects, can > they be pickle saved? You can interface C++ code to Python quite easily with Boost (if your mastery of C++ is superb and you spend some time mastering Boost just as well -- if you think your mastery of C++ is NOT superb, I think you might be best advised to stay as far from C++ as you can, for production uses, until you HAVE mastered it thoroughly). But objects coded in C or C++ cannot be pickled unless, in their Python interface strata, you expose suitable __getstate__ &c special methods -- Python cannot guess what state each such object might need to save and restore, but you may be able to express this. Alex From hat at se-46.wpa.wtb.tue.nl Tue Mar 18 04:30:30 2003 From: hat at se-46.wpa.wtb.tue.nl (Albert Hofkamp) Date: Tue, 18 Mar 2003 09:30:30 +0000 (UTC) Subject: Serializing PyThreads without holding interpreter lock? References: Message-ID: On Mon, 17 Mar 2003 17:25:01 +0100, Martin v. L?wis wrote: >> At first sight, a solution to this problem seems to be releasing the >> global interpreter lock, by >> 1) adding Py_BEGIN_UNBLOCK_THREADS and Py_BEGIN_BLOCK_THREADS >> around the call to the solver, and > > You should use Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS > here. Maybe. I do need access to the state though, because I have to pass it on through the solver code down to the call-back functions, which need to restore the state before jumping back to Python. After the call to Python returns, I need to save the state again, so I can restore it after the call to the solver. > >> The question is now how to prevent this from happening, i.e. how do I >> serialize calls to the solver without holding the global interpreter lock? > > I recommend to put another lock around the solver code. See _tkinter.c > for an example; it also puts Tcl into a lock. This requires a few additional > macros, since you need a state where you hold both locks, and a state > where you just hold the solver lock. Tnx for the pointer. Luckily, my situation is somewhat easier because the solver is not multi-threaded. (phew!) >> The Python C programming manuals do give a number of primitives for >> handling thread, but blocking threads is not part of the provided >> functionality. > > That's not true. If you allocate additional locks, waiting for these locks > will block the calling thread if another thread already holds the lock. I just checked again, PyThread_lock_type, PyThread_acquire_lock, and PyThread_release_lock are _NOT_ in the (index of the) C/API manual and neither are they in the embedding/extending manual, at least I couldn't find them. Maybe there are other manuals that describe thread-programming in Python? Anyway, I think I have enough information to solve our problem. Tnx everybody. Albert -- Unlike popular belief, the .doc format is not an open publically available format. From rudy.schockaert at pandora.be Thu Mar 13 02:45:58 2003 From: rudy.schockaert at pandora.be (Rudy Schockaert) Date: Thu, 13 Mar 2003 07:45:58 GMT Subject: Long integers: to L or not to L? References: <2632446.1047448854@dbforums.com> Message-ID: > > Also, why does this raise an error? (numbers in front of lines > > indicate levels of indentation) > > > > def h(): > > 1 i = 0 > > 1 def h1(): > > 3 i = i + 1 > > 3 print 1, i > > 3 if i == 5: > > 4 return i > > 3 else: > > 4 i = h1() > > 4 return i > > 1 i = h1() > > 1 print 2, i > > > > Posting code is annoying... If you save the 'obfuscated' Python code in a file and run it with a filename as first parameter, there is no error anymore. It still is however not yet clear to me what this thing does. Rudy From Padraig at Linux.ie Tue Mar 4 06:51:49 2003 From: Padraig at Linux.ie (Padraig at Linux.ie) Date: Tue, 04 Mar 2003 11:51:49 +0000 Subject: gtk popup window question In-Reply-To: References: Message-ID: Wouter van Marle wrote: > Hi all! > > For my application I am trying to write a simple module to do the following: > > - open a popup window (usually error, or info) with only an OK button. I > made such a window in Glade, it is a GtkMessageDialog (hope I am correct... > can't use news at home where I do my programming due to wacky server). > - change it for error, information, ... (there are five or six of these > options) > - change the text > > Even a dir() on the object didn't help me out! > > What to do? > There is no settext() option, or anything similar. Hmm message boxes are a bit tricky. Examples are always best. Have a look at: http://www.pixelbeat.org/fslint/ P?draig. From sameer_ at email.com Mon Mar 31 15:05:21 2003 From: sameer_ at email.com (sameer) Date: 31 Mar 2003 12:05:21 -0800 Subject: wxpython - wxListCtrl - not showing data every other column Message-ID: <6bd9f01b.0303311205.5c244b43@posting.google.com> wxpython - wxListCtrl - not showing data every other column, yet when I click on the empty row, I know it is set correctly with the ItemData. How can I get data to show up in all rows, and not every other? Relevant python code follows. Thanks in Advance self.appts_list = wxListCtrl(self, 220, size=(220,160), style=wxLC_REPORT|wxSUNKEN_BORDER|wxLC_VRULES|wxLC_HRULES) self.appts_list.InsertColumn(0, "Check") self.appts_list.InsertColumn(1, "Time") self.appts_list.InsertColumn(2, "Text") self.appts_list.SetTextColour(wxBLUE) self.appts_list.EnsureVisible(1) ..... for i in range(len(appointments)-1, -1, -1): hour = str(appointments[i].date_time.hour) date = appointments[i].date_time.strftime("%x") time = appointments[i].date_time.strftime("%X") self.appts_list.InsertStringItem(i,'') #self.appts_list.SetStringItem(i, 0, ' ') self.appts_list.SetStringItem(i, 1, '%s. %s'%(date,time)) self.appts_list.SetStringItem(i, 2,appointments[i].getText()) self.appts_list.SetItemData(i, i) From lrl at cox.net Sat Mar 22 19:49:51 2003 From: lrl at cox.net (Luke) Date: 22 Mar 2003 16:49:51 -0800 Subject: a regular expression question References: <577e43a1.0303212331.5eaf93e5@posting.google.com> Message-ID: <577e43a1.0303221649.40498141@posting.google.com> Thanks, everyone. This was my first real encounter with re's. I need to find a better tutorial than the api info for the re package. I will heed your advice and examine parsing libraries--didn't know they existed. Guess you really do get the kitchen sink with Python. :) Luke From robin at jessikat.fsnet.co.uk Sun Mar 30 15:52:11 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 30 Mar 2003 21:52:11 +0100 Subject: Is Python overhyped (just like Java)? References: Message-ID: <7xC$7gA7j1h+Ew8I@jessikat.fsnet.co.uk> In article , Cliff Wells writes >On Sat, 2003-03-29 at 13:38, Ajay na wrote: >> Can some-one please explain why one would want to use Python? What is wrong >> with C++? > >> Those who use Python know they are sacrificing a lot in terms of memory and >> speed. > >And this is *why* they use Python: because it's slow and uses a lot of >memory. C++ is obviously outdated as it is unable to use the massive >amounts of memory and cpu tme that Python can. Think of the difference >between DOS and Windows XP: which uses more memory? Which is slower? >It's clear that *modern* software gets full utilization of that >expensive CPU you bought, while old stuff, like DOS and C++ just let it >go to waste. > >Regards, >Cliff I think Cliff has a valid point. Without Python I don't think we could get in tune with modern OSes. If we used C/C++ the OS would begin to seem slower and slower as we got more hyperspeed apps and we would become dissatisfied. -- Robin Becker From skip at pobox.com Wed Mar 19 15:21:33 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 19 Mar 2003 14:21:33 -0600 Subject: OT: Recommended Linux Laptops, suppliers? In-Reply-To: <1048104887.1118.9.camel@software1.logiplex.internal> References: <1048100028.1301.98.camel@software1.logiplex.internal> <15992.51278.390163.895099@montanaro.dyndns.org> <1048104887.1118.9.camel@software1.logiplex.internal> Message-ID: <15992.53581.64027.578138@montanaro.dyndns.org> Cliff> Returning to the topic of disorders, IANAP, but it appears you've Cliff> got that one where you just don't get it. Ah, I see. The missing smileys fooled me. explicitness-is-next-to-cleanliness-ly, y'rs, Skip From tebeka at cs.bgu.ac.il Mon Mar 24 06:20:26 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 24 Mar 2003 03:20:26 -0800 Subject: xml.dom.minidom on os x References: <20030323215111818+0100@news.freenet.de> Message-ID: <33803989.0303240320.32f4f9ad@posting.google.com> Hello Sascha, > #!/usr/bin/env python > from xml.dom.minidom import parseString > try: > > dom3 = parseString('Some data some more data') > > print "succeded" > except: > print "failed" > > has anybody an idea, why the parser does not work? Remove the try/except from the code and you'll get a stack trace with much more information. HTH. Miki From DennisR at dair.com Tue Mar 4 21:36:43 2003 From: DennisR at dair.com (Dennis Reinhardt) Date: Wed, 05 Mar 2003 02:36:43 GMT Subject: Vote on PEP 308: Ternary Operator References: <882b0a41.0303020225.3caf0334@posting.google.com> <1046630521.114725@yasure> Message-ID: <%od9a.788$LF3.693@newssvr16.news.prodigy.com> CCE: > Agreed. But I think you are throwing out the baby with the > bathwater here. What is useful about the terinary operator > is that for assignments it is clear that the lhs is uniform. > > z_of_useful_length = select abs(z_of_useful_length) > case < .0001: 1.0 > else: 1.0 + z_of_useful_length The assignment is spread across lines 1,2,3 and the comparison is on lines 1,2. I don't see the baby which is thrown out here. DR: > | if abs(z_of_useful_length) < .0001: > | z_of_useful_length = 1.0 > | else: > | z_of_useful_length += 1.0 > | > | ... much more readable. I think my example based on existing syntax is still more readable. Existing syntax allowing for single lhs is: def ternary(in_z): if abs(in_z)< .0001: return 1.0 else: return 1.0 + in_z z_of_useful_length = ternary(z_of_useful_length) -- Dennis Reinhardt DennisR at dair.com http://www.dair.com From brian at sweetapp.com Mon Mar 17 19:34:26 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 17 Mar 2003 16:34:26 -0800 Subject: OT: Recommended Linux Laptops, suppliers? In-Reply-To: <1047944775.1108.51.camel@software1.logiplex.internal> Message-ID: <016501c2ece6$219373e0$21795418@dell1700> > Indeed. However, I'm surprised to hear that Dell isn't shipping > Linux-only laptops. I think that they stopped selling consumer Linux computers, citing a lack of demand. > They certainly were for desktops (at least at one > time). How about IBM? I understand they've certified Linux for every > system they make, so I'd think a Windows-free system would be easy to > obtain from them. If there is limited demand for Windows-free systems, it doesn't make sense for them to support another product line. > Have to disagree here. Intel boxes, whether laptop or desktop tend to > be far cheaper than Apple products. If you are looking at the bottom end of the performance barrel, this is definitely true. > I have a catalog in hand at the moment (Global Computer) which features > a Systemax 2GHz Celeron, 15" TFT display, 128MB DDR, 20GB HDD, modem, NIC, > and WinXP for $899. No Powerbook ships with that little RAM, that small a hard drive, no CD burning ability, etc. The Systemax is also 1024x768, while the 15" Powerbook is 1280x854 i.e. 40% more display area. Looking at the Systemax laptop on the web, I also don't know: how fast the NIC is, what the specs are on the display (e.g. brightness, constrast) and what the expected battery life is. The bottom line is that computer comparisons require more information that two lines of text from a catalog. > A > similarly configured iBook or PowerBook (*if* they had one at 2GHz) > would cost well over $2000. Are you sure that a 1GHz G4 is slower than a 2GHz Celeron? I'm not. > Does OSX use X11? I ssh'd to my gf's school where they've got OSX and > it didn't seem like it. If not, that would be a sad decision. I'm not sure what using X11 would have gotten for Apple. What are X11 strengths? OTOH, using PDF as a display technology is a boon for Apple's traditional market of artists and publishers. Cheers, Brian From gh at ghaering.de Wed Mar 5 15:45:48 2003 From: gh at ghaering.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 5 Mar 2003 20:45:48 GMT Subject: ConfigParser: Bug or feature? References: Message-ID: Thor Arne Johansen wrote: > Quick question about the ConfigParser module: > > It raises an exception when you try to insert an already existing section > (which is good). > > However when parsing an external file (.read() or .readfp()) with multiple > defined sections it silently ignores all but the last one encountered. > > I looked at the source, and identified where this is happening, and it > appears this behavior is by design? > > I modified the code to raise an DuplicateSectionError exception, and it > gives the expected behavior (?). > > The docs say: > > """ > exception DuplicateSectionError > Exception raised when multiple sections with the same name are found, or if > add_section() is called with the name of a section that is already present. > """ > > I'm using Python 2.2.2 on linux, but I've verified the same behavior on > 2.2.1 (win98 and linux) > > Is this a bug or a feature?? I'd consider it a bug. You might want to submit your patch: http://python.org/patches/ -- Gerhard From clifford.wells at attbi.com Wed Mar 26 07:23:14 2003 From: clifford.wells at attbi.com (Cliff Wells) Date: 26 Mar 2003 04:23:14 -0800 Subject: More PyZEN? In-Reply-To: References: <1048619097.22313.60.camel@software1.logiplex.internal> Message-ID: <1048681394.3390.13.camel@cliff> On Wed, 2003-03-26 at 00:57, Harald Massa wrote: > >> It also appears that decompyle is choking on wmain.pyc =( > > So should we add to PyZEN: > > Don't spam on comp.lang.python > it will get decompyled And fixed, in this case. Except for the adware part, which somehow became broken. Win some, lose some Cliff From mail at heikokoehler.de Mon Mar 10 07:04:09 2003 From: mail at heikokoehler.de (Heiko =?ISO-8859-15?Q?K=F6hler?=) Date: Mon, 10 Mar 2003 13:04:09 +0100 Subject: embedded python: "integer is required", when calling PyRun_SimpleString References: <3e6b7168$0$27674$9b4e6d93@newsread4.arcor-online.net> Message-ID: <3e6c7f04$0$27685$9b4e6d93@newsread4.arcor-online.net> "Martin v. L?wis" wrote: > Heiko K?hler wrote: >> Im writting a QT and Scintilla based text editor with an embedded python >> interpreter. Sometimes when I call PyRun_SimpleString( "any_string") >> python aborts with message: "an integer is required". But when I call >> PyRun_SimpleString("pass"); PyRun_SimpleString("any_string") it works. > > I guess the implied question is: Why does that happen? > > This is difficult to tell: it depends on the actual value of > "any_string". Most likely, that contains a function call which requires > integers. > > Regards, > Martin A concret example: PyRun_SimpleString("print \"Hello\""); will cause the interpreter to abort too, but PyRun_SimpleString("pass"); PyRun_SimpleString("print \"Hello\""); works. The print function does not require an integer. Heiko From tweedgeezer at hotmail.com Thu Mar 6 13:27:09 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 6 Mar 2003 10:27:09 -0800 Subject: why self instead obj ? References: Message-ID: <698f09f8.0303061027.698b4e7e@posting.google.com> "Gerard Breiner" wrote in message news:... > I am beginner in Python and i wonder why the first argument of the__init__ > function is called "self" instead "obj" whereas self indicates > the object itself . It's just a method argument -- if you want to call yours "obj" rather than self, feel free, it's your choice. > Moreover, "obj" is easier to type on the keyboard and shorter than "self". I don't really think this is the case. On a QWERTY keyboard, self is a quick four taps of the keyboard, each using a different finger, three belonging to the home row and one belonging to the slightly-slower top row. obj, on the other hand, is three taps of the keyboard, the first two of which are the same finger, one of those two is even a ghastly bottom-row-stretch key. I think if you timed yourself, you could type self a lot faster and with a lot less strain than you could type obj. > Other people would think that "this" is better (as in java), but "obj" seems > to me more suitable. I think "self" is the most suitable name because (in most cases) we're not talking about *any* object, we're talking about the self object. We're talking about the instance itself. "obj" and "this" are both ambiguous -- we could be referring to any number of objects. "self", on the other hand, is explicitly the object being operated upon. Jeremy From tomchance at gmx.net Mon Mar 17 07:46:51 2003 From: tomchance at gmx.net (Tom Chance) Date: Mon, 17 Mar 2003 12:46:51 +0000 Subject: Finding child pids References: Message-ID: <5wjda.198$js2.4@newsfep3-gui.server.ntli.net> >> How can I get the pid of the command, and not just sh? > > Don't use a string. Use a list of strings with one string for each > argument. E.g. instead of > > "mycommand arg1 arg2" use ["mycommand", "arg1", "arg2"] Aha! Thank you, that works perfectly. Running external programs is always such a pain! ;) Tom From strachon at asd-software.cz Wed Mar 5 01:46:14 2003 From: strachon at asd-software.cz (strachon) Date: 4 Mar 2003 22:46:14 -0800 Subject: list in list of objects References: <29415857.0303040152.282448ec@posting.google.com> <6p%8a.2792$zo2.94628@news2.tin.it> Message-ID: <29415857.0303042246.19784eb0@posting.google.com> what i expected is something like 'similar syntax get similar results' that is why i was confused now i hope i underestand it better thanks for great explanation From simonb at webone.com.au Fri Mar 7 16:49:32 2003 From: simonb at webone.com.au (Simon Burton) Date: Sat, 08 Mar 2003 08:49:32 +1100 Subject: This sucks. References: <2614138.1047017673@dbforums.com> Message-ID: On Fri, 07 Mar 2003 13:52:23 +0000, Steve Holden wrote: > "Tetsuo" wrote in message > news:2614138.1047017673 at dbforums.com... >> >> No matter how much I look at my code, I can't see how 0>=10. I fixed a >> few things today, but the program still beyond fails. >> > It's all a question of what you're comparing: > >>>> 0 >= 10 > 0 >>>> "0" >= 10 > 1 >>>> > what the ? how/why are strings comparable to ints?? oh my goly: >>> "">[]>{}>1 1 what's the use of this :) i think i'd rather have an exception than be able to compare these guys! Simon Burton. From fredegar at haftmann-online.de Mon Mar 3 13:58:12 2003 From: fredegar at haftmann-online.de (Florian Fredegar Haftmann) Date: Mon, 03 Mar 2003 18:58:12 +0000 Subject: Invoking JavaScript event handler in Internet Explorer by python/win32com References: <8a27e309.0303030621.4c031256@posting.google.com> Message-ID: <3E63A5C4.9050003@haftmann-online.de> R.Marquez schrieb: > Not sure, but I think that you can invoke it by the index of the > button: > > class ButtonHandler(html.HTMLButtonElementEvents): > > def __init__(self, button, oldevt = None, idx): > self.idx = idx > > def Ononclick(self): > > [... any action ...] > if self.oldevt: > doc.[self.idx].click() > > If not, try finding out a way to do this. I us this code to click on > the third button on the first form of a page: > > doc.forms[0][3].click() Thank you very much, but this works only for onClick-events >>Of course you could use the .click method, but since I'd like to do >>the same procedure with other event handlers, too, that is'nt useful. Florian From tjreedy at udel.edu Sat Mar 29 16:10:08 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 29 Mar 2003 16:10:08 -0500 Subject: Metaphors and politics References: <1MudnTyOEK1mauGjXTWcqg@speakeasy.net> <3E835DC2.3678BD7F@engcorp.com> Message-ID: "Lulu of the Lotus-Eaters" wrote in message news:mailman.1048965415.15853.python-list at python.org... > "Terry Reedy" wrote previously: > |> In a dispatch from Amman, Jordan, distributed by UPI and published in > |> the Washington Times on March 23, veteran foreign correspondent > > Btw. for non-USA readers who may be unaware: the _Washington Times_ is > the house organ for Sun Myung Moon's Unification Church. Politically, > it is somewhere to the right of Ghengis Khan. Truth comes in many > guises, but the medium provides an initial clue. For someone claiming to be of superior intelligence and knowledge, this is pretty pathetic. UPI (United Press International), the *source* of the story (reread the first line of my quoted text above), is a major news service founded in 1907. Its reporters have included 'right-wingers' such as Walter Chronkite and Helen Thomas (well know liberals, for those who don't know). (See www.upi.com for more.) Their story was picked up by more than one of their subscribing newspapers. I picked the first that appeared on google's list. Here is another from Australia's Sunday Mail (another right-wing rag?) that combines the UPI info (I presume) with a local source. They quote from 3!! separate disillusioned (by reality) 'human-shield' returnees. Given people's general reluctance to reexamine deeply held beliefs even in the face of strong contrary evidence, this is pretty remarkable. http://www.thesundaymail.news.com.au/common/story_page/0,5936,6208143% 255E903,00.html ''' We were so naive 30mar03 HUMAN shields who fled Iraq after experiencing Saddam Hussein's brutal regime have admitted they were naive to volunteer for the role. [1] Australian Jake Nowakowski, 25, who spent three weeks in Baghdad, got his first glimpse of the true feelings of many Iraqis only on his way out. "It wasn't until we crossed the Iraq border back into Jordan that I asked the driver what he really thought about a war," Mr Nowakowski said on his return to Melbourne this week. "He said they didn't want war but they wanted to get rid of Saddam Hussein and it was an opportunity for that to happen." Mr Nowakowski said human shields were treated like pawns by Saddam's regime. "In retrospect I think we were being naive," he said. "We went into a country that was being run by a dictator." Mr Nowakowski was in Baghdad as a shield for the Truth, Justice, Peace group. He said accommodation and meals were paid by the Iraqi Government. The group first realised they were being used by Saddam when they were posted to a Baghdad power station. The Republican Guard set up barracks 500m away and the protesters found out the site had communication towers certain to become military targets. "We set out to shield humanitarian sites but the Iraqi officials were continually trying to manipulate where we could be," Mr Nowakowski said. "We were denied access to schools, hospitals and orphanages." Eventually he was posted to a grain storage terminal at al-Taji, 35km from Baghdad, that stored rice, barley and Australian wheat. But Mr Nowakowski said government control caused their enthusiasm to wane. They found out that their "minder" was a former high-ranking official in Saddam's Ba'ath Party. [2] Another human shield with a changed view is an American, the Reverend Kenneth Joseph, who said his trip "shocked me back to reality". He helped to secretly film 14 hours of uncensored video of Iraqi civilians. "Some told me they would commit suicide if the American bombing didn't start," Mr Joseph said. "They were willing to see their homes demolished to gain freedom from Saddam's bloody tyranny." Mr Joseph described Saddam as "a monster" the likes of which the world had not seen since Stalin and Hitler. "He and his son are sick sadists," he said. [3] Another human shield, American photographer Daniel Pepper, revealed how he was "a naive fool" to be a human shield. "I was shocked when I first met a pro-war Iraqi in Baghdad - a taxi driver taking me back to my hotel late at night. I explained that I was American and said, as we shields always did, 'Bush bad, war bad, Iraq good', " he wrote in London's Daily Telegraph. "He looked at me with an expression of incredulity. As he realised I was serious, he slowed down and started to speak in broken English about the evils of Saddam's regime. "Until then I had only heard the president spoken of with respect but now this guy was telling me how all of Iraq's oil money went into Saddam's pocket and that if you opposed him politically he would kill your whole family." Mr Pepper said he left Baghdad by taxi for Jordan with five other human shields. Over the border, they asked the driver what he felt about the regime and the threat of bombing and he replied that Iraqis " want America to bomb Saddam". After five weeks in Baghdad, Mr Pepper said: "Anyone with half a brain must see that Saddam has to be taken out. "It is extraordinarily ironic that the anti-war protesters are marching to defend a government which stops its people exercising that freedom." ''' Terry J. Reedy From aleax at aleax.it Sat Mar 15 03:19:36 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 15 Mar 2003 08:19:36 GMT Subject: Flying With Python (Strong versus Weak Typing) References: <37a869bc.0303102102.4533973@posting.google.com> <1047398589.950487@yasure> Message-ID: Paul Foley wrote: ... > On Fri, 14 Mar 2003 12:14:20 GMT, Alex Martelli wrote: > >> I've often daydreamed about having a language where I can offer >> such hints and compile my programs in at least two ways: > >> -- a debugging mode, where hints let the compiler insert checks >> for me and raise warnings or errors when my hints don't match >> reality, >> -- an optimizing mode, where the compiler trusts the hints (at >> least to some extent) and uses them to make fast code. > > Why daydream? You can have that today -- in Python, even! > > > Python the CMU Common Lisp compiler, that is :-) I have elaborated elsewhere as to why I prefer to use Python than Lisp -- I'm far more productive with Python. People who find themselves more productive with Lisp instead would be very well advised to consider using Lisp, particularly given the maturity of the compilers available for Lisp. >> But static typing doesn't come close to making the daydream any >> closer to true -- often such hints would be things of the form, e.g.: >> x > y >> rather than ones of the form, e.g.: >> isinstance(x, y) >> and why should I use a language that arbitrarily lets me (or even >> forces me to) offer hints of the latter and not of the former kind? > > I don't know. In CL you can say that x is of type (integer (y) *) > [assuming "y" is actually a number] to mean "integer with exclusive > lower bound y and no upper bound"; i.e., x > y Extending the concept of "type" in such ways (as Pascal also does, at least for integers) never stretches far enough (are "integers divisible by 3" a ``type''? If no, why should that particular constraint, x%3 == 0, not be modelable identically to x > y ...?) AND plays havoc with most other concepts normally related to "type" (what type is the result of e.g. x/y, x*y, x-y, ... when each of x and y is of type "integer with bounds A and B"...?). Not a winner, in my experience. Alex From none at of.your.business Fri Mar 14 14:41:53 2003 From: none at of.your.business (lynx) Date: Fri, 14 Mar 2003 14:41:53 -0500 Subject: No Do while/repeat until looping construct in python? References: <4017400e.0303130007.5762bf65@posting.google.com> <3bXba.70188$zo2.1844793@news2.tin.it> Message-ID: On Fri, 14 Mar 2003 00:45:42 +0000, Steven Taschuk wrote: [...] > But they're not equivalent, logical massage or no. > while not clean > rinse > lather > doesn't rinse and lather if already clean, while > repeat > rinse > lather > until clean > rinses and lathers at least once in all cases. i phrased that poorly. the insight i meant to talk about was that the two can be made effectively equivalent, through rewriting the conditional as appropriate; the one exception would be when you don't want the loop to run at all, in which case no amount of rewriting the conditional will make a postcondition loop work for you - but if *that's* the case, most likely you can just remove the loop entirely. -- PGP/GnuPG key (ID 1024D/3AC87BD1) available from keyservers everywhere Key fingerprint = FA8D 5EA4 E7DC 84B3 64BC 410C 7AEE 54CD 3AC8 7BD1 "...if you can fill the unforgiving minute with sixty seconds' worth of distance run..." From aleax at aleax.it Fri Mar 14 06:21:39 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Mar 2003 11:21:39 GMT Subject: strings in Python (newbie) References: <9397bfd5.0303120610.6d7b2f20@posting.google.com> Message-ID: <7Xica.56121$pG1.1289243@news1.tin.it> zif wrote: > Thanks, I'll try that as well. Another question: how > can I break long text/array elements across multiple > lines? If I'm reading your question correctly, the answer is easy -- Python concatenates multiple adjacent "physical" lines into a single "logical" line as long as an open parens (or bracket) hasn't yet been closed. So for ex: longstuff = [ 0, 1, 45, 67, 223, 23, 15, 43, 88, 99, 1, 0, 23, 24, 42, 15, 0, 2 ] just works. Note that indentation is arbitrary for all the physical lines except the first one (also known as "continuation lines") -- the one I'm showing here is just one reasonably popular convention (there are others, too). Alex From ark at gmx.net Mon Mar 24 15:03:11 2003 From: ark at gmx.net (Arne Koewing) Date: Mon, 24 Mar 2003 21:03:11 +0100 Subject: Python 2.3 True = False References: <3E7EB0C1.FB2A76EB@alcyone.com> Message-ID: Rene Pijlman writes: > Martin v. L?wis: >>At one point, there was a patch to restrict assignments to True and False >>for 2.3. This patch wasn't implemented as too much code actually did >>assign to True and False. > > You have got to be kidding :-D > > What did it assign True and False to? And why? it is often defined in scripts written in python before True and False were added to the language. I would welcome to restrict the assignment so that True could only get an value that is treated as true and False could only get an value that is treated as false and raise an exception or print a warning if a mutable object was assigned. From max at alcyone.com Fri Mar 14 17:13:41 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 14 Mar 2003 14:13:41 -0800 Subject: P.E.P. 3.0.8 ??? References: <3E71B03A.3A90C341@engcorp.com> <3E71B427.7BE071DE@alcyone.com> Message-ID: <3E725415.B3B3490C@alcyone.com> Skip Montanaro wrote: > I find it interesting that people involved in this PEP 308 debate have > begun > to resort to tactics similar to those used by spammers to try to > squeeze > their messages past peoples' spam/procmail/outlook/whatever filters. Yes, I am not exactly impressed with peoples' real-world demonstrations of how to lie with statistics. Don't like the official result? Tweak it until you get what you want. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ There is nothing wrong with sobriety in moderation. \__/ John Ciardi Physics reference / http://www.alcyone.com/max/reference/physics/ A physics reference. From sabbyxtabby at yahoo.com Mon Mar 3 22:34:38 2003 From: sabbyxtabby at yahoo.com (Sabby and Tabby) Date: 3 Mar 2003 19:34:38 -0800 Subject: Vote on PEP 308: Ternary Operator References: <882b0a41.0303020225.3caf0334@posting.google.com> Message-ID: Sheila King wrote: > Yes, very good idea. I actually decided to reject all preferences after > trying them out. Reason: I might actually have to read someone's code with > that nonsense in it some day. :((( Nonsense is nonsense is nonsense. Was this your vote? :) Q accept c and x or y Q accept (c and [x] or [y])[0] Q accept (lambda: x, lambda: y)[not c]() Sheila King x = "door" + (quantity>1 and "s" or "") data = (hasattr(s, 'open') and s.readlines() or s.split()) z = 1.0 + (abs(z) < .0001 and 0 or z) t = v[index] = (t<=0 and t-1.0 or -sigma /(t + 1.0)) return (len(s)<10 and linsort(s) or qsort(s)) -- Tabby From staschuk at telusplanet.net Thu Mar 6 03:12:08 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 6 Mar 2003 01:12:08 -0700 Subject: Waffling (was Re: single-line terinary operators considered harmful) In-Reply-To: ; from intentionally@blank.co.uk on Thu, Mar 06, 2003 at 03:20:32AM +0000 References: Message-ID: <20030306011208.A3116@tibia.amotlpaa.bogus> Quoth Stephen Horne: > On Wed, 5 Mar 2003 12:31:34 -0700, Steven Taschuk > wrote: [...] > >So, in Python: > > [1, 2, 3,] > > [1, 2, 3] > >Is the comma a terminator or a separator? > > Same thing. With either semicolons for (at least Pascal) statements > and commas in the above lists, the most pragmatic answer is 'who > cares'. [...] Why, surely this is an important theoretical point! How can we say we know Python if we don't even know whether its commas are separators or terminators?! After donning my holy war hat (to banish the thought that these terms are not a disjoint partition of the marks in question), I see they're definitely terminators in tuples, but probably separators elsewhere. > [...] Of course I tend to see commas as separators and find your top > example strange, and of course I might well see semicolons the same > way if I hadn't used them as terminators in several other languages. Did you see semicolons thus when you started programming? They're separators in all the natural languages which use them, afaik. I agree a final comma is strange in a one-line list such as [1, 2, 3,], but as pointed out in another thread a little while back, it's very handy when the list is long: spam = [ a_big_long_expression, another_big_long_expression, a_third_big_long_expression, ] The superfluous final comma makes this list easier to edit; no puncutation adjustments needed when moving items to and fro. Good style, imho. > > while ((*p_Dest++ = *p_Src++) != 0) > > ; > > I'm not sure. With modern compilers, using side effects like this is > IMO inherently bad - without the side-effects the loop has no purpose. > So while your right about the 'this line intentionally left blank' > effect, I still wouldn't use it myself. This style of code had value > when C was created (before decent optimisers had been developed), but > IMO it's had its day. Hm. How about a case like this? def consume(iterator, sentinel): """Consume elements from iterator up to and including first occurrence of sentinel, or end of stream. """ try: while it.next() != sentinel: pass except StopIteration: pass (Could be useful for error recovery in parsers, for example.) -- Steven Taschuk w_w staschuk at telusplanet.net ,-= U 1 1 From news at manuelmgarcia.com Tue Mar 25 14:54:04 2003 From: news at manuelmgarcia.com (Manuel Garcia) Date: Tue, 25 Mar 2003 19:54:04 GMT Subject: In need of a binge-and-purge idiom References: Message-ID: On Sun, 23 Mar 2003 14:19:53 -0500, "Tim Peters" wrote: >If the code made sense , something like > >def terminated_iterator(iterable, a_seperator): > for element in iterable: > yield element > yield a_separator > >would produce the original sequence, then tack a_separator on to the end. Isn't it a general rule that terminators are easier to work with than separators? I remember some programming guru saying this (Jon Bentley?) I think it was Pascal's use of separators between statements that convinced Dennis Ritchie to use terminators instead. When I have to deal with separators, I always tack an extra one on the end, using a trick like the one above, or a simple append or concatenation. This is usually good to make a boolean or repeated code vanish. For string processing, I usually throw an extra one on the front too, for good luck. Separator is also harder to spell than terminator. ;-) Manuel From aleax at aleax.it Thu Mar 20 09:37:57 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 20 Mar 2003 14:37:57 GMT Subject: Question regarding a recent article on informit.com References: Message-ID: <9nkea.125445$zo2.3289148@news2.tin.it> Cameron Laird wrote: ... > For examples, see anything Alex writes (one suspects he > manages to invoke list comprehensions on trips to the food > market or automobile repair shop). Are the *Linux Magazine* > articles on-line? In any case, his two (or one-and-a-fraction) > Python books are both quite clear in their use of list com- > prehensions. Heh, thanks! Yes, the LM articles are online: for URLs to much of the stuff I've written, see http://www.strakt.com/dev_references.php . Alex From mhammond at skippinet.com.au Sat Mar 22 20:49:49 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 23 Mar 2003 01:49:49 GMT Subject: Free-threading, COM and Multiple CPU's In-Reply-To: References: Message-ID: <1p8fa.2103$Ov1.12214@news-server.bigpond.net.au> Engel, Gregory wrote: > At the very end of Mark Hammond and Andy Robinson's excellent book, Thanks! > "Python Programming on Win32" they provide example code for creating > free-threaded objects, demonstrating that COM spins up a new thread > to host objects created by a main thread. My question is, under > these conditions would the free-threaded COM objects utilize the > resources of multiple CPU's? Unfortunately, I am not developing on a > multiple CPU box yet may be required to deploy on a multiple CPU box. In general, no. Only one processor can ever be executing in the Python VM at a time. But if the COM objects you use are implemented in *say) C++ and Python is only driving them, then although Python will not execute on both at once, the objects themselves might. Of course, if you are talking about implementing these objects in Python, we are back in the same boat. It may be possible for you to use RemoteServer COM objects, thereby having each object in its own process, and this would execute concurrently. Mark. From aleax at aleax.it Thu Mar 13 13:20:38 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Mar 2003 18:20:38 GMT Subject: Generic optional delegation: is it possible? References: Message-ID: Eric Brunel wrote: ... > I just stumbled on a problem and I can't see a way of doing it in an > "elegant" way. Here it is: I have objects that may have another object > attached to them. If this object is actually attached, I want all methods > to be delegated to it. Otherwise, I want the object to call the methods on > its super-class. Having a superclass, as you've noticed, means automatic delegation and thus in particular it means "having" all methods of the superclass. If you could avoid the inheritance, you'd therefore save yourself a lot of trouble. Still, even if you're doomed to inherit anyway, there may be some solutions -- depending on the amount of (memory) overhead you're able and willing to tolerate, and on whether you can do without special methods (OR can stick with "classic classes", in which case the following also works for special method -- for newstyle classes, you need a slightly trickier solution based on a special-purpose dynamically generated class). E.g.: > class Delegating(SuperClass): > def __init__(self, delegate=None): > self.__delegate = delegate add here (warning -- untested code): if self.__delegate: for name in dir(self): if hasattr(self.__delegate, name): attrval = getattr(self.__delegate, name) setattr(self, name, attrval) key idea: "override" the superclass's attributes with the similarly-named attributes of the delegate *in self*. You can also leave in the following: > def __getattr__(self, attr): > if self.__delegate is not None: > return getattr(self.__delegate, attr) to catch attributes that are ONLY in the delegate and NOT in the superclass, but you don't need the else branch: > else: > return getattr(SuperClass, attr) > But it doesn't work: of course, object o1 *has* an attribute m (the method > inherited from SuperClass), so __getattr__ doesn't get called. > > Any ideas on how this can be achieved without having to type again all > methods on my sub-class? There are many other approaches, with different complications and applicability, including __getattribute__ (for newstyle classes only) and custom metaclasses (ditto). Python's introspective abilities DO ensure that you'll never need to "type again" such things;-). Alex From usenet at prettyhipprogramming.com Wed Mar 12 17:47:13 2003 From: usenet at prettyhipprogramming.com (Joel) Date: Wed, 12 Mar 2003 22:47:13 GMT Subject: win32com: Accessing MAPIOBJECT Message-ID: I've been tinkering with win32com in the hopes of being able to convert some of the mail in some of my Outlook folders into a mbox for use with SpamBayes. I've figured out how to access them messages, but they seem to only have the interfaces that Outlook itself needs: Body, Subject, etc, and not the full headers for example. I assume that to get to the complete data of the message, I need to somehow access the MAPIOBJECT. Each message does have an attribute called MAPIOBJECT with a method called QueryInterface(). My question is that now I'm not sure what I'm supposed to do. QueryInterface calls for a CLSID but which one? Below is the code I've got so far. As it stands now, it walks through all of the folders in Outlook printing out the subject of each message. ######################################## from win32com.client import Dispatch import pythoncom def ol_walk(Folders, depth = 0): for fnum in range(Folders.Count): msgs = Folders.Item(fnum+1).Items spacer = " " * (5 * depth) dash = "-" * depth print "%sFolder: %s Number of Messages: %d" % \ (dash, Folders.Item(fnum+1).Name, msgs.Count) if msgs.Count: #msgs[n] is also valid instead of msgs.Item(n) for mnum in range(msgs.Count): #for mnum in range(1): try: print "%s Subject: %s" % \ (spacer, msgs.Item(mnum+1).Subject.encode()) except UnicodeError, msg: print "%s Unicode Error: %s" % (spacer, msg) ol_walk(Folders.Item(fnum+1).Folders, depth + 1) ol = Dispatch("Outlook.Application") ns = ol.GetNamespace("MAPI") ol_walk(ns.Folders) ###################################### Thanks Joel From db3l at fitlinxx.com Wed Mar 12 16:46:41 2003 From: db3l at fitlinxx.com (David Bolen) Date: 12 Mar 2003 16:46:41 -0500 Subject: Visual Python without ActivePython Message-ID: I was looking to evaluate Visual Python, but was wondering if anyone knew a way to get it to operate with a regular distribution (not ActiveState's ActivePython) since it seems to check specifically for ActivePython on startup. I've already got 5 versions of Python installed on my system (and have carefully picked which ones get involved in the few single-use registry settings), and would prefer not to need ActivePython just for an evaluation (not to mention I'm not sure what registry "adjustments" installing it might do for free). I'd expect my standard 2.1 or 2.2 installation, including win32all, should be more than sufficient to run Visual Python. Thanks. -- -- 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 roy at panix.com Sat Mar 8 23:03:23 2003 From: roy at panix.com (Roy Smith) Date: Sat, 08 Mar 2003 23:03:23 -0500 Subject: A suggestion for a possible Python module References: Message-ID: Mark VandeWettering wrote: > Honestly, what commonly programmed task requires string reversal? Commonly used in the biosciences. Given a DNA sequence, you often want to reverse it. Either that, or as somebody else already mentioned, you got a homework assignment in your Into To Programming course :-) From aleax at aleax.it Wed Mar 12 12:55:36 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 12 Mar 2003 17:55:36 GMT Subject: Pre-PEP: Refusing to guess in string formatting operations References: <7h3smtsmy1r.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson wrote: > Jp Calderone writes: > >> In retrospect, I would rather have the method named __mod__. It is the >> only thing that -really- makes sense, and it clears up two related warts: >> using the % operator on strings calls no function reachable from Python, >> and subclasses of str cannot override the % behavior. > > This is fixed in 2.3, I'm fairly sure. Yep -- a % b does indeed call type(a).__mod__(b) in Python 2.3. Alex From max at alcyone.com Wed Mar 26 21:19:14 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 26 Mar 2003 18:19:14 -0800 Subject: Help me please : Rounding-down numbers References: <7b424d28.0303261608.47ba9dd3@posting.google.com> Message-ID: <3E825FA2.358C5D67@alcyone.com> Skip Montanaro wrote: > There is also the floor() function in the math module: > > >>> math.floor(4.71) > 4.0 > >>> int(4.71) > 4 Note that math.floor and int don't have quite the same behavior (glossing over the obvious difference that the former returns a float) for the case of negative numbers. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Even paranoids have real enemies. \__/ Delmore Schwartz Official Omega page / http://www.alcyone.com/max/projects/omega/ The official distribution page for the popular Roguelike, Omega. From knight at baldmt.com Fri Mar 28 11:13:44 2003 From: knight at baldmt.com (Steven Knight) Date: Fri, 28 Mar 2003 10:13:44 -0600 (CST) Subject: ANNOUNCE: SCons 0.12 (build tool in Python) is now available Message-ID: SCons is a software construction tool (build tool, or make tool) written in Python. It is based on the design which won the Software Carpentry build tool competition in August 2000. Version 0.12 of SCons has been released and is available for download from the SCons web site: http://www.scons.org/ Or through the download link at the SCons project page at SourceForge: http://sourceforge.net/projects/scons/ RPM and Debian packages and a Win32 installer are all available, in addition to the traditional .tar.gz and .zip files. WHAT'S NEW IN THIS RELEASE? IMPORTANT: Release 0.12 contains the following interface changes: - SCons now changes to the directory in which an SConscript file resides while reading that SConscript file. See the release notes for more information about this change. This release adds the following features: - Support has been added for fetching source files from the SCCS, RCS, CVS, Perforce and BitKeeper source code management systems. - A separate src_dir argument to SConscript() allows explicit specification of where source files can be found. - Current Builder-based command generators can be replaced by more flexible generators based on callable construction variables. - The Install() and InstallAs() builders now copy files. This behavior is now configurable via the INSTALL construction variable. - SCons now issues a warning if you try to use the reserved variable names TARGET, TARGETS, SOURCE or SOURCES. - Builders for Tar and Zip files have been added. - SCons now supports an explicit Exit() function for terminating early. - The masm tool now supports SharedObject() builds. This release removes the following deprecated features: - Builder objects no longer support a "name" argument. - The Environment.Update() method has been removed. The following fixes have been added: - The string value of a File or Dir node now rturns a path relative to the calling SConscript file's directory, not the top-level directory. - Commands that expand the third or later argument from $TARGET, $TARGETS, $SOURCE or $SOURCES now calculate signatures properly. - Exceptions thrown by Scanners are no longer silently eaten. - A built file may no longer be pushed to a CacheDir() with a signature of None. - Built files are no longer copied to a CacheDir() if they're already there. - Files copied to a CacheDir() are now written to a temporary file and renamed, to avoid corrupt partial copies. - The -U option with no Default() targets no longer throws an exception. - The -u option, when used from a source directory with no local targets, will now build corresponding targets in any associated BuildDir()s. - The WhereIs() function now returns normalized path names. - An Aliased source that doesn't exist no longer generates an incorrect dependency-cycle error. Performance has been improved as follows: - The internal to_String() function has been sped up. The documentation has been improved: - Clearer explanation has been added of how to export variables to a subsidiary SConscript file. - Bugs in various Tool examples have been fixed. - The man page now correctly describes that the -f option doesn't change to the directory in which the SConstruct file lives. ABOUT SCONS Distinctive features of SCons include: - a global view of all dependencies; no multiple passes to get everything built properly - configuration files are Python scripts, allowing the full use of a real scripting language to solve difficult build problems - a modular architecture allows the SCons Build Engine to be embedded in other Python software - the ability to scan files for implicit dependencies (#include files); - improved parallel build (-j) support that provides consistent build speedup regardless of source tree layout - use of MD5 signatures to decide if a file has really changed; no need to "touch" files to fool make that something is up-to-date - easily extensible through user-defined Builder and Scanner objects - build actions can be Python code, as well as external commands An scons-users mailing list is available for those interested in getting started using SCons. You can subscribe at: http://lists.sourceforge.net/lists/listinfo/scons-users Alternatively, we invite you to subscribe to the low-volume scons-announce mailing list to receive notification when new versions of SCons become available: http://lists.sourceforge.net/lists/listinfo/scons-announce ACKNOWLEDGEMENTS Special thanks to Charles Crain, Lachlan O'Dea, Jeff Petkau and Anthony Roach for their contributions to this release. On behalf of the SCons team, --SK From mhammond at skippinet.com.au Fri Mar 28 19:18:44 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 29 Mar 2003 00:18:44 GMT Subject: Profiling Embedded Code In-Reply-To: <3e84bf28$0$59852$65c69314@mercury.nildram.net> References: <3e84bf28$0$59852$65c69314@mercury.nildram.net> Message-ID: Andrew Wilkinson wrote: > Hi, > > I've got some Python code that is embedded into a C application, and I'd > like to profile it. Unfortunatly I can't get the standard profile module to > work. > > My C code imports a module, and then at the appropriate time calls the > UpdateGameData function. When the module is imported I'd like to do a 'test' > run of the function, with the profiler on to perform a simple check on it. > (I know this is not a particually good way to profile the code, but I'd like > to get it working and then move on...) > > The module is given (slightly trimmed) here... > --- > def UpdateGameData(time): > ... > > > import profile > p = profile.Profile() > p.run('UpdateGameData(0)') > -- > > With this code I get the following exception... > Traceback (most recent call last): > File "./python/core.py", line 28, in ? > p.run('UpdateGameData(0)') > File "c:/programming/python/lib/profile.py", line 403, in run > return self.runctx(cmd, dict, dict) > File "c:/programming/python/lib/profile.py", line 409, in runctx > exec cmd in globals, locals > File "", line 1, in ? > NameError: name 'UpdateGameData' is not defined > > Now this seems very silly to me as 'UpdateGameData' obviously is defined. I > had a look in the code for profile and it seems to mess around with > __main__, but I'm not sure that it's pointing at the right place. __main__ is not what you want in this situation. Try the "runcall" method in the profiler - you pass the function itself to this. Mark. From grante at visi.com Fri Mar 7 12:04:56 2003 From: grante at visi.com (Grant Edwards) Date: 07 Mar 2003 17:04:56 GMT Subject: Socket connection References: Message-ID: <3e68d138$0$52899$a1866201@newsreader.visi.com> In article , sik0fewl wrote: > I had no idea that x = y just references y to x Not really. The assignment statement x = y Causes the name "x" to be bound to whatever object the name "y" is currently bound to. In this usage, "bound to" means the same thin as "references" in your posting. > (when x & y are lists). When x and y are anything. x = [] That creates a list object and points the name "x" at it: "x" --> Then the assignment y = x Points the name "y" at the same object: "x" --> "y" --> The important thing is to realize that when you do x = [] That doesn't make "x" a list. "x" is just a name in a namespace. The actual list is an independant object that lives off in some undefined place. The assignment creates a name "x" and makes it reference that object. The list object doesn't even _know_ that it is pointed to by the name "x" in some namespace or other. [Unless you want to talk about reference counted garbage collection. Then the list knows that it is indeed pointed to, but that's an under-the-covers implimentation mechanism that isn't part of the language definition.] -- Grant Edwards grante Yow! NOT fucking!! Also at not a PACKAGE of LOOSE-LEAF visi.com PAPER!! From christoph at mmc-startup.com Thu Mar 6 07:01:57 2003 From: christoph at mmc-startup.com (Christoph Becker-Freyseng) Date: Thu, 06 Mar 2003 13:01:57 +0100 Subject: Help on sys.getrefcount Message-ID: <3E6738B5.1050208@mmc-startup.com> Hello, I wrote the following test-program: import sys l= ['x', 'y', 'z', 'a'] for iR in l: refD= sys.getrefcount(iR) print str(iR) + '::' + str(refD) It's output is: x::7 y::7 z::7 a::8 I expected the output to be: x::3 y::3 z::3 a::3 I don't see why the refcount is so high (7 or 8 instead 3). What's even more strange to me is: Why is the refcount for 'a' higher than for e.g. 'x'? This also is the fact when the order of the list is changed: import sys l= ['x', 'y', 'a', 'z'] for iR in l: refD= sys.getrefcount(iR) print str(iR) + '::' + str(refD) Output: x::7 y::7 a::8 z::7 This happens with Python 2.0 on SuSE Linux 7.3 with 2.218 Kernel. Many Thanks, Christoph Becker-Freyseng From aleax at aleax.it Fri Mar 14 08:16:50 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Mar 2003 13:16:50 GMT Subject: Flying With Python (Strong versus Weak Typing) References: <37a869bc.0303102102.4533973@posting.google.com> Message-ID: <6Dkca.82244$zo2.2085763@news2.tin.it> Cameron Laird wrote: > In article , > Alex Martelli wrote: > . >>Static typing makes it easier for the compiler to generate fast >>code, and (depending also on other issues) may slightly enhance >>programmer productivity by catching a small percentage of errors >>a bit earlier than testing would catch them -- that's all. It has > . > At the cost, of course, of what are likely to be > *larger* cuts in programmer productivity through > the overspecification static typing so often in- > volves. That's part of the "depending on other issues" parenthesis I had so glibly inserted. I think that static typing "done RIGHT" need not imply over-specification. However, I can think of only two examples of such "done RIGHT" along different routes: -- Haskell-like typeclasses: the compiler can infer the class T of types to which object X belongs by seeing what functions are called on X -- you may also optionally specify T yourself, in which case you also get the option to specify some T' that is more restrictive than T... but presumably you'll do so only advisedly, for specific purposes of expressing some very clear design intentions, not "overspecifying"; -- Dylan-like optional specification of types, which serves essentially to guide the compiler to generate faster code -- if you see type-specifications as part of _optimizing_ your program, then, again, you presumably won't be doing it _prematurely_ (as we all know, per Knuth, that premature optimization is the root of all evil in programming) -- so that choosing to express a type before the optimization phase can, again, be taken as an explicit expression of some very clear design intention. Static-typing systems that FORCE you to specify types needlessly (as a pure redundancy to what the compiler could perfectly well infer on its own) are subject to the specific criticism you express -- by MAKING you (prematurely?) specify something, they do indeed make it more likely that you'll over-specify it, with unfavourable productivity impact. But it would take as little as a local coding guideline to the extent that "thou shalt specify all types rather than rely on the compiler's type-inferencing system" (and sadly I _have_ seen that suggested for Haskell!) to make your criticism extend even to languages that, per see, _should_ be exempt from it. Alex From sholden at holdenweb.com Sun Mar 16 11:51:20 2003 From: sholden at holdenweb.com (Steve Holden) Date: Sun, 16 Mar 2003 16:51:20 GMT Subject: Upload of binary files References: Message-ID: "Peter Mott" wrote in message news:HBr4EA.oDB at leeds.ac.uk... > The problem described by myself has been solved in Ben Hutchings post: The > code belows works as we would wish - the binary file is uploaded and the > number of bytes returned to the client: > > > > try: > import msvcrt, os > msvcrt.setmode(0, os.O_BINARY) # stdin = 0 > msvcrt.setmode(1, os.O_BINARY) # stdout = 1 > except ImportError: > pass > > import cgi > import cgitb; cgitb.enable() > > form = cgi.FieldStorage() > > if form.has_key("Data"): > fileinfo=form["Data"] > chunk = fileinfo.file.read() > > > print "Content-type: text/plain\n\n" > print "Bytes read:",len(chunk) > > > The point is that without the import of msvcrt (providing low level Windows > support) the cgi module tries to treat all files as text and so the uploads > do not work. I am not a seasoned Python person but I don't think the above > code is very 'Pythonic' but for me it is a perl none the less. Thanks Ben! > One last thing you might try if your web server honors the shebang convention (as Xitami and Apache both do, for example, even on Windows) is to use a first line similar to #!C:/python22/python -u This will cause Python to run unbuffered, and should obviate the need to explicitly use the mscvrt module. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Register for PyCon now! http://www.python.org/pycon/reg.html From peter at engcorp.com Sat Mar 8 14:42:23 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 Mar 2003 14:42:23 -0500 Subject: Concerns about performance w/Python, Pysco on Pentiums References: <3E660EB3.4065D81F@engcorp.com> <3E66BA3F.7691C3B0@engcorp.com> <3e677433$0$87747$edfadb0f@dread11.news.tele.dk> <7h3bs0oh25s.fsf@pc150.maths.bris.ac.uk> <3E6784AD.E4D523BD@engcorp.com> <7h3y93sfldh.fsf@pc150.maths.bris.ac.uk> <3E67A2F2.187785EA@engcorp.com> <3E689FE6.9F117D30@engcorp.com> Message-ID: <3E6A479F.BB04C074@engcorp.com> Pedro Rodriguez wrote: > > If I focus on the "try/except", and pick up your comment that this should > not be frequent to fall in the exception case, so why clutter your code > with this test (or any test, like the one I posted) ? Just consider that > all opcodes are valid, but that the action for some will raise the > exception (def executeINVALIDOPCODE(): raise ...). That's an excellent idea that I hadn't considered. Although the HC12 itself has effectively no unimplemented opcodes, and my exception is there just until more than 34 are implemented, it's likely I will never implement some 50 or so of the opcodes as our real code doesn't use them. I'll throw in something to auto-build 256 "dummy" opcodes on startup, then allow them to be substituted with the real ones as they are defined. Thanks. :) > What about the next test, with the returned new PC, why not have the > opcode method do the proper job, only when needed (by passing the > opcode mode to the execute method, or just knowing, by design of the > opcode method, how it will affect the CPU PC). Something like that will probably happen, eventually, but right now the opcode handler functions are actually unaware of the specific opcode being executed and therefore don't know which addressing mode should be used. I could pass in the opcode, but as far as I can tell I'm then making the opcode handlers do something that the CPU itself is supposed to do (thus increasing the amount of duplicated code, thus reducing maintainability), *plus* I'm now passing in two parameters instead of just one when I call execute(). Thanks for the ideas. The thoughts on restructuring are good, but I'm going to trust in the test-driven development (TDD) approach to lead the design. If the code needs to go in the direction you suggest, it will lead me there on its own. -Peter From stevehanawalt at yahoo.com Wed Mar 12 17:51:26 2003 From: stevehanawalt at yahoo.com (Steve Hanawalt) Date: 12 Mar 2003 14:51:26 -0800 Subject: void pointers with SWIG Message-ID: <66f88664.0303121451.53598af1@posting.google.com> Hello, I've been trying to use SWIG to gain access to a DLL from a 3rd party which I don't have the source code for, but I do have the .dll, the .h, and the .lib. The .h contains many functions such as: FT_STATUS FT_ListDevices( PVOID pvArg1, PVOID pvArg2, DWORD Flags ); pvArg1 and pvArg2 can be both inputs and outputs depending on the value of Flags. A typical C call to this function would be: FT_STATUS ftStatus; DWORD numDevs; ftStatus = FT_ListDevices(&numDevs,NULL,FT_LIST_NUMBER_ONLY); If all works as expected, the number of devices connected is placed into numDevs.. Alternatively if the function is called as: FT_STATUS ftStatus; char *BufPtrs[3]; char Buffer1[64]; char Buffer2[64]; DWORD numDevs; BufPtrs[0] = Buffer1; BufPtrs[1] = Buffer2; BufPtrs[2] = NULL; ftStatus = FT_ListDevices(BufPtrs,&numDevs,FT_LIST_ALL|FT_OPEN_BY_DESCRIPTION); If all works as expected, the number of devices connected is placed into numDevs and product descriptions are placed into Buffer1 and Buffer2. I've tried various typemaps, but I can't seem to get it to work. I keep getting an error in Python like: "Expected _p_PVOID" Anyone been through this already that can provide me with the proper insight. I'm very new to SWIG and still fairly new to Python. Thanks in advance. Steve From LogiplexSoftware at earthlink.net Wed Mar 26 20:34:57 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 26 Mar 2003 17:34:57 -0800 Subject: wxPython win32 install absolute newbee In-Reply-To: References: Message-ID: <1048728897.1219.48.camel@software1.logiplex.internal> On Wed, 2003-03-26 at 16:22, toddmarshall2002 at yahoo.com wrote: > I cannot get wxpython running, in the most simple sense. > First of all the setup says > "No installation of Python 2.3 found in registry. Make sure that the version of wxPython you downloaded matches your version of Python. It sounds like you've got Python 2.2 installed and are trying to install the version of wxPython that's meant for Python 2.3. Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From rballard_99 at yahoo.com Tue Mar 4 13:55:18 2003 From: rballard_99 at yahoo.com (Bob Ballard) Date: Tue, 4 Mar 2003 12:55:18 -0600 Subject: md5 for large files References: Message-ID: You guys are great. I just need a nudge in the right direction from time to time. thanks Bob "Skip Montanaro" wrote in message news:mailman.1046800088.5929.python-list at python.org... > > Bob> Can someone provide me with a snippet or pointer to usinging Python > Bob> to verify the md5 value for a large file? All examples I've seen > Bob> are for a small string. I'm not yet using GPG for NT and I need to > Bob> verify or generate md5 values for file xfers. > > How about the library reference manual section at: > > http://www.python.org/doc/current/lib/module-md5.html > > The first example uses the .update() method. Read your file in chunks and > call .update(), then .digest() when you're through. > > Skip > From timr at probo.com Mon Mar 17 01:29:16 2003 From: timr at probo.com (Tim Roberts) Date: Sun, 16 Mar 2003 22:29:16 -0800 Subject: a simple question about string object References: Message-ID: "Frank Zheng" wrote: >Hi, all: > >>>> s = '12345' >>>> s[2] = 'x' >Traceback (most recent call last): > File "", line 1, in ? >TypeError: object doesn't support item assignment > >i know the string object is immutable, so if i want to do 'item assignment', >i should do: >>>> new_s = s[0:1] + 'x' + s[2:] >( i think it's ugly) It's also wrong: new_s = s[0:2] + 'x' + s[3:] Better yet is: new_s = "%sx%s" % (s[0:2],s[3:]) >Is there other ways to do this? >should i define a function to do this? Is there any modules existing can do >this? There is no standard module to do this. If you need to do this a lot, you can just convert the string to a list and manipulate the list: C:\tmp>python Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> s = '12345' >>> s_lst = list(s) >>> s_lst[2] = 'x' >>> s_lst ['1', '2', 'x', '4', '5'] >>> s = ''.join(s_lst) >>> s '12x45' >>> -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jmarshal at mathworks.com Mon Mar 3 16:31:45 2003 From: jmarshal at mathworks.com (Joshua Marshall) Date: Mon, 3 Mar 2003 21:31:45 +0000 (UTC) Subject: Why no RE match of A AND B? References: Message-ID: John Machin wrote: > Tim Peters wrote in message news:... >> >> For a so-called DFA algorithm, yes, because the intersection of regular >> languages is also regular, and membership in any regular language can be >> recognized in one pass over the string in question. What to do in the >> presence of (non-regular) backreferences is clear as mud, though, and >> Python's regexp package isn't a DFA engine anyway. I don't know of any >> regexp package that supports an intersection operator, so it would also >> suffer from novelty. All in all, better to do the obvious thing (i.e., run >> more than one regexp). > I seem to detect two quite different usages of "intersection": > (1) The regular language (RL) characterised by the RE "abc" produces > just one string i.e. 'abc'. Ditto the RL described by the RE "xyz" > produces just one string 'xyz'. I (a mug punter, not an expert) would > understand the intersection of the two RLs to be empty i.e. [] i.e. > the two RLs produce no common strings. Same with "a+" and "b+", > whereas "a*" and "b*" have a non-empty intersection ['']. > (2) The effect that the OP (together with Tim and other posters) > seemed to expect from the & operator was that (abc)&(xyz) would match > (abcxyz)|(xyzabc). I think the difference is that in Python, the RE "abc" matches any string containing 'abc', not just the exact string itself. I'd guess most formalists who aren't familiar with Python would write that regular expression as ".*abc.*", and expect they's need to write "(.*abc.*)&(.*xyz.*)" to match both 'abcxyz' and 'xyzabc'. From dfan at dfan.org Mon Mar 3 11:03:30 2003 From: dfan at dfan.org (Dan Schmidt) Date: Mon, 03 Mar 2003 11:03:30 -0500 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <8fb66v8qbv45eatnblq80p131793ej7e3m@4ax.com> Message-ID: Jack Diederich writes: | My major problem with 'lambda' is just the way it jars the eye when | reading code. Even with a colorizing editor the fact that it is a | word and a longish one at that adds to the cost of both writing and | reading map(), filter(), etc. 'lambda' is the only long keyword to | always appear in the middle of a line[2]. | | I know how the folks who want a ternary operator - ANY ternary | operator - feel, I'd take almost any way to make lambdas look nicer. | I've even considered recompiling my local Grammar with 'L' replacing | 'lambda'. I am a big fan of functional programming and I never use lambdas in my Python code because they're too ugly looking. (It's different in Lisp, where all the syntax looks the same, but even there I think lambda is too verbose - and so does Lisp guru Paul Graham, who's renamed lambda to fn in his new Lisp dialect Arc.) I'd complain more loudly, but I think Guido likes the fact that their ugliness dissuades people from using them... Luckily, in at least half of the places that I would want to use anonymous functions I can now use list comprehensions, which are quite pretty and clear. Dan -- http://www.dfan.org From jsaul at gmx.de Mon Mar 10 04:28:38 2003 From: jsaul at gmx.de (jsaul) Date: Mon, 10 Mar 2003 10:28:38 +0100 Subject: time.strftime() Message-ID: <20030310092838.GB695@jsaul.de> Hi there, I have a problem when using time.strftime() to compose a RFC822 date, namely the printed time zone is incorrect: >>> time.strftime("%a, %d %b %Y %H:%M:%S %z", time.localtime()) 'Mon, 10 Mar 2003 10:26:51 +0000' It should be '+0100' because this is CET time zone: >>> time.strftime("%Z",time.localtime()) 'CET' >>> time.timezone -3600 >>> time.strftime("%a, %d %b %Y %H:%M:%S %z", time.gmtime()) 'Mon, 10 Mar 2003 09:26:54 +0000' This is all correct. But I don't want to go via 'time.timezone' to get the proper offset into the date string. Unless the above behaviour is a bug, I must have overlooked something, but what? Cheers, jsaul From me at privacy.net Wed Mar 12 17:18:54 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Thu, 13 Mar 2003 11:18:54 +1300 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... In-Reply-To: References: <58q36vgv1ga8ovde5ftub9t8ugaa2pnum5@4ax.com> <3E62778F.EED49083@alcyone.com> <3E629E93.B94F7631@alcyone.com> <3E63AFA0.A3CAC045@alcyone.com> Message-ID: Thomas Bellman wrote: > From what I understand, code blocks in Smalltalk > execute in the same namespace/scope as the surrounding code, and > cam thus bind variables in the surrounding code. As far as I remember, they can have their own local variables, so it's probably more accurate to say that they execute in a lexically nested scope. But there's no problem with rebinding variables in an outer scope in Smalltalk, since all variables are declared. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bokr at oz.net Tue Mar 25 20:02:01 2003 From: bokr at oz.net (Bengt Richter) Date: 26 Mar 2003 01:02:01 GMT Subject: doing hundreds of re.subs efficiently on large strings References: <3E80CE1D.1000200@NOmyrealCAPSbox.com> Message-ID: On Tue, 25 Mar 2003 21:46:04 GMT, nihilo wrote: >I have a simple application that converts a file in one format to a file >in another format using string.replace and re.sub. There are about 150 >replacements occuring on files that are on the order of a few KB. Right >now, I represent the file contents as a string, and naively use >string.replace and re.sub to replace all the substrings that I need to >replace. I knew that I would have to come up with a faster, more memory >friendly solution eventually, but I just wanted to implement the basic >idea as simply as possible at first. > >Now I am at a loss as to how to proceed. I need a stringbuffer >equivalent that supports at least re.sub. Two alternatives that I have >seen for StringBuffer are using lists and then joining into a string at >the end, or using an array. Neither of these seems to be of much use to >me, since I am doing more than just appending to the end of the string. >Is there another pre-existing alternative that I'm overlooking? Or has >anybody come up with a good solution for this issue? > Is your substitution recursive? I.e., does each substitution operate on the finished result of a previous substitution? As in >>> 'abc'.replace('b','x').replace('xc','z') 'az' If not, you could split on the befores and then walk through the list and substitute corresponding afters and join the result, e.g., An example source: >>> s = """\ ... before1, before2 plain stuff ... and before3 and before4, and ... some more plain stuff. ... """ >>> print s before1, before2 plain stuff and before3 and before4, and some more plain stuff. Regex to split out befores: >>> import re >>> rxo = re.compile(r'(before1|before2|before3|before4)') The parens retain the matches as the odd indexed items: >>> rxo.split(s) ['', 'before1', ', ', 'before2', ' plain stuff\nand ', 'before3', ' and ', 'before4', ', and\nsome more plain stuff.\n'] A dict to look up substitutions: >>> subdict = dict([('before'+x, 'after'+x) for x in '1234']) >>> subdict {'before4': 'after4', 'before1': 'after1', 'before2': 'after2', 'before3': 'after3'} As above, but bind to s, so we can do substitutions on the odd elements: >>> s = rxo.split(s) >>> s ['', 'before1', ', ', 'before2', ' plain stuff\nand ', 'before3', ' and ', 'before4', ', and\nsome more plain stuff.\n'] Do the substitution: >>> for i in xrange(1,len(s),2): s[i] = subdict[s[i]] ... >>> s ['', 'after1', ', ', 'after2', ' plain stuff\nand ', 'after3', ' and ', 'after4', ', and\nsome more plain stuff.\n'] Join into single string: >>> ''.join(s) 'after1, after2 plain stuff\nand after3 and after4, and\nsome more plain stuff.\n' Print it to see in original format: >>> print ''.join(s) after1, after2 plain stuff and after3 and after4, and some more plain stuff. You could easily wrap this in a function, of course. Regards, Bengt Richter From lists at ghaering.de Thu Mar 20 11:20:22 2003 From: lists at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 20 Mar 2003 17:20:22 +0100 Subject: Object oriented databae for Python In-Reply-To: <15021177882.20030320174337@garret.ru> References: <15021177882.20030320174337@garret.ru> Message-ID: <3E79EA46.108@ghaering.de> Konstantin Knizhnik wrote: > I would like to announce embedded object oriented database for > languages with dynamic type checking: DyBASE. Currently APIs for Python, Ruby > and PHP are available. Great news you're doing Python now! I even thought once about wrapping GigaBASE for Python, but it seemed impractical :-) > DyBASE is easy to use and provide high performance. It is intended to be used in applications > which needs to deal with persistent data in more sophisticated way than load/store object tree > provided by standard serialization mechanism. Although DyBASE is very simple, it provides fault > tolerant support (ACID transactions) and concurrent access to the database. > > DyBASE is free and open source software distributed under MIT license. > You can find more information about it and download this product at > www.garret.ru/~knizhnik/dybase.html For all those who want to try it, it needs Python 2.2.2. With a simple trick, you could make it work on any 2.2.x, but people should use 2.2.2, anyway :-) Attached is a patch that: - adds a setup.py file to be able to use the distutils-based build processs for the Python extension. It will currently only work with gcc, though. The setup.py will just statically link in the dybase library, so *all* you need to do is a simple "python setup.py build" (or install, or bdist_wininst) and no more need to invoke any silly Makefiles :-) - uses DL_EXPORT in the Python extension and does away with an unnecessary win32 #ifdef - Makes the whole thing compilable under Cygwin and win32 native through mingw (both GCC flavours, the later being a native win32 one). This change is to use malloc instead of valloc on these compilers, because valloc doesn't seem to be available with them. And from what I checked here, valloc isn't available under MSVC6, either. Note that this patch doesn't yet make it possible to use the specific combination distutils+MSVC. But this can trivially be added later. Last but not least, thanks a lot for giving us this library. I'm sure I'll find some tasks where I'll use it. -- Gerhard [1] try: True except: True, False = 1, 0 -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: dybase_patch.dif URL: From tim.one at comcast.net Tue Mar 18 13:57:00 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 18 Mar 2003 13:57:00 -0500 Subject: What is PyInt_Fini? In-Reply-To: Message-ID: [Lexy Zhitenev] > All I have found out it is something from C part of Python API and it is > from Stackless. > > Actually I don't need detailed specifications, it's just curiosity. If the > answer can't be short please mail me or give a link. It's one of many "fini" routines called by Py_Finalize(), which shuts down an interpreter. PyInt_Fini releases storage that was allocated for Python integer objects. If you run Python with the -v flag, PyInt_Fini() is what prints the line like this as you exit the interpreter: # cleanup ints: 4 unfreed ints in 4 out of 108 blocks For more, read the source code. From franga at shentel.net Wed Mar 26 03:36:23 2003 From: franga at shentel.net (Francis Avila) Date: Wed, 26 Mar 2003 03:36:23 -0500 Subject: Unbuffer stdout? References: <1048659589.577001@yasure> Message-ID: "Donn Cave" wrote in message news:1048659589.577001 at yasure... > Quoth "Francis Avila" : > | >>> sys.stdout.write( os.popen2("yes", 'r', 0)[1].readline() ) > | y > | >>> > > It would, if the pipe ever closed, but the above doesn't make that > happen, I imagine because some internal references keep the file > object from being deleted. By the way, I don't think your parameters > to popen2() are right. You're right. It's meaningless to specify 'r' or 'w' on popen?(), since they return separate file objects for reading and writing. However, the function doesn't seem to complain.... I'm still curious as to why popen2() is not closing the pipe in this context, while popen() is. > Sort of. What do you think read() is supposed to do? Check it out: > > >>> print sys.stdin.read.__doc__ > read([size]) -> read at most size bytes, returned as a string. > > If the size argument is negative or omitted, read until EOF is reached. I realized this soon after I posted. I had somehow got it stuck in my head that read() should stream, or something, if the pipe were opened with bufsize=0. But of course that doesn't even make sense, since you can only return once. (Pipes are so _magical_ on the command line, I never really thought about implementation.) > | What I'm looking for is to pipe the stdout of a child process directly to > | the stdout of the parent process (i.e., the python script), without any > | buffering along the pipeline. As I see it, this is either not possible in > | python, or I'm going about this the wrong way. > > Well, it really is not possible to control this where it counts, which > is on the child process end. It will work only when the child process > takes it upon itself to flush its output buffer; some applications, > notable the shell, already do this, but most don't. With further investigation it seems that this is indeed my problem, since the app blocks any sort of pipe, even at the shell, even after being terminated. However, it doesn't seem to have any problem with writing directly to a terminal. I suppose I'm going to have to start digging into its code to see what's going on. > If you don't want to read a line at a time but just whatever input is > available, then I think it makes more sense (as usual) to forget the > file object and use the pipe file descriptor directly -- > fp = os.popen('yes') > fd = fp.fileno() > while 1: > data = os.read(fd, 16000) > if data: > os.write(1, data) > else: > break > fp.close() Is there any appreciable advantage to reading from the file descriptor directly verses passing an argument to read() or readline()? It seems as though: p = os.popen('yes') while 1: data = p.read(16000) if data: sys.stdout.write(data) else: break would do much the same, and be more intuitive. I guess it'd be faster, since there are fewer layers to cut through. > Because popen is in the os module? Built-in basically means that the > os module was written in C. popen is a C library function, so you > might find some documentation for it with "man 3 popen". Ah, I didn't realize "built-in" was that general (i.e., anything written in C). I thought it only referred to core functions, which is how the term seems to be used in the Library Reference. Thanks aplenty, you've really helped me think things straight. -- Francis Avila From achrist at easystreet.com Sat Mar 15 14:31:47 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Sat, 15 Mar 2003 11:31:47 -0800 Subject: [Q] Databases -- Gadfly vs Metakit vs SQLite Message-ID: <3E737FA3.51AB478E@easystreet.com> I'm looking for a simple database for a single-user Windows desktop application. The user's data will be text, maybe 10-20 data tables, with identifying keys and a few short fields plus plenty of long text memo-type fields. I should like to plan for databases up to about 50k rows and 100 MB of data, but the typical will be far less than this. It looks like Python gives me 3 good choices for this, Gadfly, SQLite, Metakit. I'd like comments that compare and contrast these for such an application. This is a desktop productivity app, so I'd like to get snappy response, no 1 or 2 second delays for a single update or retrieval. This should work to such a standard on a user's 300 MHz, 64 MB Windows machine. Does Gadfly need to fetch the entire database into RAM? This would be fine for me 99% of the time, but I don't want to worry about the user with the big database and the small machine. Other criteria: 1. Very high reliability -- Which of these can give us zero database failures from 1000's of users? 2. Simple -- We want to hide all details of the database from the end-users, and easy to program wouldn't hurt either. It looks like all three will meet this criteria. Any traps? 3. Storage efficiency -- We don't want 10 MB of user data to take 100 MB of disk space. I know that disk is cheap, but we want the data to be easy to back up, send, and transport. The hierarchical non-SQL aspects of Metakit are probably OK. Can anyone with experience with more than one of these advise? Thanks much in advance. Al From dsavitsk at e-coli.net Wed Mar 12 21:08:50 2003 From: dsavitsk at e-coli.net (dsavitsk) Date: Thu, 13 Mar 2003 02:08:50 GMT Subject: No Do while/repeat until looping construct in python? References: <3e6fcf6b@news.nz.asiaonline.net> Message-ID: "Colin Brown" wrote in message news:3e6fcf6b at news.nz.asiaonline.net... > Hi Lars > > ... > > Why is there no do-while looping construct in Python? > > Others have explained the Python way to do this, fine. > > I think this points out deficiencies of the documentation. > Also, it would be helpful for the docs to come > with built-in search capability. In keeping with the pythonic spirit of no being redundant, simply add "site:python.org" to a google search. why should python docs replicate this? -d From dave at boost-consulting.com Mon Mar 31 16:47:11 2003 From: dave at boost-consulting.com (David Abrahams) Date: Mon, 31 Mar 2003 16:47:11 -0500 Subject: Is Python overhyped (just like Java)? In-Reply-To: (Alex Martelli's message of "Sat, 29 Mar 2003 23:53:56 GMT") References: Message-ID: Alex Martelli writes: > Ajay na wrote: > >> Can some-one please explain why one would want to use Python? > > One word: *PRODUCTIVITY*. > >> What is wrong with C++? > > One word: *COMPLEXITY*. > > >> In my opinion, the problem with C++ has nothing to with the language >> semantics. The problem is that when people are confronted with a >> powerful language like C++, they tend to want to optimize everything >> to death. That's when they get themselves in trouble. > > You're over-generalizing. Not all users of C++ are so naive as to > have failed to read Knuth -- "Premature optimization is the root of > all evil in programming". But the point is -- by choosing a lower > level language, like C++, at the start of your project, rather than a > higher level one, like Python, you ARE optimizing WAY prematurely. In my experience, it may be even more powerful to begin with hybrid development from the ground up. On one project, when I tried to start with Python and push time-critical code into C++, I found that although algorithm prototyping had been fast, the Python interface I had developed for those critical components was not well-suited to the C++ world. In my application it was easy to predict where the bulk of the time would be spent, and had I written the core engine in C++ early on I might have saved myself a redesign effort. That may not apply everywhere, though. Another nice effect of this approach is that you end up with a well-designed core C++ library that can be used by C++-only applications, instead of something that really only works well with a Python wrapper. > One example I give is a task for which C++ is quite suited, with its > standard library -- reading a text file, breaking it into > whitespace-separated 'words', building an index from each word to > the line numbers on which it appears, and showing the index with > words in alphabetical order, one per line, each followed by the line > numbers on which it appears. Boy, that sure sounds like a job for Python to me. Something like "high-performance linear algebra with sparse matrices" sounds more like a job for which C++ is "quite suited". > Thanks to the excellent support given for these tasks by the standard > library, the C++ source is ONLY twice as big as the Python source for > the same job (a more usual ratio is around 5:1). This holds for both > the simplest versions, and the slightly more complicated ones with > somewhat better optimization. The runtimes on my box (Linux Mandrake > 9.0, gcc 3.1, Python 2.3) are, when the programs are run on the 4.4 MB > of the "King James Bible" in plain ASCII text: 17.4 seconds for the > simplest C++, going down to 15 with optimizations; 11.2 seconds for > the simplest Python, going down to 8.1 with optimizations (CPU times > are in very similar ratios). Of course, this basically reflects the > excellence of Python's intrinsics (dictionaries, lists, strings) > versus the lesser quality of C++'s library implementation (maps, > vectors, strings) -- with different implementations, you may see > different ratios. Really? Are you sure that time wasn't sunk into I/O? "Read all the lines from a file" is a primitive in Python, but not in C++. Also, it's only fair to point out that C++ doesn't have one library implementation -- each compiler comes with its own. Which implementation(s) were you testing? Oh, I see it was probably libstdc++ that comes with gcc 3.1. Well, IIRC GCC-3.1 was well known to optimize poorly (it took them some time to figure out how to integrate all the new optimizations that came in with GCC-3, and they actually made things slower for a while), and I wouldn't exactly say that libstdc++ is the fastest implementation. In other words, there's nothing intrinsic about C++ which says that it has to be twice as slow as Python at this job. I don't think it's fair to talk about "the lesser quality of C++'s library implementation." Aren't you glad I'm asking these questions now, instead of at your talk in Oxford? ;-) > The simplest and most flexible C++ you can write is still way > bigger, more complicated, and less flexible than the most refined > and optimized Python code it may make sense to write -- it's as > simple as this. I think when you're comparing the use of the core language I have to agree. However, when it comes to functionality provided by libraries, it really depends on the quality and availability of the library interface. That said, I think Python probably still has many more useful libraries than C++ does. > and the Boost Python Library (if you don't know Boost, DO give it a > look -- it WILL increase your C++ productivity, and not just by > easing integration of C++ to Python, either). Thanks :-) >> people who don't understand C++, are afraid to use the 'virtual' >> features of that language because it's 'too expensive'. But that's >> stupid...because Python's 'virtualness' is even more expensive! > > It's quite inconsiderate of you to imply that Python users are > "people who don't understand C++", when among those users are people > like Andrew Koenig (author of "Ruminations on C++" and other great > C++ books, as well as a towering figure of C++ development -- the > algorithm for name lookup in the C++ language is called "Koenig > lookup" because HE developed it...!), Actually, Andrew resists being associated with that particular feature, as I found out at the last committee meeting. IIRC, he said that he had little if anything to do with it, and wasn't sure why people put his name on it. Some might consider that association to be undesirable (http://www.boost-consulting.com/writing/qn.html). ...but that doesn't change the enormity of Andrew's contribution to the C++ language and community. > Bruce Eckel (author of best-sellers "Thinking in C++" and "Thinking > in Java"), and so many others whose C++ competence is in all > likelihood AT LEAST as good as yours. Yeah; what Alex said. -- Dave Abrahams Boost Consulting www.boost-consulting.com From mcherm at mcherm.com Wed Mar 26 13:40:06 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 26 Mar 2003 10:40:06 -0800 Subject: pseudoPython Message-ID: <1048704005.3e81f40600791@mcherm.com> I found everything quite readable EXCEPT the line continuations. I'd probably try indenting your line continuations. For example: line 1 of code: line 2 of code line 3 of code\ looks like line 4 actual line 4 of code could be improved with either of these: line 1 of code: line 2 of code line 3 of code\ clearly a continuation actual line 4 of code line 1 of code: line 2 of code line 3 of code\ clearly subsidiary to line 3 actual line 4 of code I personally prefer the last of these. -- Michael Chermside From tim.one at comcast.net Wed Mar 12 21:17:01 2003 From: tim.one at comcast.net (Tim Peters) Date: Wed, 12 Mar 2003 21:17:01 -0500 Subject: GCD in standard library? In-Reply-To: Message-ID: [Blake Garretson] > Unless I've been missing something for years, I don't believe > there are any functions built-in or in the standard library that > find the Greatest Common Divsor (GCD) of two integers. That's so. > This seems like a common enough math function that I would *think* it > ought to be in the math module (and gain the advantage of being coded > in C.) What advantage would that be? The speed of gcd on large integers is dominated by the speed of large-integer arithmetic, and that's coded in C no matter how it's *driven*. > I guess I'm wondering why it isn't there. Because it's trivial to code in (literally) a few lines of Python. > Was it to keep out code bloat? I realize we can't include everyone's pet > function, so it's fine if it stays out. I'm just guessing it is > very common for people to have to add this to their programs: > > def gcd(x,y): > if x % y == 0: return y > else: return gcd(y,x%y) Nope, I've never seen it written that way in Python. This spelling is common, in the relative handful of programs that want it: def gcd(a, b): while b: a, b = b, a % b return a > ... > If Python comes with "batteries included", where's GCD? httplib and builtin unbounded ints are batteries; gcd is a throwaway finger exercise in a Usenet posting. BTW, I've never seen another user community so keen to lobby for inclusion of every 1-, 2- and 3-line function they can dream up. Even Common Lisp had the good grace to restrict itself to 12-liners, like builtin Roman numeral output . From tdelaney at avaya.com Sun Mar 2 19:23:30 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 3 Mar 2003 11:23:30 +1100 Subject: code coverage tool Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE2E7027@au3010avexu1.global.avaya.com> > From: Dave Brueck [mailto:dave at pythonapocrypha.com] > > On Fri, 28 Feb 2003, Delaney, Timothy C (Timothy) wrote: > > > > >phil hunt wrote: > > > >> > > > >> Is there an open-source code coverage tool for Python? I have a > > > >> program for which I have written sevewral unit tests, > and I want to > > > >> see if any of the lines in my program aren't being > exercised by the > > > >> tests. > > > > I'm still waiting for permission to release my coverage tool :( > > > > It's still incomplete, but it's faster than the other > options I've tried > > and collects more information. > > Does it work with multithreaded programs? Hope you get > permission soon! :) Nah - unfortunately, that's one of the major parts that's incomplete about it :( A python coverage tool which automatically attaches to multiple threads is a non-trivial task. Of course, if I *do* get to release it (I'm waiting on a VP to sign something off ...) then I could leave it to *someone else* to add the multi-threading part ;) Tim Delaney From max at alcyone.com Mon Mar 3 06:22:44 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 03 Mar 2003 03:22:44 -0800 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <8fb66v8qbv45eatnblq80p131793ej7e3m@4ax.com> Message-ID: <3E633B04.A9425D14@alcyone.com> Stephen Horne wrote: > A major problem with 'lambda' is simply that it is an obscure name. I don't agree. The term "lambda" is well-recognized throughout the computer science community as a construct which introduces an anonymous function. Is the term "lambda" recognizable to a random guy in the street? I'm quite sure it isn't. But programming can't be made trivial to non-programmers simply by giving things trivial names, just as mathematics can't be made simple simply by using common terms instead of all those technical terms; I'm reminded here of Mathematics in the Common Tongue: http://www.earth360.com/mathtongue.html Myself, I'm not much interested in what the average non-programmer things about programming terminology. Even for those involved with teaching, there's got to be a tradeoff: The learned has to understand upfront that everything can't be instantly understandable without some manner of investment. If you're new to programming and you're learning a language and you bump into a "lambda," one would hope you'd have the actual energy and willpower to look it up. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ I can paint a portrait of myself / I will call me a black Mona Lisa \__/ Lamya Bosskey.net: Unreal Tournament 2003 / http://www.bosskey.net/ut2k3/ A personal guide to Unreal Tournament 2003. From jzgoda at usun.gazeta.pl Thu Mar 6 17:51:03 2003 From: jzgoda at usun.gazeta.pl (Jarek Zgoda) Date: Thu, 6 Mar 2003 22:51:03 +0000 (UTC) Subject: Perl Vs Python References: <7DT6a.104385$zL6.65899@news2.central.cox.net> <930f6vsg4c6d78gbe69c2dfvmiactvqd9e@4ax.com> Message-ID: Matija Papec pisze: >>>If you are interested, there is really nice book about text processing >>>in Python (I don't remember URL :(). >> . >> . >>Sean McGrath's *XML Processing with Python*? > > Yes, but anyway who would pick Python over Perl(or Ruby?) for text > processing? :) I do. The first day I saw iSeries I asked the question: "is any fancy language available for this beast?" and a guy from IBM answered "yes, there's REXX...". "No!", I replied, "You must be kidding, you really call REXX a fancy language? Gosh, you must be one of those funny creatures, that still love Fortran and use Perl to manipulate XML files like usual text files..." I love this beast, it's really fantastic machine, unless you want to do anything interactively. ;) -- Jarek Zgoda http://www.zgoda.biz/ JID:zgoda at jabber.atman.pl From bobsl at ananzi.co.za Wed Mar 26 05:29:35 2003 From: bobsl at ananzi.co.za (Bob Screenlevel) Date: 26 Mar 2003 02:29:35 -0800 Subject: Extension Debugging Message-ID: <8ced17b6.0303260229.19195de8@posting.google.com> Hello everyone.. I'm working with a set of DLL extension modules which mask the Dialogic telephony API. They have been compiled using Visual Studio (.NET), and they are being run on windows nt 4.0 with python 2.2. The server.py that uses these modules uses 120 threads, one for each line device. occasionally it crashes with this, information: The instruction at "0x00000008" referenced memory at "0x00000000". The memory could not be "read". the addresses are always the same, looks to be a NULL pointer thing, I've been lucky so far to discover as many of these errors as I have - this one eludes me still. My biggest problem is a lack of experience using C and the MS IDE. I don't even fully understand all the debugging options available to C programmers (debug symbols! compile options! etc), having never needed them before now. If anyone has any tidbits/websites/articles which could help me find the cause of this error, either C/python or just C debugging hints: Please share!! I have a headache from not sleeping too well, and I'm starting to feel more incompetent than I am used to. Thanks in advance. --- Bob. From aleax at aleax.it Sat Mar 22 10:08:42 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 22 Mar 2003 15:08:42 GMT Subject: Prime number algo... what's wrong? References: Message-ID: <_%_ea.140120$zo2.3651340@news2.tin.it> L. B. wrote: > Hi all, > > it's two days i'm trying to make this stuff work!! ;-) I really may be > dumb! Now i think i'm on the right way and close to the result but > still the algo doesn't work... could you please tell me what i'm > missing? You're missing Aristotle's "Law of the Excluded Middle" - the heart of your code is: > if test != 0: > x += 1 #still may be prime so go on trying > elif test == 0: > mayP += 1 #is not prime, test the second prime candidate > else: > pCount += 1 #increment counter > isP = mayP #may --> is > print "%u | %u" % (pCount, isP) #uhm... prints results?! and of course the 'else' branch can NEVER be taken -- since test is either different from or equal to zero, there IS no third case. > Also are you aware of more sophisticated and efficient algos for prime > testing implemented in Python? David Eppstein has a neat Eratosthenes-sieve-based generator in the online cookbook, at URL http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117119 Unfortunately the indents are messed up, at least as Opera shows me the code. So here's a comsmetically enhanced version (for Python 2.3, showing off a minor enhancement;-): def primes(): q = 2 # next candidate for primeness D = {} # map non-primes to their factors while True: # infinite generator, terminate otherwise ps = D.pop(q, None) # get & remove known factors (if any) if ps: # has some factors -> it's not a prime for p in ps: # move each factor to its next multiple D.setdefault(p+q, []).append(p) else: # has no factors -> it's a prime D[q*q] = [q] # mark the only newly-discovered multiple yield q # yield each prime one after the other q += 1 # next candidate if __name__ == '__main__': # example: print the first 20 primes for i, p in enumerate(primes()): print p, if i>=20: break prints 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 It may be more instructive to add a "print q, D" right after the "while True:" loop header to show what's going on. Here's the result, with the loop limited to just 8 primes to avoid too much output, and a clearer print "%d-th prime is %d" % (i+1, p) in the main loop's body: 2 {} 1-th prime is 2 3 {4: [2]} 2-th prime is 3 4 {9: [3], 4: [2]} 5 {9: [3], 6: [2]} 3-th prime is 5 6 {9: [3], 6: [2], 25: [5]} 7 {8: [2], 9: [3], 25: [5]} 4-th prime is 7 8 {49: [7], 25: [5], 8: [2], 9: [3]} 9 {49: [7], 25: [5], 9: [3], 10: [2]} 10 {49: [7], 25: [5], 10: [2], 12: [3]} 11 {49: [7], 25: [5], 12: [3, 2]} 5-th prime is 11 12 {49: [7], 25: [5], 121: [11], 12: [3, 2]} 13 {49: [7], 25: [5], 121: [11], 14: [2], 15: [3]} 6-th prime is 13 14 {49: [7], 169: [13], 25: [5], 121: [11], 14: [2], 15: [3]} 15 {16: [2], 49: [7], 169: [13], 25: [5], 121: [11], 15: [3]} 16 {16: [2], 49: [7], 18: [3], 121: [11], 25: [5], 169: [13]} 17 {49: [7], 18: [3, 2], 121: [11], 25: [5], 169: [13]} 7-th prime is 17 18 {49: [7], 18: [3, 2], 121: [11], 25: [5], 169: [13], 289: [17]} 19 {49: [7], 121: [11], 21: [3], 25: [5], 169: [13], 289: [17], 20: [2]} 8-th prime is 19 we see that in this version having a list of known factors corresponding to each nonprime that is a current key in dict D is necessary to deal with numbers that have more than one prime factor smaller than their square root, such as 12 and 18 in this small run. Alternatively, therefore, one might choose a tiny variant for D's values, keeping them to single numbers but also ensuring that an entry is never duplicated: it suffices to change the "while True:" loop's body to: p = D.pop(q, None) if p: x = p + q while x in D: x += p D[x] = p else: D[q*q] = q yield q q += 1 and this proves to be a small but worthwhile optimization, e.g with the following test code to check we're finding the smalles prime larger than 100,000, and check our runtime: import time start=time.clock() for p in primes(): if p>100000: break stend=time.clock() print p print stend-start on my machine, the original version using a dict of lists takes about 0.9 CPU seconds to come up with the result (100003), the modified version using a dict with numbers as values takes about 0.5 CPU seconds. Similarly, for the smallest prime larger than 1,000,000, we have 10.34 CPU seconds for the original version, 6.13 for the modified one -- again, a small but useful improvement. Alex From bobnotbob at byu.edu Wed Mar 19 14:48:54 2003 From: bobnotbob at byu.edu (Bob Roberts) Date: 19 Mar 2003 11:48:54 -0800 Subject: minimum python for distribution on Windows Message-ID: I just tried out py2exe, and it worked great. Is it possible to do something similar, but with my python source code still available (and able to be modified)? I tried just copying my source code, python.exe, and the modules I use into a new directory, but it keeps complaining about not having a lot of modules, such as "site", that I never imported. From aleax at aleax.it Mon Mar 3 10:31:14 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 03 Mar 2003 15:31:14 GMT Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <8fb66v8qbv45eatnblq80p131793ej7e3m@4ax.com> Message-ID: <6zK8a.268598$0v.7396380@news1.tin.it> Jack Diederich wrote: ... > I'm a big functional programming fan, but most python user's aren't. ... > filter() and only two dozen [very simple!] list comprehensions. So I guess your "functional programming" enthusiasm doesn't come from Haskell, who some consider amont the best FP languages -- as Python got list comprehensions from Haskell, with just little syntax-sugar changes, I'd expect LOTS of list comprehensions in Python code written by Haskell-savvy FP fans...!-) Alex From air_jlin at yahoo.com Tue Mar 4 18:39:13 2003 From: air_jlin at yahoo.com (Johnny Lin) Date: 4 Mar 2003 15:39:13 -0800 Subject: Newbie Looking for Scientific Python TkWidgets Example Message-ID: <67bd2f4f.0303041539.543cab1d@posting.google.com> Hi! Does anyone have sample code of using Scientific Python TkWidgets to make a line plot? I'm trying to figure out what I'm doing wrong and can't find any sample code online. Thanks! Best, -Johnny ------------------------------------------- Johnny Lin University of Chicago Department of the Geophysical Sciences Web: http://www.johnny-lin.com/ ------------------------------------------- From ulope at gmx.de Tue Mar 4 22:06:09 2003 From: ulope at gmx.de (Ulrich Petri) Date: Wed, 5 Mar 2003 04:06:09 +0100 Subject: os.execv References: Message-ID: "Skip Montanaro" schrieb im Newsbeitrag news:mailman.1046828168.14751.python-list at python.org... > >>> import os > >>> os.execv("/usr/bin/find", ("find", "/ -name test")) > find: / -name test: No such file or directory > > Maybe > > os.execv("/usr/bin/find", "find", "/", "-name", "test") > > is what you're after. > > Skip Thanks that did it. Kinda stupid behaviour (imho) Ciao Ulrich From roy at panix.com Thu Mar 13 08:09:10 2003 From: roy at panix.com (Roy Smith) Date: Thu, 13 Mar 2003 08:09:10 -0500 Subject: Python presentation at Unigroup (New York) Message-ID: New York's Unigroup is presenting Python at their March 20th meeting. For more details, see http://www.unigroup.org/unigroup-next.html From eric.brunel at pragmadev.com Fri Mar 21 05:11:18 2003 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Fri, 21 Mar 2003 11:11:18 +0100 Subject: sort(): Giving third argument? References: Message-ID: Thomas Guettler wrote: > Hi! > > If I have a list of IDs and a hash which maps > each ID to a name: > > ids=[1, 2, 3, 4] > > names={ > 1: "foo", > 2: "bar", > ...} > > I can't do the following: > > def mycmp(a, b): > return cmp(names[a], names[b]) > > ids.sort(mycmp) > > since "name" is unkown in mycmp. > > What's the best solution? def dictCompare(key1, key2, theDict): return cmp(theDict[key1], theDict[key2]) ids.sort(lambda x, y, d=names: dictCompare(x, y, d)) or even: ids.sort(lambda x, y, d=names: cmp(d[x], d[y])) (There may be a better solution if your Python version supports nested scopes, but mine doesn't...) So no need to give sort a third argument, which is a bit awkward for this particular puprpose (at least IMHO) HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From geoff at gerrietts.net Tue Mar 4 18:06:04 2003 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Tue, 4 Mar 2003 15:06:04 -0800 Subject: help! advocacy resources needed fast Message-ID: <20030304230604.GB5237@isis.gerrietts.net> I didn't think I was going to need to do this, but it looks like I might. Within the next couple days, the firm I work for is likely to be meeting to decide what we're doing in terms of technology change. We've been using Python, ILU, and Zope for a long time as the backbone of our business. We're now talking about changing that, but we're trying to decide to what. The problem is, we're drowning under traffic, and we have very strong plans/deals/whatever going into place that will multiply that traffic. We need to start building now for that day. One of the guys who's been with the organization for a long time wants to go to a Java-based approach. The long term viability, he maintains, is better, and the short term boost in performance per box in the cage is also better. I could be persuaded to let Zope go -- it's nice, but it's not really a very good fit for our organization. And I welcome the day ILU is no longer part of our technology framework. But I quail at the thought of losing Python. So I'm hunting for options, and hard facts (preferably with numbers attached). My current read is that Webware + Twisted, or mod_python + Twisted, would be the "fastest" web server platform python supports. Does anyone else have better numbers? Solid comparisons of any kind? I've got lots of anecdotal evidence I can point at, but very little in the way of hard numbers. Thanks, --G. -- Geoff Gerrietts "That's it! I've had it with your sassy mouth! I didn't want to do this! (Well, actually, http://www.gerrietts.net/ I did....)" -- Mojo Jojo, "Bubblevicious" From gerrit at nl.linux.org Sun Mar 2 07:55:17 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 2 Mar 2003 13:55:17 +0100 Subject: Vote on PEP 308: Ternary Operator In-Reply-To: References: <882b0a41.0303020225.3caf0334@posting.google.com> Message-ID: <20030302125517.GA3221@nl.linux.org> James Kew schreef op zondag 2 maart om 13:46:11 +0000: > Raymond Hettinger wrote: > > > Note, the examples are required but will not be used. > > Try to get them right, but it is okay if they are wrong. > > If they're not used, and can be wrong, what on *earth* are they for? Raymond's original mail states: > The purpose of the examples section is voter education. This > provides some assurance that each voter has at least tried > their own preferred syntax. Although it's true that if one rejects all, it's strange to have to do this. yours, gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From drifty at bigfoot.com Wed Mar 19 01:25:28 2003 From: drifty at bigfoot.com (Brett C.) Date: 18 Mar 2003 22:25:28 -0800 Subject: python-dev Summary for 2003-03-01 through 2003-03-15 Message-ID: +++++++++++++++++++++++++++++++++++++++++++++++++++++ python-dev Summary for 2003-03-01 through 2003-03-15 +++++++++++++++++++++++++++++++++++++++++++++++++++++ This is a summary of traffic on the `python-dev mailing list`_ from March 1, 2003 through March 15, 2003. It is intended to inform the wider Python community of on-going developments on the list and to have an archived summary of each thread started on the list. To comment on anything mentioned here, just post to python-list at python.org or `comp.lang.python`_ with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join python-dev! This is the thirteenth summary written by Brett Cannon (same number as my predecessor, Michael Hudson =). All summaries are archived at http://www.python.org/dev/summary/ . Please note that this summary is written using reStructuredText_ which can be found at http://docutils.sf.net/rst.html . Any unfamiliar punctuation is probably markup for reST_ (else it is probably regular expression syntax); you can safely ignore it (although I suggest learning reST; its simple and is accepted for PEP markup). Also, because of the wonders of programs that like to reformat text, I cannot guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the original text file. .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _last summary: http://www.python.org/dev/summary/2003-02-16_2003-02-28.html .. contents:: ====================== Summary Announcements ====================== As I am sure most readers of this summary know by now, I am going to PyCon_. This means that I will be occupied the whole last week of this month. I suspect python-dev traffic will be light since I believe most of PythonLabs will be at Pycon and thus not working. =) But still, I will be occupied myself and thus won't have a chance to work on the summary until I come home. This means you should expect the next summary to be rather late. I will get to it, though, at some point. And in case you haven't yet, register for PyCon_. .. _PyCon: http://www.python.org/pycon/ =============================== `Ridiculously minor tweaks?`__ =============================== __ http://mail.python.org/pipermail/python-dev/2003-March/033962.html Splinter threads: - `How long is your shopping tuple? `__ - `Tuples vs lists `__ - `Re: lists v. tuples `__ - `mutability `__ The original point of this thread was Jeremy Fincher finding out if patches changing lists to tuples where the list was not mutated would be accepted for a miniscule performance boost (the answer was no). But this wasn't the interesting knowledge that came out of this thread. This thread led to Guido stating his intended uses of tuples and lists. And you might be going, "lists are for mutable sequences of objects while tuples are for immutable sequences of objects". Well, that is not what Guido thinks of lists and tuples (and don't feel bad if you thought otherwise; Christian Tismer didn't even know what Guido had in mind and Python does not exactly require you to agree with Guido on this). Turns out that tuples, in Guido's view of the world, are "for heterogeneous data" and "list[s] are for homogeneous data"; "Tuples are *not* read-only lists". Guido spelled out his thinking on this in a later email. He basically said that he viewed lists as "a sequence of items of type X" while tuples are more like "a sequence of length N with items of type X1, X2, X3, ..." This makes sense since lists can be sorted while tuples can't; sorting on different types don't necessarily result in a sequence sorted the way you think about it. And if you are still having issues of wrapping your head around this, just view tuples as structs and lists as arrays as in C. This thread then led to another topic of comparisons_ in Python. Guido ended up mentioning how he wished == and != worked on all types (with disparate types always being !=) while all of the other comparisons only worked on similar types for the interpreter's default comparison abilities. This then led to Guido saying how he wished the __cmp__() magic method and the cmp() built-in didn't exist. This is because there are currently two ways to do comparisons; __cmp__(), and then all of the other rich comparison magic methods. You can implement the same functionality as __cmp__() using just __lt__() and __eq__(). There can also be an unneeded performance penalty for __cmp__() since (using the previously mentioned way of re-implementing __cmp__()) you might have to do some unneeded comparisons when all you need is __eq__(). This discussion is still going on. .. _comparisons: http://www.python.org/dev/doc/devel/ref/customization.html#l2h-91 =========================== `Capabilities in Python`__ =========================== __ http://mail.python.org/pipermail/python-dev/2003-March/033820.html Splinter threads: - `Capabilities `__ - `about candy `__ This is a continuation of a discussion covered in the `last summary`_. This was *definitely* the thread from hell for this summary. =) It is very long and there was confusion at multiple points over terminology. You have been warned. Three things were constantly being discussed in this thread; restricted execution, capabilities, and proxies. We discuss them in this order. Restricted execution basically cuts out access to certain objects at execution time. Currently, if you replace the global __builtins__ with something other then what __builtin__.__dict__ has then you enable restricted execution in Python. This cuts off access to built-in objects so as to prevent you from circumventing security code by, for instance, importing the sys_ module so you can replace a module's code in sys.modules. Both capabilities and proxies are worthless without restricted execution since they could be circumvented without it. Capabilities can be viewed as references or bound methods (but not both at the same time, necessarily). Security with capabilities is done based on possession; if you hold a reference to an object you can use that object without issue. The distribution of capabilities becomes the issue with this system. Proxies are a wrapper around objects that restrict access to the object. This restriction extends all the way to the core; even core code such as built-ins can't get access to parts of a proxied object that it doesn't want any object to get a hold of. The trick with proxies is making them secure on their own since they get passed around without worrying who gets it since it is the proxy that provides security, not possession like with capabilities. Two examples of proxies are `Zope proxies`_ and mxProxy_. There was talk of a PEP on all of this but one has not appeared yet; it is currently being worked on by Ben Laurie, though. .. _sys: http://www.python.org/dev/doc/devel/lib/module-sys.html .. _Zope proxies: http://dev.zope.org/Wikis/DevSite/Projects/ComponentArchitecture/TransitionToSecurityProxies .. _mxProxy: http://www.egenix.com/files/python/mxProxy.html ========= Quickies ========= `Codec registry `__ Gustavo Niemeyer asked someone to review a patch. `Changes to logging in CVS `__ Vinay Sajip if someone checked-in changes to the logging_ package could be rolled back since it broke compatibility with Python 1.5.2 which the logging package tries to keep (as mentioned in `PEP 291`_). The changes were removed. .. _logging: http://www.python.org/dev/doc/devel/lib/module-logging.html .. _PEP 291: http://www.python.org/peps/pep-0291.html `__slots__ for metatypes `__ Christian Tismer asked Guido and the list to take a look at a patch that would allow meta-types to have a __slots__. The patch was accepted and applied. `new bytecode results `__ Damien Morton continues on his quest to get performance boosts from fiddling with the eval loop contained in `ceval.c`_ and trying out various opcode ideas. It was pointed out that pystone_ is a good indicator of how Zope_ will perform on a new box. It was also stated by Tim Peters that since it is such an atypical test that it helps to make sure any improvements you make *really* do make an improvement. Damien also requested more people contribute statistical information to Skip Montanaro's stat server (more info at http://manatee.mojam.com/~skip/python/ ). .. ceval.c: .. _pystone: .. _Zope: http://www.zope.org/ `module extension search order - can it be changed? `__ This was discussed in the `last summary`_. Tim Peters mentioned how he doesn't use linecache_ often and that it's printing out of date info is not of any great use for tracebacks. .. _linecache: http://www.python.org/dev/doc/devel/lib/module-linecache.html `JUMP_IF_X opcodes `__ Damien Morton, still on the prowl for better opcodes, suggested introducing opcodes that combined branching opcodes and POP_TOP (which pops the top of the interpreter stack)??and did the pop based on the truth value of what was being tested. Neal Norwitz suggested that instead the branching instructions just always pop the stack. But then Raymond Hettinger came up with prediction macros that give a great speed boost to loops and conditionals by checking if the next opcode is one that normally follows the current opcode. If it does, it skips going through the eval loop for the next opcode, thus saving on overhead. If all of this cool opcode stuff that Damien keeps doing interests you, you will want to read `opcode.h`_, `ceval.c`_, and learn how to use the dis_ module. .. _opcode.h: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Include/opcode.h .. _ceval.c: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Python/ceval.c .. _dis: http://www.python.org/dev/doc/devel/lib/module-dis.html `Fun with timeit.py `__ A new module named timeit_ was added to the stdlib at the request of Jim Fulton. The module times the execution of code snippets. Guido timed the execution of going through a 'for' loop a million times with interpreters from Python 1.3 up to the current CVS (2.3a2 with patches up to that point). The result was that CVS was the fastest by a large margin. .. _timeit: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Lib/timeit.py `Pre-PyCon sprint ideas `__ I asked the list to suggest ideas to sprint on at PyCon_. `More Zen `__ Words of wisdom from Raymond Hettinger that everyone should read. And if you have never read Raymond's `School of Hard Knocks`_ email you owe yourself to stop whatever you are doing and read it **now**. I can personally vouch that email is right on the money; I have experienced (or suffered, depending on your view =) every single thing on that list sans writing a PEP (although writing the Summary is starting to be enough writing to be equal =) . .. _School of Hard Knocks: http://mail.python.org/pipermail/python-dev/2002-September/028725.html `xmlrpclib `__ : `xmlrpclib: Apology `__ Bill Bumgarner, the "hillbilly from the midwest of the US", asked if the xmlrpclib_ module was being maintained. The lesson was also learned to not call Fredrick Lundh "Fred" on the list since Fred L. Drake, Jr. tends to be associated with the name. =) .. _xmlrpclib: http://www.python.org/dev/doc/devel/lib/module-xmlrpclib.html `httplib SSLFile broken in CVS `__ Something got broken and fixed. `super() bug (?) `__ Samuele Pedroni thought he may have found a bug with super() but turned out it wasn't. `test_popen broken on Win2K `__ Win2k does not like quoting of commands when there is no space in the command as Tim Peters discovered. There were discussions on how to deal with this. The suggestion of coming up with an sh-like syntax that works on all platforms (like what tcl's exec command has) was suggsted. `Change in int() behavior `__ David Abrahams rediscovered the joys of the road to which leads to int/long unification when he noticed that ``isinstance(int(sys.maxint*2), int)`` returns False. This will not be an issue once we are farther down this road. `acceptability of asm in python code? `__ Damien Morton popped his optimizing head back up on python-dev asking if assembly code was acceptable in the core. As of right now there is none, but Tim Peters stated that if there was some that had "a huge speedup, on all programs" then it would be considered, although "on the weak end of maybe". Christian Tismer (who plays with assembly in Stackless_) warned against it because it could cause a compiler to not use optimizations. .. _Stackless: http://www.stackless.com/ `Internationalizing domain names `__ Martin v. L??wis asked someone to look over his patches to implement IDNA (International Domain Names in Applications) which allows non-ASCII characters in domain names. `VERSION in getpath.c `__ Guido explains to someone what compile variables are used to generate some compile-based search paths. `Where is OSS used? `__ Greg Ward asked what OSs use OSS_. .. _OSS: http://www.opensound.com/ossfree/ `Audio devices `__ Greg Ward asked for opinions on some API issues for ossaudiodev_. .. _ossaudiodev: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Modules/ossaudiodev.c `bsddb3 test errors - are these expected? `__ Skip Montanaro asked if some errors from the testing of bsddb3_ on OS X were expected. .. _bsddb3: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Modules/_bsddb.c `os.path.dirname misleading? `__ Kevin Altis was surprised to discover that `os.path.dirname`_ would return the tail end of a directory instead of an empty string when the argument to the function was just a directory name. .. _os.path.dirname: http://www.python.org/dev/doc/devel/lib/module-os.path.html#l2h-1443 `Care to sprint on the core at PyCon? `__ Me asking the world if they wanted to sprint on the core at the pre-PyCon sprint (if you do, read the email for details). `Iterable sockets? `__ Andrew McNamara wished that socket objects were iterable on a per-line basis without having to call makefile(). Guido said he would rather come up with a better abstraction for Python 3 and prototype it in Python 2.4 or later. `More int/long integration issues `__ David Abrahams noticed that range() and xrange() couldn't accept a long. It basically led to Guido stating he considers xrange() a mistake and wished it didn't exist now that we have iterators. But since getting rid of it would break code he can at least prevent it from gaining abilities. It also led to Guido mentioning again how he would like to prohibit shadowing of built-ins. `tzset `__ A new function, time.tzset(), was added to Python and the tests had failed under Windows. The tests and the ./configure check were changed as needed. `PyObject_New vs PyObject_NEW `__ Lesson of the thread: PyObject_NEW is only to be used in the core; use `PyObject_New()`_ for extension modules. .. _PyObject_New(): http://www.python.org/dev/doc/devel/api/allocating-objects.html `are NULL checks in Objects/abstract.c really needed? `__ ... They are not required, but they are there to protect you against poorly written extensions. Skip Montanaro subsequently suggested a --without-null-checks compile option. `PyEval_GetFrame() revisited `__ A possible API for manipulating the current frame was still being discussed. From lorenzo at mysurname.net Sat Mar 29 23:03:23 2003 From: lorenzo at mysurname.net (Lorenzo Bolognini) Date: Sun, 30 Mar 2003 04:03:23 GMT Subject: Is Python overhyped (just like Java)? References: Message-ID: "Ajay na" ha scritto nel messaggio news:mailman.1048973984.17441.python-list at python.org... > Can some-one please explain why one would want to use Python? What is wrong > with C++? Just a link... http://www.catb.org/~esr/writings/taoup/html/why_not_c.html What you will read is written by Eric Raymond a well known old school Unix hacker ex Perl and C/C++ fanatic has now turned to Python programming for quite everything... just have a look at a couple of his interviews on IBM developer's work and somewhere else... Lorenzo From tzot at sil-tec.gr Tue Mar 4 18:21:40 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 05 Mar 2003 01:21:40 +0200 Subject: A suggestion for a possible Python module References: Message-ID: On Tue, 04 Mar 2003 16:15:02 +0100, rumours say that Alex Martelli might have written: >since Italian is >even farther from English in terminology (e.g., in common speech we >do not distinguish between 'time' and 'weather', using the same >word, 'tempo', for both -- hopefully this specific trap is big >enough that I can manage to avoid falling into it, but who knows >how many others there may be...!-) Ha! Una faccia, una razza. Same dual meaning in my (your south-eastern neighbour) language. Therefore the tongue in check word for word translation to English: "Do you have weather for a coffee?" :) -- TZOTZIOY, I speak England very best, bofh at sil-tec.gr (I'm a postmaster luring spammers; please spam me! ...and my users won't ever see your messages again...) From malteneumann at web.de Wed Mar 19 04:49:28 2003 From: malteneumann at web.de (Malte Neumann) Date: Wed, 19 Mar 2003 10:49:28 +0100 Subject: compiling python on HP-UX Message-ID: <3E783D28.203@web.de> Hi Folks, I am just trying to compile python 2.2.2 on my HP-UX 10.20 machine. After several tries with different compilers I am finally stuck at this error message: gcc -Wl,-E -Wl,-E -Wl,+s -Wl,+b/usr/local/lib/python2.2/lib-dynload -o python \ Modules/python.o \ libpython2.2.a -ldld -lcma -lm case $MAKEFLAGS in \ *-s*) CC='gcc -Wl,-E' LDSHARED='ld -b' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes -D_REENTRANT ' ./python -E ./setup.py -q build;; \ *) CC='gcc -Wl,-E' LDSHARED='ld -b' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes -D_REENTRANT ' ./python -E ./setup.py build;; \ esac Fatal Python error: unlock_import: not holding the import lock /bin/sh: 11074 Abort(coredump) Any help is appriciated. Thanks a lot in advance. Malte -- -------------------------------------------------------------------------- Malte Neumann -------------------------------------------------------------------------- Institut fuer Baustatik / Institute of Structural Mechanics Prof. Dr.-Ing. Ekkehard Ramm Universitaet Stuttgart / University of Stuttgart Pfaffenwaldring 7, D-70550 Stuttgart, Germany mailto:malte.neumann at statik.uni-stuttgart.de phone: ++49-711-685-6121 http://www.uni-stuttgart.de/ibs/members/neumann/ fax: ++49-711-685-6130 -------------------------------------------------------------------------- From aleax at aleax.it Thu Mar 20 10:04:19 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 20 Mar 2003 15:04:19 GMT Subject: Question regarding a recent article on informit.com References: <3E79C378.6176BC77@engcorp.com> Message-ID: Peter Hansen wrote: > Ben S wrote: >> >> Are there any good tutorials of examples of list comprehension use? In >> particular, I'm interested in how to replicate the functionality of >> reduce? Map and filter seem easy to do, though. > > Doesn't reduce return a non-list (or at least, isn't it the case that > it doesn't necessarily return a list the way map and filter do)? Exactly: reduce CAN return a list (when a list is what's returned by the function that is its first argument) but that rarely happens. > An *abuse* of a list comprehension, or a list comprehension in > conjuction with something else, could probably replicate reduce(), > but why bother? reduce() isn't really like map and filter. Absolutely right. More often than not, the right replacement for reduce is just a simple loop. Consider...: $ python timeit.py 'reduce(lambda x, y: x+y, range(100))' 10000 loops, time: 81.392 usec $ python timeit.py -s 'import operator' 'reduce(operator.add, range(100))' 10000 loops, time: 36.212 usec $ python timeit.py 'x=0' 'for y in range(100): x += y' 10000 loops, time: 32.864 usec These numbers are very repeatable on my machine (a good, if dated, Athlon + DDR box) with Python 2.3 (built right out of CVS). So why would you pay the 10% performance price for using reduce (assuming you do NOT use a lambda in it -- otherwise, 150% price or so...)? Do you REALLY think it makes things so much clearer and more obvious as to be worth slowing your code down? In my opinion, it makes things LESS clear and obvious for most readers. So, I would normally prefer the simple, obvious loop -- even in the "sum all of these numbers" case, which is reduce's main use case. I think Python would be a marginally but definitely better language if it had no reduce built-in: it's just one more thing that the Python newbie has to learn, basically just in order to be able to understand existing code that uses it -- reduce might migrate into some "legacy built-ins existing solely for purposes of backwards compatibility" ("from __past__ import..." ?-) AND avoid certain "attractive nuisances" such as...: $ python timeit.py -s 'import operator' 'reduce(operator.add, map(str,range(1000)))' 100 loops, time: 2612.000 usec $ python timeit.py -s 'import operator' '"".join(map(str,range(1000)))' 1000 loops, time: 1430.569 usec where the performance penalty for using reduce rather than doing things the right way can reach and exceed 80% (or higher costs too, for long-enough lists of strings...) -- not necessarily "in the noise" any more...! Alex From hst at empolis.co.uk Mon Mar 3 03:59:02 2003 From: hst at empolis.co.uk (Harvey Thomas) Date: Mon, 3 Mar 2003 08:59:02 -0000 Subject: Why no RE match of A AND B? Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB04F484@hendrix.empolisuk.com> Paddy wrote: > > Just looking through the docs to confirm it and their seems > to be no regular expression > construct that matches 'A and B' - an equivalent to the '|' > character that matches A or B > To paraphrase the documentation it could be documented as: > > "&" > A&B, where A and B can be arbitrary REs, creates a regular > expression that will match both > A and B in any order. An arbitrary number of REs can be > separated by the "&" in this way. > This can be used inside groups as well. REs separated by "&" > are tried in arbitrary order, > the beginning of the first matching branch up to the end of > the last branch that allows > the complete pattern (all branches) to match is considered > the span of the match. > > I envision it being used where a string is accepted at > present if it matches multiple REs. > The REs could be rewritten as r"&&...". > > The use of "&" could be supported by more efficient, > (simultaneous?), matching of all > branches of the "&" construct - if such algorithms exist! > > Just an idea, > > Paddy. > One of the simplifications of SGML made in the creation of XML was the dropping of the & operator in content models. I believe there were two reasons for this: 1) & was hardly ever used. 2) Implementation problems. Suppose you have a&b&c&d&e&f&g&h. There are 40320 patterns that match this, but this is more than the number of backtracking states that the Python RE engine supports. _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From glt2010pas.de.spam at yahoo.fr Thu Mar 20 18:03:13 2003 From: glt2010pas.de.spam at yahoo.fr (lt) Date: Fri, 21 Mar 2003 00:03:13 +0100 Subject: help with (x)html / xml encoding... Message-ID: <3e7a47f1$0$29135$626a54ce@news.free.fr> hello, i'm looking for a way to extract encoding from a file retrieved by urllib, i'm planning of creating a "restricted" parser which will only examine or do you think that is enough ? how should you do it ? my solution is below, please feel free to comment this code, i *really *need to improve my python !!! (inspired by sgmllib.py) s will be the string to check out and more precisely the string returned while parsing by a SGMLParser object that will only handle_pi and start_meta import re _encoding = re.compile( r'\s*encoding\s*=\s*' r'(\'[^\']*\'|"[^"]*"|[-a-zA-Z0-9./:;+*%?!&$\(\)_#=~\'"]*)') _charset = re.compile( r'\s*charset\s*=\s*' r'(\'[^\']*\'|"[^"]*"|[-a-zA-Z0-9./:;+*%?!&$\(\)_#=~\'"]*)') def get_encoding(s): encoding = None search = _encoding.search(s) if not search: search = _charset.search(s) if not search: return encoding encoding = search.group(1) while encoding[:1] == '\'' == encoding[-1:] or \ encoding[:1] == '"' == encoding[-1:]: encoding = encoding[1:-1] return encoding thanks... From mwh at python.net Wed Mar 19 08:46:36 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 19 Mar 2003 13:46:36 GMT Subject: Python and Nuclear Safety (Re: PEP 312 (and thus 308) implemented with a black magic trick) References: Message-ID: <7h33cljii4k.fsf@pc150.maths.bris.ac.uk> Tim Churches writes: > Please tell me that those four Python programmers are not now > sitting with their fingers hovering over the Enter key, waiting for > the word from you-know-who. Nah, we're waiting for Kaz: http://dspace.dial.pipex.com/town/green/gfd34/art/bloopers.html Cheers, M. -- Enlightenment is probably antithetical to impatience. -- Erik Naggum, comp.lang.lisp From dimour at mail.ru Wed Mar 26 08:43:27 2003 From: dimour at mail.ru (Dmitri Mouromtsev) Date: Wed, 26 Mar 2003 16:43:27 +0300 Subject: PyInstance_New fails with new Python classes Message-ID: I have new python class derived from 'object' in my module: class MyClass(object): pass And I embed python in C++. When I'm tryig create new instance by using PyInstance_New - function return NULL: Py_Initialize(); PuObject *my_module = PyImport_ImportModule("MyModule"); PyObject *my_class = PyObject_GetAttrString(my_module, "MyClass"); if (!my_class) return; PyObject *instance = PyInstance_New(my_class, NULL, NULL); // retuns NULL It happen because PyClass_Check in PyInstance_New function fails with new classes (they have type PyType_Type). So, how can I create instances in embedded python? Thanks Dmirti From dave at pythonapocrypha.com Wed Mar 5 17:10:54 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 5 Mar 2003 14:10:54 -0800 (PST) Subject: Thread processing In-Reply-To: <8yvty3v0.fsf@morpheus.demon.co.uk> References: <8yvty3v0.fsf@morpheus.demon.co.uk> Message-ID: On Wed, 5 Mar 2003, Paul Moore wrote: > I've just started working with threads in Python, and I'm having a bit > of a hard time getting my head round the concepts. Hi Paul, Your question seems very similar to the one you asked yesterday, so even though you're reluctant to go into too much detail, maybe a specific example will help you get the answer you're looking for. > I can use a Queue to have the threads notify when they have finished, > but that means rewriting the thread procedures to do the notification, > which isn't really what I want. Something like: > > q = Queue() > # All the threads need to get q as input, and do > # q.put(self) when the run method finishes > > while threads: > thread = q.get() > thread.join() You don't need to join the thread if it is just going to terminate on its own. > threads.remove[thread] Do you actually need a list of all the threads? Why bother? > # post-processing for thread here This is what you need to clarify - what sort of post-processing needs to be done? Do you really need to have a handle to the thread object or just the data to be post-processed? > That's nasty because I have to write my thread procedures specifically > to work with this idiom (and I'm trying to make this stuff as generic > as possible, because I have a lot of potential code which will follow > this pattern) Is it really _that_ big of a deal to have the worker thread put done work on a queue? Short of coming up with a better idiom, having threads place finished work onto a Queue is very flexible and generic - easily reusable. Also, the model extends quite well to scenarios where each thread does more than one piece of work before terminating - a pool of workers that pop data of one queue, do stuff, and then place the finished work on the done queue. > Am I right in thinking that there isn't a good way of doing this? If > anyone can point out what I might have missed, I'd be very grateful. A common pattern for a pool of worker threads is to dump finished work into a queue. IMO that _is_ a good way of doing this as it is very flexible, not problematic, and very simple to write in Python. > PS Sorry I can't give a specific example - I'm trying to write a > fairly generic library here - I have 4 main use cases already, with > more appearing fairly fast... (Actually, I could probably describe > my particular current problem if that would help, but this message > is already too long, and I don't want to lose the general question > in details of the one specific case...) Maybe the specific case would shed light on what you don't like. -Dave From kdahlhaus at yahoo.com Mon Mar 17 09:00:08 2003 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 17 Mar 2003 06:00:08 -0800 Subject: Fw: pyslang for Python 2.2? References: <283adf56.0303140711.574fa7ae@posting.google.com> Message-ID: <283adf56.0303170600.39fd87c7@posting.google.com> It works great for me. Thanks! > I've put up the slang.pyd at > http://www.fh-giessen.de/~hg10836/crowproductions/dev/pyslang.zip From 2002 at weholt.org Wed Mar 12 16:20:13 2003 From: 2002 at weholt.org (Thomas Weholt) Date: Wed, 12 Mar 2003 22:20:13 +0100 Subject: lightweight, fast http server References: Message-ID: SimpleHTTPServer is very easy to set up, but people told me when I asked a similar question some time ago, that it'll scale very badly. Look into medusa or Twisted instead. Thomas "John Hunter" wrote in message news:mailman.1047489049.3389.python-list at python.org... > > I am looking for recommendations for a python based http server. It > will need to server large files (several 100 meg) over a nonstandard > port (ie, not 80), preferably as fast as possible, but will not have > to handle a large number of requests. I need basic authentication. > > Will SimpleHTTPServer fill these needs? > > Thanks, > John Hunter > From chenpuqing at 163.net Sun Mar 2 19:45:38 2003 From: chenpuqing at 163.net (Chen) Date: Mon, 3 Mar 2003 08:45:38 +0800 Subject: Is the OS win9x or winnt? How to detect it? References: Message-ID: "Tim Peters" wrote in message news:mailman.1046623684.25117.python-list at python.org... > [Chen] > > Is it possible to detect whether the OS is win9x or winnt? > > > > I used os.name but it returns "winnt" even on win98se. While sys.platform > > returns "win32". > > sys.getwindowsversion() is new in Python 2.3, and returns a 5-tuple of > values built from from calling the Win32 GetVersionEx() function. > > Before 2.3, you have to do something trickier. For example, > > version_string = os.popen("ver").read() > > and then parse version_string, assuming the box's COMPSPEC points to a shell > that supports the VER command. > > It works very well! Many thanks to all of you! Chen From mk at net.mail.penguinista Thu Mar 27 13:31:46 2003 From: mk at net.mail.penguinista (=?UTF-8?B?0LTQsNC80ZjQsNC9INCzLg==?=) Date: Thu, 27 Mar 2003 19:31:46 +0100 Subject: davlib - I stepped in it. References: <3E831714.6070804@indy.rr.com> Message-ID: <3e834392@news.mt.net.mk> > Well, it turns out to be a web folder, and I need a quick > crash course in webDAV. I downloaded the davlib and its > friends and those import okay and all. I connect to the > server just fine. :-) I can connect and close the connection. > Big deal. > > My problem is that I haven't used webDAV and have never > read an article on it. Is there a quick summary somewhere > which will tell me how to upload files to the server this > way? I just need something quick, and I promise to go > RTFM on webDAV (and maybe a book or two) later! WebDAV is an extension of the HTTP protocol. To upload files you just use the PUT method. It also defines some other HTTP methods that help in finding the properties of the objects(files,folders), listing collections (folders) , locking files, etc... -- ?????? (jabberid:damjan at bagra.net.mk) Secret hacker rule #11: hackers read manuals. From cnetzer at mail.arc.nasa.gov Thu Mar 27 15:13:57 2003 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: 27 Mar 2003 12:13:57 -0800 Subject: Pmw ScrolledText background In-Reply-To: References: Message-ID: <1048796037.1746.19.camel@sayge.arc.nasa.gov> On Wed, 2003-03-26 at 08:42, student wrote: > I need to change the background color of a Pmw.ScrolledText widget > > by default it is white ... i have the following code: In the future, if at all possible, please post short pieces of code that can be cut and pasted into an interpreter to show the desired effect (or misfeature). It will generally lead to more and faster responses. We are all busy people, and can't afford to spend time filling in all the details to test non-working code. The code you posted, once I edited it to work (importing modules, initialization, etc.) set the background to red for me, on my Linux system (I'm not able to easily test Windows right now). I suspect your problem results from using a Pmw class method (Pmw.Color.changecolor) on a Tkinter widget (text). I use the Tkinter wiget method configure() (on the component you extracted), to achieve the same effect. I believe my technique is more the more common, and more proper, of the two. Here is a minimal working version of the code for me. Does it produce a red background for you? import Pmw r = Pmw.initialise() s = Pmw.ScrolledText(r) s.pack() s.component('text').configure(background = 'red') r.mainloop() -- Bay Area Python Interest Group - http://www.baypiggies.net/ Chad Netzer (any opinion expressed is my own and not NASA's or my employer's) From grante at visi.com Wed Mar 26 19:37:36 2003 From: grante at visi.com (Grant Edwards) Date: 27 Mar 2003 00:37:36 GMT Subject: Integer arithmetic References: Message-ID: <3e8247d0$0$83887$a1866201@newsreader.visi.com> In article , James Gregory wrote: >>> Am I so far off in thinking maybe this should be provided by >>> the language? >> >> IMHO, you are. "integral types with N bits ignoring overflows" > > So wait, all you want to do is algebra in the ring Z_{2^32}? Don't know about him, but what I want to do is 2's compliment add and subtract, bitwise and/or/not/xor and left/right shift operations on 8, 16, and 32 bit values. If that's "algebra in the ring Z_{2^8|16|32}, then yes. > Assuming this is right, why not just make a RingElement class > that has all the operators overloaded to perform the > appropriate operation and then perform the appropriate modulus. > With appropriate optimizations if needs be. -- Grant Edwards grante Yow! I think I am an at overnight sensation right visi.com now!! From timr at probo.com Sat Mar 15 02:15:13 2003 From: timr at probo.com (Tim Roberts) Date: Fri, 14 Mar 2003 23:15:13 -0800 Subject: python as a web glue ? References: <3e7190c2$0$236$626a54ce@news.free.fr> <3e719b4a$0$15897$79c14f64@nan-newsreader-02.noos.net> <3e71aade$0$2728$626a54ce@news.free.fr> <3e71e919$0$7891$626a54ce@news.free.fr> Message-ID: "shagshag13" wrote: >Nikolaus Wagner wrote: >> um, whaddya mean? >> Just setup your apache webserver and use mod_python with that. > >well i'm reading things about zope, isn't it more adapted than using apache >+ mod-python ? Zope is a powerful system, but it is a "way of life". Once you go Zope, you really have to do things the Zope way. That's certainly a fine way to go, if you're going to be doing a big job, but for many small tasks, Python CGI scripts are much lighter weight and easier to grasp. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From roy at panix.com Mon Mar 31 09:23:01 2003 From: roy at panix.com (Roy Smith) Date: Mon, 31 Mar 2003 09:23:01 -0500 Subject: Is Python overhyped (just like Java)? References: Message-ID: abpillai at lycos.com (Anand B Pillai) wrote: > [Python] is a true object-oriented language in the spirit of > Smalltalk/Java whereas C++ is not one. I'm all for C++ bashing, but in what way do you think C++ is not "a true object oriented language"? I've heard C++ guys bash Python as not object oriented because Python doesn't support private data. "You mean I can bypass the accessor functions and touch an object's data directly!?" OO seems to be different things to different people. The concept of "true OO" is probably best left for religeous wars. As far as I can tell, most people think OO is whatever was supported by the first OO language they learned. From andy at reportlab.com Thu Mar 20 16:47:10 2003 From: andy at reportlab.com (Andy Robinson) Date: Thu, 20 Mar 2003 21:47:10 +0000 Subject: pointing to the correct python References: Message-ID: On Sat, 15 Mar 2003 04:04:40 GMT, Andrew Koenig wrote: >Bob> I am running cygwin under windows. If I have a python program that >Bob> starts with >Bob> #!/usr/bin/python >Bob> it uses the cygwin python, which for most stuff is fine. But I need >Bob> to use the windows version of python any time I want to use PIL, >Bob> pygame, etc.. How do I tell the environment which python to use >Bob> (besides using #!/n/Python22/python)? > If you start a script with "python myscript.py" then it depends which python is on your path. If, as most do, you just use "myscript.py" then it will be passed to the application associated with ".py". You can change this from View | Options | File Types in explorer (AFAIR) to the Python of your choice, but it's system wide. So, why not associate .py with a little batch file which looks in the first line for a shebang, and passes it to that Python? Then you could basically do what you do on Unix. Or (simpler) give you top level scripts distinctive extensions like '.cpy' for Cygwin. - Andy Robinson From dave at boost-consulting.com Wed Mar 5 12:35:07 2003 From: dave at boost-consulting.com (David Abrahams) Date: Wed, 05 Mar 2003 12:35:07 -0500 Subject: Vote on PEP 308: Ternary Operator References: <882b0a41.0303020225.3caf0334@posting.google.com> <2259b0e2.0303040823.f8c8974@posting.google.com> Message-ID: Paul Moore writes: > mis6 at pitt.edu (Michele Simionato) writes: > >> This voting procedure forces me to write what I like the best (even >> in the 'reject' case, I must check the last hated expression). I >> have no way to express what I dislike the most. > > I have now voted, and no longer really care, but yes, I agree that > this was the most annoying aspect of the voting system. Not being able > to say how much I *loathe* > > (if c: x else: y) > > was a definite lack for me. Yeah, I had the feeling when I saw that, that it was proposed just as a way of killing the whole idea ;-) -- Dave Abrahams Boost Consulting www.boost-consulting.com From tim_one at email.msn.com Sun Mar 23 22:51:52 2003 From: tim_one at email.msn.com (Tim Peters) Date: Sun, 23 Mar 2003 22:51:52 -0500 Subject: type function does not subtype In-Reply-To: Message-ID: [Lenard Lindstrom] > Would someone please explain why subtyping of type 'function' is not > permitted in Python 2.3? Nothing implemented in C is subclassable unless somebody volunteers the work to make it subclassable; nobody volunteered the work to make the function type subclassable. It sure wasn't at the top of my list . From sheershion at mailexpire.com Mon Mar 24 15:13:14 2003 From: sheershion at mailexpire.com (Robert Amesz) Date: Mon, 24 Mar 2003 20:13:14 -0000 Subject: Text Editor with wxPython References: <3e7c561a.8718311@news.utanet.at> Message-ID: Franz Steinh?usler wrote: > Hello Newsgroup, > > I'd like to write a small text editor with wxPython. > How would you program a simple, but extensible editor? I wouldn't: I'd use the wxStytledTextCtrl class which is already in the wxPython library. There are plenty of examples of how to use it in the demo code, and you could also dissect pyCrust. I'm certain you'll find this to be a much more productive approach. Re- inventing the wheel might be fun, but it's still only a wheel. To make anything as sophisticated as the wxStytledTextCtrl - which wraps the excellent Scintilla editor widget - takes a huge effort, time better spent in tweaking the wxStytledTextCtrl to do exactly what you want. Robert Amesz From intentionally at blank.co.uk Wed Mar 5 10:12:21 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Wed, 05 Mar 2003 15:12:21 +0000 Subject: OT: polyamory (was Re: [OT] Re: Python training time) References: Message-ID: <9j4c6v0gbooth50533vu0l0tan7cluib7q@4ax.com> On 28 Feb 2003 15:46:32 -0500, aahz at pythoncraft.com (Aahz) wrote: >Anyone who's really curious about the subject is welcome to drop by I'm a little surprised you advertise so openly - somehow, I'd expect that group to draw periodic flamefests from judgemental types which would make people a little more cautious? But then again, is there a newsgroup that doesn't draw periodic flamefests? -- steve at ninereeds dot fsnet dot co dot uk From mcfletch at rogers.com Thu Mar 13 00:14:07 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 13 Mar 2003 00:14:07 -0500 Subject: pygame and pyopengl In-Reply-To: References: Message-ID: <3E70139F.5030900@rogers.com> PyOpenGL can be used quite nicely with PyGame. PyOpenGL also works quite nicely with wxPython, or GLUT (a GLUT wrapper is included with PyOpenGL), or if you're desperate for the masochistic thrills of retro GUI interfaces, Tkinter ;) . It should, in fact, work with any GUI library that has an OpenGL context and tools for all the GUI-level goodness that's necessary for manipulating such a context (e.g. FxPy or Qt _should_ work, it's just been a while since I've tested FxPy, and I've never used Qt with PyOpenGL). You don't need PyGame to work with PyOpenGL, but you'll find a considerable overlap in the communities of users. You might find using PyGame as your GUI environment lets you talk to the same people for questions about either part of the system. Of course, the same thing applies to GLUT, where there's only the PyOpenGL community to go to. HTH, Mike Bob Roberts wrote: >What is the relationship between pygame and pyopengl? If I want to >play with opengl, which one should I use? > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From antonmuhin at sendmail.ru Wed Mar 5 11:22:56 2003 From: antonmuhin at sendmail.ru (Anton Muhin) Date: Wed, 05 Mar 2003 19:22:56 +0300 Subject: Concerns about performance w/Python, Pysco on Pentiums In-Reply-To: <3E660EB3.4065D81F@engcorp.com> References: <3E660EB3.4065D81F@engcorp.com> Message-ID: Array or Numeric modules might lead to better performance. HTH, Anton. From franga at shentel.net Tue Mar 25 19:24:43 2003 From: franga at shentel.net (Francis Avila) Date: Tue, 25 Mar 2003 19:24:43 -0500 Subject: Unbuffer stdout? Message-ID: I'm trying to run the stdout of an os.popen*() to sys.stdout. Problem is that the output seems to get trapped in a buffer until the command exits. Code: >>> import os, sys >>> sys.stdout.write( os.popen("yes", 'r', 0).readline() ) yes: standard output: Broken pipe y >>> I assume the broken pipe is from having the pipe closed before 'yes' exits. Strangely enough, the popen[2-4]() variants don't have this problem: >>> sys.stdout.write( os.popen2("yes", 'r', 0)[1].readline() ) y >>> Anyway, this: >>> sys.stdout.write( os.popen("yes", 'r', 0).read() ) hangs forever (with some disk activity after a while) until you interrupt the interpreter. I strongly suspect this is because the output is getting trapped in a buffer until the command exits (which is what I want to avoid) because the following works fine: >>> sys.stdout.write( os.popen("ls", 'r', 0).read() ) directoryOne directoryTwo someRandomFile >>> This: >>> sys.stderr.write( os.popen("yes", 'r', 0).read() ) does the same, which seems odd to me because stderr is never buffered, at least not by the OS. In any case, even _this_: #!/bin/sh yes | more does give you a screen of y's as soon as 'yes' fills the buffer, but before 'yes' exits. So python is somewhere doing extra buffering of the whole output of popen(). What I'm looking for is to pipe the stdout of a child process directly to the stdout of the parent process (i.e., the python script), without any buffering along the pipeline. As I see it, this is either not possible in python, or I'm going about this the wrong way. BTW, I was trying to look at the code of popen(), but I couldn't find it anywhere in the python library, much less in os.py. What's more: >>> os.popen But if it's a built-in, why do I have to import os? I'm running python 2.1.3 on a linux system, if it matters. Help? -- Francis Avila From ianb at colorstudy.com Tue Mar 18 21:10:24 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 18 Mar 2003 20:10:24 -0600 Subject: Serving a file through HTTP In-Reply-To: <3e770934$0$1129$4d4ebb8e@news.nl.uu.net> References: <3e770934$0$1129$4d4ebb8e@news.nl.uu.net> Message-ID: <1048039824.665.4394.camel@lothlorien> On Tue, 2003-03-18 at 05:55, Gumuz wrote: > I recently played with the HTTP & CGIHTTP servers. > The're great fun and I see plenty of possibilities with them :) > > I was wondering: how can I 'serve' a file through this server to a client, > so the client(browser) will start a file-download(save-as,blabla)? Maybe you already got it figured out, but if you do set_header('Content-type', 'application/octet-stream') it should force a save-as dialog. Ian From peter at engcorp.com Fri Mar 14 08:52:11 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 14 Mar 2003 08:52:11 -0500 Subject: Python code! References: Message-ID: <3E71DE8B.29D26FF8@engcorp.com> Gunnar Kongsrud wrote: > > Hi, I have a question about a code in pyhton. If the code below make my articals sort automatacly articals after 01.01.2003 ho do i get it to sort articals from 01.01.2001 to 01.01.2002 by using a simular code? > > python:object.portal_catalog(meta_type='Artikkel', level=object.level(), sort_on='Date', Date=['2003-01-01'],sort_order='reverse', Date_usage='range:min') This is not a Python question, it's a Zope question. Better check the Zope mailing list, or if there's one for the specific product used (CMF?) then ask on it instead. -Peter From dave at boost-consulting.com Sat Mar 29 22:31:20 2003 From: dave at boost-consulting.com (David Abrahams) Date: Sat, 29 Mar 2003 22:31:20 -0500 Subject: Best way to embed Python in a C++ app? References: Message-ID: Roy Smith writes: > I'm toying with the idea of embedding Python in an existing C++ > application. As far as I can tell, there are three possible paths I > could take. There's the raw API, there's SWIG, and there's boost.python. > > I've played with the first two a little over the years, but don't really > know anything about boost beyond what little I've learned from reading > the boost web site. It looks like I'm going to need to pass objects > back and forth from C++ to Python, and (at least on the surface) boost > looks like it can handle a lot of the messy details of this. On the > other hand, I'm a little worried that it's still a bit of a work in > progress. Except in that we keep slowly adding improvments, it's not a work in progress. I don't think it's any different from SWIG in that respect. > Anybody with experience in all three willing to offer a comparitive > evaluation? I would suggest that you avoid the raw API if you can. There are so many details that are easy to get wrong that a high-level wrapping tool is almost always a better choice. -- Dave Abrahams Boost Consulting www.boost-consulting.com From peter at engcorp.com Sat Mar 29 07:51:16 2003 From: peter at engcorp.com (Peter) Date: Sat, 29 Mar 2003 07:51:16 -0500 Subject: Running python on unix References: <3E84C6A2.7457D2DE@engcorp.com> Message-ID: <3E8596C4.6D7265D3@engcorp.com> Peter Hansen wrote: > > experimentation, not for creating programs. What you need is to use > a text editor (even Notepad under windows would work, provided you > [...] > Or you could just use PythonWin, or IDLE, but I can't provide much > help for you there. D'oh! Read the subject line, Peter! Of course the OP was using Linux, so info about using Windows is remarkably unhelpful... -Peter From logistix at zworg.com Fri Mar 14 19:55:13 2003 From: logistix at zworg.com (logistix) Date: 14 Mar 2003 16:55:13 -0800 Subject: Stupid *nix Question. Where are the HTML docs? Message-ID: Do the HTML docs get installed by default on *nix systems? If so, where? If not, do most people 'make' them or just download the .tgz from python.org? Thanks, logistix From mwh at python.net Wed Mar 19 08:43:39 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 19 Mar 2003 13:43:39 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 17) References: Message-ID: <7h3bs07ii9h.fsf@pc150.maths.bris.ac.uk> Tim Peters writes: > Also, AFAIK, no absolutely normal number is known (constructed or > not). This is curious because the set of non-normal reals has > measure 0 ("almost all" reals are absolutely normal). But for a number to be "known", it must be comptuable in some sense and there are only countable many Turing machines... Why does anyone care about normality, anyway? Cheers, M. -- Or here's an even simpler indicator of how much C++ sucks: Print out the C++ Public Review Document. Have someone hold it about three feet above your head and then drop it. Thus you will be enlightened. -- Thant Tessman From gerhard.haering at opus-gmbh.net Mon Mar 10 08:04:35 2003 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 10 Mar 2003 13:04:35 GMT Subject: How to obtain the reference name References: Message-ID: Paco wrote: > Hy, somebody know how to obtain the name of an instance out of any methods > of the claas. > Example: > > class A: > def __init__(self): > print 'hello' > > j=A() > > I need to obtain the name of the instance "j", something as is: > "j.name" and the value returned was "j" That's not possible. One object needn't be referred to by only one name. It can be referred to by many names. For example if you continue the above code with: j2 = j j3 = j j4 = j2 j = None -- Gerhard From mertz at gnosis.cx Sat Mar 29 14:08:53 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sat, 29 Mar 2003 14:08:53 -0500 Subject: Metaphors and politics References: <1MudnTyOEK1mauGjXTWcqg@speakeasy.net> <3E835DC2.3678BD7F@engcorp.com> Message-ID: "Terry Reedy" wrote previously: |> In a dispatch from Amman, Jordan, distributed by UPI and published in |> the Washington Times on March 23, veteran foreign correspondent Btw. for non-USA readers who may be unaware: the _Washington Times_ is the house organ for Sun Myung Moon's Unification Church. Politically, it is somewhere to the right of Ghengis Khan. Truth comes in many guises, but the medium provides an initial clue. Yours, Lulu... -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad ---[ Postmodern Enterprises ]-------------------------- From grante at visi.com Wed Mar 12 18:24:08 2003 From: grante at visi.com (Grant Edwards) Date: 12 Mar 2003 23:24:08 GMT Subject: win32com: Accessing MAPIOBJECT References: Message-ID: <3e6fc198$0$83879$a1866201@newsreader.visi.com> In article , Bjorn Pettersen wrote: >> From: Joel [mailto:usenet at prettyhipprogramming.com] >> >> I've been tinkering with win32com in the hopes of being able to >> convert some of the mail in some of my Outlook folders into a >> mbox for use with SpamBayes. > > Why? There's allready an Outlook plugin from Mark Hammond The only thing I can find on Mark's site has to do with SpamBayes. What is an "Outlook plugin", and how does it help in fetching the full message headers? -- Grant Edwards grante Yow! If this is the DATING at GAME I want to know your visi.com FAVORITE PLANET! Do I get th' MICROWAVE MOPED? From xxdigitalhellxx at hotmail.com Fri Mar 7 09:59:39 2003 From: xxdigitalhellxx at hotmail.com (sik0fewl) Date: Fri, 07 Mar 2003 08:59:39 -0600 Subject: Socket connection In-Reply-To: References: Message-ID: Hey, I fixed the problem, thanks for your input, guys. It problem ended up having to do with assigning a list to another list. (That's what I get for not posting all my code) I had no idea that x = y just references y to x (when x & y are lists). ie, >>> x = [] >>> y = x >>> id(x) 17763920 >>> id(y) 17763920 Could somebody point me to the documentation on this? -- Thanks, Ryan From mis6 at pitt.edu Fri Mar 14 11:44:57 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 14 Mar 2003 08:44:57 -0800 Subject: another super wart References: Message-ID: <2259b0e2.0303140844.33dd270d@posting.google.com> SOLVED!! Finally, after quite a lot of thought, I have understood how does it work. There is no bug, here, super is OK and also __new__ is OK. I was mislead by a wrong intuition. The hierarchy I have used in my original posting is the following: 5 object / | 2 A type 4 / | / | 1 B--. Type 3 \ \ / \ M 0 \ : C The colon in the graph denotes instantiation, i.e. C is an instance of M. On the same time, C inherits from B and M inherits from B and Type. The point is that C is both a subclass of B and an instance of M. This generates an ambiguity in super with two possible interpretations (and only one correct): 1. First interpretation (the wrong one!). super(B,C) is interpreted as "the superclass of B with respect to the MRO of C". According to this interpretation, the superclass of B is A and therefore super(B,C).__new__ calls A.__new__ which is object.__new__: but this is not true! 2. Second interpretation (the correct one!) super(B,C) is interpreted as "the superclass of B with respect to the MRO of type(C)". Now the MRO of type(C)=M is MRO[M]=[M B A Type type object] therefore super(B,C).__new__ calls A.__new__ which is Type.__new__ and not object.__new__! My example with a staticmethod called new defined both in A and in Type was misleading, since the wrong interpretation was giving the same result of the right one: super(B,C).new calls A.new that overrides Type.new. All the trouble came because I did not understand how super works, but now I am happy ;) Michele From theller at python.net Fri Mar 21 08:12:06 2003 From: theller at python.net (Thomas Heller) Date: 21 Mar 2003 14:12:06 +0100 Subject: Raising an exception in the caller's frame References: Message-ID: <7kas50ex.fsf@python.net> Alex Martelli writes: > Thomas Heller wrote: > ... > > Hopefully I can explain it: check_result() is not the 'cause' of the > > error, it's purpose is simply to detect the error. The 'exception' > > really occurrs in dosomething(). > > Yes, your purpose is very clear to me and I agree there _should_ > be a way to achieve it, but I can't think of one. > > The best I came up with so far is to *return* an exception instead of raising it, and do a typecheck in the caller: def check_result(value): if somecondition(value): return ValueError(value) # or whatever return value def do_some_work(): value = dosomething() result = check_result(value) if isinstance(result, Exception): raise result return result Thomas From dcengija_remove_ at inet.hr Wed Mar 19 03:21:04 2003 From: dcengija_remove_ at inet.hr (Davor Cengija) Date: Wed, 19 Mar 2003 09:21:04 +0100 Subject: Looking for a specific html parser References: <1215917.HbSNDBvpua@lothar.cengija.com> <19fc7v4m78rkb0m8s6bc4l8oun7prnnnfv@4ax.com> <1579260.71CaRllVEo@lothar.cengija.com> Message-ID: <3557263.ImUbC4YbnA@lothar.cengija.com> Grzegorz Adam Hankiewicz wrote: > On Tue, Mar 18, 2003 at 09:07:47AM +0100, Davor Cengija wrote: >> Basically, I need a DOM like parser for HTML, with xpath >> capabilities. xml.dom might help me, but before that I obviously >> need some kind of html-tidy. > > I required something similar for a small script and I found most > useful to create first an HTMLParser which translated all code to > xml and feed that into Python's minidom. It's quite easy to do if > your input HTML is 'correct', otherwise the xml parsing will surely > fail, unless you filter all through tidy, of course. > I doubt all of my input would be correct HTML, therefore I obviously need tidy-like library. Unfortunatelly, I couldn't find native python tidy, only the before-mentioned wrapper. However, I found java tidy implementation, which could be helpful, together with jython. Thanks -- Davor Cengija, dcengija_remove_ at inet.hr From gaultier at emi.u-bordeaux.fr Wed Mar 19 08:17:15 2003 From: gaultier at emi.u-bordeaux.fr (denis gaultier) Date: Wed, 19 Mar 2003 14:17:15 +0100 Subject: Dialog box. Message-ID: <3E786DDB.F257CC90@emi.u-bordeaux.fr> Do you know which class I must use to create a dialog box ? Thanks. From wsonna at attglobal.net Sat Mar 15 08:03:34 2003 From: wsonna at attglobal.net (William Sonna) Date: Sat, 15 Mar 2003 07:03:34 -0600 Subject: use of "self", was "No Do while/repeat until looping construct in python?" References: Message-ID: On Fri, 14 Mar 2003 13:20:53 -0500, Chermside, Michael wrote: [snip] > PS: Problem for the readers: name another advantage of using self > BESIDES distinguishing local and instance scopes. Extra credit if you > come up with one I haven't heard before. I'll take that one on - "Effective Java - Bloch" "Item 16 - Prefer interfaces to abstract classes". The author makes a pretty convincing case for interfaces because all things being equal, less state is better. Well, all things are rarely equal, and Python has neither interfaces nor abstract classes. But if you take that point one step further to gratuitous state is usually trouble, Python actually helps you out quite a bit. It makes it painful, thus discouraging it. Now does THAT qualify for extra credit? From phil at river-bank.demon.co.uk Sat Mar 22 11:54:57 2003 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Sat, 22 Mar 2003 16:54:57 +0000 Subject: Building PyQT with QScintilla support In-Reply-To: References: <200303211539.26891.phil@river-bank.demon.co.uk> Message-ID: <200303221654.57218.phil@river-bank.demon.co.uk> On Saturday 22 March 2003 6:22 am, Kim Cuong Pham wrote: > Hi, > > I installed the lastest snapshot of ( PyQt, SIP , and Qscintilla) on the > web, python version 2.2.2. > This is what i got > > /usr/lib/qt3-gcc3.2/include/qextscintillaapis.h: In function `PyObject* > sipDo_QextScintillaAPIs_autoCompletionList(PyObject*, PyObject*)': > /usr/lib/qt3-gcc3.2/include/qextscintillaapis.h:67: `QStringList > QextScintillaAPIs::autoCompletionList(const QString&, bool)' is private > sipqtextQextScintillaAPIs.cpp:127: within this context > sipqtextQextScintillaAPIs.cpp: In function `PyObject* > sipDo_QextScintillaAPIs_callTips(PyObject*, PyObject*)': > sipqtextQextScintillaAPIs.cpp:159: no matching function for call to ` > QextScintillaAPIs::callTips(QString&, int&)' > /usr/lib/qt3-gcc3.2/include/qextscintillaapis.h:68: candidates are: > QStringL QextScintillaAPIs::callTips(const QString&, int, int) > sipqtextQextScintillaAPIs.cpp: In function `PyObject* > sipDo_QextScintillaAPIs_callTipsSubset(PyObject*, PyObject*)': > sipqtextQextScintillaAPIs.cpp:189: no method > `QextScintillaAPIs::callTipsSub ' > make[1]: *** [sipqtextQextScintillaAPIs.o] Error 1 > make: *** [sub-qtext] Error 2 > > Do you have any clue? "The latest snapshot" changes from day to day. What are the names of the tarballs you used (they include a date)? Looking at the above, I would guess that your PyQt snapshot is too old for your QScintilla snapshot. Phil From someone at invalid.com Tue Mar 4 01:30:42 2003 From: someone at invalid.com (Sean Richards) Date: Tue, 04 Mar 2003 06:30:42 GMT Subject: Code speedup tips References: Message-ID: On Sun, 02 Mar 2003 01:52:37 -0700, Fernando Perez wrote: > You should take a look at scipy, in particular the weave tool: > http://www.scipy.org/site_content/weave > > Here: > http://www.scipy.org/site_content/weave/python_performance.html > you'll find a good comparison of various approaches to problems similar to > what you have. Using inline C looks pretty interesting. Perhaps I will have another go at getting scipy installed. Sean -- +---------------------------------------------------------------+ | All spelling errors are intentional and are there to show new | | and improved ways of spelling old words. | +---------------------------------------------------------------+ From dcengija_remove_ at inet.hr Mon Mar 17 02:10:26 2003 From: dcengija_remove_ at inet.hr (Davor Cengija) Date: Mon, 17 Mar 2003 08:10:26 +0100 Subject: file browser References: Message-ID: <5730153.ndrHx2fXtn@lothar.cengija.com> Ali Dada wrote: > hi all: > > i am writing an application in Python/Tkinter that excessively uses a file > browser .. > > any idea if there is a ready implementation or useful library or if not > how i proceed???? Use tkFileDialog module. import tkFileDialog print tkFileDialog.askopenfilename(filetypes=[("All files","*"), ("Executables", "*.exe")]) -- Davor Cengija, dcengija_remove_ at inet.hr From Olivier.POYEN at clf-dexia.com Mon Mar 3 09:02:30 2003 From: Olivier.POYEN at clf-dexia.com (POYEN OP Olivier (DCL)) Date: Mon, 3 Mar 2003 15:02:30 +0100 Subject: how to debug a python program normally run in windows console Message-ID: <8963D6370B323E4AA3241200F0EAF7318C0CB4@FCEXVEXM002.dcl.int.dexwired.net> Or maybe just typing some python -i myFile.py It will get executed, and then, you'll have the hand on it just to debug it. > -----Message d'origine----- > De : Phil Lacy [mailto:ycal at grapevine.net] > Envoy? : samedi 1 mars 2003 18:47 > ? : python-list at python.org > Objet : Re: how to debug a python program normally run in windows > console > > > vincent wehren posted in > news:b3qqd7$h37$1 at news1.tilbu1.nb.home.nl > > > > > Maybe you could try setting the environment from within the python > > file, using os.environ > > I thought about that, thanks for the language help, saves a newby some > time. > > > > > > > - > Phil > -reverse ycal for email- > -For MSACCESS, comments are made > -regarding vers9.0 (2000) UON > - > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- ----------------------------------------------------------------- Ce message est confidentiel ; son contenu ne represente en aucun cas un engagement de la part de Dexia Credit Local ou de Dexia CLF Banque. Toute publication, utilisation ou diffusion, meme partielle, doit etre autorisee prealablement par l'emetteur. Si vous n'etes pas destinataire de ce message, merci d'en avertir immediatement l'expediteur. This message is confidential ; its contents do not constitute a commitment by Dexia Credit Local or Dexia CLF Banque. Any unauthorised disclosure, use or dissemination, either whole or partial, is prohibited. If you are not the intended recipient of the message, please notify the sender immediately. ----------------------------------------------------------------- Consultez notre site internet www.dexia-clf.fr La cle d'une gestion optimisee du secteur public local ----------------------------------------------------------------- From donn at drizzle.com Wed Mar 26 01:19:54 2003 From: donn at drizzle.com (Donn Cave) Date: Wed, 26 Mar 2003 06:19:54 -0000 Subject: Unbuffer stdout? References: Message-ID: <1048659589.577001@yasure> Quoth "Francis Avila" : | I'm trying to run the stdout of an os.popen*() to sys.stdout. Problem is | that the output seems to get trapped in a buffer until the command exits. | | Code: | | >>> import os, sys | >>> sys.stdout.write( os.popen("yes", 'r', 0).readline() ) | yes: standard output: Broken pipe | y | >>> | | I assume the broken pipe is from having the pipe closed before 'yes' exits. | Strangely enough, the popen[2-4]() variants don't have this problem: | | >>> sys.stdout.write( os.popen2("yes", 'r', 0)[1].readline() ) | y | >>> It would, if the pipe ever closed, but the above doesn't make that happen, I imagine because some internal references keep the file object from being deleted. By the way, I don't think your parameters to popen2() are right. | Anyway, this: | | >>> sys.stdout.write( os.popen("yes", 'r', 0).read() ) | | hangs forever (with some disk activity after a while) until you interrupt | the interpreter. I strongly suspect this is because the output is getting | trapped in a buffer until the command exits (which is what I want to avoid) | because the following works fine: | | >>> sys.stdout.write( os.popen("ls", 'r', 0).read() ) | directoryOne | directoryTwo | someRandomFile | >>> | | This: | | >>> sys.stderr.write( os.popen("yes", 'r', 0).read() ) | | does the same, which seems odd to me because stderr is never buffered, at | least not by the OS. In any case, even _this_: | | #!/bin/sh | yes | more | | does give you a screen of y's as soon as 'yes' fills the buffer, but before | 'yes' exits. So python is somewhere doing extra buffering of the whole | output of popen(). Sort of. What do you think read() is supposed to do? Check it out: >>> print sys.stdin.read.__doc__ read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. | What I'm looking for is to pipe the stdout of a child process directly to | the stdout of the parent process (i.e., the python script), without any | buffering along the pipeline. As I see it, this is either not possible in | python, or I'm going about this the wrong way. Well, it really is not possible to control this where it counts, which is on the child process end. It will work only when the child process takes it upon itself to flush its output buffer; some applications, notable the shell, already do this, but most don't. If you don't want to read a line at a time but just whatever input is available, then I think it makes more sense (as usual) to forget the file object and use the pipe file descriptor directly -- fp = os.popen('yes') fd = fp.fileno() while 1: data = os.read(fd, 16000) if data: os.write(1, data) else: break fp.close() | BTW, I was trying to look at the code of popen(), but I couldn't find it | anywhere in the python library, much less in os.py. What's more: | | >>> os.popen | | | But if it's a built-in, why do I have to import os? Because popen is in the os module? Built-in basically means that the os module was written in C. popen is a C library function, so you might find some documentation for it with "man 3 popen". Donn Cave, donn at drizzle.com From corrada at ciirsrv.cs.umass.edu Mon Mar 3 11:39:51 2003 From: corrada at ciirsrv.cs.umass.edu (Andres Corrada-Emmanuel) Date: Mon, 3 Mar 2003 11:39:51 -0500 (EST) Subject: Installing 2.2.2 without Tkinter Message-ID: Hello, I'm trying to turn off Tkinter installation in my local version of Python. In previous installations, I used to be able to do this by commenting the lines in Modules/Setup but this seems to have changed. What am I missing? Andres Corrada-Emmanuel Senior Research Fellow Center for Intelligent Information Retrieval University of Massachusetts, Amherst From Padraig at Linux.ie Mon Mar 24 10:53:56 2003 From: Padraig at Linux.ie (Padraig at Linux.ie) Date: Mon, 24 Mar 2003 15:53:56 +0000 Subject: n-ary tree widget In-Reply-To: References: Message-ID: <3E7F2A14.10404@Linux.ie> student wrote: > Hi, I have an application where i have a tree like structure that i > would like to be able to interact with. Is there a tree widget with > collapsable/expandable branches. For my particular application nodes > can have references to other nodes in the tree... for example > > * > /| > / | > / | > ------------- > | / | | | > |/ | | | > * * * * > > notice the first node in the 2nd row points to the root. yep that's a graph not a tree. I never actually visualised a graph in python yet, but was considering it for a project: otter http://www.caida.org/tools/visualization/otter/paper/ graphviz http://www.research.att.com/sw/tools/graphviz/ http://www.cs.brown.edu/~er/software/ chiclid (3d) http://moat.nlanr.net/Software/Cichlid/ http://graphdrawing.org/ http://www.aisee.com/ (? http://www.aisee.com/apps/fxviz.htm This is free and mentions it uses vcg?) http://www.tulip-software.org/ P?draig. From whisper at oz.net Tue Mar 4 18:12:09 2003 From: whisper at oz.net (David LeBlanc) Date: Tue, 4 Mar 2003 15:12:09 -0800 Subject: Curses, PC and Python In-Reply-To: Message-ID: It's not curses, but you might find "s-lang" of interest. It does character based screen stuff on Windows and other os'. www.s-lang.org An application called Woody, written in Python, uses it. It has pyslang, an s-lang wrapper. http://sourceforge.net/projects/woody David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Bob Ballard > Sent: Tuesday, March 04, 2003 9:24 > To: python-list at python.org > Subject: Curses, PC and Python > > > I've googled until I'm googled out. Is there a curses lib for NT > that I can > drive with Python? > > Bob > > > -- > http://mail.python.org/mailman/listinfo/python-list From joshp at cra.com Fri Mar 21 10:37:13 2003 From: joshp at cra.com (Joshua Pollak) Date: Fri, 21 Mar 2003 10:37:13 -0500 Subject: Program stalls when called via Popen4? References: Message-ID: Thanks! Thats probably the problem, I'll try it soon! Ulrich Petri wrote: >> > Everything seems to be working correctly, EXCEPT that the popen2.Popen4 >> > instance I'm using to actually build our project never returns. When I >> > 'watch' what the subprocess is doing by using 'ps aux', it seems that >> > it has stalled on the first call to 'echo'! I'm not sure how to debug >> > this because when I try to duplicate the results manually, everything >> > works fine. >> > >> Do you read the output of compileProcess? >> If not the buffer of the pipe will fill and then block the child. >> >> You can use something like this: >> >> data = compileProcess.fromchild.read(1) >> while 1: >> if data == "": >> ret = compileProcess.poll() >> if ret != -1: >> break >> ret = compileProcess.read(1) >> -- Joshua Pollak 617-491-3474 x586 Software Engineer joshp at cra.com Charles River Analytics From erez at actona.com Mon Mar 3 10:17:52 2003 From: erez at actona.com (erez) Date: 3 Mar 2003 07:17:52 -0800 Subject: Expect on window (from python script) References: Message-ID: claird at lairds.com (Cameron Laird) wrote in message news:... > In article , > erez wrote: > >Hi, > >when i try to run python-script (on linux device) that uses pexpect > >module, and try to telnet window device, i can't do so ( the sendline > >function send only the first cur at a time ) > >does someone know how could i interact window telnet ??? by expect > > > >Thanks, Erez > > Let's be clear on our terms. From the Linux command-line, > can you telnet to the Windows host, and "manually" drive > the Windows process to achieve the result you're after? > Is that indeed a correct model for what you're after? > Briefly, can you get what you're after withOUT Python? > > Even if you say, "No", it might still be possible to achieve > what you're after with Python. All that answer would mean > is that I don't yet understand your requirements. To be more specific: i try to automate telnet process on window device, using the pexpect module, The action can be done by hand (telnet my_window_device) using windows -telnet- server, (from a command line from some Unix) for my understanding the Expect (like) module should works for windows device , (when i contact the windows device), it is working via Perl Expect (TCL too), i want to do so by Python. Jeff (Hi), what is it xmlrpc/Pyro can it help me ??? Thanks again, Erez From max at alcyone.com Fri Mar 14 23:50:04 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 14 Mar 2003 20:50:04 -0800 Subject: pointing to the correct python References: Message-ID: <3E72B0FC.E2CB623D@alcyone.com> Andrew Koenig wrote: > One way is to start your file with > > #!/usr/bin/env python > > and then be sure that the right python directory is the first one in > your PATH variable. But not if he's running Windows, right? -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Who, my friend, can scale Heaven? \__/ _The Epic of Gilgamesh_ The laws list / http://www.alcyone.com/max/physics/laws/ Laws, rules, principles, effects, paradoxes, etc. in physics. From peter at engcorp.com Mon Mar 31 20:03:43 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 31 Mar 2003 20:03:43 -0500 Subject: try:else: w/o except: - why not? References: <1c004553.0303311553.53a9a92b@posting.google.com> Message-ID: <3E88E56F.5CB4EB92@engcorp.com> Manus Hand wrote: > > I know that if you want to use else: on a try: block, you need to > specify one or more except: clauses. I guess my question is why > this should need to be. > > Personally, I have cases where it would be nice to do this: > > try: > # some code that may except > else: > # but if it didn't except, I want to do this > > Instead of writing the code that way, I need to write this: > > try: > # some code that may except > except: > # and if it does, then, okay, just ignore it > pass > else: > # but if it didn't except, I want to do this No, actually to get the behaviour you presumably want, you would have to write this: try: # stuff except: raise # pass would just swallow the exception! else: # do this when no exception What you wrote in the first place is exactly the same as this: # some code that may except # but if it didn't except, I want to do this In other words, the "try" in your first block is useless.... -Peter From simonb at webone.com.au Mon Mar 10 17:25:45 2003 From: simonb at webone.com.au (Simon Burton) Date: Tue, 11 Mar 2003 09:25:45 +1100 Subject: A fun tool for demonstrating or teaching python? References: <9s7ba.2698$4q6.305236@news20.bellglobal.com> Message-ID: On Mon, 10 Mar 2003 16:30:27 +0000, WP wrote: > There was a discussion (I found it using groups.google.com) a while ago with > some people interested in building a very easy-to-use IDE for teaching Python, > possibly even with Kids. > > I am thinking of whipping up something, perhaps with the ability to walk > through the code ('animated' debugger) and to do something visual or > graphical, turtle graphics, or a game, or something like that. > > Anybody got any recommendations on where to start? So far I'm leaning > towards wxPython and maybe PythonCard. The system would either be a > hyper-card like tool using Python, or perhaps it would be a Python Logo, > with the code window on the bottom and a graphics window on the top. > > The old Smalltalk 'Alice99' system was a pretty cool way to demonstrate Squeak > (smalltalk) but although the new Alice (which uses Python) is cool looking, it > is closed source, so that's no good. > > Regards, > > Warren Yes, i'm in the same boat. Am trying pygame now; already have a working turtle and have started on an animated execution tracer... pygame cause i've had trouble with other stuff on the various platforms i need it for. (haven't tried wx yet...) Let me know if you get pygame working; i'll send you what i have done. Simon Burton. From paul at shiningrose.co.uk Mon Mar 17 17:55:23 2003 From: paul at shiningrose.co.uk (P Brian) Date: Mon, 17 Mar 2003 22:55:23 -0000 Subject: New python interview Message-ID: Dear all, My naked attempt to use the goodwill of Python contributors in order to promote the Python UK conference is drawing towards an end. We have the penultimate interview up on http://www.python-uk.org with Martin von Loewis, famous for, amoungst other worthy qualities, being tall, on the PSF board, and deeply into parse trees. Guido's interview will be up at the weekend, and I hope that we have enticed some more of you good people into joining us in Oxford. Should you wish to speak at the conference there are still some slots in the "Lightning Talks" (about 10 mins each on any python related subject you wish) so please do let me know. cheers ---------------- paul brian From davecook at nowhere.net Tue Mar 4 03:33:02 2003 From: davecook at nowhere.net (David M. Cook) Date: Tue, 04 Mar 2003 08:33:02 GMT Subject: PyGTK-2 Full-Screen mode. References: <14bd1399.0303021258.67171d44@posting.google.com> <14bd1399.0303031047.6032597b@posting.google.com> Message-ID: <2xZ8a.165517$zL6.135975@news2.central.cox.net> In article <14bd1399.0303031047.6032597b at posting.google.com>, kkennedy wrote: > Question: How in the world did you interpret those two method calls > from the documentation? In the documentation the method names are > different and they both require that the GtkWindow be passed as the > first argument. However, what you have written in Python are > different method names and the exclusion of the GtkWindow argument. > How did you come up with this? Better docs specifically for the Python API are being worked on. Until then here are some rules for translating from C to Python: Namespaces: o gtk_ -> gtk. o gnome_ -> gnome. or gnome.ui. (depending on header file) o g_ -> gobject. o gdk_ -> gtk.gdk. Class names are in "StudlyCaps" (same as the C typenames without the "Gtk" part): o gtk_class_name_new() -> gtk.ClassName() e.g. gtk.TreeView() o gtk_class_name_new_with_foo(myfoo) -> gtk.ClassName(myfoo) e.g. gtk.TreeView(model) Method names are generally the same as C method names. gtk_class_name_method_name(instance, params) -> instance.method_name(params) e.g. gtk_tree_view_get_column(treeview, 4) -> treeview.get_column(4) In general, in/out parameters become return values. Usually in cases where a "failure" would be returned, None is returned. gtk_class_name_method_name(instance, a, b, &c, &d) -> c, d = instance.method_name(a, b) e.g. gtk_tree_view_get_path_at_pos(treeview, x, y, &path, &column, &cell_x, &cell_y) -> path, column, cell_x, cell_y = treeview.get_path_at_pos(x, y) Constants, e.g.: GTK_WINDOW_TOPLEVEL -> gtk.WINDOW_TOPLEVEL GDK_KEY_PRESS -> gtk.gdk.KEY_PRESS FALSE, TRUE -> gtk.FALSE, gtk.TRUE Others: o instance.connect() instead of signal_connect() o paths in TreeView/Models are just tuples. o string lengths do not need to be specified o The TreeViewColumn constructor can take named parameters for the CellRenderer properties: cell = gtk.CellRendererText() column = gtk.TreeViewColumn(colname, cell, text=i, editable=j) Dave Cook From erikprice at mac.com Sun Mar 2 23:25:30 2003 From: erikprice at mac.com (Erik Price) Date: Sun, 2 Mar 2003 23:25:30 -0500 Subject: using builtin exceptions Message-ID: <2AFB97B8-4D30-11D7-8ED7-00039351FE6A@mac.com> Hi, Is it considered bad practice to appropriate the "builtin" exceptions that ship with the stdlib in our own programs? For instance, "ValueError" is explicitly described by the documentation as being for the use of builtin functions only ("Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError."), but it's the exact same purpose I have in mind if I use it in my code: ### def __init__(self, shift_type, shift_start, shift_stop): if not Shift.pay_rates.has_key(shift_type): raise KeyError if shift_start > shift_stop: raise ValueError ... ### So is this okay to do? I ask this not strictly from a pragmatic perspective but also from a stylistic one.... Thanks, Erik -- Erik Price email: erikprice at mac.com jabber: erikprice at jabber.org From jslavin at cfa.harvard.edu Mon Mar 3 15:10:38 2003 From: jslavin at cfa.harvard.edu (Jon Slavin) Date: 3 Mar 2003 12:10:38 -0800 Subject: diff for (text only) manuscripts Message-ID: This is not Python specific, but it seems that Python offers hope for a solution. I've been looking for a form of diff that is good for manuscipts -- rather than programs. That is, a diff that is word as opposed to line oriented. My motivation is that, as a scientist I often collaborate with others on papers wherein we take turns editing a LaTeX file. Sometimes I'd like to know exactly how the file has been changed but I don't care if the lines wrap at a different point -- so I don't want to see noted as changed an entire paragraph if a couple words in the beginning have been added and the line breaks re-done. I have a little experience with Python and tried altering ndiff.py (in Python 2.1 Tools/scripts) but without too much luck. The problem is that even if you make it do a diff on a series of words rather than lines, it's not clear how to put it all back together to make the result readable. Any suggestions welcome. Jon Slavin From sadams123 at optushome.com.au Tue Mar 4 01:17:43 2003 From: sadams123 at optushome.com.au (Steven) Date: Tue, 04 Mar 2003 06:17:43 GMT Subject: binary data into MS-SQL server via ODBC Message-ID: Could anyone provide a snippet of sample code to insert binary (image) data into a database. I'm current using the ODBC module on WinXP to connect to an MS-SQL Server, the field is an 'image' type. Inserting text works fine, however when trying to insert the data from an image I get: TypeError: argument 1 must be string without null bytes, not str I'm using the the cursor.execute and giving it my own "INSERT foo (x,y,z) VALUES (.... " SQL statements, but cannot get it to work, any help is much appreciated (and needed) thanks Steven From tim.one at comcast.net Wed Mar 19 15:26:56 2003 From: tim.one at comcast.net (Tim Peters) Date: Wed, 19 Mar 2003 15:26:56 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 17) In-Reply-To: Message-ID: [Robin Becker] > I assume absolute normality excludes the case where one expresses the > number in itself as a base or am I being more than usually stupid. It has to do with digit distribution in conventional positional notation in positive integer bases (>= 2). Google will lead you to a precise definition faster than I can regurgitate one. > Also I suppose that being non-random implies finiteness (in some sense) > so are we just talking 'symbol' count or information. Sorry, I couldn't parse that -- but digits is digits, and the requirement that all k-digit subsequences appear equally often, for each k >= 1, is intuitively simple. See Knuth (Volume 2) for an entertaining argument that piles on more intuitive requirements, until he ends up with a definition for randomness that (it turns out) no number can meet! Intuition isn't always enough -- or maybe it is, and randomness doesn't exist. From gaultier at emi.u-bordeaux.fr Wed Mar 19 07:59:44 2003 From: gaultier at emi.u-bordeaux.fr (denis gaultier) Date: Wed, 19 Mar 2003 13:59:44 +0100 Subject: problem with py2exe Message-ID: <3E7869C0.35E9E6D5@emi.u-bordeaux.fr> Hello everybody, I've got a bug with py2exe, when I execute the exe file I got the error message : Traceback : File "", line 7, in ? File "imputil.pyc", line 98, in _import_hook File "", line 52, in _import_top_module File "imputil.pyc", line 207, in _import_top File "imputil.pyc", line 262, in _import_one File "", line 128, in _process_result File "Pmw\__init__.pyc", line 34, in ? IndexError: list index out of range I found on a forum that I need to install the bundlepmw, I did it (maybe a wrong way) but the problem stay. Maybe the problem come from my script : # setup.py from distutils.core import setup import py2exe setup(name="Trivial", scripts=["Gestion.py"], data_files=[("Images", ["Images/Allemagne.gif", "Images/A.gif","Images/fond.gif",\ "Images/continuer.gif","Images/B.gif","Images/C.gif",\ "Images/D.gif","Images/texte.gif"])], ) My main file is Gestion.py and call 3 others files Joueur.py, Etape.py and Coordonnees.py, I don't know if i have to add them in the script or if it's automatic. If I need to put them in how could I do ? Thanks From sjmachin at lexicon.net Mon Mar 24 06:21:38 2003 From: sjmachin at lexicon.net (John Machin) Date: Mon, 24 Mar 2003 11:21:38 GMT Subject: Python 2.3 True = False References: Message-ID: <3e7ee95c.3854662@news.lexicon.net> On 23 Mar 2003 22:58:14 -0800, anand at calbay.com (Anand) wrote: >>>> True = False >has anyone tried this before? Yes. Also lots of other exciting exploits like this >>> import sys >>> sys.maxint 2147483647 >>> sys.maxint = 1 >>> sys.maxint 1 >>> but don't worry; it's not addictive, and contrary to what your mum says, it won't send you blind. After a while, you'll stop messing about and get back to programming. From peter at engcorp.com Wed Mar 5 21:48:03 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 05 Mar 2003 21:48:03 -0500 Subject: Concerns about performance w/Python, Pysco on Pentiums References: <3E660EB3.4065D81F@engcorp.com> Message-ID: <3E66B6E3.A2886DE3@engcorp.com> Anton Muhin wrote: > > Array or Numeric modules might lead to better performance. Hmm... I don't see how. Unless you are thinking along the lines of Gerhard's suggestions about using a buffer instead of a list to simulate memory. I really think this is a small aspect of the problem, though, but without profiling I guess I won't know. -Peter From mhammond at skippinet.com.au Thu Mar 6 19:25:37 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 07 Mar 2003 00:25:37 GMT Subject: building python under windows In-Reply-To: References: Message-ID: <5GR9a.29397$Xh1.82547@news-server.bigpond.net.au> Damien Morton wrote: > Im building python 2.3a2 using MSVC 6.0 under windows 2000. > > The projects in the pcbuild directory builds python.exe and python23.dll > > I want to build several versions of python, with various profiling options > and optimisations turned on, and am trying to figure out how to build a > statically linked version of python.exe > > I would have, for example, > python.exe (2.3a2 unchanged) > python_dxp.exe (2.3a2 with dynamic profiling turned on) > etc etc > > > Any help, suggestions, etc greatly appreciated. I don't think you will find much support in the core for this. As Martin mentions, it will be a matter of *setting up* the correct defines etc, not simply flipping them. If you manage to do this fairly cleanly, consider adding a patch to sourceforge, so others could do it should they be so inclined. Mark. From nospam at garen.net Mon Mar 31 11:48:02 2003 From: nospam at garen.net (Garen Parham) Date: Mon, 31 Mar 2003 08:48:02 -0800 Subject: Is Python overhyped (just like Java)? References: Message-ID: Anand B Pillai wrote: ... > Why would anyone use Python ? Well, first of all it is a true > object-oriented language in the spirit of Smalltalk/Java whereas > C++ is not one. It has a clean syntax and comes with many pre-built > libraries, most of them written in C(CPython) or Java(Jython). It > is a higher-level programming language when compared to C++, as Alex > pointed out. Come on, lets be honest here. Things like being a "true" OO language is pretty subjective without any criteria to qualify what OO is. ... > > Python on the other hand is a free language developed by a group of > programmers based on the idea of software freedom. ... And here I thought it was just created by Guido to solve some real problems. ... > > The single biggest advantage of python is SPEED. You can map your > problem space to solution space with 10% of the time you need to > prototype > in C++, in python(Probably lesser, but this question is better > answered > by professional python programmers). C++ burdens the programmer with > mundane > tasks like freeing memory, declaring headers, writing macros to feed > the preprocessor, the list is endless. 80% of the time to program a > C++ project > is taken in deciding on the code modules, preparing the header files > and > the directory structure, deciding which symbols to be > exposed(exported). The productivity boost in Python is believable. The 10% and 80% magic numbers aren't. I'm sure you wouldn't like seeing someone pulling out magic numbers in comp.lang.c++ saying Python was 200%, 5000% slower out of context. ... > Python makes programming fun. ... > Learn python today and you will agree that it was time well spent. :) From andy at wild-flower.co.uk Thu Mar 20 16:53:00 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Thu, 20 Mar 2003 21:53:00 +0000 Subject: Is Python the Esperanto of programming languages? In-Reply-To: <20030319194019.B6746@localhost.localdomain> References: <200303192233.30383.andy@wild-flower.co.uk> <3E7908A7.CCEF27E8@alcyone.com> <20030319194019.B6746@localhost.localdomain> Message-ID: <200303202153.00545.andy@wild-flower.co.uk> On Thursday 20 Mar 2003 12:40 am, Jack Diederich wrote: > On Wed, Mar 19, 2003 at 04:17:43PM -0800, Erik Max Francis wrote: > > Jack Diederich wrote: > > > On Wed, Mar 19, 2003 at 10:33:30PM +0000, Andy Jewell wrote: > > > > Just thought I'd throw the cat amongst the pigeons... I just > > > > occurred to me > > > > that Python is designed to be elegant from the ground-up, and takes > > > > many of > > > > the 'best' features of many other programming languages, but always > > > > with > > > > elegance in mind, similarly to Esperanto, ... > > > > > > -1 Troll. > > > > > > I would wager there are more people using python than know > > > Esperanto! > > > > Even if true (which isn't that easy of a call, since both figures are > > extremely hard to estimate reliably), what's that got to do with it? > > The comment was clearly intended as a compliment for Python. Where's > > the troll? > > Saying "good, great, thoughtful, best intentions - exactly like this widely > heckeled massive failure who's crowning acheivement was a movie starring > William Shatner." hardly strikes me as a compliment. Ok, Jack, you've got me there. Got me confused, that is. 1) I don't consider Esperanto a failure - people DO use it. I may not be one of them, but having learned a teensy-weensy bit about it, I beleive that the *IDEA* behind it is good. Having taught English reading and writing to my children (who are in any case English) was hard enough. Strangely, teaching my eldest, aged 7, Python is proving /far/ easier. Esperanto is far easier to learn than English, and I am told, most other spoken languages - by design. I don't think it has a ternary operator, though :-)) 2) What film was that? Really - I didn't know there *was* a film which featured Esperanto. That's probably because it starred William Shatner... 3) I think Python is the best thing since Bubblegum, Sliced Bread, Oberon etc. etc. I'm serious: I REALLY LIKE PYTHON. I use it at work and "play" totally out of choice. If I was trolling, I'd have said something like... No, actually, I won't say it: it would give you more ammo than you need :-) From sjmachin at lexicon.net Wed Mar 26 03:15:51 2003 From: sjmachin at lexicon.net (John Machin) Date: 26 Mar 2003 00:15:51 -0800 Subject: Finding out the weekday References: <86adfjz286.fsf@ieee.org> <1ZKcnQPKB9e4Kh2jXTWcpQ@comcast.com> Message-ID: "Terry Reedy" wrote in message news:<1ZKcnQPKB9e4Kh2jXTWcpQ at comcast.com>... > "Jorge Godoy" wrote in message > news:86adfjz286.fsf at ieee.org... > > Is there any Python module that given a particular date it returns > me > > the day of the week? I'm needing it for some special calculations > > involving dates... > > don't know if new datetime module has that. But formula is easy to > program. This has been asked various times on various newgroups. > Google 'day week formula', first hit says > " > To add to Ben's article (appended below), John Conway's > method is by far the easiest to use. A general method > of finding the special day of the week for any year (what > Conway calls 'Doomsday') is as follows: Write the year [snip] > which is the day of the week (Sunday = 0, Saturday = 6). Thus, > Monday=1 is the Doomsday for 1994. > > E is the century number, which repeats on a 400 year cycle. > This century E=3; in 16YY and 20YY it is 2; in 17YY and 21YY > it is 0, and in 18YY and 22YY it is 5. It goes back to 3 again > in 23YY. > " > > Terry J. Reedy What is this "Doomsday" thingy? The above description certainly shows that it is a function of the year only, i.e. doesn't depend on the day and the month -- which would appear not to be what the OP was looking for e.g day_of_week(today()) returns "Wednesday" (in my timezone/locale combination) and will return "Thursday" tomorrow. From gh at ghaering.de Thu Mar 6 14:33:21 2003 From: gh at ghaering.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 6 Mar 2003 19:33:21 GMT Subject: why self instead obj ? References: <698f09f8.0303061027.698b4e7e@posting.google.com> Message-ID: Jeremy Fincher wrote: > [...] obj, on the other hand, is three taps of the keyboard, the > first two of which are the same finger, On a QWERT(YZ) keyboard, B is to be typed with the left hand. On my ergnomic keyboard, doing otherwise is nearly impossible ;-) -- Gerhard From sholden at holdenweb.com Fri Mar 7 08:55:10 2003 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 07 Mar 2003 13:55:10 GMT Subject: IndentationError: two many levels of indentation References: Message-ID: <2x1aa.209264$zL6.39034@news2.central.cox.net> "Two Inches" wrote in message news:b49ia1$d5o$1 at mamenchi.zrz.TU-Berlin.DE... > We've got this error when we tried to execute code that was created with > a generator tool. The code had about 500 levels of indentation (nested > if blocks). It is no problem for us to change the generator. > > However, I couldn't find this limitation in the language reference. > Shouldn't it be in there? What is the exact limit? > > Is there any technical rational for this limit? > The limit will be set by a configuration parameter. It would seem more sensible to me to alter your generation routines: is it *really* necessary to generate code indented to 500 levels? Isn't there some way you could paraphrase the generated Python so it doesn't require something that a real programmer would never do in practice? regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Register for PyCon now! http://www.python.org/pycon/reg.html From aleax at aleax.it Tue Mar 4 12:11:15 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 04 Mar 2003 17:11:15 GMT Subject: How to use threading and Queue modules References: <182bcf76.0303040901.23690dcc@posting.google.com> Message-ID: Paul Moore wrote: > I have a problem trying to use the threading and Queue modules. What > I'm trying to do is to fire off a host of background threads, and let > them do some work. In my main thread, I want to wait for the > background workers to complete, and then pick up their results. > > The best way to handle the results seems to be via a Queue.Queue, so > that I don't have to worry about locking issues. Oh yes, definitely! > But now I hit a problem: How do I wait for the workers to all finish? > If I just join all the workers in turn, I risk the queue filling up, > resulting in deadlock. If I wait on the queue, I don't know when all > the workers have finished. Simplest: have each worker post to the results Queue a distinguished message saying "I'm finished" -- the main thread collects and processes those to count the number of worker threads still outstanding, and when that "number still outstanding" is 0, well, there you are! > Maybe a queue isn't the right data structure here. Is there another, > more suitable, data structure which can collect results from worker > threads? Maybe all I want is a locked list. After all, the queue would > be fine if it couldn't fill up. (There isn't enough data here for it > to be a problem to keep it all in memory). Queue.Queue is unbounded by default, except for memory limitations, so I may not be understanding exactly what you mean. > I'm new to multi-threading, so I don't want something too hard :-) I think that either of the solutions -- not worrying about "filling up" if memory limitation isn't an issue, counting threads still outstanding by use of distinguished messages signifying thread termination -- is pretty simple. > Basically, the only reason I'm using threads at all is to multiplex a > lot of database conversations (50 or more) where IO and network times > are the bottleneck - with threading, I can run all 50 in the time it > takes the slowest to connect! Sounds like a good reason to me. Alex From ipellew at pipemedia.co.uk Sun Mar 2 17:59:59 2003 From: ipellew at pipemedia.co.uk (Ian Pellew) Date: 2 Mar 2003 14:59:59 -0800 Subject: Shared Memory Message-ID: <30875970.0303021459.662787af@posting.google.com> Hi; Has any one done any work with Python using Shared Memory ! I have the need to load some small Database tables into memory that I will constantly use. In C I would simply create some shared memory (The Unix world) and put my data there. Any help / pointers please. Regards Ian From MFranklin1 at gatwick.westerngeco.slb.com Thu Mar 20 04:45:11 2003 From: MFranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 20 Mar 2003 09:45:11 +0000 Subject: comparing lists References: Message-ID: <3E798DA7.4050205@gatwick.westerngeco.slb.com> Enrique Palomo wrote: > Hello all > > I must compare the contained of several directories in several pcs. Each > directory must contain about 17000 files. > > Do you know any special method to compare the lists of listdir quickly? Enrique, Lists can be tested for equality with == but I suspect this is too simplistic. So my question is what exactly do you want to compare? Martin From tim.one at comcast.net Mon Mar 3 20:24:14 2003 From: tim.one at comcast.net (Tim Peters) Date: Mon, 03 Mar 2003 20:24:14 -0500 Subject: Dumb question on assignment chaining In-Reply-To: <984e2f1d.0303031713.3ad6e931@posting.google.com> Message-ID: [Manus Hand] > ... > So it seems that in the construction x = y = z, the assignments take > place in left-to-right order (i.e., x = z and then y = z; Yes. > the opposite of how the C language implements its assignment operation). > I checked the Python documentation to see if this is etched in stone and > can be depended upon, Yes. > but I saw nothing (am I just missing it?) Yes. > in section 6.3. Try reading the second sentence again : An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. In your x = y = z example, z is "the expression list", and "x" and "y" are two "target lists", which are assigned to (as it says) left to right. This follows from the grammar rule given there: assignment_stmt ::= (target_list "=")+ expression_list In your example, the target_list "=" part is expanded twice. From a.schmolck at gmx.net Mon Mar 3 13:21:14 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 03 Mar 2003 18:21:14 +0000 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <58q36vgv1ga8ovde5ftub9t8ugaa2pnum5@4ax.com> <3E62778F.EED49083@alcyone.com> <3E629E93.B94F7631@alcyone.com> Message-ID: Andrew Koenig writes: > Alex> (Hint: in case the point of how mere "differences in keystrokes" > Alex> can widely affect design choices in a language and its libraries > Alex> was lost on you; do you really think anyone would dream of > Alex> introducing a ternary operator if you could just do > > Alex> def when(cond, a,b): > Alex> if cond: return a() > Alex> else: return b() > > Alex> res = when(cond, :b, :c) > > Alex> instead of > > > Alex> res = when(cond, lambda : b, lambda :c) > > Alex> ?) > > Yes, definitely. > > What's wrong with when(cond, :b, :c) is that it's too easy to forget > one of the colons, in which case the error goes undiagnosed until the > corresponding branch is actually executed. [...] > For that reason, although I wouldn't mind having a more compact way of > writing lambda-expressions, I don't think that the colon syntax is > the best way to do it. Fair enough, my main point simply was that apparently small differences in verbosity of constructs do sometimes matter *a lot*, to the extent that not only library interfaces but even language design decisions can be affected by it. Whether or not :x is a good way to write lambda: x, my bet would still be that *if* a similar lighweight lambda idiom had already existed, the chances of a ternary making it into the language would be nil. alex From member16943 at dbforums.com Mon Mar 3 00:18:36 2003 From: member16943 at dbforums.com (Tetsuo) Date: Mon, 03 Mar 2003 05:18:36 +0000 Subject: XP or something References: <2593169.1046568078@dbforums.com> Message-ID: <2595838.1046668716@dbforums.com> Okay, now I feel stupid. Or maybe I am. I clicked the link in Start, and it works fine. Before, I tried to open the file "pythonw.exe" directly. But I can't figure out the path that link points to... I guess it isn't too important, but it'd be nice. -- Posted via http://dbforums.com From cartermark46 at ukmail.com Wed Mar 26 12:12:43 2003 From: cartermark46 at ukmail.com (Mark Carter) Date: 26 Mar 2003 09:12:43 -0800 Subject: urllib and persistence References: <_Pffa.104805$pG1.2227390@news1.tin.it> <7t_fa.10826$i26.247708@news2.tin.it> Message-ID: > > to know your surname, for example. So I don't think that wget will > > help. > > Actually wget is able to load cookies from Netscape-format cookies.txt > files, so if you did a first login with Netscape you could then use > wget with the --load-cookies option. I read on wget's manual, but > haven't tried myself, that from Internet Explorer you can produce a > textfile that wget can use It works! I used wget rather than python to do the download - it just seems plain easier to do it that way. Here's a summary of what I discovered, in case others find it useful: One can view cookie details in Nestcape (7.02) by selecting menu item Edit - Preferences category Privacy & Security subsection Cookies button Manage Stored cookies tab Stored Cookies This presents a list of cookies whose details you can inspect. Cookies can be exported from Internet Explorer menu File - Import & Export This exports the cookies as a text file. TIP: You may need to edit some of the entries in the cookies.txt file. Most of the entries are of the form www.boo.com and probably require no ammendement, but where you see boo.com you may have to prepend a dot, thus: .boo.com This can happen if there is more than one way to access the server, e.g. via www1.boo.com and www2.boo.com Alex Martelli wrote in message news:<7t_fa.10826$i26.247708 at news2.tin.it>... > Mark Carter wrote: > > >> > http://wwwsearch.sourceforge.net/ClientCookie/ may thus > >> > prove of help. > >> > >> As will wget, if you want a non-python solution. > > > > Alas, the site requires logging in, but not in a strict > > account/password way - it wants > > to know your surname, for example. So I don't think that wget will > > help. > > Actually wget is able to load cookies from Netscape-format cookies.txt > files, so if you did a first login with Netscape you could then use > wget with the --load-cookies option. I read on wget's manual, but > haven't tried myself, that from Internet Explorer you can produce a > textfile that wget can use: > > """ > You can produce a cookie file Wget can use by using the File menu, Import > and Export, Export Cookies. This has been tested with Internet Explorer 5; > it is not guaranteed to work with earlier versions. > """ > > There are a few recipes in the Python Cookbook for dealing with > cookies as saved by both Netscape and IE. > > > > I must admit that I'm a bit lacking in understanding how urllib2 > > and/or ClientCookie > > are supposed to work. Does ClientCookie work with Internet Explorer > > cookies, or not? > > MSIECookies SHOULD let you use cookies saved by IE -- I think it's > prominently enough explained among the FAQ's at > http://wwwsearch.sourceforge.net/ClientCookie/ . Using netscape- > formatted cookies may be preferable even there, though -- better > tested/clearer/more understood (as it's text, it's easier to > understand and "reverse engineer". > > > > Alex From pedronis at bluewin.ch Thu Mar 6 08:38:37 2003 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Thu, 6 Mar 2003 14:38:37 +0100 Subject: Can __iter__ be used as a classmethod? References: <60FB8BB7F0EFC7409B75EEEC13E20192022DD8D3@admin56.narex.com> <2259b0e2.0303050740.52a92487@posting.google.com> <89G9a.12708$pG1.332485@news1.tin.it> Message-ID: <3e674f91_4@news.bluewin.ch> "Alex Martelli" ha scritto nel messaggio news:89G9a.12708$pG1.332485 at news1.tin.it... > Actually, a very typical use case for class methods (in Smalltalk at > least) is for *factories* -- which of course are only useful for > classes that ARE meant to be instantiated, because they typically > return class instances. > yes. On Smalltalk and class methods: in Smalltak class methods are methods on the meta class, a meta class is automatically created behind the scene for each class, and class methods are only accessible through the class as in: MyClass metamethod... myinst class metamethod... but: myinst metamethod would cause a message not understood exception. From aahz at pythoncraft.com Thu Mar 6 00:34:54 2003 From: aahz at pythoncraft.com (Aahz) Date: 6 Mar 2003 00:34:54 -0500 Subject: ANN: Ballot for Complementary PEP308 Ternary VOTE References: <3E668321.2B19756F@alcyone.com> Message-ID: In article , phil hunt wrote: >On Wed, 05 Mar 2003 15:07:13 -0800, Erik Max Francis wrote: >>Aahz wrote: >>> >>> And I disagree with this. From my POV, an expanded approval vote >>> makes >>> much more sense for this specific situation. (By "expanded", I mean >>> that each item to be voted on can be marked as YES/NO/ABSTAIN.) >>> >>> While in some sense that would be less robust than Condorcet, the >>> increase in simplicity and raw data would be well worth it. >> >>I agree -- at the very least there should be been some feedback on each >>and every form (including a "no change" option), whether >>affirmative/negative, or affirmative/indifferent/negative. > >The whole point of Condorcet is that it allows you to do this. Figuring out how to do a properly nuanced vote with Condorcet isn't trivial. The mechanism for voting is the same as STV, and I've seen too many people screw up in not understanding that the way to vote against something is to not rank it. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Register for PyCon now! http://www.python.org/pycon/reg.html From 'tert at pncen.hf'.decode Thu Mar 6 13:48:44 2003 From: 'tert at pncen.hf'.decode (Greg Krohn ('rot-13')) Date: Thu, 6 Mar 2003 12:48:44 -0600 Subject: Parsing Search Criteria Message-ID: I want to parse a criteria string, counting words enclosed in quotes as one 'word'. Like this: >>> parse_criteria('parrot "I like Python." ternary operator trouble') ['I like Python.', 'parrot', 'ternary', 'operator', 'trouble'] I haven't found anything Googling, so I wrote the following. So I have two questions. One: Do any modules exsist that do this better? Two: If not One, do you see any potential pifalls with my code? Could it be more elegant? (Pretend that's one question.) Thanks for any help. def parse_criteria(criteria): """Parse a search criteria string in to a list of words.""" quotes = [] #indices of quotes quotepos = -1 words = [] #all words found counting a fragment in quotes as one word #find all the quotes while 1: quotepos = criteria.find('"', quotepos + 1) if quotepos == -1: break else: quotes.append(quotepos) #remove an unmatched quote from the end if len(quotes) % 2: del quotes[-1] #add the quoted fragments to the word list #Note: the list comp. creates a list of (start, end) tuples for sq, eq in [(x, x+1) for x in range(0, len(quotes), 2)]: frag = criteria[quotes[sq]+1:quotes[eq]] frag = frag.replace('"', '') words.append(frag) #remove the quoted frags from the criteria for word in words: criteria = criteria.replace('"%s"' % word, ' ') #remove empty words for word in criteria.split(): word = word.strip() if word: words.append(word) return words -- Greg Krohn 'tert at pncen.hf'.decode('rot-13') From sross at connectmail.carleton.ca Mon Mar 3 10:08:46 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Mon, 3 Mar 2003 10:08:46 -0500 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: Message-ID: "Roman Suzi" wrote in message news:mailman.1046677684.8629.python-list at python.org... > On Sun, 2 Mar 2003, Sean Ross wrote: > > > How about "do", instead of "fn"?: > > As on of the PEP 312 authors, I must explain. PEP 312 is not about adding > new keywords, etc. > Yes. I was aware of that when I made my post. PEP312 is about removing keywords, or, more precisely, making them "optional in some cases where it is not grammatically ambiguous" I was not suggesting otherwise. I was suggesting "do" over "fn". Someone suggestion "fn". I didn't care for that, so I suggested "do", mostly because it was not an abbreviation but also because it has been used in Ruby to delimit blocks. Nothing more than that - idle speculation, what if's, that sort of thing...i.e., If you were going to change the keyword lambda(and not make it optionally implicit), then I think "do" would be a better replacement than "fn". >And I am already allergic (thanks PEP 308) to such > suggestions. I rather enjoyed reading the PEP308 debate. I find the idea of language design to be very interesting and I found the discussions and differences of opinions over a single feature fascinating. Perhaps if I had to implement this language, I would be more concerned by idle speculations that include keyword introductions but, for the moment, I'll just enjoy playing with the syntax to see if there is a better way. Or, at least, a way that I'd prefer were I to implement a language. In general, this is my point of view when I post syntax alteration ideas. I'm just trying them out. Seeing if one way is better than another, or more preferred. If they were more than that, I should write a PEP. (or a language) >The only problem with PEP 312 as I see it is that lambdas are > more useful when they have arguments. And this is hard to help without > "lambda" keyword. > Our opinion differ slightly here. Personally, I have no problem with "lambda", but I can see where it could be intimidating. And, given my preference, I would have chosen "do", but we won't go there at the moment IMO, the problems with PEP 312 are twofold: (1) it favors implicit over explicit and (2) it introduces inconsistent syntax - two possible lambda forms without arguments, and one form with arguments. I could argue that my objection to (1) is not strictly correct, since, in the new form ":expression", the colon, in certain unambiguous cases, and once we have learned the new idiom, explicitly signifies that we are dealing with an anonymous function. I don't find that it's level of "explicitness" matches my taste but, either way, (1) does not concern me greatly in this particular case. (None of them "concern me greatly", but it's a nice turn of phrase... moving on...) However, if you prefer consistent syntax, which I do, then I should think that (2) would be of more concern. Of course, the new syntax is optional, so if consistency is your bugaboo, you can still use the "lambda" for argumentless anonymous functions, if you want to, but others may not, and you'll have to remain aware of each form. Anyway, all if this is just to say, I saw a post suggesting "fn" and thought, "Well, 'do' is not 'lambda', it's less intimidating, it's shorter, it's been used in other languages, it can be used explicitly and consistently, it's not 'fn', and it's not abbreviated, I think I'll fly that idea out there, what the hey. It's not like anyone's going to rush out and add it to the language..." speculatively-yrs Sean From sdahlbacSPAMSUX at abo.fi Tue Mar 18 09:50:09 2003 From: sdahlbacSPAMSUX at abo.fi (Simon Dahlbacka) Date: Tue, 18 Mar 2003 16:50:09 +0200 Subject: script filename and autorun References: <3e77229a$1@newsflash.abo.fi> <3E77306D.5501D6A6@engcorp.com> Message-ID: <3e773275$1@newsflash.abo.fi> "Peter Hansen" wrote in message news:3E77306D.5501D6A6 at engcorp.com... > Simon Dahlbacka wrote: > > > > I was thinking that I wanted to "autostart" my python program at bootup, I'm > > using windows and planned to use the registry through the win32api > > functions. > > > > 1) how do I get the filename of the current script running? (I want to > > detect location at runtime) > > import sys > currentScript = sys.argv[0] hmm.. why didn't I think of that?, the solution is so obvious when you see it.. :) > > > 2) is it enough with just a key "python > > c:\whateverthepathistomyprogram\prog.py" in ...\Run or do I also need full > > path to python? > > Why not try it? Normally a file association is set up so that "executing" > a .py file will automatically invoke Python, but it's conceivable this > doesn't work for items in "Run". It's really rather easy to try this > though. I'll do.. > The real question, though, is why don't you just drag a shortcut to your > .py file to the Startup folder? That way you are guaranteed that the > usual file associations will work, and it's much easier than munging > around in the registry. I was thinking that I would allow the user to set from within the program if it should be autostarted or not, but then again, it could also be done by creating deleting a shortcut in the Startup folder.. I'll have a look.. /Simon From tim_one at email.msn.com Fri Mar 14 01:00:12 2003 From: tim_one at email.msn.com (Tim Peters) Date: Fri, 14 Mar 2003 01:00:12 -0500 Subject: P.E.P. 3.0.8 ??? Message-ID: [Roman Suzi] > (I mangled the subject as I guess people put it into their filters ;-) It worked. > So, what is the progress of the subject? Limbo. > I seem to miss voting altogether. And I understood that proposal failed > public approval. That depends on which subset of votes you look at, or how creative you are in combining them. Some people have invented entirely new tallying schemes, just to prove they're unbiased by rigging the outcome to one they despise. > Has Guido already decided this way or that? Nobody knows yet: he hasn't broken silence. For monumental decisions like this, he likes to wander in the Amsterdam desert, fasting for 40 days first. That was admittedly before he got married, though. Heck, for all I know, he's forgotten he asked for a vote. That would teach the community a valuable lesson . From blakeg at metalink.net Wed Mar 12 21:50:39 2003 From: blakeg at metalink.net (Blake Garretson) Date: Wed, 12 Mar 2003 21:50:39 -0500 Subject: GCD in standard library? References: <3E6FE2A7.DCDE0C96@alcyone.com> Message-ID: "Erik Max Francis" wrote... > > def gcd(x,y): > > if x % y == 0: return y > > else: return gcd(y,x%y) > > I would hope you'd use the iterative form. Function calls are > expensive, and can't recurse to arbitrary depths. Right. Maybe I'm doing something wrong, but the recursive version appears faster. Here's my little test: ### gcd.py ### def gcd_iter(a, b): while a != 0: a, b = b%a, a return b def gcd_rec(a,b): r = a%b if r == 0: return b else: return gcd_rec(b,r) import profile x, y = 4502, 950 profile.run('print gcd_iter(x, y)') profile.run('print gcd_rec(x, y)') ### END FILE ### This results in: ### 2 3 function calls in 0.048 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.003 0.003 0.003 0.003 :1(?) 1 0.000 0.000 0.000 0.000 gcd.py:1(gcd_iter) 1 0.045 0.045 0.048 0.048 profile:0(print gcd_iter(x, y)) 0 0.000 0.000 profile:0(profiler) 2 10 function calls (3 primitive calls) in 0.003 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.002 0.002 0.002 0.002 :1(?) 8/1 0.000 0.000 0.000 0.000 gcd.py:6(gcd_rec) 1 0.001 0.001 0.003 0.003 profile:0(print gcd_rec(x, y)) 0 0.000 0.000 profile:0(profiler) ### So I'm thinking the recursive version is faster? Is that right? Blake G. From tssmith at velocio.com Sat Mar 22 19:48:40 2003 From: tssmith at velocio.com (Tim Smith) Date: Sat, 22 Mar 2003 16:48:40 -0800 Subject: Newbie question about reference References: Message-ID: "Terry Reedy" wrote: >You here bind 'list' to the object [1,2,3]. (Note: DON'T use builtin >names as vars unless you have a positive reason for so doing.) OK, I had thought that L = [x,y,z] was binding the list L as an ordered set of references/pointers to the variables x, y, z. Obviously not, as integers are, along with strings etc., immutable types. So >>>x = 1 #and >>>x = 2 would show two different pointers for x, the first one eventually being gc'd. (?) This is not clearly explained in the material I have read so far. It's emphasized that strings are immutable, but not ints, tho' I suppose it should be obvious, especially to one who's thinking in implementation terms (I don't think that way :-). (And oh, I wouldn't use a builtin name normally, but thanks for the warning.) From aleax at aleax.it Mon Mar 31 04:24:09 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 31 Mar 2003 09:24:09 GMT Subject: List of given type References: Message-ID: Zaur Shibzoukhov wrote: > "Terry Reedy" wrote: > > TR> You *might* find either the array module or (3rd party) numerical > TR> Python lib of interest also (if you have not checked them out > TR> already). > > I know about array module and numerical extensions. But I want another > thing. I need standard list of objects with a given type: > list of int, list of float, list of list, list of dict, list of string, > ... - list of any type. > > My lists aren't large and in this case array module and numerical dosn't > speedup computation very much. Then I think your general approach -- trying to turn whatever's being inserted / appended / itemassigned / sliceassigned / etc etc, into the target type, is OK. However, I would refactor out the issue of deciding how to "turn things into the target type" to a separate callable, as it really depends on details, and your 'listofX' type has a big job to ensure it's catching ALL ways to poke items into self (a tad easier with Python 2.3, since you don't need to worry about _setslice__ any more, but, that IS a detail;-)...: class listofX(list): def __init__(self, trasf, parm=()): self.trasf = trasf list.__init__(self.trall(parm)) def trall(self, seq): return [self.trasf(x) for x in seq] def __setitem__(self, index, item): if isinstance(index, (int,long)): list.__setitem__(self,index,self.trasf(item)) else: # slice assignment, perhaps list.__setitem__(self,index,self.trall(item)) def append(self, item): list.append(self, self.trasf(item)) def insert(self, index, item): list.insert(self, index, self.trasf(item)) def extend(self, seq): list.extend(self, self.trall(seq)) I may be forgetting something here, but roughly this seems to be what you need. You may also want to override other methods such as count, index, and __contain__, so that items being checked for being in the list get transformed AS IF they were about to be inserted -- otherwise, with the code as just presented, you'd get some behavior such as: lo = listofX(str) lo.append(23) print lo.count(23) printing 0 even though you just appended that 23 (but what got appended was transformed into a str -- so the == check implicitly done by lo.count isn't succeeding...). For many target types you may just pass the target type itself as the 'trasf' parameter, since calling the type with one of its instances as the argument works acceptably, and calling it with an argument of some other type does transformation. But you might not want e.g. listofX(list), which appends &c COPIES of list objects you're appending, so for such issues you'll want to code and pass in different 'trasf' arguments -- which is why I think 'trasf' should DEFINITELY be "out of the way", coded separately and passed in to listofX as an argument, NOT "rolled into" the listofX code as you had it originally. But that's really the only change I would suggest. Alex From mwm at mired.org Thu Mar 20 09:28:53 2003 From: mwm at mired.org (Mike Meyer) Date: Thu, 20 Mar 2003 14:28:53 GMT Subject: Incomparable abominations (was: python-dev Summary) References: Message-ID: mertz at gnosis.cx (David Mertz, Ph.D.) writes: > I completely DO NOT BUY Guido's point in the thread. The failure of > .sort() depending on obscure combinations of list contents is, to my > mind, the BIGGEST WART that Python has. I'm hoping this is a sign that what I think of as one of Python's warts - the near-total ordering of objects - is going to be repaired. Given the number of people who think that complex objects ought to compare, maybe I ought to explain that. One of the things Python does that I like is it doesn't try and guess what I mean. I noticed this coming from scripting in Perl, where doing stupid things gives stupid results instead of an error. I feel much safer using Python to manipulate my data than I do using Perl because of this. Right now, when I compare incomparable types, I get a result. Worse yet, I get one that can vary from Python implementation to Python implementation. To get results I can trust, I have to convert one of the two objects to something that is comparable to the object in question. I claim I should get an error when I compare incomparable types, because explicit beats implicit, and the current behavior has no practical value. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From Gareth.McCaughan at pobox.com Wed Mar 5 17:51:27 2003 From: Gareth.McCaughan at pobox.com (Gareth McCaughan) Date: Wed, 5 Mar 2003 22:51:27 +0000 Subject: Vote on PEP 308: Addenda References: Message-ID: Troy Melhase wrote: > I sincerely hope Guido takes the fundamentally flawed nature of this voting > process into account when he makes his decision. All voting processes are fundamentally flawed. That's Arrow's theorem. -- Gareth McCaughan Gareth.McCaughan at pobox.com .sig under construc From just at xs4all.nl Thu Mar 13 16:19:27 2003 From: just at xs4all.nl (Just) Date: Thu, 13 Mar 2003 22:19:27 +0100 Subject: Reading line-by-line on a socket References: Message-ID: In article , sik0fewl wrote: > Hey, > > Is there any way to read line by line on a socket, without having to > recv() a chunk and the keep it in some sort of queue to retrieve later? > > The reason this doesn't work for me is because I would like select() to > still be able to detect that there is data waiting to be read from the > socket. If all else fails I'll just have to do a loop through the > incoming queue after my socket has data to be read. > > In short, I want a readline() for a socket. > > Any suggestions? sock.makefile() Just From martin.vonloewis at hpi.uni-potsdam.de Mon Mar 31 05:00:27 2003 From: martin.vonloewis at hpi.uni-potsdam.de (Martin v. Löwis) Date: Mon, 31 Mar 2003 12:00:27 +0200 Subject: using a private embedded python References: Message-ID: > is there a common technique for embedding python with your application? It depends on your requirements, and how much modifications to the standard installation you allow/can accomodate. > i > need to guarantee product stability and since python is completely open, > anyone can build their own version or install multiple versions, or beta's, > etc.. so, i'm forced to have our own verson of python installed in our own > private location. if the end user wants to install python2.3a3 so be it, > our product must run on 2.2.2 which our QA department as validated with our > product. than means on windows, it'll probably end up being in program > files/common files//python and moving the python22.dll from the > windows directory there too. Notice that people could still interfere with such an installation, e.g. by setting PYTHONPATH, or adding registry keys. > on unix maybe it's playing around with > symlinks? On Unix, you will typically link with libpythonxy. I recommend that you use the static library (libpythonxy.a), not any shared library your installation may have. That way, your application becomes stand-alone with respect to core object files. If you want to become stand-alone with respect to the Python library as well, I recommend to use freeze. The same approach (freeze) works on Windows: You can arrange not to have to rely on pythonxy.dll, but instead link all of Python statically. > my question is how can i guarantee that from PyInitialize() to > PyFinalize() will use this private version? If you link statically, then you have an absolute guarantee. If you link dynamically, you have to make sure you understand the search mechanism of the operating system; the user can then defeat this mechanism by removing the shared library; on Unix, setting LD_LIBRARY_PATH may also have effects. > do i have to build a version of > python22.dll that doesn't (on windows) look in the registry but is hard > coded to another location? or should i modify sys.path to include only our > python build area? If you are concerned about these things, I really recommend to use freeze. Python will always look in the frozen modules first, so if you arrange to freeze any module you will ever use, sys.path and the registry become irrelevant. HTH, Martin From aleax at aleax.it Sat Mar 22 03:31:07 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 22 Mar 2003 08:31:07 GMT Subject: Is Python the Esperanto of programming languages? References: <7i65qe953z.fsf@enark.csis.hku.hk> <3E7A9C89.D5D01F85@engcorp.com> <7i4r5w7i7u.fsf@enark.csis.hku.hk> <3E7B703D.D3EB19E@engcorp.com> <7illz729a5.fsf@enark.csis.hku.hk> Message-ID: Isaac To wrote: ... > The contextual information is still there in inflected languages, so the > first part of above makes inflection an unnecessary cruft (and of course, > even more for agreement). What makes it "something I hate" is the latter > part. It forces the speaker to consciously reveal irrelevant information. Interesting parallel wrt Python vs languages with mandatory declarations; the latter also "force the programmer to reveal [declare]" information they may deem irrelevant to the working of their program. > (You'd say, but the listener might think that it's relevant! But that's > not the point: if the speaker can expect that, he will speak in a way that > the listener is given the information.) The parallel is weaker here -- it might be better with languages with optional declarations such as Dylan, where the the programmer "reveals" just the information he or she wants to "reveal" (declare). As to the usefulness or otherwise of inflections and concordances, hmmm, well... Even though the languages I speak best are both inflected and do require some concordance, there are enough differences that the kind of irrelevant information required to be revealed is sometimes very different. E.g., in Italian, I can say "ha preso la sua borsa" without reflecting at all on whether the subject is male or female, and on whether the owner of the bag is -- in English I can't, I have to know whether to say "he took his bag", "he took her bag". "she took his bag", or "she took her bag" (in Italian, I might specify if necessary to make myself clear -- "lei ha preso la borsa di lui" to mean "she took his bag" -- but laziness, hurry and the lack of grammatical requirement may often push me towards using the simplest, gender-ambiguous equivalent anyway). And viceversa, in English I can exclaim "Beatiful!" without having to reflect on whether whatever I find beautiful is grammatically masculine or feminine -- in Italian I can't, I'd have to say "Bella!" of a dawn ("alba", grammatically feminine) but "Bello!" of a sunset ("tramonto", grammatically masculine). Overall I think these requirements and concordances serve mostly as a trap for non-native speakers and thus would heartily agree with Isaac -- were we designing an artificial auxiliary language for human speech -- to drop grammatical gender (using some explicit particle or word to distinguish male from female in the rare occasions where that's useful). I'm not quite as sure about verb tenses and quantities, because my experience in different usages for them between languages is more limited. But where it comes (e.g. "furniture" is arbitrarily deemed to be singular -- in Italian we have "mobili", plural, "furniture", and "mobile", singular, "one piece of furniture"; or "people", a singular, often used as if it was the plural of "person"; etc), it does often feel artificial and arbitrary more than it feels useful in communication. So, on limited experience and general principles, making inflections optional would feel reasonable to me. Alex From dave at pythonapocrypha.com Thu Mar 6 11:51:48 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 6 Mar 2003 08:51:48 -0800 (PST) Subject: Thread processing In-Reply-To: References: <8yvty3v0.fsf@morpheus.demon.co.uk> Message-ID: On Wed, 5 Mar 2003, Paul Moore wrote: > In practice, I'd nearly always want to write a log message saying the > processing had finished, so I'd wait for all the threads to complete. > For that, simply joining in any order is fine (but I need to keep a > list of the threads so I can join them all, and hence actually know > when I finished). FWIW I very rarely use thread.join because of the problems you've already discovered. Besides, IMO it emphasizes the thread as the important thing in your framework rather than the work the thread is doing. > The basic problem is that I can easily *see* my solution in terms of > waiting for "the next thread to finish". But I can't *code* it that > way. So whatever I do is a workaround, and makes it harder for me to > express what I really want, because the infrastructure is getting in > the way. And therein lies the problem, IMO. Again, maybe things would "feel" more right if you focus more on the work being done than on the threads. I mean, do you really care about which thread finishes next or is it the completion of a chunk of work? The rest of the program doesn't really care how the work is getting processed. For example, it may be processed in any of these ways: - a single thread handles all work one chunk at a time in a FIFO manner - a new thread is started for each piece of work - you start a fixed number of threads and each takes a piece of work, does it, gets a new piece of work, etc, until all the work is done - the work is I/O related so it's all handled asynchronously by select/poll If you take the work-centric view, then any of the above implementations can "feel" fine because your focus is on getting the work done. > > You don't need to join the thread if it is just going to terminate on its > > own. > >> > >> threads.remove[thread] > > > > Do you actually need a list of all the threads? Why bother? > > So that I can do the "while threads" above. Otherwise, I have no way > of knowing when I have no threads left, and hence no way of knowing > when to *stop* waiting on the queue. Another approach to use is to use a semaphore as a counter of outstanding work: counter = threading.Semaphore(0) def ThreadFunc(a,b,c): try: # do some work finally: counter.release() WORK_COUNT=10 for i in range(10): threading.Thread(targe=ThreadFunc).start() for i in range(10): counter.acquire() > (OK, a simple counter is probably enough here, but the thread gives me > better generality for if I have a thread subclass with useful extra data > in it). I know it's tempting to come up with a general-purpose framework, but to be honest, there's so little code involved that it might not be worth the effort - once you're familiar with the patterns then it takes about the same amount of effort to write it as to find/import/use a prebuilt framework. For example, the above 10 lines of code is a pattern I use from time to time but it's so tiny that I've never bothered to save it to some library. > Can you explain how you'd structure the above without needing a "while > threads" loop? So that the main thread stops waiting on the queue when > the last worker has finished. If I could see that, I might be closer > to understanding this.] Here's another pattern that's sometimes useful (coding from memory, not tested): WORKER_COUNT = 5 WORKER_QUIT = 'quit!' class GV: pass GV.inQ = Queue.Queue() GV.outQ = Queue.Queue() def StartWorkers(): for i in range(WORKER_COUNT): threading.Thread(target=Worker).start() def StopWorkers(): for i in range(WORKER_COUNT): GV.inQ.put(WORKER_QUIT) def Worker(): while 1: work = GV.inQ.get() if work == WORKER_QUIT: break # do something with work # add result to GV.outQ if needed Using this approach you call StartWorkers to create a fixed-size pool of workers - useful in cases when you have e.g. 1000s of jobs to do so one-thread-per-job isn't feasible. Anyway, each worker waits for work to do, finishes it as quickly as possible, and optionally adds results to some output queue. If your work was to fetch 1000 objects off the web then your main thread might look something like this: StartWorkers() # Hand off all the work count = 0 f = open('urls.list') for line in f.xreadlines(): count += 1 GV.inQ.put(line) # Process the results for i in xrange(count): obj = GV.outQ.get() # do something with it StopWorkers() The above approach seems very natural to me because it is work-centric - you care about doing work and for all you know the worker pool could be a single thread, a fixed number of threads, no threads, whatever. Notice that the main thread doesn't ever explicitly wait for the threads to finish - they _do_ finish, of course, but the how and when isn't something the rest of the program really cares about. > > Is it really _that_ big of a deal to have the worker thread put done work > > on a queue? > > For cases where all the worker is saying is "I've finished", I believe > so. For a start, I have to pass that queue to the worker in the first > place, which constrains the form of my worker. As someone else pointed out - your worker func could simply return a value (making it easy to test in isolation) and you could just wrap the worker function in some other function that takes the result and adds it to a work queue. This also generalizes well to the cases where there are no results to report - the worker function implicitly returns None anyway. -Dave From maney at pobox.com Sun Mar 9 21:28:17 2003 From: maney at pobox.com (Martin Maney) Date: Mon, 10 Mar 2003 02:28:17 +0000 (UTC) Subject: A suggestion for a possible Python module References: Message-ID: In article you wrote: > Lance LaDamage: >> > I have noticed that there is one thing that everyone wishes to do >> > ... in Python reverse a string. > > Mark VandeWettering: >> Honestly, what commonly programmed task requires string reversal? I can't >> ever remember doing it even once during 20+ years of programming. > > The ones I could think of are: > - insert commas in a number, as in "10000" -> "10,000" > > def commafy(s): > s = s.reverse() > terms = [] > for i in range(0, len(s), 3): > terms.append(s[i:i+3]) > return ",".join(terms).reverse() Hmmm... I think we can walk backwards almost as easily as forwards: def commaficate(s): t = [] for i in range(0, len(s), 3): t.insert(0,s[-3-i:len(s)-i]) return ','.join(t) Nope, no need for s.reverse() at all, at all here. :-) >>> s = '1234567890' >>> for i in range(len(s)): ... print '%s -> %s' % (s[:i], commaficate(s[:i])) ... -> 1 -> 1 12 -> 12 123 -> 123 1234 -> 1,234 12345 -> 12,345 123456 -> 123,456 1234567 -> 1,234,567 12345678 -> 12,345,678 123456789 -> 123,456,789 I suppose it ought to raise a range error exception if there's a period in the argument, but that's not any different than the reverse() version... > - for sequence analysis, compute the "reverse complement" of a sequence. > That's the sequence used for the other side of the DNA helix from the > current sequence, eg, so that "aatccgatcg" -> "cgatcggatt" Whyever do they want it backwards? That's much more interesting, IMO, than the trivial computation involved! From sludin at ludin.org Thu Mar 13 20:30:16 2003 From: sludin at ludin.org (Stephen Ludin) Date: 13 Mar 2003 17:30:16 -0800 Subject: Thread safety of the python API Message-ID: <412a1fa3.0303131730.2ebe6238@posting.google.com> I am developing an application that I may want to make scriptable with python. If I do so I'd like to use the convenience of the Python API in the rest of my application for containers and user defined method dispatch. I am concerned though about using the API in a multit-hreaded program. For example, a browse of intobject.c shows: static PyIntObject *free_list = NULL; ... PyObject * PyInt_FromLong(long ival) { ... if (free_list == NULL) { if ((free_list = fill_free_list()) == NULL) return NULL; } /* PyObject_New is inlined */ v = free_list; free_list = (PyIntObject *)v->ob_type; ... } The use of the linked list 'free_list' could result in a race condition in MT code. There are a number of similar cases in the objects defined in the Objects directory. I have not found much information on this, so I am wondering if I am missing something. If all of my use was limited to embedded interpreters, the global interpreter lock would take care of synchronization, but I want to use it in the rest of my program as well. Is it a bad idea to use the Python API in multi-threaded code? Is there an easy way around the seemingly unsafe code? I am using the 2.0 version of python running on a RedHat 6.2 box with gcc 2.91. Thanks, Stephen From peter at engcorp.com Mon Mar 31 12:40:56 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 31 Mar 2003 12:40:56 -0500 Subject: Check for programs that are in full screen mode References: Message-ID: <3E887DA8.FE725A4D@engcorp.com> Robin Munn wrote: > > The one > time I tried serious Windows programming I think I swore more often in a > single month (usually at the poor quality of the documentation) than I > normally do in an entire year. Usually along the lines of "What the > were they thinking?" I won't do that (attempt any serious > programming in Windows) ever again if I have any choice in the matter. :-( Many years ago, I switched from the Amiga to OS/2, for various decent reasons. I struggled mightily with the difficulties involved in doing OS/2 development, but unfortunately never made it off the ground and my results were limited and unsatisfactory. More importantly, OS/2 basically tanked and I was stuck with switching to Windows as the only viable option (again, for various decent reasons). After some period of considering the looming problem, I determined that I was not remotely interested in attempting to learn the hideous API, struggling with the abominable tools, and becoming frustrated with the pitiful level of reliability I could expect achieve on that platform. I swore never to program anything in the Windows API, and I'm very happy to say I survived the era where that felt almost necessary (largely by working on embedded systems, or real-time DOS-based systems which were much simpler and manageable). Python, however, has made me a Windows programmer. No wait, actually, that label offends me... I mean it has let me program a wide variety of things, *including* nice GUI programs, on Windows, but without ever (okay, rarely) having to feel like I'm actually dealing with the crap dished out of Redmond. Even better, it has acted as a nice stepping stone from the world of M**soft to the world of Linux, without me feeling yet again like I'm abandoning a huge investment in learning. Windows bad. Python on Windows (or on anything else :-) good. -and-that's-all-I-have-to-say-about-that-ly y'rs, Peter From REMOVEjimdon at sympatico.caREMOVE Thu Mar 20 08:22:02 2003 From: REMOVEjimdon at sympatico.caREMOVE (Jim) Date: Thu, 20 Mar 2003 13:22:02 GMT Subject: Boost help please Message-ID: <_fjea.3599$j5.16816@news> Hi, I am switching some C++ code over to use boost ... but i am having some problems just getting things to compile ... the compile error is not very helpful so i'll leave it out for now ... the problem i think is more related to the fact i need return a structure from a boost function .... can anyone help ;-) The original un-boosted function is here: ----------------------------------------- static PyObject *cosim_get_board(PyObject *self, PyObject *args) { return Py_BuildValue("(ddddddddllll)", theboard.x60_clk/1e6, theboard.pwm_clk/1e6, theboard.utx_clk/1e6, theboard.urx_clk/1e6, theboard.local_ref_clk/1e6, theboard.pcr_ref_clk/1e6, theboard.mod_ref_clk/1e6, theboard.demod_ref_clk/1e6, static_cast(theboard.mod_utopia), static_cast(theboard.demod_utopia), static_cast(theboard.dac_type), static_cast(theboard.adc_type) ); } The my attempt at a boosted function is here: --------------------------------------------- struct boardInfoStruct { double d1; double d2; double d3; double d4; double d5; double d6; double d7; double d8; long l1; long l2; long l3; long l4; }; boardInfoStruct BOOSTED_cosim_get_board() { boardInfoStruct * ret = new boardInfoStruct(); ret.d1 = theboard.x60_clk/1e6; ret.d2 = theboard.pwm_clk/1e6; ret.d3 = theboard.utx_clk/1e6; ret.d4 = theboard.urx_clk/1e6; ret.d5 = theboard.local_ref_clk/1e6; ret.d6 = theboard.pcr_ref_clk/1e6; ret.d7 = theboard.mod_ref_clk/1e6; ret.d8 = theboard.demod_ref_clk/1e6; ret.l1 = theboard.mod_utopia; ret.l2 = theboard.demod_utopia; ret.l3 = theboard.dac_type; ret.l4 = theboard.adc_type; return ret; } From zhitenev at cs.vsu.ru Sat Mar 29 04:50:36 2003 From: zhitenev at cs.vsu.ru (Lexy Zhitenev) Date: Sat, 29 Mar 2003 12:50:36 +0300 Subject: Printing in wxPython References: Message-ID: "Anand B Pillai" wrote in message: news:bd993a2f.0303280717.3f7a19d at posting.google.com... > Hi Hi, also > Moreover the python interpreter gives a NameError for the methods > wxPrintout_GetDC() and wxPrintout_OnBeginDocument(). What I am trying Certainly, wxPrintout_GetDC() doesn't exist. You can get a dc by issuing self.GetDC(), or wxPrintout.GetDC(self). Neither wxPrintout_OnBeginDocument() > wxPython note: If this method is overridden in a Python class then > the base class version can be called by using the > methodbase_OnBeginDocument(startPage, endPage). A bit mistaken: wxPython note: If this method is overridden in a Python class then the base class version can be called by using the method base_OnBeginDocument(startPage, endPage). Note the ' ' between method and base. You have to call method which name is 'base_OnBeginDocument(startPage, endPage)'. Don't be confused. > The printing example given is also very confusing. It is not very clear > how the device context of the current window is passed to the printer. > It would be helpful if anyone who has got it right could enlighten. :-) You don't need to pass a device context to your document dc. You have to _draw_ on this dc. You issue BeginDoc, draw on a printer DC, issue EndDoc, and after that printer prints what you have drawn on this DC between BeginDoc and EndDoc. In your particular example, you have to copy the information from your panel's DC to Printer DC. See DC method Blit. I can give you only a rough example: def OnPrintPage(self, pgno): dc = self.GetDC() pandc = self.panel1.GetDC() sz = pandc.GetSizeTuple() dc.Blit(0,0, sz[0], sz[1], 0, 0, pandc) This should print the content of your panel without zooming (if there are no errors). Remember that screen resolution and printer resolution are very different (72dpi and 300 dpi, e.g.). You may have to zoom your drawings. See also wxDC.SetUserScale and wxMemoryDC. > Thanks for your help, I am glad to help you. > Anand Pillai Regards, Lexy. From pinard at iro.umontreal.ca Mon Mar 24 08:14:49 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois_Pinard?=) Date: 24 Mar 2003 08:14:49 -0500 Subject: psyco in the standard distribution In-Reply-To: <37xfa.360$Gd3.240@news02.roc.ny.frontiernet.net> References: <2grfa.42301$UV6.3277036@news1.telusplanet.net> <37xfa.360$Gd3.240@news02.roc.ny.frontiernet.net> Message-ID: [RPM1] > Of course, the standard Pythonic answer to this will be, "Well you should > be writing an extension module in C." But the only reason I was using > Python in the first place was because I really like Python and didn't want > to use C. We are having much success with Pyrex as a way to recover about all of the C speed, once analysed the bottlenecks, without actually writing any new C. Well, to be honest, Pyrex invites you to think in C (yet also in Python) while using Python syntax, a rather elegant compromise in my opinion. So, for our team, the argument that Python is slow does not hold anymore. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From aleax at aleax.it Sun Mar 23 06:03:04 2003 From: aleax at aleax.it (Alex Martelli) Date: Sun, 23 Mar 2003 11:03:04 GMT Subject: a regular expression question References: <577e43a1.0303212331.5eaf93e5@posting.google.com> <577e43a1.0303221649.40498141@posting.google.com> Message-ID: Luke wrote: > Thanks, everyone. This was my first real encounter with re's. I need > to find a better tutorial than the api info for the re package. I If you want to become a RE guru, I recommend Friedl's "Mastering Regular Expressions" (O'Reilly) -- not specifically about Python, but for RE's themselves (as opposed to, how you program with them, in detail) there's over 90% overlap between the "Perl" stuff Friedl covers, and Python. In the Nutshell I devote 13 pages to RE's, mentioning some common idioms and typical usage as well as covering the essentials of RE objects, but that's really just the beginning of a long and VERY complicated story. > will heed your advice and examine parsing libraries--didn't know they > existed. Guess you really do get the kitchen sink with Python. :) Oh yes -- I find myself using RE's about 100 times less than I was using them back when I programmed in Perl, thanks on one side to the useful built-in methods of string objects, on the other to higher level library modules and extensions. Personally, the features that do occasionally lead me to use RE's in Python are: convenient case-insensitive matching; word-boundaries and word-characters matching; ability to look for "any one of these N" for large N thanks to the | alternation; in roughly decreasing order of importance to stuff I typically find myself programming. Alex From ivo at NOSPAMamaze.nl Tue Mar 4 11:18:43 2003 From: ivo at NOSPAMamaze.nl (ivo at NOSPAMamaze.nl) Date: 04 Mar 2003 16:18:43 GMT Subject: affordable Zope hosting References: Message-ID: <3e64d1e3$0$49110$e4fe514c@news.xs4all.nl> Bob Horvath wrote: : What are some recommended Zope hosting companies for affordable hosting? : : I maintain 5 domains, most of them small/lame, but one is for an artist : so it has lots of images. Some of the lamer ones I can get away with : using web forwarding, but it would be nice to not have to do that. None : of them get very much traffic. : : I currently have some stuff at freezope.org using their $15 a year option : to associate a domain to a freezope account, but I have a feeling I : will someday outgrow that account, and their add-ons appear to cost more : than hosting other places. I would like a nice selection of Products, : but don't necessarily need to install my own. I'll stick to the popular : ones for now. : Which add-ons cost more than hosting elsewhere? : : The one I stumbled upon that looks pretty reasonably priced is zettai.net. : Are there others like this? : : As all but one of these are lame/personal sites, and the other one : is already hosted at your-site.com for $5 per month, my budget is : pretty low. I'm thinking about $10 per month. My goal is to lean some : Zope by having real work to do on it, and save myself time in upating : all of these sites. : We started a discussion a while ago about 'paid freezope', where people get more for a small fee ($10-$15/month), but we didn't receive much response. : I am happy to see some reaonably priced Zope hosting. Last time I : checked it didn't exist. What is the best of the bunch? Free is still the cheapest :) Cheers Ivo -- Drs. I.R. van der Wijk -=- Brouwersgracht 132 Amaze Internet Services V.O.F. 1013 HA Amsterdam -=- Tel: +31-20-4688336 Linux/Web/Zope/SQL Fax: +31-20-4688337 Network Solutions Web: http://www.amaze.nl/ Consultancy Email: ivo at nospamAmaze.nl -=- From chenpuqing at 163.net Mon Mar 3 21:24:00 2003 From: chenpuqing at 163.net (Chen) Date: Tue, 4 Mar 2003 10:24:00 +0800 Subject: embedding Python in Python References: Message-ID: wrote in message news:mailman.1046741647.23523.python-list at python.org... > Hi, > > Maybe this has been done or asked before, but with Google I couldn't find > anything about it. > > I want to make an interface from TeXmacs to Python (and later IPython). I > translated the C++ example (mycas.cc) into mycas.py and it works fine. But > now I want to embed (..or call it what you like..) a Python interpreter in > mycas.py. > > Thus I would like to be able to write something like: > > py_interpreter_instance = Python_Embedded_Interpreter() > output_string = py_interpreter_instance.execute(command_string) > or > py_stdout, py_stderr = py_interpreter instance.execute(command_string) > > I took a look at IPython's code, which implements something similar. It works > by trapping the stdout and stderr, but I hope that there is a nicer way to > do this... > > I wouldn't mind writing the Python_Embedded_Interpreter class myself. I played > with the idea of simply using eval() but eval("print") doesn't even work as > expected. > > bye, > Kasper > > use exec() instead. Chen From geoff at gerrietts.net Tue Mar 11 11:44:04 2003 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Tue, 11 Mar 2003 08:44:04 -0800 Subject: GUI Toolkits(Python and XUL) In-Reply-To: References: <3E6A40CB.6010301@rsballard.com> Message-ID: <20030311164404.GB12183@isis.gerrietts.net> Quoting Marc Van Riet (marcvanriet at yahoo.com): > If you're going for cross-platform then you might want to consider Qt. > It's GPL'd on Linux, but you have to pay for it under Windows. Last I looked (and I admit it's been a couple months now), if you were developing open source apps for Windows (not the norm, but a growing percentage), a slightly older version of Qt was available for your project under Windows. Granted, if you need today's dope new features, that doesn't help you. And if you don't want to release your software as free, that also doesn't help you. But it's not totally black and white, there's an orange for these apples. --G. -- Geoff Gerrietts http://www.gerrietts.net/ "Now, now my good man, this is no time for making enemies." --Voltaire, on his deathbed, when asked to renounce Satan From grante at visi.com Mon Mar 17 16:09:37 2003 From: grante at visi.com (Grant Edwards) Date: 17 Mar 2003 21:09:37 GMT Subject: Rudeness (was: Re: OT: Aspergers link) References: Message-ID: <3e763991$0$80690$a1866201@newsreader.visi.com> In article , Eric Stechmann wrote: > At 07:08 PM 3/17/03 +0000, Carl Banks wrote: >>Please accept my apologies for suggesting that you're not really >>mentally ill. > > It appears that Mr Banks has little or nothing of worth to contribute. > > Filter by sender, "transfer to trash". Is that MS-Speak for "plonk?" -- Grant Edwards grante Yow! FIRST, I was in a at TRUCK...THEN, I was in visi.com a DINER... From marshall at spamhole.com Thu Mar 13 03:38:23 2003 From: marshall at spamhole.com (marshall) Date: 13 Mar 2003 00:38:23 -0800 Subject: #line directive References: <7d728336.0303110543.4a85b9f7@posting.google.com> <3E6DEE2D.B69B7A68@engcorp.com> <7d728336.0303112358.4b95dd1b@posting.google.com> Message-ID: <4017400e.0303130038.6d37f931@posting.google.com> zunlatex at hotmail.com (zunbeltz) wrote in message news:<7d728336.0303112358.4b95dd1b at posting.google.com>... > Peter Hansen wrote in message news:<3E6DEE2D.B69B7A68 at engcorp.com>... > > zunbeltz wrote: > > > > > > Has Python a #line directive like C preprocesor? > > > > The functionality you are looking for is probably included, > > but in a different way. Can you describe what you want to > > do with that information? Check whether a combination of > > sys._getframe() and the "inspect" or "traceback" modules > > might not do the job. > > > > -Peter > I'm writing a programe in a literate programming way using nuweb. > Nuweb permit to mix code and comments and to arrange the code in > diferent way. I proces the nuweb file and get a .py file. When i run > this .py file sometimes i get error mensages ( a lot of times :-) This > mensages referes to lines in the .py file and no in the nuweb file, > which is my "source file". I want to be able to say the python > interpreter that the line it is reading is not that of the .py and is > line number XXXX in the nuweb file > > thanks > > Zunbeltz You will want to look at this: https://sourceforge.net/projects/leo/ Leo is designed for just this kind of literate programming. Marshall From whiteflame52 at y.a.h.o.o.com Wed Mar 19 05:44:04 2003 From: whiteflame52 at y.a.h.o.o.com (White Flame (aka David Holz)) Date: Wed, 19 Mar 2003 02:44:04 -0800 Subject: Multiple simultaneous Python interpreters Message-ID: Hi, I'm evaluating Python as a scripting language in a project I'm defining. Is there any way to encapsulate the interpreter so that multiple ones can exist in a program? Some would be in their own thread, some would get called from the same one sequentially. However, in the docs I've read, there's always just been one "global" interpreter. Not very OO for an OO language. ;-) From exarkun at intarweb.us Sat Mar 15 13:56:08 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sat, 15 Mar 2003 13:56:08 -0500 Subject: Strange rounding problem In-Reply-To: <3E736D6A.42C9355A@engcorp.com> References: <4378fa6f.0303141540.de857b8@posting.google.com> <3E736D6A.42C9355A@engcorp.com> Message-ID: <20030315185608.GB14733@meson.dyndns.org> On Sat, Mar 15, 2003 at 01:14:02PM -0500, Peter Hansen wrote: > Grant Edwards wrote: > > > > In article , Marc wrote: > > > So I still don't understand that if I enter a number to be an exact value of > > > .00000096, why it can't be stored as 9.60000000e-007? > > > > Becausing you entered it in base 10, and it's stored in base 2. Just > > because it's an exact value in base 10 it doesn't mean it can be represented > > exactly in base 2. > > And it might help to envision a base 3 representation, in which > the value 1/3 *could* be represented exactly, but values like 1/2 > could not! In fact, here's a case where a different base than 10 > can handle values that base 10 cannot handle... I believe the rule is generally expressable - a base can exactly represent fractions which can be expressed as sums of the inverses of powers of factors of the base. This makes bases with many relatively prime factors able to express more fractions exactly. 2 and 3 are poor, because they have only powers of 1/2 and 1/3 respectively. 4 is just as bad, since it has no factors that are relatively prime to any factors of 2 (All bases that are powers of two are equally inexpressive. Bye bye, hexidecimal). 15 is the next best base after 10, and 30 after that. Of course, no base can exactly represent any fraction, and this doesn't even take into consideration bases which are, themselves, fractional ;) Jp (PS - I worked this all out years ago, and only really remember the part about the relatively prime factors - if the general expression of the rule is wrong, I hope it is only because I incorrectly deduced it from the parts I do remember. Corrections welcome :) -- 1.79 x 10^24 furlongs per picofortnight - It's not just a good idea, It's the law! -- up 12 days, 9:59, 9 users, load average: 1.08, 1.02, 0.79 From tim.golden at viacom-outdoor.co.uk Fri Mar 7 12:24:02 2003 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 7 Mar 2003 17:24:02 -0000 Subject: Perl Vs Python Message-ID: (lightly snipped) The disadvantages I think is probably speed, poor documentation. Documentation as such is poor, since we have one or two accredited python books out there when compared to scores of Perl books. People (like you) ,rely more on the internet and newsgroups than standard documentation for fixing their python related problems. Every so often this kind of thing comes up... number of books as an index of popularity (and implicitly success). I find this a false index in one respect at least: the paucity of Python books reflects the excellence of its native documentation set, in my opinion. The combination of the standard bundled documentation, the introspection coupled with the invaluable help () when it arrived and c.l.py all give me pretty much all I need. I do have the MH/AR Win32 book and David Beazley's Library Reference on my shelf and I use Safari to browse the Cookbook (until I buy a copy) but by and large I can get by admirably without shelling out for (often overpriced) doorstops, no matter how well written. I simply don't need them. Granted, I am a professional programmer with a degree in Computer Science (or Computation, as my degree certificate from UMIST calls it), but I think the information's there for any intelligent hacker to read, learn and inwardly digest with ease. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From tdelaney at avaya.com Tue Mar 18 23:21:58 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 19 Mar 2003 15:21:58 +1100 Subject: It feels so good, so quick and not C! Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE2E7DAF@au3010avexu1.global.avaya.com> > From: Steven Taschuk [mailto:staschuk at telusplanet.net] > > > (3) The cuteness of swapping by "x, y = y, x" hides the overhead of > > packing and unpacking a 2-tuple, which may or may not be faster than > > the traditional 3-assignment method. > > I confess a weakness for the cute swapping method; on my machine > it is, in fact, perhaps 5% slower. I don't usually worry about it. Indeed. Readability comes first. Not polluting the namespace is also important. Performance (esp. such a small improvement) is well and truly down the list - until proven that you need it. In any case, IIRC psyco will use virtual-time tuples in the swap case, leading to effectively no performance loss :) Tim Delaney From gmuller at worldonline.nl Sun Mar 2 14:10:23 2003 From: gmuller at worldonline.nl (GerritM) Date: Sun, 2 Mar 2003 20:10:23 +0100 Subject: Vote on PEP 308: Ternary Operator References: <882b0a41.0303020225.3caf0334@posting.google.com> <1046630521.114725@yasure> Message-ID: "Donn Cave" schreef in bericht news:1046630521.114725 at yasure... > Quoth m.faassen at vet.uu.nl (Martijn Faassen): <...snip...> > Here's how mine looks: > > X reject (whatever) > Y reject (whatever) > Z reject (whatever) > Donn Cave > N/A > N/A > N/A > N/A > N/A > <...snip...> > > Donn Cave, donn at drizzle.com Here's mine: --begin of voting message-- A...Q rejected #line 1 A...Q rejected #line 2 A...Q rejected #line 3 Gerrit Muller # line 4 #line 5 #line 6 #line 7 #line 8 #line 9 ## I have never experienced the need for a ternary operator, so I would not make the language any more bloated/heavy by adding it, even if the addition is small. --end of voting message-- -- www.extra.research.philips.com/natlab/sysarch/ From exnihilo at NOmyrealCAPSbox.com Fri Mar 28 17:29:06 2003 From: exnihilo at NOmyrealCAPSbox.com (nihilo) Date: Fri, 28 Mar 2003 22:29:06 GMT Subject: OT: Re: Prime number algo... what's wrong? In-Reply-To: References: <1MudnTyOEK1mauGjXTWcqg@speakeasy.net> <_iJga.16$Xf4.13@twister.nyc.rr.com> <3E836408.72F35838@engcorp.com> <3QWga.32114$i26.828378@news2.tin.it> Message-ID: <3E84CCB9.3080608@NOmyrealCAPSbox.com> Alex Martelli wrote: > Max Khesin wrote: >>(BTW, I got your book last nite - looks very good! Thanks) > > > Oh good! Now I hope some of those readers who LIKE the book would > think of posting reviews e.g. to amazon (while those who don't will > hopefully forget to)...!-) > > > Alex Alex/Mr. Martelli (which did we decide on?), do you know when O' Reilly will make the book available through Safari, their online book service (it isn't available currently in the U.S.)? The paper version is wonderful, but there is no substitute for the ability to do a full-text search (on terms that aren't indexed in the paper version or on code). cheers, nihilo From adrian at softnet.tuc.gr Thu Mar 27 20:26:38 2003 From: adrian at softnet.tuc.gr (add) Date: Fri, 28 Mar 2003 03:26:38 +0200 Subject: Fnorb problem, in fnidl Message-ID: I am using Redhat 8.0,without python 2.2.1 .I install Fnorb 1.2 normally,with python setup.py install without any errors : ***************************************************** ***************************************************** [root at adrian Fnorb-1.2]# python setup.py install running install running build running build_py creating build creating build/lib creating build/lib/Fnorb copying ./__init__.py -> build/lib/Fnorb creating build/lib/Fnorb/compiler copying ./compiler/CodeGenerator.py -> build/lib/Fnorb/compiler copying ./compiler/IDLCompiler.py -> build/lib/Fnorb/compiler copying ./compiler/SkelGenerator.py -> build/lib/Fnorb/compiler ........ ........ ........ copying build/scripts-2.2/fnifr -> /usr/bin copying build/scripts-2.2/fnior -> /usr/bin copying build/scripts-2.2/fnmkior -> /usr/bin copying build/scripts-2.2/fnoptions -> /usr/bin copying build/scripts-2.2/fnping -> /usr/bin changing mode of /usr/bin/fnidl to 755 changing mode of /usr/bin/fnaming to 755 changing mode of /usr/bin/fnendian to 755 changing mode of /usr/bin/fnfeed to 755 changing mode of /usr/bin/fngen to 755 changing mode of /usr/bin/fnifr to 755 changing mode of /usr/bin/fnior to 755 changing mode of /usr/bin/fnmkior to 755 changing mode of /usr/bin/fnoptions to 755 changing mode of /usr/bin/fnping to 755 root at adrian Fnorb-1.2]# ***************************************************** ***************************************************** But when i run official Helloworld.idl(in Fnorb1.2/examples/helloworld/ directory) with $fnidl HelloWorld.idl then i have the next response from system --> ***************************************************** ***************************************************** [root at adrian Fnorb-1.2]# cd examples/hello-world/ [root at adrian hello-world]# fnidl HelloWorld.idl Traceback (most recent call last): File "/usr/lib/python2.2/site-packages/Fnorb/parser/IDLParser.py", line 1617, in line_directive components = string.split(yytext) File "/usr/lib/python2.2/string.py", line 117, in split return s.split(sep, maxsplit) File "/usr/lib/python2.2/site-packages/Fnorb/parser/IDLParser.py", line 1617, in line_directive components = string.split(yytext) File "/usr/lib/python2.2/string.py", line 117, in split return s.split(sep, maxsplit) File "/usr/lib/python2.2/site-packages/Fnorb/parser/IDLParser.py", line 1635, in line_directive file = eval(components[2]) File "", line 1 " Message-ID: David Abrahams wrote: > "Delaney, Timothy C (Timothy)" writes: > >> Because most of the time we want to work with fully-constructed >> objects. You can't use overridden methods in a constructor - only >> from an initialiser. > > Even if that were true, it's seldom needed (only comes up rarely in > C++ where you can't do that) and often incorrect in any case because > the derived class isn't constructed yet. I think you're dismissing the issue a tad too glibly. In C++, I often found myself needing the "two-phase initialization" pattern: a costructor that did the VERY MINIMUM needed to ensure some very fundamental invariants on the object -- then, a framework would ensure that an ordinary virtual method "initialize" got called to give the object a chance to do substantial initialization work before the object got totally hooked up to the framework and started being used in earnest. The key issue was often that, for a constructor, you could never be sure if the object WAS fully constructed (or if you were in a base class) -- no such problems with 'initialize', where you could rest serene that you WERE executing in the "leaf class", with a fully constructed object, period. For example say that the purpose of my class is modeling a window object in some underlying windowing system. The actual window object must be costructed only once, and it must be constructed with detailed parameters as determined/overridden by the leaf class -- so no constructor of a class that might possibly be used as a BASE class dare invoke the underlying window system's "create window" operation, because the ctor of more-derived classes haven't been run yet so it's uncertain which parameters should in fact be used for that operation. Whence, the need for two-phase init -- the underlying window is constructed in the 'initialize' (second phase) so the leaf class has full power to control window creation parameters. Classes modeling connections to external entities of many kinds often have similar issues -- i.e. from this POV there is no necessary difference between "creating the underlying window object" and "opening the connection to the database", say -- in both cases there are creation/opening parameters and the potential need to override them, etc, etc. I can find many more use cases of "two-phase init", but this by itself should already suffice to explain that it's anything but "seldom needed"... in C++. ctor's just labor under too many constraints to make them fully satisfactory for all cases of initialization needs. How this translates to Python -- I'm not sure. The __new__ constructor, at first blush, would seem to be just as flexible as the __init__ initializer. However, some issues are apparent. It's easy for an __init__ to delegate to that of a superclass; it's NOT easy to see how similar delegation is supposed to take place for __new__ -- just as an example. It's certainly possible to arrange for the latter, mind you: __new__ does have a cls parameter so it may costruct objects of different classes from the one I'm coding it in -- so if everything is coded with extreme care perhaps there are no real obstacle cases. But consider MULTIPLE inheritance -- how would you arrange for THAT...? I.e.: class Ba1(object): def __init__(self): self.a1 = 23 super(Ba1, self).__init__() class Ba2(object): def __init__(self): self.a2 = 45 super(Ba2, self).__init__() class Der(Ba1, Ba2): def __init__(self): super(Der, self).__init__() self.b = 67 Using __new__ instead of __init__, how does class Der, derived from two independently coded bases, ensure all initialization done by the bases (here symbolically represented by mere attribute setting) is properly performed on the new object of class Der being created, before finishing it up as it likes (here with just yet another attribute setting)? Alex From skip at pobox.com Tue Mar 4 20:35:26 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 4 Mar 2003 19:35:26 -0600 Subject: os.execv In-Reply-To: References: Message-ID: <15973.21598.175804.498660@montanaro.dyndns.org> >>> import os >>> os.execv("/usr/bin/find", ("find", "/ -name test")) find: / -name test: No such file or directory Maybe os.execv("/usr/bin/find", "find", "/", "-name", "test") is what you're after. Skip From okumee at compuserve.de Thu Mar 20 11:17:51 2003 From: okumee at compuserve.de (mnietz) Date: 20 Mar 2003 08:17:51 -0800 Subject: calling a program without waiting for it to finish References: <6b9f8eda.0303170520.534f53f4@posting.google.com> <3E75D5E4.7E44DF6C@engcorp.com> Message-ID: <6b9f8eda.0303200817.2c957428@posting.google.com> Peter Hansen wrote in message news:<3E75D5E4.7E44DF6C at engcorp.com>... > mnietz wrote: > > > > Hey Guys, > > > > I looking for a way to execute a command-line programm from Pyhton > > without having to wait for it to finish. > > AFAIK i can't use os.popen() or os.system() because these methods wait > > for a return-value. Or can I use the unix command exec in way like > > start in windows os.system("start ping -t www.google.com")? > > That does exactly what i need. > > Under Linux, appending an ampersand to the end of the command should > do roughly what you want, shouldn't it? > > os.system("ping -blah -blah www.google.com &") > > (Of course, pinging something without checking the return value > sounds pretty much useless to me, but maybe you were just giving > a contrived example.) > > -Peter Adding an ampersand seems to work fine. Can you tell me what exactly it does? Thanks, mnietz From kristofer at hotpop.com Fri Mar 14 00:37:18 2003 From: kristofer at hotpop.com (Kristofer Wouk) Date: Fri, 14 Mar 2003 05:37:18 GMT Subject: newbie Pygame question Message-ID: I've been looking all over and can't figure out a way to do this, I know it's something simple. How can a make a sprite(a bullet, to be exact) travel from point A(the player sprite's position) to point B(the mouse position)? Any help would be appreciated. Thanks. From ruediger.maehl at web.de Thu Mar 13 04:23:14 2003 From: ruediger.maehl at web.de (Rüdiger Mähl) Date: 13 Mar 2003 09:23:14 GMT Subject: pyslang for Python 2.2? References: Message-ID: "Terry Reedy" wrote: > Did you try the links returned by Google "Python pyslang" ? Are they > all 1.5? I downloaded two from different locations, both depended on 1.5. Ruediger From mwh at python.net Thu Mar 6 08:23:31 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 6 Mar 2003 13:23:31 GMT Subject: OT: polyamory (was Re: [OT] Re: Python training time) References: <9j4c6v0gbooth50533vu0l0tan7cluib7q@4ax.com> Message-ID: <7h34r6giqdl.fsf@pc150.maths.bris.ac.uk> Alex Martelli writes: > Not sure if you've already counted me, but I should point out that > MANY advanced Pythonistas are poly -- we're not averse to coding in > (e.g.) C, C++, pyrex, Fortran, or other programming languages, as > and when the job requires it... It's bizarre that at one stage I could claim to know to some degree C, C++, Eiffel, Haskell, Python, scheme, Common Lisp and some others that I'm probably forgetting. Nowadays, I only often program in C and Python and 90+% of the C is for the Python core. I do try to keep my CL neurons working, but the others have faded quite a lot. Time to learn a new language, I guess. Cheers, M. -- Sufficiently advanced political correctness is indistinguishable from irony. -- Erik Naggum From staschuk at telusplanet.net Fri Mar 21 00:42:02 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 20 Mar 2003 22:42:02 -0700 Subject: Working with binary data, S-records (long) In-Reply-To: ; from hjwidmaier@web.de on Thu, Mar 20, 2003 at 07:58:30PM +0100 References: Message-ID: <20030320224202.A2778@tibia.amotlpaa.bogus> Quoth Hans-Joachim Widmaier: > [...] Thus I wrote a pure Python > reader, which looks like (this is the whole class so far): It would be nice to see a small sample of the input as well. > def __init__(self, init=0xff, checkcs=True): [...] > self.check = checkcs Bug! You test self.checkcs later, not self.check. > def readrecord(self, line): [...] > elif type in ('S3', 'S7'): > adr = (long(data[0]) << 24) + (data[2] << 16) \ > + (data[3] << 8) + data[4] Bug? data[0] and not data[1]? > On my development machine (1.7 GHz) it's reasonably fast with a file worth > 100 KB. But I'm afraid it'll suck on our production machines, which run at > 166 MHz (give or take some). [...] On my 233 MHz machine your code can process about 2500 records a second (with some made-up records which might not be realistic). Would that be acceptable performance? > Anyway, does anyone see a way to speed this up? I'm not going to inline > readrecord(), as I don't care about 10 %. I'm asking if you see a real > flaw in my algorithm. I see nothing obviously wrong. -- Steven Taschuk "The world will end if you get this wrong." staschuk at telusplanet.net -- "Typesetting Mathematics -- User's Guide", Brian Kernighan and Lorrinda Cherry From chris.lyon at spritenote.co.uk Sun Mar 9 13:03:32 2003 From: chris.lyon at spritenote.co.uk (Chris Lyon) Date: 9 Mar 2003 10:03:32 -0800 Subject: Really, Amazingly Silly Question References: <%Qhaa.505$LR7.340479160@newssvr30.news.prodigy.com> Message-ID: Tim Roberts wrote in message news:... > "Nilesta" wrote: > > > >Second, the question: Just how exactly do you compile python? I'm talking > >write the program, translate it into assembly, smack an .exe on the end of > >the name and give it to someone who's never heard of python and allow them > >to run it on their machine by the incredibly complex process of double > >clicking. > > The others have given you suggestions about how to create a single .exe > from your Python programs, but none of them have attempted to correct your > fundamental misunderstanding: Python, at this time, is not a compiled > language. It does not pass through assembler on its way to being executed. > The suggestions you got, like py2exe, just bundle up the interpreter exe, > your script, and any of the standard library scripts you use. Then, on the > client system, it expands those into a temporary directory and starts > interpreting the code. > I think this touches on a very interesting aspect of a particular camp of programmers view of python. If you arrive from the 'self taught/ learn by infection' school of computing which involves NO formal computer training, then you feel learning the language is all there is to it. You glow at your comprehension of objects, you nod sagely contemplating the joy of a good pickle... But the actual culture and procedure around the language still appear alien. Installion seems to fall squarely in this camp. This seems more a cultural aspect. For instance trying to build a directory structure of an installed programme seems to not be a concept that installers seem to address. Now this could be because as a sensible approach this sort of stuff should be the concern of the programme once it is run on the final host, but I don't know and nowhere seems to tell me. Now in this particular case I am probably trying to condense the computer communities entire thinking on this issue, probably many procedures have been won out over many years of tribulation, but I really don't have the time because that timescale is measured generally in years. Now there is a try it and see approach that teaches a great deal. But included in that is the adoption of bad habits and generation of folk law. I feel this is particularly relevent when you hit linux after working your way from other more popular operating systems. If you've used windows installers, it is difficult to understand the advantages of ./Configure,make, make install especially when they seem to break more often than not at some stage. Now this has turned into a os rant, but it is a dilema I have arrived at because of the world I believe python can reveal. yours, A snakelet who wishes to shed the final skins :-) From max at alcyone.com Thu Mar 27 22:43:48 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 27 Mar 2003 19:43:48 -0800 Subject: Beginner Question References: <1048817552.69484.0@despina.uk.clara.net> Message-ID: <3E83C4F4.303CAD43@alcyone.com> Kevin Reeder wrote: > And that may be what they're getting at as a way to make me analyze > the > process, but isn't the sequence assignment more or less an abbreviated > way > of doing the same thing? I've been thinking that there is some other > way that is eluding me. They're just asking you for another way of doing a swap rather than tuple assignment. Using a temporary variable is certainly one way (and is the typical way of doing it in languages which don't support something like automatic sequence packing/unpacking like Python does). -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ It's soulful music. It doesn't necessarily sound like ... soul ... \__/ Sade Adu Bosskey.net: Quake III Arena / http://www.bosskey.net/q3a/ A personal guide to Quake III Arena. From max at alcyone.com Thu Mar 20 02:49:32 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 19 Mar 2003 23:49:32 -0800 Subject: Is Python the Esperanto of programming languages? References: <200303192233.30383.andy@wild-flower.co.uk> <8b5e42a6.0303192123.2f7b5187@posting.google.com> Message-ID: <3E79728C.AED36CCD@alcyone.com> Alex Martelli wrote: > Levente Sandor wrote: > > > Searched the web for esperanto. Results 1 - 10 of about 1,260,000 > > Something strange here -- I'm seeing only 151 K hits... (?!) I'm getting 1.26 million as well. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ There's this perfect girl / Someone no one can see \__/ Lamya Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From gerhard.haering at opus-gmbh.net Fri Mar 14 07:12:04 2003 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 14 Mar 2003 12:12:04 GMT Subject: Python code! References: Message-ID: Gunnar Kongsrud wrote: > Hi, I have a question about a code in pyhton. If the code below make my articals sort automatacly articals after 01.01.2003 ho do i get it to sort articals from 01.01.2001 to 01.01.2002 by using a simular code? > > python:object.portal_catalog(meta_type='Artikkel', level=object.level(), sort_on='Date', Date=['2003-01-01'],sort_order='reverse', Date_usage='range:min') That's hard to say with knowning neither implementation nor specification of the function. -- Gerhard From martin at v.loewis.de Sun Mar 23 16:17:58 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 23 Mar 2003 22:17:58 +0100 Subject: additional information References: <20030323215111818+0100@news.freenet.de> <20030323220915670+0100@news.freenet.de> Message-ID: Sascha Ernst writes: > i guess there is something wrong with my installation, but what exactly? You have not built pyexpat, which is most likely due to Expat not being installed on your system (see Modules/Setup for details). Regards, Martin From imbosol-1049135446 at aerojockey.com Mon Mar 31 14:35:56 2003 From: imbosol-1049135446 at aerojockey.com (Carl Banks) Date: Mon, 31 Mar 2003 19:35:56 GMT Subject: Breaking out of a while loop with a key press? References: <3e885ad5@mail.hmgcc.gov.uk> Message-ID: Robin Munn wrote: > Richard wrote: >> Hi, >> >> Can anyone suggest a simple way of detecting a key press and existing the >> program? I have a program which at the moment uses a while True: statement. >> However this is not ideal as I have to close down the console window to >> exist the program. Can anyone tell me the proper way of doing this? So that >> a CTRL-C, for example, can quit the program correctly? > > You could use a "try: ... except KeyboardInterrupt: ..." block to detect > Ctrl-C. Although KeyboardInterrupt *should* by default not be caught, so > a Ctrl-C *should* be able to shut down your program. In this case, it shouldn't. He's running his program in a console window created within Python. The idea of a console is (theoretically) to give a program complete control of this input; therefore, console windows often disable KeyboardInterrupt and treat Control-C like any regular keystroke. -- CARL BANKS From exarkun at intarweb.us Thu Mar 6 22:44:30 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 6 Mar 2003 22:44:30 -0500 Subject: Generators and co-routines In-Reply-To: <10F0E58C0018054484E329DC494C4D7F949053@mexper1> References: <10F0E58C0018054484E329DC494C4D7F949053@mexper1> Message-ID: <20030307034430.GC1641@meson.dyndns.org> On Fri, Mar 07, 2003 at 11:32:47AM +0800, Simon Wittber (Maptek) wrote: > Hello python people! > > [snip] > > The .poll() method checks if the user is logged in, if not, calls the > .login() method (which is the co-routine/generator). My problem is the > .login() method is not being called! I put a print statement at the > start of the function, and nothing gets printed. I am entirely unfamilar > with python generators, if someone can enlighten me, please do so! > > ------------ > > class User: > def __init__(self, conn): > self.conn = conn > self.isLoggedIn = False > > def poll(self): > if not self.isLoggedIn: > self.login() > This is your problem. Generators must be iterated over. If you change "self.login()" to "for something in self.login()" you'll see some more action, though this will probably have undesirable effects for the rest of your program ;) An approach that might make sense is to return the generator from the poll() method. Then whatever is invoking the poll() method can collect these generators and iterate them in some lockstep manner. For example: def gameIteration(users, routines = {}): for user in users: if not routines.has_key(user.id): r = user.poll() if r: routines[user.id] = r prune = [] for user, routine in routines.iteritems(): try: routine.next() except StopIteration: prune.append(user) for user in prune: del routines[user] def runGame(): users = [] ... while 1: gameIteration(users) Generators are iterators, so their "next" method causes them to be resumed, and returns whatever value is yielded. When the generator (or any iterator) finishes, it raises StopIteration. You may want to alter the above to examine the return value of .next(), or allow more than one generator at a time per user. Jp -- up 3 days, 19:58, 5 users, load average: 0.02, 0.01, 0.00 From wsonna at attglobal.net Sat Mar 15 00:35:56 2003 From: wsonna at attglobal.net (William Sonna) Date: Fri, 14 Mar 2003 23:35:56 -0600 Subject: No Do while/repeat until looping construct in python? References: Message-ID: On Fri, 14 Mar 2003 18:09:39 -0600, sismex0 wrote: >> > "Questionable design". That's a pretty subjective qualification, >> > because it's "questionable" from your point of view, using your scale >> > of what's important and what's not. >> > >> EVERY design decision in the world is subject to question, therefore >> questionable. That is an OBJECTIVE fact. >> >> > There is no absolutely perfect language, because absolute perfection >> > does not exist. Python is "perfect" in it's own niche, which means >> > it's "relatively perfect". You might disagree, certainly you're >> > entitled to it; but don't go spouting off pseudo-data and pseudo- >> > knowledge, implying that we *have* to agree with you. >> > >> First two sentences of paragraph - I agree. >> >> Third sentence - YOU are the one throwing flames here, not me. >> >> > Calling you a "troll" is flaming you? Read the paragraphs preceding your respnse again. You didn't call me a troll in that paragraph. In fact, the word "troll" DOESN'T EVEN APPEAR in any of the above text. So you are responding to nothing. You really ought to READ THE TEXT and confine your responses to what's ACTUALLY WRITTEN. Not to what you think is implied by what is written. You tend to look less foolish that way. FWIW, I guessed Spanish by your difficulty parsing English double negatives several posts back. Your response to tu MADRE cabron, along with your perception that the insults you were throwing at me were less heinous than those that involve the word "mother", coupled with the mex in sismex0, leads me to believe that you are probably Mexican. In hindsight, I should have used DESMADRE in the dialog, because an strong response THAT one would POSITIVELY identify you as Mexican, since nobody but Mexicans know what it means. My point being that if you now tell me you're actually from Honduras, I look foolish for not confining MY posts to what is ACTUALLY WRITTEN. So how are things in Mexico City these days, anyway? [snip] From anthony_barker at hotmail.com Tue Mar 18 17:05:55 2003 From: anthony_barker at hotmail.com (Anthony_Barker) Date: 18 Mar 2003 14:05:55 -0800 Subject: Python popularity crosspost Message-ID: <899f842.0303181405.1f5cf247@posting.google.com> There is a thread from the ocaml mailing list which may be of interest: http://groups.google.ca/groups?q=g:thl2093231537d&dq=&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=fa.bk3st1d.rmudq5%40ifi.uio.no It is an answer to the question: Ocaml is fast ..etc why isn't it more popular? I believe most of today's mainstream language kick started their popularity with a killer app : C was once the only language you could hack Unix with Java had web applets Perl had regular expressions Visual Basic had that really nice beginner-friendly dialog box editor PHP does server side web page generation. Tcl had Tk We could strive to find (or develop) something ocaml can do that cannot be done with any other mainstream language. Or, alternatively, something that is an order or two faster in ocaml than in any other language. So easy in fact, that the time time saved on a single project offsets the time cost of learning the rudiments ocaml [*]. While writing these lines reminds me of Todd Proebsting's presentation at LL2. http://ll2.ai.mit.edu/talks/proebsting.ppt Among other things, he offered a starter list of domains which are begging for better support at the programming language level. If only we could nail one of them solid... One other unrelated observation on language acceptance: In the the industry, they accept new languages as their IDE become usable. Somehow, a solid IDE has become the sign that the language matured and is now stable enough for industrial usage. Also, by their own account, industrial coders spent so much time in VC++, they are now IDE-dependent. IDE in this context means one-key compilation, hypertext jumps between name usages and definitions, and a tree overview of the components of the project, context sensitive work completion and context sensitive help, etc. Ocaml would gain at having an official IDE project which implement these features. From xxdigitalhellxx at hotmail.com Thu Mar 6 16:32:15 2003 From: xxdigitalhellxx at hotmail.com (sik0fewl) Date: Thu, 06 Mar 2003 15:32:15 -0600 Subject: Socket connection Message-ID: Hi, I'm having some problems with some socket/thread code. What I'm doing is starting another thread to do the actual connect() so that my process doesn't block while connect does socket.getaddrinfo(). What I have works fine if the host is localhost, otherwise it doesn't seem to ever connect. Here's the basis of my code: ----- def threaded_connect(sock, address, port = None): try: sock.connect((address, port)) except: pass x = socket.socket(socket.AF_INET, socket.SOCK_STREAM) x.setblocking(0) thread.start_new_thread(threaded_connect, (x, 'www.hotmail.com', 80)) while 1: # then I do select that waits for x to become writable # (ie, connected) ----- Like I said, the select() works fine when connecting to localhost, but when I try any other address (like www.hotmail.com) the select keeps timing out and x never becomes connected. Any thoughts? Also, if there's a better way to do this, I'd like to know about it, too :) Although, I'd still like to know why this isn't working the way I expect. -- Thanks in advance, Ryan From aleax at aleax.it Sun Mar 30 04:22:09 2003 From: aleax at aleax.it (Alex Martelli) Date: Sun, 30 Mar 2003 09:22:09 GMT Subject: use for jython? References: <3E865F10.C63F93E4@alcyone.com> Message-ID: <5Hyha.41973$i26.1202235@news2.tin.it> Erik Max Francis wrote: > David McNab wrote: > >> Jython seems good for browser applets. >> Wonderful to be able to write those suckers in Python without having >> to touch a single line of J--- > > Well, I can sympathize with your reaction (it's darn neat), but it > doesn't seem fair to call > > from java.applet import Applet > > class HelloWorld(Applet): > def paint(self, g): > g.drawString("Hello from Jython!" 20, 30) > > "not touching a single line of Java," given that this wouldn't make a > lot of sense without already knowing at least some elements of the Java > standard library. Some Java advocates steadfastly refuse to distinguish between the LANGUAGE Java, the LIBRARIES that Java can use, and deployment aspects such as Java _virtual machines_. Personally, I've always found this confusion deplorable. I prefer to use Java, in the right context, to mean *the Java LANGUAGE* -- just as I use other language names. Admittedly the use of X to mean "the X language" AND the rather different concept of "the X language PLUS its standard library" is ambiguous. When one needs to pedantically distinguish, one CAN rephrase the sentence you object to "not coding a single line in the Java language". But that should be the normal interpretation in this context -- calls to some Java _libraries_ are clearly needed (though they might well be hidden, e.g. if anygui ever grows an AWT front-end;-) -- so it's not all that "unfair". > It's Python, but it's really Python-as-Java rather than something > entirely independent of Java. It's "independent of Java" much like classic Python is "independent of C", i.e., no real connection to the _language_ (Java or C) used under the covers to implement Python, but plenty of connections to the _libraries_ accompanying said implementation language (classic Python gradually moves away from such library dependencies, e.g. by now using a Python implementation of strptime rather than relying on that in the underlying C libraries if any, but it's a long and slow process and Jython is still young;-). Today there is no practical way to use Jython productively without SOME background knowledge of Java-oriented libraries relevant to your project, and the docs and examples for such libraries are no doubt going to be "talking Java" so you need a nodding acquaintance with how to *read* Java snippets. But being able to read and understand a programming language is still quite a way from CODING stuff in that language. And, at least in theory (were the market to expand enough to warrant writing such specialized books), there would be no problem writing a book that teaches some relevant subset of Java's standard library in Jython terms, requiring no knowledge of the Java *language*. Today, I still recommend to would-be users of Jython to get some fundamental Java reference (e.g. "Java in a Nutshell") next to a Python one (e.g. "Python in a Nutshell", but of course I'm biased) AND a Jython-specific book too (e.g "Jython Essentials") -- PLUS whatever tutorial or reference materials (books or otherwise) one needs for specific libraries one needs to use. But then, I've always been a keen fan of RTFM'ing; I know some other people who prefer to "dive in, feet first", and that approach suits them -- it's applicable to Jython at least as well as to other cases, a bit more I'd say because Jython's interactive mode can let you explore in a reasonably effective way. Alex From mwm at mired.org Thu Mar 27 10:15:30 2003 From: mwm at mired.org (Mike Meyer) Date: Thu, 27 Mar 2003 15:15:30 GMT Subject: _sre module? References: Message-ID: "Martin v. L?wis" writes: > > Could someoen let me know when _sre was added to the list, and if > > there's some way to avoid that dependency? > > Added to what list? And avoid what dependency? Sorry - from the behavior of plpython, it appears that _sre was added to the list of python modules at some point in the past - and after sre itself was added. And the dependency of re on _sre. Right now, everything in plpython is working except importing re - which fails because it can't import _sre. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From tismer at tismer.com Mon Mar 24 19:17:06 2003 From: tismer at tismer.com (Christian Tismer) Date: Tue, 25 Mar 2003 01:17:06 +0100 Subject: pickling generators In-Reply-To: <20030322231805.GA68261@hishome.net> References: <20030322135642.GA16562@soniq.net> <20030322231805.GA68261@hishome.net> Message-ID: <3E7FA002.6060604@tismer.com> Oren Tirosh wrote: > On Sat, Mar 22, 2003 at 02:56:42PM +0100, Paul Boehm wrote: > >>hi, >> >>we're developing a python based adventure game engine for a >>fangame effort, and we'd like to use generator based lightweight threads, >>to let each of our objects be scripted mostly independently of each other, >>without all of the hassles of strictly event oriented coding. >> >>our problem, however, is that we can't properly do savegames with this design, >>as generator instances are not pickle- and unpickleable. >> >>we're now looking for options, and advice, on the feasability >>of getting support for this into future python versions, either by learning >>how to do it, and implementing it ourselves, or by finding someone willing >>to help us out. > > > Stackless python has picklable execution state somewhere in its roadmap > for exactly this kind of application. I'm afraid it won't be available > soon enough for your purposes. I know that Christian Tismer is looking > for sponsors for his work on Stackless. I think I can do some support for this. With generators in their current shape, it would be even possible without Stackless, although the latter would give you more flexibility. Tasklets are more flexible than generators, but generators might do what you need. If you're interested, let's talk about details. Thanks Oren for your support. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From lyle at users.sourceforge.net Wed Mar 12 18:49:32 2003 From: lyle at users.sourceforge.net (Lyle Johnson) Date: Wed, 12 Mar 2003 17:49:32 -0600 Subject: void pointers with SWIG In-Reply-To: <66f88664.0303121451.53598af1@posting.google.com> References: <66f88664.0303121451.53598af1@posting.google.com> Message-ID: <3E6FC78C.1060904@users.sourceforge.net> Steve Hanawalt wrote: > I've tried various typemaps, but I can't seem to get it to work. I > keep getting an error in Python like: "Expected _p_PVOID" Before the declaration of functions like FT_ListDevices() that use the PVOID type, you need to have a typemap defined for PVOID, e.g. %typemap(in) PVOID { /* code to convert Python input to a PVOID */ } FT_STATUS FT_ListDevices( PVOID pvArg1, PVOID pvArg2, DWORD Flags ); Having said that, it is criminal that the library's author(s) have overloaded the FT_ListDevices() function in such an insane way. I agree with the other reply to your post, which recommended writing a little wrapper library of some kind around this C API and then using SWIG or Boost to wrap that instead. Hope this helps, Lyle From davidccarson at hotmail.com Wed Mar 26 10:37:11 2003 From: davidccarson at hotmail.com (David Carson) Date: 26 Mar 2003 07:37:11 -0800 Subject: critical sections protecting multiple processes (not threads) Message-ID: <12257ec4.0303260737.c42faf3@posting.google.com> All the discussion I've seen regarding critical sections has revolved around multithreaded applications. I have the need to protect a resource that is shared between different Python PROCESSES. I don't think the threading discussion applies, right? Specifically, I want to test for the existence of a file and open if non-existent in an atomic fashion. Obviously, if I cannot do this atomically, it is possible for the file to not exist when the test is done but to exist before the creation is done. I don't really know where to look in the documentation for this. Any help would be appreciated, as always. Cheers, David P.S. I do NOT generally read the e-mail address associated with this posting. For answers sent directly to me, please use dccarson AT yahooooooooo DOT com (with a little less enthusiasm). From tzot at sil-tec.gr Tue Mar 4 18:25:21 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 05 Mar 2003 01:25:21 +0200 Subject: A suggestion for a possible Python module References: Message-ID: <3dda6vs1i2atq88o7jnrqcf2nf4qcepfml@4ax.com> On Wed, 05 Mar 2003 01:21:40 +0200, rumours say that Christos "TZOTZIOY" Georgiou might have written: >tongue in check "tongue in cheek". Perhaps I should cheek my posts before sending them. -- TZOTZIOY, I speak England very best, bofh at sil-tec.gr (I'm a postmaster luring spammers; please spam me! ...and my users won't ever see your messages again...) From edream at tds.net Sun Mar 9 21:28:33 2003 From: edream at tds.net (Edward K. Ream) Date: Mon, 10 Mar 2003 02:28:33 GMT Subject: pep 308: why doing (almost) nothing suffices References: <3E6BF37E.4FEBD4FF@alcyone.com> Message-ID: > > def choose_eval(cond, a, b): # warning: evals all arguments > > > > if cond: return eval(a) > > else: return eval(b) > > > > Heavy duty stuff by my present bathtub standards. So to "delay" the > > evaluation of an argument, just quote it. Wow--just like lithp. > > This was actually brought up during the PEP 308 debate. The problem > with it is that it doesn't do the whole tokenization and compilation > phase at the same time; it holds some off until later. This is a > potential performance problemi if the choose_eval code appears in a loop, > which it likely will find itself at some point. Thanks for pointing this out. However, this does not change the fact that Python already provides more than enough tools for this job. In those (presumably rare) cases where performance matters, one could just use the "if" statement. In all other cases, choose or choose_eval will be more convenient. Indeed, the _only_ knock on the present "if" statement is that it is a bit clumsy. But that is a very minor inconvenience when serious performance issues are at stake. This is merely my opinion, and I won't be distressed if it is ignored, particularly since none of the other options will interfere with choose or choose_eval. OTOH, I think the three options (choose, choose_eval and if) would be quite good enough if they were documented in the usual places. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From mikael at isy.liu.se Thu Mar 13 04:35:20 2003 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 13 Mar 2003 10:35:20 +0100 Subject: GCD in standard library? In-Reply-To: <15983.56570.349810.8509@montanaro.dyndns.org> References: <15983.56570.349810.8509@montanaro.dyndns.org> Message-ID: <20030313103520.3e7f3eaa.mikael@isy.liu.se> On Wed, 12 Mar 2003 19:20:58 -0600 Skip Montanaro wrote about GCD: > Depends on what field you're in. ^^^^^ Make that ring (Euclidean ring, I think). In a field, any non-zero element divides any non-zero element. Nit-picking-math-again-ly y'rs /Mikael ----------------------------------------------------------------------- E-Mail: mikael at isy.liu.se WWW: http://www.dtr.isy.liu.se/dtr/staff/mikael Phone: +46 - (0)13 - 28 1343 Telefax: +46 - (0)13 - 28 1339 /"\ \ / ASCII Ribbon Campaign X Against HTML Mail / \ This message was sent by Sylpheed. ----------------------------------------------------------------------- Link?pings kammark?r: www.kammarkoren.com From staschuk at telusplanet.net Tue Mar 18 03:40:10 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 18 Mar 2003 01:40:10 -0700 Subject: changes to shelf items fail silently? In-Reply-To: <7gptop2ryj.fsf@pikespeak.metacarta.com>; from eichin@metacarta.com on Mon, Mar 17, 2003 at 11:56:20PM -0500 References: <7gy93dmzzu.fsf@pikespeak.metacarta.com> <7gptop2ryj.fsf@pikespeak.metacarta.com> Message-ID: <20030318014010.A16528@tibia.amotlpaa.bogus> Quoth eichin at metacarta.com: > > > They're mutating the returned list (to which you retain no > > references, and which therefore is immediately discarded). > > Ah, so I'm missing the distinction that it's returning a list, and not > being a reference to one. (Knowable only by looking at the code to > shelve, since the syntax hides it, right?) Erk? I've never looked at the code to shelve, so, no, you don't need to look at that code. The code container[key].mutate() evaluates container[key] (which might mean calling the container's __getitem__ method), obtaining thereby an object, and calls the given method of that object. This is the case for dicts or anything subscriptable, including shelves. In the case of dicts, container[key] evaluates to a reference to the very object which is in the dict, so mutating the value of this expression mutates the object in the dict. In the case of shelves, container[key] evaluates to a reference to an object which is the result of unpickling the contents of a record found in the backing dbm database; that object isn't the same thing as the record in the database, so mutating it doesn't alter that record. No knowledge of the internals of shelve is necessary. It's just expression evaluation plus the concept of shelve as a combination of a key-value database on disk (dbm) and a generic object serialization protocol (pickle). Am I skipping over some important assumption without realizing it? > > You want *every* change to the object to cause the shelve to be > > updated immediately? Really? > > I certainly want every change to happen to the in-memory copy, which > was what alerted me to the problem; having a sync() to flush it out to > disk would suffice. [...] The change *is* happening to an in-memory copy when you do container[key].mutate() It's just that the mutated copy is immediately discarded and not written to the shelf. > [...] But yes, in this particular case I do want live > changes. If it were large, using a real database might make sense, > but only *after* benchmarking shelve and finding it slow, which I > don't expect to :-) *chuckle* Good point. (I assume you also don't need multiple users reading and writing simultaneously.) > (Note that I'm coming from perl, and would have done this with a tie'd > hash there.) I don't know Perl, as it happens. What's a tied hash? > > That's pretty hard in general, since the shelve-like thing can't > > know a priori what operations mutate an object and what operations > > don't. (It could make an effort to detect changes after the fact > > Or just pass back wrapped-objects, whose methods are "like" the input > type but commit themselves on __setitem__ calls? In the specific case of shelved lists and dicts, yes, that's a good start. We'd have to trap __setslice__ calls and others as well, but I'll agree that it's doable. Now, what about shelved foobar.wombat objects? Which of their methods should cause commits? [...] -- Steven Taschuk "The world will end if you get this wrong." staschuk at telusplanet.net -- "Typesetting Mathematics -- User's Guide", Brian Kernighan and Lorrinda Cherry From fpm at u.washington.edu Sun Mar 9 20:39:46 2003 From: fpm at u.washington.edu (Frank Miles) Date: 10 Mar 2003 01:39:46 GMT Subject: vim/linux doesn't highlight mismatched parens in scripts References: Message-ID: In article , John J Lee wrote: >On 9 Mar 2003, Frank Miles wrote: >> In article , >> Alex A. Naanou wrote: >> >fpm at u.washington.edu (Frank Miles) wrote in message news:... >[...] >> Thanks, I already have showmatch set; and the use of '%' is pretty cool >> too. Still, nothing like the coloring effect for bash, C, or C++. > >How about Emacs + python-mode, with vi keybindings? I'm sure there's a vi >mode of some kind. Thanks, I'll look into that. -frank -- From manus at python.net Mon Mar 31 18:53:13 2003 From: manus at python.net (Manus Hand) Date: 31 Mar 2003 15:53:13 -0800 Subject: try:else: w/o except: - why not? Message-ID: <1c004553.0303311553.53a9a92b@posting.google.com> I know that if you want to use else: on a try: block, you need to specify one or more except: clauses. I guess my question is why this should need to be. Personally, I have cases where it would be nice to do this: try: # some code that may except else: # but if it didn't except, I want to do this Instead of writing the code that way, I need to write this: try: # some code that may except except: # and if it does, then, okay, just ignore it pass else: # but if it didn't except, I want to do this I know it's a core language decision and therefore up to Guido, but I am curious (Guido?) if there is something I am missing that would make a simple try:else: construction (without requiring any except: blocks) not make sense? Manus From joe at nall.com Fri Mar 28 00:20:53 2003 From: joe at nall.com (Joe Nall) Date: 27 Mar 2003 21:20:53 -0800 Subject: How do you set self.compiler.include_dirs from configure? Message-ID: <9d1ed006.0303272120.4a3bdf66@posting.google.com> I'm trying to configure Python on HP 10.20. Packages are installed in /opt/zlib, /opt/libiconv ... and I would like to get /opt/zlib/include into self.compiler.include_dirs without patching setup.py. Is this possible? Something like --with-libs, but for includes? joe From pmagwene at speakeasy.net Tue Mar 11 09:30:04 2003 From: pmagwene at speakeasy.net (Paul M) Date: Tue, 11 Mar 2003 09:30:04 -0500 Subject: Tkinter displaying 300 records sluggish In-Reply-To: References: Message-ID: Anand B Pillai wrote: > Hi > > Probably this is out of context. But you should strongly > consider using wxPython for these kind of tasks. Speed is not > a virtue of tkinter. I am not familiar with tkinter though I > can tell you that wxPython would be surely faster than tkinter > for most performance intensive apps. > How are you able to make such definitive statements about the speed and appropriateness of tkinter when you're "not familiar with tkinter"? --Paul From peter at engcorp.com Mon Mar 17 23:21:39 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 Mar 2003 23:21:39 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 17) References: <3E75D574.8EF68D97@engcorp.com> <7h31y16jchm.fsf@pc150.maths.bris.ac.uk> <3E7601B2.154DC1B3@engcorp.com> <3E765B44.837774E2@alcyone.com> <3E769921.11B7F840@engcorp.com> <3E769B8C.E1761D2A@alcyone.com> Message-ID: <3E769ED3.B0C858B6@engcorp.com> Erik Max Francis wrote: > > Peter Hansen wrote: > > > But it's irrational, right? So irrationality is now defined as > > normal? > > No. Irrational does not necessarily imply normal. Take for instance > the irrational number (decimal expansion): [snip] Sorry, I missed a smiley. Also probably should have said something closer to "so irrationality can be normal in some cases?"... I was trying, poorly, to make a joke. :-) (I.e. I understand about irrational/normal etc...) Cheers, -Peter From exarkun at intarweb.us Mon Mar 10 01:22:09 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 10 Mar 2003 01:22:09 -0500 Subject: Easy way to store stdout to a variable? In-Reply-To: References: Message-ID: <20030310062209.GA15163@meson.dyndns.org> On Sun, Mar 09, 2003 at 08:41:45PM -0800, mike wrote: > Hi, > > I am a python newbie and am trying to migrate my simple shell-script > tasks to python. When writing shell scripts, I make common use of > unix pipes and filters, e.g. "ls *.txt | grep -v old | wc -l". > > I know I can use "os.system()" to invoke system calls, but I don't > know how to store the stdout of the system call into a python > variable. > > I realize I could do all of my filtering in python, but who wants to > rewrite grep and the hundred other unix tools? > > So what is an easy one-liner way to store stdout of a sytem-call to a > variable? output = os.popen('command').read() BTW import glob, re, fileinput i = 0 match = re.compile('old') for line in fileinput.FileInput(glob.glob('*.txt')): if not re.match(line): i += 1 print i Much of the functionality has already been implemented for you, just need to know where to look ;) Jp -- Seduced, shaggy Samson snored. She scissored short. Sorely shorn, Soon shackled slave, Samson sighed, Silently scheming, Sightlessly seeking Some savage, spectacular suicide. -- Stanislaw Lem, "Cyberiad" -- up 6 days, 21:59, 10 users, load average: 0.08, 0.16, 0.13 From martigan at libero.it Sun Mar 9 08:34:28 2003 From: martigan at libero.it (Mauro) Date: Sun, 9 Mar 2003 13:34:28 -0000 Subject: [newbie] PIL ImageFont References: Message-ID: > effbot has an "experimental" _imagingft.pyd available at: > http://effbot.org/pil/index.htm . I am testing this right now. > effbot also has a pilfonts.zip containing PIL versions of the basic X11 > fonts; and I found PIL versions of some Windows fonts at > http://www.cazabon.com/python/ . This seem to be a good alternative but, unfortunately some of the files are missing from the internet site. > James Kew > james.kew at btinternet.com Thanks a lot I will let you know Mauro From spam at magnetic-ink.dk Fri Mar 14 14:55:13 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Fri, 14 Mar 2003 19:55:13 +0000 (UTC) Subject: Using SHA1 as RNG References: <3e7228e0$0$49110$e4fe514c@news.xs4all.nl> <4d0ec854-54f9-46a0-99ea-86534e100ba1@news.szn.dk> <3e722e78$0$49105$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: >>> Even if the hash doesn't repeat itself, you still get a 100% >>> predictible sequence of numbers because the SHA algorithm is >>> repeatable. >> >> But the same goes for the original Wichmann-Hill generator, >> doesn't it? > > Umm.. perhaps. I don't know that much about strong random number > generators. Can anybody enlighten me (us)? The Wichmann-Hill PRNG is basically multiplication and modulus with 2?3 known constants (snipped from whrandom.py): #v+ def random(self): """Get the next random number in the range [0.0, 1.0).""" # This part is thread-unsafe: # BEGIN CRITICAL SECTION x, y, z = self._seed # x = (171 * x) % 30269 y = (172 * y) % 30307 z = (170 * z) % 30323 # self._seed = x, y, z # END CRITICAL SECTION # return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0 #v- Start with the same seeds, and you end up with the same sequence of numbers. Oh, and it seems the cycle for the Wichmann-Hill RNG is not 30268*30306*30322-1, but (30268*30306*30322-1)/4. See (?). I believe the strength of the W-H generator is that it is portable and computational inexpensive. // Klaus (?) -- ><> unselfish actions pay back better From usenet2002 at krap.dk Wed Mar 12 16:22:06 2003 From: usenet2002 at krap.dk (Svenne Krap) Date: Wed, 12 Mar 2003 22:22:06 +0100 Subject: ReportLab, PDF and Latin-1 characters References: Message-ID: Btw. running IDLE on winblows On Wed, 12 Mar 2003 21:47:24 +0100, Svenne Krap wrote: >Hi - yes, it's me again :) > >Being a native danish speaker, we are blessed with three extra letters >:) >Working with pdfgen, i get > > >from reportlab.pdfgen import canvas >c = canvas.Canvas("C:\\mypdf.pdf") >c.setFont('Arial',12) >c.setFont('Helvetica',12) >c.drawString(10,10,'???') > > >but then, I get : > > >UnicodeError: ASCII encoding error: ordinal not in range(128) > > >How do I manage to get Latin-1 (or even better full unicode) support >in pdfgen ? > >Svenne From peter at engcorp.com Mon Mar 17 07:21:28 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 Mar 2003 07:21:28 -0500 Subject: P.E.P. 3.0.8 ??? References: Message-ID: <3E75BDC8.D301790A@engcorp.com> Martijn Faassen wrote: > > John Baxter wrote: > > In article , > > "Tim Peters" wrote: > > > >> For monumental decisions like > >> this, he likes to wander in the Amsterdam desert, fasting for 40 days first. > > > > AARGH...that would seem to *invite* being hit by a bus. > > > > Wander carefully, Guido! > > True, the busses of the Amsterdam desert are reknowned for their > aggressiveness, though the viciousness of the smaller but more numerous > bicycle should never be underestimated. I hate it when one of those little bikes rides up and kisses me viciously as I crawl around Amsterdam looking for water. -a-passenger-on-a-bus-gave-me-a-buss-ly yr's, Peter From cmlambert at hotmail.com Wed Mar 12 02:56:10 2003 From: cmlambert at hotmail.com (theKid) Date: 11 Mar 2003 23:56:10 -0800 Subject: string.replace() produces TypeError: an integer is required Message-ID: As far as I can tell, I'm using the function correctly: import string import types print type(data) print data data = string.replace(data, '\t', '\\t') # line 58 data = string.replace(data, '\n', '\\n') print data Output: HI THERE Traceback (most recent call last): File "./2_sm_client.py", line 58, in ? data = string.replace(data, '\t', '\\t') TypeError: an integer is required This is with Python 2.2.2 Am I using string.replace() correctly? TIA Craig From skender at webman.com Sun Mar 23 10:19:43 2003 From: skender at webman.com (Skender) Date: Mon, 24 Mar 2003 02:19:43 +1100 Subject: I/O Serial and Parallel References: Message-ID: Klaus Meyer wrote: > Use the sourceforge, Luke ;-) > > Maybe this is, what you are searching for: > http://sourceforge.net/projects/pyserial/ > Great. Thanks for that :) From fpm at u.washington.edu Sat Mar 8 15:23:52 2003 From: fpm at u.washington.edu (Frank Miles) Date: 8 Mar 2003 20:23:52 GMT Subject: vim/linux doesn't highlight mismatched parens in scripts Message-ID: Though I have syntax highlighting turned on, my Debian/'sarge' installation doesn't highlight parentheses (or brackets) when editing python scripts. It does when editing C or C++ or bash scripts. Does this happen with all vim installations? Or is it peculiar to my installation/configuration? Thanks... -frank -- From xxdigitalhellxx at hotmail.com Fri Mar 14 11:28:30 2003 From: xxdigitalhellxx at hotmail.com (sik0fewl) Date: Fri, 14 Mar 2003 10:28:30 -0600 Subject: asyncore module Message-ID: Hey, Is asyncore ideal for programs with user input as well as sockets? It doesn't seem so with asyncore.loop() not returning until all sockets are closed, but maybe I'm missing something. Otherwise, threading seems like the way to go (not like there are any other ways to go). -- Thanks, Ryan From aleax at aleax.it Thu Mar 13 14:02:27 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Mar 2003 19:02:27 GMT Subject: clear derived list References: Message-ID: <7B4ca.77073$zo2.1957978@news2.tin.it> Steven Taschuk wrote: > Quoth John Hunter: > [...] >> class mylist(list): >> def set(self, seq): >> # flush the old list >> [self.pop() for i in range(len(self))] >> self.extend(seq) > > How about using slice assignment? > > def set(self, seq): > self[:] = seq This will break, while the original code would work, if seq was a non-list sequence. Easy fix: self[:] = list(seq) Alex From dave at boost-consulting.com Sat Mar 22 20:56:03 2003 From: dave at boost-consulting.com (David Abrahams) Date: Sat, 22 Mar 2003 20:56:03 -0500 Subject: A library approach to the ternary operator References: Message-ID: Alex Martelli writes: > David Abrahams wrote: > >> >> I still like the idea of a ternary operator, and I'm not afraid to >> admit it. However, none of the language solutions were particularly >> compelling, so I got to thinking about a library approach and came up >> with this one: >> >> ---- ternary.py------- >> def select(x): return x[0] >> --------------------- > > I would name this 'choose' (let's avoid the confusion with the select > module and function therein, please!) No problem; I don't know all the standard libs as well as you do or I'd have avoided 'select' in the first place. > AND make it VERY picky to help > catch usage errors: > > def choose(x): > assert type(x) is list > assert len(x) == 1 > return x[0] Oh sure: I would do that in real code but I was seduced by the simplicity ;-) > Note that with -O the assert statements get compiled away, so there > is no real price to pay for this pickiness when the code gets into > production use -- it's just there to help catch (likely!) mis-usage > during the development phase. > > But, yes, I do like the overall approach. > > >> # then... >> >> from ternary import * > > (Note what WILL happen each time this from statement is executed > in a module that also does "import select" -- that's why it's > somewhat important to pick a better name for the function...!). > Another likely name might be "pick". y = choose(x < 0 and [22.5] or [f(x)]) y = ternary(x < 0 and [22.5] or [f(x)]) y = pick(x < 0 and [22.5] or [f(x)]) y = cond(x < 0 and [22.5] or [f(x)]) y = if_(x < 0 and [22.5] or [f(x)]) I guess I like the last two, and the last one best of all, because in my mind there's a nice association between the function name and the adjacent condition. >> select(condition and [true_result] or [false_result]) >> >> it's just enough prettier than >> >> (condition and [true_result] or [false_result])[0] >> >> to be worth using. Having a function name ("select") there gives us >> something to attach a nice verbose comment to, while the above, since >> it uses only language primitives, remains obscure. > > Yes, I concur. Moreover, this ternary.py can easily be widely > spread and popularized or spurned, as the case may be ;-) > to establish a usage base for 'choose' IF people like the approach > (I'm not gonna guess if they will) -- this may help make a case for > 'choose' as a built-in, later, if and only if people like and use it > so much as to warrant that. It's always nicer to have a transition plan that goes through a library-only approach first without making core language changes. That gives the concept a chance to live or die on its own without forcing people to accept more than they can stomach. -- Dave Abrahams Boost Consulting www.boost-consulting.com From jepler at unpythonic.net Mon Mar 17 16:28:24 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 17 Mar 2003 15:28:24 -0600 Subject: Logging _into_ an application In-Reply-To: References: Message-ID: <20030317212824.GA16952@unpythonic.net> On Mon, Mar 17, 2003 at 10:13:07PM +0100, Stefan Schwarzer wrote: > I would like to know if there's a framework available for logging into a > Python > application, in the same sense I can use a command line database client to > query > a database (e. g. psql for PostgreSQL). Example for the Python case: twisted has "manhole". Jeff From warrenpstma at ____hotmail__.com Thu Mar 20 00:38:33 2003 From: warrenpstma at ____hotmail__.com (Warren Postma) Date: Thu, 20 Mar 2003 00:38:33 -0500 Subject: My CTO is learning Python.... References: Message-ID: > "There doesn't seem to be any good books on Python" Not everyone should learn Python from a book. In my humble opinion, books are for building offline what you have already started to learn by doing. In other words, without a clear goal in mind (WHY DO I WANT TO LEARN PYTHON? WHAT AM I GOING TO WRITE?), there is no use trying to learn a second language. Perhaps his brain is full. No shame in that. Okay, well, maybe a little. So, if the tutorial did not whet his appetite, if the idea of a dynamically typed object oriented language, with introspection, and standard libraries out the yinyang don't turn this guy's crank, I'm tempted to think he's not as brilliant as you give him credit for. In my not so humble opinion, it ought to take a bright programmer about ten seconds to figure out: 1) Not everything should be written in Java or C++. 2) Very High Level OOP Languages are a powerful tool. 3) Several places where Python could be used to solve a real problem your boss is experiencing right now. There is no good way to learn a language by futzing around. Either you want to write real code, or you don't. It's like trying to learn to be a concert pianist, and only playing scales, and never learning any actual pieces. Tutorial code should give a flavour, and then you go out and bang your head, until you get it. The time (minimal) from first trying python, until the time one can actually write out working, useful python code is probably one of the big things that helped me get religion. ;-) Warren Postma From exml at libero.it Tue Mar 4 06:59:05 2003 From: exml at libero.it (Giuseppe Ricioppo) Date: Tue, 04 Mar 2003 11:59:05 GMT Subject: lambda 4 dummies Message-ID: Hi All. Given the following code: >>> f = lambda a, b, c: a + b +c >>> f(1,1,1) 3 Here, f is assigned the function object the lambda expression returns. Is f, the object returned, a reference to an anonymous function? Best regards. Gius. From paul at boddie.net Fri Mar 21 12:21:25 2003 From: paul at boddie.net (Paul Boddie) Date: 21 Mar 2003 09:21:25 -0800 Subject: Program stalls when called via Popen4? References: Message-ID: <23891c90.0303210921.77323f9b@posting.google.com> Joshua Pollak wrote in message news:... > > Everything seems to be working correctly, EXCEPT that the popen2.Popen4 > instance I'm using to actually build our project never returns. When I > 'watch' what the subprocess is doing by using 'ps aux', it seems that it > has stalled on the first call to 'echo'! Quite often with popen2 functions, it can be advisable to close the output stream to the child process. For example (with popen3, since I don't know what popen4 returns): t = popen2.popen3(command) # Close output, which is the standard input of the command. t[1].close() # Read from t[0] and t[2]. That might prevent certain blocking conditions from occurring. Paul From pwatson at redlinec.com Wed Mar 12 17:49:02 2003 From: pwatson at redlinec.com (Paul Watson) Date: Wed, 12 Mar 2003 16:49:02 -0600 Subject: little programming probleme References: <3e6fab9d$0$83883$ba620e4c@news.skynet.be> Message-ID: import string blob = "now is\nthe was#yesterday\ntime\n" chunk = string.split(blob, "\n") print chunk for i in range(len(chunk)): print chunk[i] for j in range(len(chunk[i])): if chunk[i][j] == '#': break print chunk[i][j] import re p = re.compile("\#") for i in range(len(chunk)): m = p.split(chunk[i]) print m[0] "Jonas Geiregat" wrote in message news:3e6fab9d$0$83883$ba620e4c at news.skynet.be... > I have a string and I want to delete all comments , comments start with a # > > here is my code > conf is my string where I want to delete comments I think the probleme > is that if he finds a comment he delete's the element of the list but > then he can't loop true that element anymore so I should break the loop > and start the first one again but I don't know how if it could be any > help I added my error code un the code > > > chunk = string.split(conf,"\n") > for i in range(len(chunk)): > for x in range(len(chunk[i])): > if chunk[i][x] == "#": > print chunk[i] > > > > > > > > > > > > > for x in range(len(chunk[i])): > IndexError: list index out of range > > > regards Jonas > From exarkun at intarweb.us Mon Mar 3 19:33:48 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 3 Mar 2003 19:33:48 -0500 Subject: xml.sax.XMLReader and document encodings Message-ID: <20030304003348.GA17556@meson.dyndns.org> I'm parsing an XML document (an RDF), with code along these lines: import xml.sax class ProjectContentHandler(xml.sax.ContentHandler): # Various things h = ProjectContentHandler() p = xml.sax.make_parser() p.setContentHandler(h) f = file('projects.rdf', 'r') p.parse(f) I am interested in the encoding of the document, though. I can't seem to find the API which provides this functionality. Does anyone know? Thanks in advance, Jp -- "There is no reason for any individual to have a computer in their home." -- Ken Olson, President of DEC, World Future Society Convention, 1977 -- up 15:58, 8 users, load average: 0.05, 0.15, 0.25 From sholden at holdenweb.com Fri Mar 7 08:52:23 2003 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 07 Mar 2003 13:52:23 GMT Subject: This sucks. References: <2614138.1047017673@dbforums.com> Message-ID: "Tetsuo" wrote in message news:2614138.1047017673 at dbforums.com... > > No matter how much I look at my code, I can't see how 0>=10. I fixed a > few things today, but the program still beyond fails. > It's all a question of what you're comparing: >>> 0 >= 10 0 >>> "0" >= 10 1 >>> Remember that Python data is strongly-typed! regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Register for PyCon now! http://www.python.org/pycon/reg.html From npetry at accesscomm.ca Wed Mar 5 01:18:30 2003 From: npetry at accesscomm.ca (Norman Petry) Date: 05 Mar 2003 00:18:30 -0600 Subject: ANN: Ballot for Complementary PEP308 Ternary VOTE In-Reply-To: <3E656589.5A91838A@alcyone.com> References: <3E656589.5A91838A@alcyone.com> Message-ID: <1046845111.1035.622.camel@chomsky> On Tue, 2003-03-04 at 20:48, Erik Max Francis wrote: > Norman Petry wrote: > > > This is NOT a ballot for the "official" PEP-308 vote being run by > > Raymond Hettinger. It is for a different vote that is intended to > > COMPLEMENT the results of the official vote, by using a different type > > of ballot, and a different method of tallying the results (Condorcet's > > Method), for those who may be interested. If enough people choose to > > participate, it will provide a high-quality source of additional > > information about the preferences of the Python community regarding > > the > > ternary operator. > > In my opinion this is a very bad idea. All a second concurrent vote is > going to do is create more confusion about which vote is official, > whether people have already voted, etc. I do not see how I could possibly have been more clear about which vote is official -- for those of you who might be confused: it ISN'T MINE. I honestly see no reason to believe that any one will be confused by this additional vote. Each of the posted ballots has its own self-contained and consistent procedure for submission. Whichever ballot the voter uses, they will generally just forward the message via email to the specified address, filling in the ballot and removing the directions before sending it. There hasn't been any confusion so far, in the 20 or so ballots I've received. > Saying "This is not the official vote" and "This is a different vote" is > all well and good, but conducting the vote at all is going to great more > confusion than it is going to be worth. Imagine five or six people > getting the same idea and concurrently conducting their own (unofficial) > votes, all while we're still waiting for the results on the official one > (the only one which counts). I don't think we need to worry about that particular slippery slope :-) Organizing a vote like this is a fair amount of work, so I do not foresee another half-dozen people deciding to conduct their own polls any time soon. I clearly stated in my ballot message that I will NOT be posting the results of my vote until AFTER the voting period for the official vote is complete. I have no wish to bias the outcome of the official vote in any way by prematurely releasing results. > > > The two-day nomination period for additional syntax proposals has now > > ENDED. No additional nominations were received, so the ballot is as > > follows: > > Uh, I never even read about any nomination period _beginning_. > Damn. I posted it to Usenet, and had thought that the message would be routed to the mailing list as well, but it seems that something went wrong. I now cannot find the message in the mailing list archives, or anywhere on the web! Maybe that's why the response to the nomination period wasn't very good (or maybe it's because people felt that 21 choices was more than enough...) The strange thing is that I DID receive one early response via email on March 3rd, so at least some people must have received this message: ANNOUNCE: Complementary VOTE re: PEP 308 Ternary Proposal, Sun, 02 Mar 2003 17:44:33 -0600 I can only suppose that the message was cancelled by someone, although I can't understand why (it was long - about 500 lines, but I've seen messages double that length. Is there some limit on message size that I violated? I'm a beginner when it comes to Usenet). Anyway, the subject of my vote and the reasons for it were explained in that message, so I will resend some or all of it tomorrow so that people have the necessary background information. The unofficial vote will continue as planned in any case -- too late to turn back now, even if I wanted to. -- Norman Petry From martin at v.loewis.de Fri Mar 28 02:18:09 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 28 Mar 2003 08:18:09 +0100 Subject: 2.2.1 crashes on Linux (RH7.3) trying to load python shared library timemodule.so References: Message-ID: morden writes: > 1. Why does 2.2.1 goes looking for timemodule.so in > /usr/lib/python2.2/lib-dynload/ even though I've built it statically > with prefix /u/local That is hard to believe, unless you have added somehow /usr/lib/python2.2 to sys.path. Are you sure your app is linked with the library you have built? > 2. How could I tell configure that I want modules statically linked with > libpython.a? I'm not sure I understand this question. Which modules? The ones of the standard Python distribution? They are never linked with libpython.a: they are *part* of it. Your own modules? which configure do you want to tell something, then? Regards, Martin From irmen at -NOSPAM-REMOVE-THIS-xs4all.nl Sat Mar 8 11:13:50 2003 From: irmen at -NOSPAM-REMOVE-THIS-xs4all.nl (Irmen de Jong) Date: Sat, 08 Mar 2003 17:13:50 +0100 Subject: CGI ZIP In-Reply-To: References: Message-ID: <3e6a16bd$0$49107$e4fe514c@news.xs4all.nl> Simon Faulkner wrote: > I would like to read in a .txt file then send it out to a browser as a > .zip file > > Can the zipfile module only write to a file system? No. It can write to any file-like object: import cStringIO s=cStringIO.StringIO() z=zipfile.ZipFile(s,"w",zipfile.ZIP_DEFLATED) z.write("yourfilehere.txt") z.close() Now you can do anything you want with the generated zip file that is contained in s, for instance: open("test.zip","wb").write(s.getvalue()) In your case you'd probably send it as part of the HTTP response over a socket to the client. --Irmen. From tatebll at aol.com Mon Mar 10 07:04:17 2003 From: tatebll at aol.com (Bill Tate) Date: 10 Mar 2003 04:04:17 -0800 Subject: Using mail merge in Word using win32com & Python Message-ID: Has anyone come across this requirement using python & win32com? I need to be able to programmatically create a list of addressees to receive a form letter using Word's mail merge feature. I've check all the usual sources including Mark's win32 programming book. While I can obtain instances of a MailMerge & MailMergeDataSource COM objects, I can't seem to find a method that would allow me to add/remove records to the data source. The help reference doesn't appear to offer any answers either. Any feedback or suggestions would be greatly appreciated. Bill Tate From MFranklin1 at gatwick.westerngeco.slb.com Tue Mar 25 04:03:21 2003 From: MFranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 25 Mar 2003 09:03:21 +0000 Subject: scrolltext widget,appending to References: <3E7F7FE5.5070008@netscape.net> Message-ID: <3E801B59.3020405@gatwick.westerngeco.slb.com> vector wrote: > Hi > ref:(pythonwin 2.2.2)newbie > Im using a scrolltext widget to display the incoming bytes from the > seral port. currently the code snip is simply > siobuf=ser.read(nbr) #nbr =number of bytes in buffer > oldbuf=f.terminalIn.get() #terminalIn is a scrolltext widget > siobuf=oldbuf+siobuf > f.terminalIn.settext(siobuf) > If you are tqalking about the Tkinter scrolled text widget then use the insert method like so:- f.terminalIn.insert("end", siobuf) HTH Martin From reply.in at the.newsgroup Tue Mar 4 12:16:40 2003 From: reply.in at the.newsgroup (Rene Pijlman) Date: Tue, 04 Mar 2003 18:16:40 +0100 Subject: How to use threading and Queue modules References: <182bcf76.0303040901.23690dcc@posting.google.com> Message-ID: Paul Moore: [Thread pool with Queue] >How do I wait for the workers to all finish? See this example code from Aahz: http://starship.python.net/crew/aahz/OSCON2001/ThreadPoolSpider.py And related stuff: http://starship.python.net/crew/aahz/OSCON2001/ -- Ren? Pijlman From logistix at zworg.com Wed Mar 19 21:33:23 2003 From: logistix at zworg.com (logistix) Date: 19 Mar 2003 18:33:23 -0800 Subject: Does Python do try: except: finally: ? References: <20030319135147.A1830@ash.int.ca.pason.com> <1048108451.2357.6.camel@jwilhelm.ofsloans.com> Message-ID: "Ulrich Petri" wrote in message news:... > "Skip Montanaro" schrieb im Newsbeitrag > news:mailman.1048112434.6123.python-list at python.org... > > > > Maybe, but that's not what try/finally does. Try/finally says, "Execute > the > > code in the try block, and irregardless of any exceptions which might get > > raised, execute the code in the finally block when finished." > > Try/except/else says, "Execute the code in the try block. If an exception > > is raised, execute the code in the except block, otherwise execute the > code > > in the else block." > > > > I allways asked myself of what practical use finally (except the syntactical > "clearness of code") is? > I can simply write like: > > try: > do_this() > except: > print "error" > #now here is what will be executed next, so what for i do need finally? > > Ciao Ulrich It gets really ugly if you're trying to defer the error handling: >>> def fileOp(): ... try: ... print "Pretend to open a file" ... print "Pretend to process" ... raise RuntimeError("Pretend I had an error") ... finally: ... print "Pretend to close a file" ... >>> fileOp() Pretend to open a file Pretend to process Pretend to close a file Traceback (most recent call last): File "", line 1, in ? File "", line 5, in fileOp RuntimeError: Pretend I had an error >>> try: ... fileOp() ... except: ... print "Ignoring Error" ... Pretend to open a file Pretend to process Pretend to close a file Ignoring Error >>> >>> >>> def fileOp(): ... errStatus = 0 ... try: ... print "Pretending to open a file" ... print "Pretending to process" ... raise RuntimeError("Pretend I had an error") ... except: ... print "Pretending to close file" ... errStatus = 1 ... if errStatus: ... print "Reraising Error" ... raise ... >>> fileOp() Pretending to open a file Pretending to process Pretending to close file Reraising Error Traceback (most recent call last): File "", line 1, in ? File "", line 6, in fileOp RuntimeError: Pretend I had an error >>> From joso at iespana.es Thu Mar 6 05:24:40 2003 From: joso at iespana.es (Iespana) Date: Thu, 6 Mar 2003 11:24:40 +0100 Subject: spawn and NO window Message-ID: <037301c2e3ca$990c8a30$5700a8c0@agora2000.com> Hi, My problem is that I execute "os.spawnv(os.P_NOWAIT, "fich.exe",[var1,var2])" and it's launched in other window. I want to execute fich.exe in background, not opening other window. I don't write any message on screen. This execution is in windows (not linux) Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Mon Mar 31 22:03:35 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 31 Mar 2003 22:03:35 -0500 Subject: try:else: w/o except: - why not? References: <1c004553.0303311553.53a9a92b@posting.google.com> <3E88E56F.5CB4EB92@engcorp.com> Message-ID: <3E890187.ED7A27A2@engcorp.com> John Roth wrote: > > "Peter Hansen" wrote: > > What you wrote in the first place is exactly the same as this: > > > > # some code that may except > > # but if it didn't except, I want to do this > > > > In other words, the "try" in your first block is useless.... > > Not quite. Consider a test that's supposed to throw an exception > in a testing harness like unittest or xUnit. If it throws an exception, > the test passes, and if it doesn't, I want to put out a diagnostic > message. Hmmm... interesting and valid point. I would suspect that this is an extremely unusual use case, so not worth considering for addition to the core, and in the particular case of unittest, it's already supported by self.assertRaises()! > Now, that's a bit too simplistic for my use - I'd like to know that > it threw the *correct* exception. But that's a use case for the > facility he's asking for. Exactly... if this is for testing, it's really inadequate to check that it threw *an* exception, since it might not be the one that was intended. Also, adding the "unnecessary" 'except: pass' is of course as easy as pie. Manus, we await your justification of the request with bated breath! :-) -Peter From googlegroups at tekNico.net Wed Mar 12 18:02:29 2003 From: googlegroups at tekNico.net (Nicola Larosa) Date: 12 Mar 2003 15:02:29 -0800 Subject: Tuples, what are they: read-only lists or heterogeneous data arrays? References: <15982.24855.181016.568236@montanaro.dyndns.org> <200303111449.42035.fincher.8@osu.edu> <200303120211.h2C2BCH28989@pcp02138704pcs.reston01.va.comcast.net> Message-ID: <6fb43e5d.0303121502.683c615f@posting.google.com> [WARNING: pet peeve ahead] > FAQ entry 6.15 states: > >> 6.15. Why are there separate tuple and list data types? >> This is done so that tuples can be immutable while lists are >> mutable. There's more than that. The tutorial states: "Tuples have many uses. For example: (x, y) coordinate pairs, employee records from a database, etc." http://www.python.org/doc/2.3a2/tut/node7.html#SECTION007300000000000000000 I was using MySQLdb, and naturally enough, it returns tuples. I built another tuple with the values from one field for a number of records, and I wanted the index of the record with a particular value, so I reached for a tuple.index() method, and guess what? There is no such thing. :^( I went to Google and searched through c.l.py., and to my disappointment, found these discussions: PROP: tuple.index(), tuple.count() http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&th=db5333ec65d2262c&rnum=1 How come tuples don't have an index method? http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&th=99a50502426e8be5&rnum=1 which led to this Tracker entry: [ 403693 ] tupleobject.c: implement tuple.index() and tuple.count() http://sourceforge.net/tracker/?group_id=5470&atid=305470&func=detail&aid=403693 Date: 2001-02-15 05:49 Sender: gvanrossum "Why bother? I like the fact that when you want to do list-ish things you have to use lists. Use list(t).count(x) if you really want this for a tuple. "I'm rejecting this in the name of all those users who want Python to be small." Sorry, but this makes no sense. I entirely support the notion that a tuple should be *exactly* like a list, apart from the fact that it is immutable, so every read-only list method should be available for tuples, too. It's bad enough to be chided by Lua aficionados because they need just one type to do what we do with tuples, lists and dictionaries. ;^) We need no more superflous subtleties. And no, list(t).index(x) does not qualify. Neither does operator.indexOf() . Guido, can't we settle this once and for all? From mis6 at pitt.edu Wed Mar 19 17:57:32 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 19 Mar 2003 14:57:32 -0800 Subject: Aspergers link (was Re: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad...) References: <0vv17v4vn4khffgr2io0otrnni8sc6rug7@4ax.com> <%dica.80722$zo2.2065641@news2.tin.it> <7f2b571b.0303161642.320e0997@posting.google.com> <2259b0e2.0303190822.58f369dd@posting.google.com> <_22ea.58441$68.21554@nwrdny01.gnilink.net> Message-ID: <2259b0e2.0303191457.65e3ef9c@posting.google.com> Carl Banks wrote in message news:<_22ea.58441$68.21554 at nwrdny01.gnilink.net>... > Just to avoid having my words misconstrued too much, and to nitpick: > if someone can't go to party, then they have agoraphobia, or social > phobia, or avoidant personality disorder, not Asperger's "syndrome." > I don't think Asperger's syndrome exists, period. If they have a > mental problem, it's something else. > Okay, Carl your point is clear. Sorry if I have misconstrued too much your words. Anyway, I think these kinds of problems do exist, even if probably in many cases they are exaggerated; if the right name for them is "Asperger" or some other name, it is a secondary issue to me. Regards, Michele From wilk-spamout at flibuste.net Thu Mar 27 03:56:19 2003 From: wilk-spamout at flibuste.net (Wilk) Date: 27 Mar 2003 09:56:19 +0100 Subject: Simple Python web development References: Message-ID: <87el4tkx1o.fsf@flibuste.net> Afanasiy writes: > Is there a Python web development solution which : > > * Uses the Apache web server > * Does not depend solely on CGI or FastCGI > * Requires only an Apache daemon, and no others > * Does not require editing of *.conf or .htaccess every > time you want to add another page to your web application. you must explain a little bit more what you want to do ! why using apache if you don't want to use cgi ? There are a lot of solutions with a python server, without apache and cgi and .htaccess... -- William Dode - http://flibuste.net From a.schmolck at gmx.net Mon Mar 3 17:28:21 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 03 Mar 2003 22:28:21 +0000 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <8fb66v8qbv45eatnblq80p131793ej7e3m@4ax.com> <6zK8a.268598$0v.7396380@news1.tin.it> Message-ID: Dave Brueck writes: > > I don't think that follows. Python's list comprehensions are different -- they > > pollute the namespace. > > Oh, c'mon. This is a frequently cited yet overstated wart. Yeah, > technically it's a problem, but much more a theoretical than practical one It isn't a major problem, but I can remember that it did (infrequently) cause me bugs, so it's not all theoretical. Another minor cause of annoyance are things like this: SOME_GLOBAL_CONST = [(y**2, x**2) for (x,y) in SOME_OTHER_GLOBAL_CONST] del x, y # I could do without this > - in practice the only time it causes problems is when you're doing > something questionable anyway, like reusing a variable without > initializing it to some known value. Or accidently overwriting a variable (or modulename). All this might not amount to much, but I do think they violate the spirit of functional programming enough to bias some people who like FP towards map and filter. alex From alloydflanagan at attbi.com Fri Mar 7 18:00:05 2003 From: alloydflanagan at attbi.com (A. Lloyd Flanagan) Date: 7 Mar 2003 15:00:05 -0800 Subject: Python in a Nutshell: Real Soon Now! References: Message-ID: "Steve Holden" wrote in message news:... > I thought US readers, at least, might be interested to know that UPS have > just delivered my complimentary copy of "Python in a Nutshell". By using a > fine, almost onion-skin, paper they have made an excellent volume that is > quite manageable to read and carry around. Nice job, Alex ... should be on > the bookshelves any time now! > > regards Will it be available on http://safari.oreilly.com? Printed books are so old-fashioned. ;) From jepler at unpythonic.net Mon Mar 3 14:32:22 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 3 Mar 2003 13:32:22 -0600 Subject: Finally figured out member generators... In-Reply-To: <60FB8BB7F0EFC7409B75EEEC13E20192022DD883@admin56.narex.com> References: <60FB8BB7F0EFC7409B75EEEC13E20192022DD883@admin56.narex.com> Message-ID: <20030303193220.GD26674@unpythonic.net> Which version of Python are you using? I just tried a similar example on Python 2.2.2 using "from __future__ import generators", and there was no need to introduce a separate method, or call it in a strange way. >>> from __future__ import generators >>> class R10: ... def __iter__(self): ... for i in range(10): yield i ... >>> list(R10()) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> R10().__iter__ > >>> R10.__iter__ >>> r = R10() >>> list(r.__iter__()) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(R10.__iter__(r)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> iter(r) Jeff From mis6 at pitt.edu Wed Mar 5 11:55:14 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 5 Mar 2003 08:55:14 -0800 Subject: Can __iter__ be used as a classmethod? References: <3e649aa3_4@news.bluewin.ch> <2259b0e2.0303041023.43e8b81f@posting.google.com> <4B89a.6715$zo2.218162@news2.tin.it> <3e65273f$1_3@news.bluewin.ch> Message-ID: <2259b0e2.0303050855.1eece801@posting.google.com> "Samuele Pedroni" wrote in message news:<3e65273f$1_3 at news.bluewin.ch>... > import new > > class myclassmethod(object): > __debug = 0 > > def __init__(self,f): > self.__f = f > > def __get__(self,obj,typ=None): > if self.__debug: > print "MYCM__get__",obj,typ > > if typ is None: > typ = type(obj) > > return new.instancemethod(self.__f,typ,type(typ)) > > class C(object): > def g(cls): > print cls > > g = myclassmethod(g) > > class D(C): > def g(cls): > print 'Dg',cls > C.g() > > g = myclassmethod(g) > > This can be used as an argument to have them explicitely (you can implement > them anyway, so let's get them right once and for all) or to not have them > (who need them can cook them up). In my view this is an argument against them. > It is worth to notice that once you override one of them (like g in D > overriding g in C) it is impossible to call in a clean way the parent > version (C g) passing the derived class (D), which is what would happen in > case of no overriding (if D would not define g, then D.g() would call g in C > passing D), (so above C.g() obviously is calling g in C passing C). "Let's > call this their price". It seems to me that class D(C): def g(cls): print 'Dg',cls C.g.im_func(cls) works under 2.3 (and also super(D,cls).g.im_func(cls) would work). What surprised me, is that for staticmethods I can extract the wrapped function with .__get__(None): >>> def f(x): return x ... >>> s=staticmethod(f) >>> s.__get__(None) # okay, here it is the original f whereas for classmethods I have a quite different result: >>> c=classmethod(f) >>> c.__get__(None) > In a sense, staticmethods are really functions, whereas classmethods are really methods. However, I wonder if there is a direct way to extract f from the classmethod ? Michele From estechmann at advresp.com Mon Mar 17 17:56:12 2003 From: estechmann at advresp.com (Eric Stechmann) Date: Mon, 17 Mar 2003 16:56:12 -0600 Subject: Rudeness (was: Re: OT: Aspergers link) Message-ID: <5.2.0.9.0.20030317163018.03827c70@172.19.8.21> At 04:34 PM 3/17/03 -0500, you wrote: >And it appears that with the massive 21 or so lines of useless cruft that >makes >up your signature, your own signal-to-noise ratio is even less impressive. Yes, ugly, isn't it? Much of the cruft is beyond my control. I don't like it either, but I'm stuck with it. >Carl we know: he _adds_ content. Perhaps. However, the "content" in this particular thread seemed unnecessarily nasty and I decided to say so. >Who are you? Who am I? Just a lurker on the threshold. A lurker who rarely sees any reason to post, but was bothered enough to do so this time. However, I apologize for taking up bandwidth with my "cruft." I should have e-mailed Mr Banks directly rather than posting to the group. That would no doubt have been better for all parties concerned. A lesson learned. Eric Stechmann -------------------------------------------------------------------------- Eric Stechmann Direct: +1 (651) 234-1217 Domestic Feline Wrangler Fax: +1 (651) 490-1484 Advanced Respiratory, Inc. E-mail: estechmann at advresp.com 1020 West County Road F URL: www.thevest.com St.Paul MN 55126 ______________________________________________________________ Information contained in this e-mail message may be legally privileged and confidential information intended only for the use of the individual(s) named above. If the reader of this message is not the intended recipient, you are hereby notified that any use, dissemination, distribution, or copying of this e-mail is strictly prohibited. If e-mailed messages include MEDICAL RECORDS, these records ARE PRIVILEGED AND CONFIDENTIAL and may be released only upon written permission of the patient. If you have received this e-mail in error, please immediately notify the sender by telephone at 1-800-426-4224 and delete this e-mail. Thank you! ______________________________________________________________ From djn at daimi.au.dk Thu Mar 27 06:28:58 2003 From: djn at daimi.au.dk (Daniel Nielsen) Date: Thu, 27 Mar 2003 11:28:58 +0000 (UTC) Subject: signal module? In-Reply-To: <87smt9axwv.fsf@cassandra.evansnet> References: <20030327092336.GB17524@daimi.au.dk> <87smt9axwv.fsf@cassandra.evansnet> Message-ID: <20030327112857.GD17524@daimi.au.dk> On 27/03-03 10.47, Tim Evans wrote: > Daniel Nielsen writes: > > > Hi. > > > > I'm currently working on some code that uses the signal module... But > > I doesnt seem to work proberly. > > > > I'm using threads, so I'd like ctrl-c to actually terminate the > > program. If my memory serves me, ctrl-c is SIGINT, so in my code, in > > the main thread, I write: > > > > signal.signal(signal.SIGINT, gp.handler); > > > > where gp is a module and handler looks like: > > > > def handler(signum, frame): > > print "Handling signal: " + signum; > > sys.exit(2); > > > > But ctrl-c doesnt do anything! > > > > If I write: > > signal.signal(signal.SIGINT, signal.SIG_DFL); > > instead, ctrl-c actually terminates the program... > > Have I misunderstood something? > > > > /Daniel > > This works fine when for me as long as I press ctrl-c when python is > running and not waiting for input at the '>>>' prompt. Try typing > this: > > > >>> while True: > .. pass > .. > > Handling signal: 2 > > > I'm not sure why it works this way, maybe python's use of readline > changes something. > > Note that your handler function will not actually work as written. > Replace this line: > print "Handling signal: " + signum > with this: > print "Handling signal: ", signum > I'm not using the python cmd line, instead i run it from a script. I tried NOT starting seperate threads, and then it works as expected. No problems. But as soon as I reenable the threads, the handler doesn't get the signal... I cannot understand why! Anyone care to elaborate? /Daniel -- There are no great men, only great challenges that ordinary men are forced by circumstances to meet. -- Admiral William Halsey From daniel.dittmar at sap.com Tue Mar 11 10:58:01 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Tue, 11 Mar 2003 16:58:01 +0100 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <58q36vgv1ga8ovde5ftub9t8ugaa2pnum5@4ax.com> <3E62778F.EED49083@alcyone.com> <3E629E93.B94F7631@alcyone.com> <3E63AFA0.A3CAC045@alcyone.com> Message-ID: A. Lloyd Flanagan wrote: > Part of the problem, I think, is that people coming from other > languages don't understand the power and proper use of the lambda > construct. coming from Smalltalk: Python lambdas are restricted to one expression, which makes them cumbersome to use for more complex stuff and difficult to debug as you can't insert a quick 'print'. Daniel From matthew at newsgroups.com Sun Mar 30 19:04:57 2003 From: matthew at newsgroups.com (matthew) Date: Mon, 31 Mar 2003 12:04:57 +1200 Subject: Plex question Message-ID: Hi, I'm using Greg Ewing's Plex (v.cool) but for the life of me I can't figure out how to get the name of the current state. Any help much appreciated. Thanks. matthew. class PPF_Scanner(Scanner): def event_end(self, scanner): for func in callbacks[current_state_name]: etc... self.begin('') try: lexicon = Lexicon([ # EVENT: Position (Str("(0)"), Begin('position')), State('position', [ (Any("XxYy") + coordinate, set_coordinate), (Any("Tt") + turret_pos, set_turret_position), (whitespace, IGNORE), (eoln, event_end) ]), etc... From Frank at no.spam Thu Mar 6 22:41:10 2003 From: Frank at no.spam (Frank) Date: Thu, 06 Mar 2003 22:41:10 -0500 Subject: Documentation for using the system clipboard ? References: Message-ID: Thanks to all: Eric, jodocus, Grant and Paul, for your help. I figured it was time for a good book anyway, so I got Mark Lutz's "Programming Python, 2nd". He has a paragraph (8.4.2.1) about the clipboard, and uses it in his pyEdit example code. However, nothing compares to the details and warnings I found in this group. Thanks, Frank From sholden at holdenweb.com Mon Mar 17 17:33:12 2003 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 17 Mar 2003 22:33:12 GMT Subject: username cgi References: Message-ID: "Anthony Paul" wrote in message news:b54oha$1avjo$1 at baligan2.unicaen.fr... > > Hello, > > I am writing a forum on intranet using python. I don't want my users > have to enter their username when they will add a message, so I need to > read the %username% environment variable of the workstations (they're > running win2k). > > Is it possible ? > I found a solution about REMOTE_USER but it needs web > authentification... > Generally speaking, you can't expect to be able to run arbitrary code on your users' web client machines. Therefore you need to use some form of "login" or authentication mechanism that has them provide their identity once (per session or per lifetime, depending on whether you implement permanent server-side storage for the user identities), and have the server identify the user thereafter by some token provided by the client. Cookies would be the normal way to do this. Some people are cookie-phobic, and in that case they'd perhaps want to encode the identity as a part of each URL that was sent to the server. This is a fairly well-known problem (and you were correct in later saying that it's not specific to one particular web environment), so if you google for things like "web session state" you will find out a lot about the available mechanisms. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Register for PyCon now! http://www.python.org/pycon/reg.html From michael at stroeder.com Tue Mar 25 14:11:18 2003 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 25 Mar 2003 20:11:18 +0100 Subject: Searching in Active Directory (also using LDAP in Windows) In-Reply-To: References: <2d0ga.6354$t_2.924@afrodite.telenet-ops.be> Message-ID: Rudy Schockaert wrote: > > > I also tried Python-LDAP, but no avail either. > > > > Which version, which platform? > > All I'm doing for the moment is on Windows 2000 platform. I used > Python-LDAP-1.10a3.win32-py2.2.exe which was the latest version I could find > for Windows This is build against ancient Umich 3.3 LDAP libs => LDAPv2. This could be the problem (see also item 7. on http://python-ldap.sourceforge.net/faq.shtml). Ciao, Michael. From fidtz at clara.co.uk Fri Mar 7 11:42:08 2003 From: fidtz at clara.co.uk (Fidtz) Date: 7 Mar 2003 08:42:08 -0800 Subject: TextPad and Python References: <8a0bb987.0303062118.201471b8@posting.google.com> Message-ID: <24944f78.0303070516.44ffe642@posting.google.com> phrogeeb at hotmail.com (Uri) wrote in message news:<8a0bb987.0303062118.201471b8 at posting.google.com>... > Trying to get TextPad (http://www.textpad.com) to work with Python. It > has lots of neat features like a file full of syntax coloring codes > and an easy key-combination that executes the file in buffer and > places output in a new TextPad window. > > I'm running into a question that I've seen come up a couple of times > with Emacs. (Is Emacs on Win better than TextPad, even if I'm just a > newbie?) I can run simple files that come up just fine in the new > window. However, anything including input of any sort returns an error > code that looks like: > > > Hello?Traceback (most recent call last): > File "C:\test.pyw", line 1, in ? > a = raw_input("Hello?") > EOFError: EOF when reading a line > > Tool completed with exit code 1 > > > In Emacs the answer was that you use two commands: > C-c ! py-shell > C-c C-c py-execute-buffer > However, the win version of Python 2.3 apparently doesn't come with > either of these files. > Can anyone give me any suggestions? Answer from a fellow python newbie: I use TextPad quite a lot, due to it's good Macro recorder, Windows integration and easy cross file find and replace. However, it does not have any interactive facilites, meaning things that require feedback from the user in a basic shell type situation will not work. I use TextPad when re-editing programs and/or working with .html, .css and python files simulaneously but use IDLEfork (a newer version of IDLE you can find on sourceforge) when creating the first version of a program. I have written a Tkinter Organizer/Diary application and done a website with online content admin with this system and it is working well so far. I am trying SciTE out at the moment and it is looking good as an editing replacement for both, with IDLEfork becoming used for it's shell alone. It has the interactive Output windows that TextPad lacks. I did the Vim and EMACS tutorials too and I reckon the learning curve might be worth it in the long run but while I am learning python, I think easier editors are a better bet. Dom From air_jlin at yahoo.com Thu Mar 6 12:55:10 2003 From: air_jlin at yahoo.com (Johnny Lin) Date: Thu, 6 Mar 2003 09:55:10 -0800 (PST) Subject: Newbie Looking for Scientific Python TkWidgets Example In-Reply-To: <1046822124.2739.62.camel@sayge.arc.nasa.gov> Message-ID: <20030306175510.76949.qmail@web40203.mail.yahoo.com> hi Chad, thanks much for your help! here's the code i was trying to get work. am just trying to plot a set of 4 points (array c; have left out the import statements): c=[[1,2],[3,4],[3,5],[6,8]] global root root=Tkinter.Tk() line=Scientific.TkWidgets.TkPlotCanvas.PolyLine(c,width=10,color='black') pts=Scientific.TkWidgets.TkPlotCanvas.PolyMarker(c) plot=Scientific.TkWidgets.TkPlotCanvas.PlotCanvas(root,100,100) plot.draw(line,xaxis='automatic',yaxis='automatic') plot.draw(pts,xaxis='automatic',yaxis='automatic') plot.pack root.mainloop() thanks again for your help! best, -Johnny --- Chad Netzer wrote: > On Tue, 2003-03-04 at 15:39, Johnny Lin wrote: > > > Does anyone have sample code of using Scientific > Python TkWidgets to > > make a line plot? I'm trying to figure out what > I'm doing wrong and > > can't find any sample code online. > > How about you post your code, and we can try to see > what is wrong with > it (if it is long ocde, perhaps you could post a > link) __________________________________________________ Do you Yahoo!? Yahoo! Tax Center - forms, calculators, tips, more http://taxes.yahoo.com/ From mikael at isy.liu.se Tue Mar 18 06:44:20 2003 From: mikael at isy.liu.se (Mikael Olofsson) Date: Tue, 18 Mar 2003 12:44:20 +0100 Subject: Rudeness (was: Re: OT: Aspergers link) In-Reply-To: <3E76EF5B.185EBEAC@alcyone.com> References: <5.2.0.9.0.20030317140220.03820670@172.19.8.21> <1047948405.1108.89.camel@software1.logiplex.internal> <3E76EF5B.185EBEAC@alcyone.com> Message-ID: <20030318124420.1860a480.mikael@isy.liu.se> Cliff Wells wrote: > > > Everyone together: "IANAP". I wrote: > > Acronumfinder.com: > > IANAP: I Am Not A Programmer Erik Max Francis wrote: > "I am not a psychiatrist," I would presume. I did realize that. I just found it a little bit funny that my number one reference on acronyms gave _one_ interpretation, and that it was exacly the one I gave above. I mean, given that the topic of the group is programming, well at least now and then. /Mikael ----------------------------------------------------------------------- E-Mail: mikael at isy.liu.se WWW: http://www.dtr.isy.liu.se/dtr/staff/mikael Phone: +46 - (0)13 - 28 1343 Telefax: +46 - (0)13 - 28 1339 /"\ \ / ASCII Ribbon Campaign X Against HTML Mail / \ This message was sent by Sylpheed. ----------------------------------------------------------------------- Link?pings kammark?r: www.kammarkoren.com From andrew.markebo at telia.com Sat Mar 22 06:20:36 2003 From: andrew.markebo at telia.com (Andrew Markebo) Date: Sat, 22 Mar 2003 11:20:36 GMT Subject: urllib.urlretrieve and PASV mode References: <3e7b3eba.90530195@news.zianet.com> Message-ID: / "Thomas Weholt" <2002 at weholt.org> wrote: | As far as I know, passive mode is ftp-specific. Urllib is used to fetch | files served over http and passive mode is not relevant to that protocol. | Correct me if I'm wrong. URL's can both specify FTP and HTTP targets, so you are wrong.. correcting correcting... :-) |> Is there a way when using urllib.urlretrieve() to |> use passive mode for ftp transfers? It looks like |> this is supported in ftplib (set_pasv method), |> but not used by urllib. Unless I'm missing something. Throwing an eye or two at the source, nope doesn't seem so, and how to fix it.. Either use ftplib directly yourself, or copy urllib and modify it so it sets PASV. (Hmm having a global variable FTPPASV or similar, and depending on what that is, let ftpwrapperclass call set_pasv..) /Andy -- The eye of the beholder rests on the beauty! From staschuk at telusplanet.net Wed Mar 19 00:22:05 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 18 Mar 2003 22:22:05 -0700 Subject: changes to shelf items fail silently? In-Reply-To: <7gy93cp929.fsf@pikespeak.metacarta.com>; from eichin@metacarta.com on Tue, Mar 18, 2003 at 06:08:14PM -0500 References: <7gy93dmzzu.fsf@pikespeak.metacarta.com> <7gptop2ryj.fsf@pikespeak.metacarta.com> <7gy93cp929.fsf@pikespeak.metacarta.com> Message-ID: <20030318222205.C666@tibia.amotlpaa.bogus> Quoth eichin at metacarta.com: [...] > > of a key-value database on disk (dbm) and a generic object > > serialization protocol (pickle). > > While the __doc__ does say that, it isn't clear why that should cause > this effect; serialization is just "how it is stored", and doesn't > inherently imply "so you only get temporaries out". Mm... yes, I see your point. On the other hand, what I've sketched is imho the obvious implementation. Set a value in the shelf, object gets pickled and written to disk; read a value from the shelf, object gets read from disk and unpickled. Very simple to implement. It really is just a combination of dbm and pickle. Transparent persistence would be a much bigger deal (as is being discussed below) -- so much so that it wouldn't occur to me to expect it unless the documentation had some discussion of the major issue, how changes are detected. (Incidentally, in this sketch, "temporaries" is not an appropriate term for the unpickled objects; it implies that the pickled object in the shelf is the primary object, and the unpickled object in memory an imperfect copy which lacks the true object's permanence. I'd say it's the reverse: the in-memory object is the primary, and the pickled bytestream in the shelf the imperfect copy, and not an object at all (though of course it is convenient to speak of it as if it is).) [...] > > Now, what about shelved foobar.wombat objects? Which of their > > methods should cause commits? > > Mmm, throw an exception if they don't "conform" to some interface. > The reason I went down this path isn't that it silently discarded the > changes, after all; I'd have been happy if it had non-silently told me > (perhaps by having the references be non-mutable and cause exceptions > to be thrown on changes, for example.) Well, making an immutable view of an object is just as much trouble as detecting changes for automatic commits. How will the wrapper know which methods of foobar.wombat objects to raise exceptions for? You could have some interface for this kind of thing (i.e., a way to subscribe to "imminent mutation" announcements from an object, and to interfere in those mutations, as Martelli suggests), and allow only objects conforming to that interface to be shelved; but one of the nice things about shelves is that they accept anything picklable, which is pretty much anything. (Actually, detecting changes after the fact is easier than rejecting them beforehand. A wrapper could pickle the object after every method call or attribute change and compare the result to what was read from the dbm database, committing if different. This would be very expensive but would detect all changes which the shelf is capable of storing at all.) -- Steven Taschuk staschuk at telusplanet.net "I'm always serious, never more so than when I'm being flippant." -- _Look to Windward_, Iain M. Banks From franck.lepoutre at caramail.com Fri Mar 14 11:21:58 2003 From: franck.lepoutre at caramail.com (francois lepoutre) Date: Fri, 14 Mar 2003 17:21:58 +0100 Subject: python as a web glue ? References: <3e7190c2$0$236$626a54ce@news.free.fr> <3e719b4a$0$15897$79c14f64@nan-newsreader-02.noos.net> <3e71aade$0$2728$626a54ce@news.free.fr> <3e71e919$0$7891$626a54ce@news.free.fr> Message-ID: <3e720191$0$18831$79c14f64@nan-newsreader-02.noos.net> > well i'm reading things about zope, isn't it more adapted > than using apache + mod-python ? zope is a framework. With a reputation. I've not used it. Quite a number of frameworks available. Check the full list of resources at www.python.org As I said earlier concerning frameworks, if it (ther framework) fits your brain, try it. It won't hurt you:) Fran?ois From dave at boost-consulting.com Mon Mar 31 19:26:07 2003 From: dave at boost-consulting.com (David Abrahams) Date: Mon, 31 Mar 2003 19:26:07 -0500 Subject: Is Python overhyped (just like Java)? References: Message-ID: "Greg Ewing (using news.cis.dfn.de)" writes: > greg at cosc.canterbury.ac.nzDavid Abrahams wrote: >> In my application it was easy to predict where the bulk of >> the time would be spent, and had I written the core engine in C++ >> early on I might have saved myself a redesign effort. > > Or you could have designed that part of the system with > a possible C++ interface in mind, if it turned out to > be necessary later. I thought I was doing that at the time. The problem is that the edges of subsystems define themselves differently when there's a language boundary there from the beginning. -- Dave Abrahams Boost Consulting www.boost-consulting.com From cpl.19.ghum at spamgourmet.com Thu Mar 20 03:04:18 2003 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Thu, 20 Mar 2003 09:04:18 +0100 Subject: Instantiating variable classes Message-ID: Hello, I need to instantiate "variable classes". That is: myClass=replcsX() where X is 0,1,2,3,4,...7 depending on the program flow. One possibility is: if X==0: myClass=replcls0() elif x==1: myClass=replcls1() and so on .. Second possibility is: command="replcs%d()" % (X,) myClass=eval(command) I'm using the second one, but I am sure there is a way to use Python's more than powerfull class- and objekt manipulations. But I did not find out how. Any suggestions? Harald From maxm at mxm.dk Thu Mar 13 02:42:11 2003 From: maxm at mxm.dk (Max M) Date: Thu, 13 Mar 2003 08:42:11 +0100 Subject: No Do while/repeat until looping construct in python? In-Reply-To: References: Message-ID: <4BWba.125523$Hl6.11175389@news010.worldonline.dk> William Sonna wrote: > Because the person(s) who decide the language refuse to face up to the > fact that they screwed up by not including it. Its an obvious flaw that > dogma prevents from being corrected. What are you on about? I have never had the need to use the do...while construct in all the years I have been using Python. Everything in the language is designed so that they fit with the while and the for loops. The language clicks with the features it has. Not a flaw at all! I have used several other languages where there is a lot of different loop constructs. This does not make them any better. All you do is end up with 1-off errors all the time. Which you very rarely have in Python. -- hilsen/regards Max M Rasmussen, Denmark http://www.futureport.dk/ Fremtiden, videnskab, skeptiscisme og transhumanisme From aleax at aleax.it Mon Mar 17 06:08:48 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 17 Mar 2003 11:08:48 GMT Subject: Question about embedding Python References: Message-ID: <41ida.99508$zo2.2641302@news2.tin.it> Del Iablo wrote: > I've got Python running and working with my engine, to the point that I > can define variables in Python scripts, run them with my C++ code, and > then get those variables for run-time use in the C++ code. > > In order to do this I've tried encapsulating the Python variables inside a > script variable structure in the C++ code, called ScriptVariable. This > struct contains a PyObj pointer to the variable in the dictionary. I can > then do runtime conversion (e.g., PyInt_AsLong) to get the value. Do you Py_INCREF the PyObject* you're holding? If not, then there is no guarantee that the corresponding Python object will stay alive -- when the reference count of a (classic-)Python object goes to 0, Python can destroy that object (and potentially reuse its memory for other objects, but not necessarily so). From the symptoms you describe below, it sure looks like that's what's happening to you. > The reason for this eludes me. Is Python actually creating two variables, > or is it dereferencing the previous variable, causing it to be destroyed? Names, in Python, are just "post-it notes" that can be transiently attached to an object or another. "Assignment" (also known as binding) attaches a name to an object (detaching it from any other object that the name might be referencing earlier, if any). > I'd like to avoid doing the dictionary lookup every time if possible. Am I > just stuck doing it every time? If you want to know what object (if any) a name is attached to "right now", then there is indeed no alternative to asking the appropriate namespace (a dictionary) about that. Your question is somewhat analogous to saying, "if I have a C pointer, I would like to avoid dereferencing it every time if possible, am I just stuck doing it every time?" -- it sounds somewhat surprising to describe the very reason one might want to hold a pointer, rather than the pointed-to object, as "stuck with"... that is, yes, of course, if what you want to know is, to what value is this pointer pointing to *right now*, then obviously you do have to dereference the pointer -- I wouldn't call that being "stuck with" anything, but the dereferencing is indeed needed every time if you do want to know the CURRENT situation. If what you want to know instead is the situation at some given time in the past, then you do have the alternative of getting a copy of the value being pointed to (hold on directly to the object being referenced, in Python's case) -- but then of course if the pointer changes (if the variable name gets detached from an object and attached to another) you'll still be using the "old" value (object). Alex From exarkun at intarweb.us Tue Mar 11 13:44:53 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 11 Mar 2003 13:44:53 -0500 Subject: deepcopy problem In-Reply-To: References: Message-ID: <20030311184453.GB23722@meson.dyndns.org> On Tue, Mar 11, 2003 at 10:03:29AM +0000, Stephen C Phillips wrote: > Hi, > I have refined my problem and have a smaller example now. I have a > class called 'Node' which is a new-style class and has a name and a > 'neighbour' which is another Node object. I make a node 'n' and a node > 'm' and point n at m AND m at n, so n.neighbour.neighbour is n. I then do > a deepcopy of n into x. This of course makes a copy of m too. I then > print x (and it looks just like n) but the dictionary of > x.neighbour.neighbour is empty and x.neighbour.neighbour is not x. > If I make Node an old-style class (by just using "class Node:") then it > all works fine and x.neighbour.neighbour is x. I am using Python 2.2.2. > Can anyone explain what difference between old and new-style classes causes this > please? > Once again, the __getstate__() and __setstate__() methods are in there > just to help diagnose the problem and the code works the same without > them. > > Thanks. > I think the essense of this problem can be distilled thusly: import copy class Foo(object): pass f = Foo() f.foo = f g = copy.deepcopy(f) "f.foo is f" is True, while "g.foo is g" is False. I believe this to be a bug in the pickle module, one which is fixed in 2.3. There seems to be a work-around in 2.2, though I haven't explored its behavior very thoroughly: import copy class Foo(object): pass f = Foo() f.foo = f memo = {id(f): f} g = copy.deepcopy(f) Now, "g.foo is g" is True. Hope this helps, Jp -- "There is no reason for any individual to have a computer in their home." -- Ken Olson, President of DEC, World Future Society Convention, 1977 -- up 8 days, 9:59, 8 users, load average: 0.00, 0.05, 0.07 From charts at purdue.edu Mon Mar 24 17:13:31 2003 From: charts at purdue.edu (richard.a.charts.1) Date: Mon, 24 Mar 2003 17:13:31 -0500 Subject: Center new windows Message-ID: Hi, I have a fairly quick question that I haven't been able find the answer for. When opening a new window, how can I force it to open in the center of the screen? I have searched through old messages but most are over 2 years old and I am wondering if there has been changes for the better? On a small side note: How does geometry work with a given widget? Whenever I try to use it, Python says that some class has no instance of geometry or withdraw or others for that matter. Thanks From daniel.dittmar at sap.com Mon Mar 3 07:22:56 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Mon, 3 Mar 2003 13:22:56 +0100 Subject: Why no RE match of A AND B? References: <3E6270DC.3060904@tiscali.co.uk> <_Fw8a.106840$Hl6.9851028@news010.worldonline.dk> <3E629E43.D8661813@alcyone.com> <3E62A8BD.BB7A7CA6@alcyone.com> <3e6317e7$0$16108$edfadb0f@dread11.news.tele.dk> <3E6321E3.C43FBAF2@alcyone.com> Message-ID: Erik Max Francis wrote: > obviously. That is, I don't hear a lot of people clamoring for such > functionality, so it's probably not really high on anyone's list. > (This is the first time I've ever heard of someone suggesting such a > feature in many years' use of regular expressions.) The old IBM editors allowed to search for multiple words in any order, but it was not based on regular expressions. If I remember right, it was used mainly when you couldn't remember if a variable was 'string_length' or 'length_of_string', so it's more for interactive use than for writing programs. Daniel From alev0000 at stud.uni-sb.de Tue Mar 25 08:26:39 2003 From: alev0000 at stud.uni-sb.de (A. A. Golownew) Date: 25 Mar 2003 05:26:39 -0800 Subject: n-ary tree widget References: Message-ID: <6ffd7649.0303250526.523e3d9b@posting.google.com> > For my particular application nodes can have references to other > nodes in the tree... for example > > * > /| > / | > / | > ------------- > | / | | | > |/ | | | > * * * * > > notice the first node in the 2nd row points to the root. This shouldn't be any problem with VCG/aisee. Both of them allow specifying edge "priorities", with edges of higher priority being preferred when calculating the tree (graph) layout. Just give all edges in the tree a high default priority (say, 100). Then, if you give the additional references a lower priority (say, 5), they won't destroy the tree layout, no matter how many of them you specify and in which direction. With VCG/aisee, you can also specify different edge classes, which you can then interactively hide/display, see http://www.aisee.com/graph_of_the_month/cfg.htm > any node in the tree should be able to point to any number of nodes. No problem at all. > Also I need to bind keyboard events to each node in the tree Uuh... I am not sure, this could work with newer versions of aisee (they allow some kind of "user actions", see http://www.aisee.com/manual/unix/49.htm). I dont think VCG support any of these. > and text based information on each node. VCG/aisee allow up to three additional information windows to be associated with each node (apart from the node label and the node title). > it should be able to expand / collapse the nodes interactively With aisee, you can expand/collapse arbitrary node/edge groups both statically and interactively. Not sure about VCG. Cheers, Al. From b.maryniuk at forbis.lt Fri Mar 28 15:32:20 2003 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Fri, 28 Mar 2003 22:32:20 +0200 Subject: HTML / DOM Message-ID: <200303282232.20641.b.maryniuk@forbis.lt> Hello, all. Can anybody drop me a real code how to work with DOM in _HTML_ which is even not XHTML? I took a look over 4DOM but unfortunately documentation there is too silly. :( Well, for example, I have a HTML string:

Text here bar

Now, how to build a DOM from this chunk to do the following: 1. Fetch somehow a "name" attribute from the "" tag 2. Change it (not a "bar", but a "foo" value!) 3. Push it back to the same place 4. Return modified HTML back as string without doctype and so on. Any ideas? I know how to work with XML, but HTML-stuff drives me crazy since it does not XML. Yes, I've tried to RTFM and STFW, but now I gave up -- this all does not work as I need. What I need to do with it. I have a HTML's where I need to found all the tags which contains Unicode data in the "name" attribute and urllib.quote() it than return this HTML back. But how to do it with DOM in HTML -- I have no idea, since this is not XML... :( Thank you for any help and any *working* ideas and examples. :) -- Regards, Bogdan If vegetarians eat vegetables, what do humanitarians eat? From peter at engcorp.com Sun Mar 30 09:32:06 2003 From: peter at engcorp.com (Peter) Date: Sun, 30 Mar 2003 09:32:06 -0500 Subject: A default in the __init__ is like a class variable? References: <35404b41.0303300501.27ae4054@posting.google.com> Message-ID: <3E86FFE6.F2157315@engcorp.com> Jens Gelhaar wrote: > > Is this a feature? > > >>> class test: > ... def __init__(self,t=[]): > ... self.t=t > > I know why both t has the same list, but I would not expect this. Each > instance should have it's own list. As Just said, plus this fix to your "buggy" code: :-) >>> class test: ... def __init__(self,t=None): ... if t is None: t = [] ... self.t=t The rule is "Don't use mutables for default arguments unless you want the 'unexpected' behaviour." It's a fairly simple rule... -Peter From robin at alldunn.com Fri Mar 7 20:04:29 2003 From: robin at alldunn.com (Robin Dunn) Date: Fri, 07 Mar 2003 17:04:29 -0800 Subject: ANNOUNCE: wxPython 2.4.0.4 Message-ID: <3E69419D.7060100@alldunn.com> wxPython 2.4.0.4 is now available for download at http://wxpython.org/download.php wxPython is a popular cross platform GUI toolkit for the Python language that supports running Python apps on Win32, Mac OSX, and Linux/Unix systems, using native widgets and therefore natiove look and feel on the respective plafroms. From the webpage given above you can download source code, documentation and pre-built wxPython packages for various platforms and for various versions of Python (2.1, 2.2 or 2.3, except for OS X which only has a build for 2.3) Here is a list of changes since the last release: 2.4.0.4 ------- Added missing wxRect methods Add OOR support for wxApp objects too. Added wxCursorFromImage, which works on wxMSW and wxGTK so far. All platforms now send EVT_DESTROY_WINDOW. Be warned that at the time the event is sent the window is in the process of being deconstructed, and so calling some (most?) methods of the window itself may cause problems. Fixed SF Bug #689481, a method in the OGL wrappers was using the wrong return type. Fixed SF Bug #689958, an endless loop in printout.py. Added EVT_WINDOW_CREATE_ID and EVT_WINDOW_DESTROY_ID so these events can be associated with a specific window ID and more easily caught by the parent window. Fixed copy-paste error in wxListCtrl.GetFirstSelected. Added missing Init method (and an overloading wrapper) to wxLocale wrapper. Added a wxBitmap.SetMaskColour convenience method. Changed how the dynamic event tables (used for all Python wx classes, C++ wx classes typically use static event tables) are searched such that they behave from a Python perspective more like the static tables in C++. Namely that if there are identical event bindings in a base Python class and a derived Python class that the one in the derived class will be found first and that if Skip is called that the one in the base class will still be found instead of skipping directly to the static stable in the C++ class. Switched to using True/False in the wxPython lib and demo instead of true/false or TRUE/FALSE to prepare for the new boolean type and constants being added to Python. Added code to wx.py to test for the existence of the new constants and to create suitable values if not present. Added some static wxApp functions that help with integration with the Mac UI. They are no-ops on other platforms so it doesn't hurt to always call them. The functions are: wxApp_GetMacDefaultEncodingIsPC wxApp_GetMacSupportPCMenuShortcuts wxApp_GetMacAboutMenuItemId wxApp_GetMacPreferencesMenuItemId wxApp_GetMacExitMenuItemId wxApp_GetMacHelpMenuTitleName wxApp_SetMacDefaultEncodingIsPC wxApp_SetMacSupportPCMenuShortcuts wxApp_SetMacAboutMenuItemId wxApp_SetMacPreferencesMenuItemId wxApp_SetMacExitMenuItemId wxApp_SetMacHelpMenuTitleName Refactored, enhanced and added capabilites for the DrawXXXList functions, inspired by code from Chris Barker. The wxWindows .mo language catalog files are now installed in a subdirectory of the wxPython package dir on MSW since that platform doesn't have a standard place for them. Added missing deselect methods for wxGrid. Fixed typemaps for wxGridCellCoordsArray. Updated to the 0.9a version of PyCrust -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From me at privacy.net Mon Mar 24 18:25:08 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 25 Mar 2003 11:25:08 +1200 Subject: adjacent differences with a list comprehension In-Reply-To: <5fLfa.2501$FO3.237536@news20.bellglobal.com> References: <69413f9.0303241331.62f0295f@posting.google.com> <5fLfa.2501$FO3.237536@news20.bellglobal.com> Message-ID: Sean Ross wrote: > This will do what you're looking for: > > def adjacentdiffs(seq): > return [ x - y for x, y in zip (seq[1:], seq[:-1]) ] While that works, I think it obfuscates what's being done rather more than necessary. I would suggest: [seq[i+1] - seq[i] for i in xrange(len(seq) - 1)] It's a bit more efficient to boot, since it avoids constructing an intermediate list of tuples. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From davecook at nowhere.net Sat Mar 8 20:29:35 2003 From: davecook at nowhere.net (David M. Cook) Date: Sun, 09 Mar 2003 01:29:35 GMT Subject: GUI Toolkits References: Message-ID: <3Owaa.3904$1f.908@news2.central.cox.net> In article , Thomas G. Willis wrote: > I wanted to know if there are any reccomended GUI toolkits for python. > I've played around with Tkinter a little bit and I haven't noticed > anything like treeviews and listviews, so it seems a little incomplete. pygtk2 has treeviews and listviews, and it would be my choice, but is not very well documented. See http://www.async.com.br/faq/pygtk/index.py?req=all Dave Cook From martin at v.loewis.de Wed Mar 26 16:06:57 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 26 Mar 2003 22:06:57 +0100 Subject: how to use IPv6 Socket in Windows by python References: Message-ID: KANG JI-HUN writes: > I want to use IPv6 Socket in Windows by python . i can use IPv6 > Socket in Linux but i can't use one in Windows after i run IPv6 > Stack in Windows when i tried to use IPv6 Socket. but it couldn't > use IPv6 Socket. You need to recompile Python (or atleast the socket module) on Windows to use IPv6. For that, you need Visual Studio .NET, as VC++ 6 does not support IPv6 (and VC++ 6 was used to compile Python 2.2) (alternatively, you can use the Windows SDK+VC++6; this also supports IPv6). HTH, Martin From wge at wakalaka.com Fri Mar 21 23:42:20 2003 From: wge at wakalaka.com (wqe) Date: Sat, 22 Mar 2003 04:42:20 GMT Subject: cgitb for the console. [how to use] References: Message-ID: On Sat, 22 Mar 2003 04:24:52 +0000, wqe wrote: > I think cgitb is a great tool. Before things like boa came along, I used > it heavily for debugging. Anyway, I saw no reason that console error > mechanism should be worse than cgitb, so I cosmetically hacked through it > to stop outputting html. > > Anyway, I think the python community process could help improve this code > so that it could eventually be part of the normal console error mechanism. > > Code here: > > http://home.sus.mcgill.ca/~hperes/contb.py > > Please send patches and explanations to hunterp at CONFUSESPAMBOTS fastmail.fm As I said, the changes are cosmetic. So just like cgitb: http://python.org/doc/2.2/lib/module-cgitb.html http://python.org/doc/2.2/lib/node302.html you would: import contb.py contb.enable(1) #BOMBS away!! From max at alcyone.com Sat Mar 29 19:30:22 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 29 Mar 2003 16:30:22 -0800 Subject: Is Python overhyped (just like Java)? References: Message-ID: <3E863A9E.AA529B55@alcyone.com> Roy Smith wrote: > Gerhard Haring wrote: > > > I couldn't care less about which programming language you use. So I > > propose you do some internet research yourself. > > Seems to me, that's what he was doing :-) Well, it's one thing to seek independent analysis of whether Python or C++ would be a better choice for a particular task or mindset, but it's quite another to step into a community and demand that they prove to you that their language of choice is "overhyped." After all, someone inclined to research such an issue should be well aware that such a discussion has taken place many, many times in the past and would look to Google searches or articles on the Web about the issue, rather than boldly state, "Hey, I heard your language sucks, prove me wrong!" So yeah, I'd say that passive research would have been the better way to approach his needs. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Human love is often but the encounter of two weaknesses. \__/ Francois Mauriac PyUID / http://www.alcyone.com/pyos/uid/ A module for generating "unique" IDs in Python. From skip at pobox.com Mon Mar 10 09:37:49 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 10 Mar 2003 08:37:49 -0600 Subject: bsddb crashes on windows In-Reply-To: <5.1.0.14.0.20030310110131.00bc4680@131.103.204.244> References: <15976.47138.80321.755378@montanaro.dyndns.org> <20030307020101.12244.35865.Mailman@mail.python.org> <5.1.0.14.0.20030307105920.01a36010@131.103.204.244> <5.1.0.14.0.20030310110131.00bc4680@131.103.204.244> Message-ID: <15980.41789.847677.666580@montanaro.dyndns.org> Vijay> I tried using bsddb3-4.1.0.win32-py2.2.exe on WinXP with Python Vijay> 2.2.1. Iterating through a btree seems to be resulting a in open Vijay> Handles ( viewable in processes , Windows Task Manager ). About 1 Vijay> handle per 20 entries in the database is added and it is not Vijay> freed even when the db is closed.... It looks like you filed a bug report about this with the pybsddb.sf project. That's probably the best place to get an answer/fix. Skip From pprok at softlab.ece.ntua.gr Sun Mar 2 17:06:55 2003 From: pprok at softlab.ece.ntua.gr (Panayotis Prokopiou) Date: Mon, 03 Mar 2003 00:06:55 +0200 Subject: PyGTK-2 Full-Screen mode. In-Reply-To: References: <14bd1399.0303021258.67171d44@posting.google.com> Message-ID: <3E62807F.2060800@softlab.ece.ntua.gr> oups :-) i'm terribly sorry. I've just messed it up. From do-not-spam-ben.hutchings at businesswebsoftware.com Wed Mar 26 05:49:00 2003 From: do-not-spam-ben.hutchings at businesswebsoftware.com (Ben Hutchings) Date: 26 Mar 2003 10:49:00 GMT Subject: Converting time from GMT to another timezone References: Message-ID: In article , Stuart Bishop wrote: > Unfortunatly, there is no way to do timezone conversion stuff under Unix > that doesn't suck. Work is underway to provide these sucky ways in > Python 2.3. > Rumour has it that Windows provides a richer interface for timezone > stuff, but it appears to be a secret. It's a bit better, but it still sucks. Windows will only tell you whether daylight savings apply now, not at some other point in time. It does provide the current DST rules so you can apply them yourself, but those might not be the same rules that were used in some previous year in the same political time zone. From alloydflanagan at attbi.com Thu Mar 13 10:23:33 2003 From: alloydflanagan at attbi.com (A. Lloyd Flanagan) Date: 13 Mar 2003 07:23:33 -0800 Subject: Flying With Python (Strong versus Weak Typing) References: <37a869bc.0303102102.4533973@posting.google.com> Message-ID: "Greg Ewing (using news.cis.dfn.de)" wrote in message news:... > A. Lloyd Flanagan wrote: > I don't think it's fair to blame the complexity and > messiness of C++ on the idea of a parametric type > system. The messiness of templates > in C++ is mostly due to the grotty syntax chosen and > the way they interact with other complicated and > messy features of the language. > > There are languages with parametric type systems > (e.g. Haskell, Eiffel) where it doesn't seem to lead > to any of those problems, You're undoubtedly right. Still, I now think the notion of type should be 'an object which supports these operations', not 'an object that inherits from this object (or objects)'. If I've got an object that implements read(), I want to be able to use it in a function that calls read() on a parameter, without requiring the object and parameter to both inherit from the same class. You end up doing a lot of inheritance, and defining extra interfaces, just to keep the compiler happy. In fact, just like templates, the whole concept of an interface in Java exists to give capabilities to the programmer that the strong typing took away. From mail at manuelmgarcia.com Sun Mar 9 23:57:19 2003 From: mail at manuelmgarcia.com (Manuel M Garcia) Date: Mon, 10 Mar 2003 04:57:19 GMT Subject: add an indent to a stream Message-ID: I often need to add an indent to a stream, usually so the output of pprint or traceback is indented so I can tell debugging output from my program's actual output. Below is a class to help do this. I think I got the details right. The 'print' statement, when used with commas, is more complicated than I thought. What is the exact rule for when the 'print' command inserts a space because of a comma? I guess it has something to do with the attribute 'softspace'. I played around with the code from Alex Martelli's explination of 'softspace' http://groups.google.com/groups?as_umsgid=nXqA8.92311%24vF6.2766580 at news2.tin.it It looks like 'softspace' is strictly to help 'print', it really can't help me know when I am at the beginning of a line, because the 'print' statement set it at the 'wrong' time. Manuel # ################## # # indentstream.py import sys class IndentStream: """Stream with indent at start of each line. Indent can be a string or the number of spaces you wish to indent. """ def __init__(self, indent=' ', stream=None): if stream is None: self._stream = sys.stdout else: self._stream = stream try: indent = ' ' * indent except TypeError: pass self._indent = indent self._nl_indent = '\n' + indent self._indent_size = len(indent) self._comma = 0 self.softspace = 0 def write(self, s): comma = not s.endswith('\n') s = s.replace('\n', self._nl_indent) if not self._comma: s = self._indent + s if s.endswith(self._nl_indent): s = s[:-self._indent_size] self._stream.write(s) self._comma = comma if __name__ == '__main__': print 'hello' print 'hello2' print print 'hello again' print 'comma', 'comma', print print 'comma2','comma2', print print 'goodbye' print 'fiddle', print '', print 'sticks', print '!' print 'crumbs', print 'with nl\n', print 'crumbs' print 'goodbye again', print '\n', print 'goodbye again2' _indentstream = IndentStream(4) print >> _indentstream, 'hello' print >> _indentstream, 'hello2' print >> _indentstream print >> _indentstream, 'hello again' print >> _indentstream, 'comma', 'comma', print >> _indentstream print >> _indentstream, 'comma2','comma2', print >> _indentstream print >> _indentstream, 'goodbye' print >> _indentstream, 'fiddle', print >> _indentstream, '', print >> _indentstream, 'sticks', print >> _indentstream, '!' print >> _indentstream, 'crumbs', print >> _indentstream, 'with nl\n', print >> _indentstream, 'crumbs' print >> _indentstream, 'goodbye again', print >> _indentstream, '\n', print >> _indentstream, 'goodbye again2' import inspect import pprint import StringIO import tokenize import token _readline = StringIO.StringIO( inspect.getsource(inspect.getsource)).readline _pprint = pprint.PrettyPrinter( indent=4, stream=IndentStream('??????? ')).pprint def _(x): t = list(x[:4]) t[0] = token.tok_name[t[0]] if t[0] == 'STRING': t[1] = t[1].split('\n') return tuple(t) _pprint([ _(x) for x in tokenize.generate_tokens(_readline) ]) From gh at ghaering.de Sun Mar 2 08:38:42 2003 From: gh at ghaering.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 2 Mar 2003 13:38:42 GMT Subject: Simple question, how can i create a record? References: <1046608880.565095@seux119> Message-ID: EleKtR0 wrote: > Hi! > > i'm reading a good manual about Python to learn it. > it has an example where uses a module named "record" to import a class named > "record". > With record class i can create records on Python, but i'm not find the > record module. [...] There is indeed no 'record' module in the standard Python library. Perhaps the record module was implemented earlier in your tutorial text? Gerhard -- mail: gh at ghaering.de web: http://ghaering.de/ From andy at wild-flower.co.uk Tue Mar 25 17:45:34 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Tue, 25 Mar 2003 22:45:34 +0000 Subject: Is Python the Esperanto of programming languages? In-Reply-To: References: <9lBfa.217$Jg1.4622@news1.tin.it> Message-ID: <200303252245.34894.andy@wild-flower.co.uk> Pythonistas, I never intended to provoke a huge off-topic thread, with my little throw-away remark... If it's all got too off-topic, maybe we should spawn a new sub-group, maybe comp.lang.python.esperanto.sux ... ? :-) Hopefully this won't spawn another 78-odd messages, though! We could always take over an empty humanities.language sub-group (if there were one)... But it's been interesting following the ways the thread has developed. I think it says something rather nice about this newsgroup. I've largely refrained from adding fuel to the fire... but I can't let this (final) thought go: Do any of you know sign-language? My misses is learning British Sign Language, mostly simple stuff at the moment, but we were discussing her most recent lesson, and it occurred to me that BSL (and maybe ASL too) seem to be much more regular than English. Sam (the misses) hasn't done much with tenses yet, but seems to think that they are expressed explicitly. Of course, there are no inflections, nor any tonality. The 'redundancy' that the signs lack is made up for by the prescribed lip and face movements associated with each sign - derived from the English pronunciation - that disambiguate similar looking signs. The word ordering seems to be quite free, but there is also a sort of 'right' way to say things, that 'sounds' better. Purely out of interest, Sam is going to emai her tutor to ask about the accuracy of all the above. Are there any signing Pythonistas out there? I'd like to know your take on this, particularly if you use a sign language that is not BSL, ASL or Macaton. I'm just guessing, but I'm sure there must be a Chinese Sign Language... does that share common ground with ASL and BSL? Gotta slither, regards, andyj From andrea_galimberti at tin.it Tue Mar 4 08:11:09 2003 From: andrea_galimberti at tin.it (Andrea Galimberti) Date: Tue, 04 Mar 2003 14:11:09 +0100 Subject: ANN: Leo 3.11b1 outlining editor Message-ID: <3E64A5ED.3060708@tin.it> Edward K. Ream wrote: >I hope these hints will be enough for you to do what you want. I'll be >happy to answer further questions if you get stuck. When you get >something >that works please post your solution here. Thanks. Thank you for your hints. I completed the new version of the plugin. Now if the node contents are changed in the outline the temporary file is discarded, recreated and opened in VIM. Here I have pasted the output of the "Write @file nodes" command. Hope this format is suitable for you. \bye, Andrea ----------- plugin --------------- #@+leo #@+node:0::@file mod_vim.py #@+body #verbatim #@ignore #@@language python #@<< mod_vim declarations >> #@+node:1::<< mod_vim declarations >> #@+body """vim handler""" # Contributed by Andrea Galimberti. # To use this plugin do the following: # # - Start VIM as server: vim --servername "VIM" # The name of the server *must* be "VIM". # # - Single-click on a node's icon to open that node in VIM. # # - Leo will update the node in the outline when you save the file in VIM. from leoPlugins import * from leoGlobals import * import os,tempfile #@-body #@-node:1::<< mod_vim declarations >> #@+others #@+node:2::open_in_vim #@+body def open_in_vim (tag,keywords): if top(): v=keywords['v'] # find dictionary with infos about this node this=filter(lambda x: id(x['v'])==id(v), app().openWithFiles) # retrieve the name of the temporary file (if any) if this != []: path=this[0]['path'] else: path='' if os.path.exists(path): # get previous node contents try: old=v.OpenWithOldBody except AttributeError: old='' # if something changed if v.bodyString() != old: # delete old temp file os.remove(path) # remove old temp file from list app().openWithFiles=filter(lambda x: x['path']!=path, app().openWithFiles) # update old body with new contents v.OpenWithOldBody=v.bodyString() # open the node in vim (note the space after --remote) top().frame.OnOpenWith(("os.system", "vim --remote ", None)) #@-body #@-node:2::open_in_vim #@-others if 1: # Register the handlers... registerHandler("iconclick2", open_in_vim) es("...vim v1.2") #@-body #@-node:0::@file mod_vim.py #@-leo -----------------------------------END----------------------------------- From andrews at pcug.org.au Fri Mar 7 20:38:59 2003 From: andrews at pcug.org.au (Avery Andrews) Date: Sat, 08 Mar 2003 01:38:59 GMT Subject: Psyco and method calls Message-ID: Does anyone know if psyco does a good job of speeding up calls to methods of objects defined in extension modules? What this is apropos of is the possibility of using Python to split up a Delphi program into bits that can be independently rewritten in a platform-independent way. I'm presuming that normal Python method calling is much slower than in Delphi or C++, tho I'll confess that I don't know much about anything. Thanks, Avery Andrews From google.com at magicdb.com Sun Mar 9 14:44:30 2003 From: google.com at magicdb.com (Muppet) Date: 9 Mar 2003 11:44:30 -0800 Subject: Persistence Woes. Message-ID: <9418460a.0303090108.db49a99@posting.google.com> Persistence is giving me major grief. The problem is that stuff which should "obviously" work doesn't. I got into considering the whole mess trying to fiddly with Shelve so that rather than copying all of my sub-objects, they'd come out with references intact. If there's a smart way of doing that, it's so well known that I couldn't find it written down, nor find a way of doing it. I'm kinda hoping that somebody will post a fifteen line hack which takes care of it nicely, but I'm not holding my breath :-) Cog seems very promising, but I can't install new DB libraries on my deployment environment (production webservers), and it's dependent on bsddb. ZODB is overkill, really. Object Prevaylance works poorly in a CGI environment, and I was hoping to at least offer the option of running as a CGI. So, here's what I'd like to see in a lightweight persistence framework. 1> A dictionary-style interface, like Shelve. 2> Objects referenced by multiple other stored objects come back from storage as independent objects. 3> Some notion of being able to identify object graphs and operate on them (being able to pull out everything a given object depends on except items already in a given list, for example) 4> Options for storing objects in an SQL database, working with SQL-style keys to identify which objects are stored where, one object per row. (I'm thinking of a table with a key and a string, as a standard alternative to files, for storage of objects) How hard can it be? From staschuk at telusplanet.net Fri Mar 21 15:13:35 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Fri, 21 Mar 2003 13:13:35 -0700 Subject: help with (x)html / xml encoding... In-Reply-To: <3e7aeeca$0$29147$626a54ce@news.free.fr>; from glt2010pas.de.spam@yahoo.fr on Fri, Mar 21, 2003 at 11:55:05AM +0100 References: <3e7a47f1$0$29135$626a54ce@news.free.fr> <3e7aeeca$0$29147$626a54ce@news.free.fr> Message-ID: <20030321131335.D5100@tibia.amotlpaa.bogus> Quoth lt: [...] > and in python i do : > >>> import urllib > >>> sock = urllib.urlopen('http://192.168.0.1/example.html') > >>> sock.info().getencoding() > '7bit' That's the content transfer encoding of the HTTP message, which is a MIME thing to describe how the bytes of the content have been encoded for transmission over the network. 7bit is the default. In full MIME, binary files might be, for example, base64-encoded for transport over unclean protocols; HTTP is binary clean, so the problem doesn't really arise. If this seems like gobbledygook, forget it; it doesn't matter. The point is that it has nothing to do with the character set used in the text of the content, if it is text. What you want is this: >>> s = urllib.urlopen('http://zvuki.ru/A/P/6655/') >>> s.info().dict['content-type'] 'text/html; charset=windows-1251' -- Steven Taschuk staschuk at telusplanet.net "Telekinesis would be worth patenting." -- James Gleick From gherron at islandtraining.com Sun Mar 2 14:11:34 2003 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 2 Mar 2003 11:11:34 -0800 Subject: Strange regex problem In-Reply-To: References: Message-ID: <200303021111.35316.gherron@islandtraining.com> On Saturday 01 March 2003 02:11 pm, Dagur P?ll Ammendrup wrote: > Hi, > > I have this code: > > p = re.compile('') > m = p.search(file) > while m: > begin = m.end() > match = m.group(1) > n = re.search('' % match,file,begin) > locations.append((match,begin,n.start())) > m = p.search(file,begin) > > It works and everything but when I run it I get a long list of The full answer has come out in pieces here, but I'll put it all together. The problem is a mistaken use of a module function (re.search) and a collision with an undocumented flag SRE_FLAG_DEBUG. As noted by others, the third parameter of re.search is not a search position, but a collection of flag bits. So this code, using "begin" as that argument can potentially turn on or off any of those bits depending on the bit pattern of its value. The documented flags are re.IGNORECASE, re.LOCALE, re.MULTILINE, re.DOTALL, re.UNICODE, and re.VERBOSE, but the code recognizes two undocumented flags, one of which is called SRE_FLAG_DEBUG (having value 128). So when the value of "begin" has that particular bit set, set SRE_FLAG_DEBUG on and so get the debug output. I have just (last week) volunteered to take over maintenance of the regular expression code, so I'll think about fixing this, but it's not clear to me what a fix should entail. * Document the flag. * Ignore the flag. * Raise an exception for any flag bit other than the document flags. * Others? Gary Herron From endymion at myrealbox.com Mon Mar 3 19:26:06 2003 From: endymion at myrealbox.com (TuxedoKamen) Date: Tue, 04 Mar 2003 00:26:06 -0000 Subject: Generating XML. Message-ID: Hello. I have a program that needs to do the following: 1. Reads an XML file using the minidom interface 2. Proceeds to present the information to the user for viewing 3. Allows the user to update the information if desired 4. If user made any changes, saves updated information to XML file. I'm familiar with how to do one, two, and three, but four has me a little confused. I am assuming it is possible to manipulate the various nodes of the dom tree as necessary (this would certainly make editing the XML easy), but I don't see any mention of exporting the tree to an external textfile. Is this possible? If not, what's the best way to get a DOM tree out of an application and into a text file? From imbosol-1048743253 at aerojockey.com Thu Mar 27 01:16:50 2003 From: imbosol-1048743253 at aerojockey.com (Carl Banks) Date: Thu, 27 Mar 2003 06:16:50 GMT Subject: Conjugate gradients minimizer References: <3K9ga.7304$kU.2710@nwrdny01.gnilink.net> Message-ID: Gareth McCaughan wrote: > Carl Banks wrote: > >> But let me recommend something else. You have only a thousand >> variables, which is really not a lot. Conjugate gradient is best >> suited for systems of millions of variables, because it doesn't have >> to store a matrix. It doesn't scale down well. >> >> So, unless you have reason to believe conjugate-gradient is specially >> suited to this problem (indeed, I have heard of an atomic structure >> problem that was like that), or if you plan to scale up to DNA >> crystals someday, use the BFGS method instead. > > I concur. If it turns out that the overhead from BFGS > *is* too much for some reason, you might also consider > something intermediate between conjugate gradient and > BFGS, such as L-BFGS. > > But it's not true that BFGS requires inverting a matrix > at each step. The matrix you maintain is an approximation > to the *inverse* of the Hessian, and no inversion is > necessary. Oh, silly me. I probably said that but just intended to mean "you have to store an NxN matrix." I never heard of L-BFGS, though. I admit I got my optimization knowledge from 20-year-old texts. -- CARL BANKS From dave at pythonapocrypha.com Mon Mar 3 12:55:20 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Mon, 3 Mar 2003 09:55:20 -0800 (PST) Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... In-Reply-To: References: <8fb66v8qbv45eatnblq80p131793ej7e3m@4ax.com> <6zK8a.268598$0v.7396380@news1.tin.it> Message-ID: On Mon, 3 Mar 2003, Alexander Schmolck wrote: > Alex Martelli writes: > > > Jack Diederich wrote: > > ... > > > I'm a big functional programming fan, but most python user's aren't. > > ... > > > filter() and only two dozen [very simple!] list comprehensions. > > > > So I guess your "functional programming" enthusiasm doesn't come > > from Haskell > > I don't think that follows. Python's list comprehensions are different -- they > pollute the namespace. Oh, c'mon. This is a frequently cited yet overstated wart. Yeah, technically it's a problem, but much more a theoretical than practical one - in practice the only time it causes problems is when you're doing something questionable anyway, like reusing a variable without initializing it to some known value. It's a nit rather than a real divergence from Haskell's list comps. -Dave From cappy2112 at yahoo.com Sun Mar 2 21:19:52 2003 From: cappy2112 at yahoo.com (Tony C) Date: 2 Mar 2003 18:19:52 -0800 Subject: Using an operator as an object Message-ID: <8d3e714e.0303021819.24f1aa38@posting.google.com> Does Python have the ability to pass an operator (+,/,- etc) as an object (not a string), so I don't have to use an if for each operator , as in the first function below ? def docalc( operator, num1, num2): if( operator == "+") : return( num1 + num2) if( operator == "-") : return( num1 - num2) What I'd like to do is this def docalc( operator, num1, num2): return (num1 operator num2 ) Of course- the correct type of object would have to be passed in. thanks From martin.vonloewis at hpi.uni-potsdam.de Mon Mar 31 11:13:04 2003 From: martin.vonloewis at hpi.uni-potsdam.de (Martin v. Löwis) Date: Mon, 31 Mar 2003 18:13:04 +0200 Subject: using a private embedded python References: Message-ID: > here's another way to ask the same question... can you have two seperate > versions of 2.2.2 on the machine at the same time? on windows? on unix? No problem at all; this works out of the box, with no recompilation required. Regards, Martin From mwh at python.net Tue Mar 18 07:27:10 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 18 Mar 2003 12:27:10 GMT Subject: PEP 312 (and thus 308) implemented with a black magic trick References: <2259b0e2.0303171358.5a6fe337@posting.google.com> Message-ID: <7h3n0jsj1wh.fsf@pc150.maths.bris.ac.uk> mis6 at pitt.edu (Michele Simionato) writes: > Today I had an illumination on how to implement both PEP 312 and 308 > in current Python. I think I will share the idea, even if I would *not* > recommend to use such a dirty trick in production code. Do you know about my bytecodehacks? They might appeal to your hackerish instincts... I once proposed an "explosive license" for things like this: if you use them in production code, your shoes explode. Cheers, M. -- 42. You can measure a programmer's perspective by noting his attitude on the continuing vitality of FORTRAN. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From ulope at gmx.de Sun Mar 30 07:43:07 2003 From: ulope at gmx.de (Ulrich Petri) Date: Sun, 30 Mar 2003 14:43:07 +0200 Subject: import package w/ all subpackages? References: Message-ID: "Your Mom" schrieb im Newsbeitrag news:f9sha.3283$yh1.433534 at news1.east.cox.net... > There doesn't seem to be a built-in way to import a package w/ all it's > subpackages & modules. Does anyone else see value in adding a statement > like "import fully foolib"? > > I've developed a package that (in trying to keep its contents organized > properly) has ended up with a number of modules & subpackages. Currently, a > typical program attempting to use my package needs to run 'import > foolib.foo, foolib.bar, foolib.baz' for each component to be used. I've > determined that i *could* make things easier by adding 'import foo, bar, > baz' in the __init__.py file; however, this forces all programs using a > single component from the package to import them all, requiring that any > depency of any of those components be installed. Wouldn't it be nice to for > scripts that want everything in a package to be available for use to say > something along the lines of "import fully foolib", while letting other > scripts pick modules ala cart? Just a thought, anyway... Hi, imho you should put the imports into __init__ since one can still select if he does not want to import all stuff by means of: from foolib import baz Ciao Ulrich From max at alcyone.com Sat Mar 22 00:08:36 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 21 Mar 2003 21:08:36 -0800 Subject: Is Python the Esperanto of programming languages? References: <7i65qe953z.fsf@enark.csis.hku.hk> <3oyea.61654$68.41484@nwrdny01.gnilink.net> Message-ID: <3E7BEFD4.93D6F18A@alcyone.com> Carl Banks wrote: > Ok, let's say it means nothing in the same sense that sin x = x. How > about that? But sin x = x is a good approximation for small x :-). -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Grab a club and join the chorus / Evolution is a state of mind \__/ Oleta Adams REALpolitik / http://www.realpolitik.com/ Get your own customized newsfeed online in realtime ... for free! From andersjm at dancontrol.dk Thu Mar 20 04:53:53 2003 From: andersjm at dancontrol.dk (Anders J. Munch) Date: Thu, 20 Mar 2003 10:53:53 +0100 Subject: PEP 312 (and thus 308) implemented with a black magic trick References: <2259b0e2.0303171358.5a6fe337@posting.google.com> <6aicncBJyofaOuWjXTWcow@comcast.com> Message-ID: <3e798f83$0$20513$edfadb0f@dread11.news.tele.dk> "Terry Reedy" wrote: > > If, as I understand, this meta technique relies on source text, this > should work. But not if it looks at code: > > >>> def f(): return ++1 > ... [...] > > Compiler seems to optimize away second unary positive. > The second unary positive is treated as part of the integer literal. Try instead disassembling def f(x): ++x You can have as many UNARY_POSITIVEs as you like. - Anders From ycal at grapevine.net Mon Mar 24 20:06:32 2003 From: ycal at grapevine.net (Phil) Date: Mon, 24 Mar 2003 19:06:32 -0600 Subject: is win api available in native python References: <3e7e5a37_4@newsfeed> <33803989.0303240746.facc13@posting.google.com> Message-ID: <3e7faa23_4@newsfeed> Miki Tebeka posted in news:33803989.0303240746.facc13 at posting.google.com > Hello Phil, >> I see python has a windows api extension. But is there something >> available in the native python to close an open dialup connection. >> and also to exit windows or force shutdown. I guess I'm looking for >> the way to load and call one of the windows dlls if possible. I >> would think I need to identify the os so it would only be available >> to windows users. >> >> the winapi is >> InternetAutodialHangup >> and >> ExitWindowsEx > The 2'nd is supported in Mark's winapi > (http://starship.python.net/crew/mhammond/win32/Downloads.html) > maybe you can ask him to add the 1'st ;-) > > Miki wouldn't that be the windows api extension program I mentioned. I didn't want such a huge, but I'm sure useful, extension. Also I am trying to stick to the non os specific python. I was hoping python would have a way to call the loadlibrary function and whatever mac and unix equivalent would be. More of a lowlevel os starting point to execute dll functions. I am not familiar with unix or mac but it seems like an obvious need. Not the whole api just a way to build your own. -- - Phil -reverse ycal for email- -For MSACCESS, comments are made -regarding vers9.0 (2000) UON - From martin at v.loewis.de Thu Mar 27 19:07:15 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 28 Mar 2003 01:07:15 +0100 Subject: tkinter on IRIX6.5 Help needed References: Message-ID: "RENOUF, James" writes: > Can anyone tell me where I can obtain the correct _tkinter.so for Python > 1.5.2? You need to compile it yourself. Unpack the Python 1.5.2 sources, obtain the Tcl and Tk headers, and either build all of Python, or just the module. If you want to build all of Python, remember to enable _tkinter as a shared module in Modules/Setup. If you want to compile just the module, you will have to figure out the exact compiler invocations yourself. Regards, Martin From mcherm at mcherm.com Wed Mar 19 16:35:11 2003 From: mcherm at mcherm.com (mcherm at mcherm.com) Date: Wed, 19 Mar 2003 13:35:11 -0800 Subject: Unittests and external data.... Message-ID: <1048109711.3e78e28fc6793@mcherm.com> Mike Meyer writes that he wants to use unit tests, but they keep depending on external data (eg: an SQL database). What to do? I have been trying to address this for a while now, and I think I've come up with an approach that works for me. If you like to do test-driven development (write the tests first), then I can't help you... I couldn't find a sensible way to do that, because in the usual case I don't REALLY trust that I understand the behavior of the external system (the database in this example) until I've tested it. For some reason the databases (and other systems) that I use keep not behaving exactly according to spec (or what I thought the spec was). But if you've already got working code and you just want to have tests so you can go on your merry way refactoring things and making other unrelated changes and know that you're not breaking anything, then I can help. The solution that I've found is to use mock objects. (See http://c2.com/cgi/wiki?MockObject if you aren't familiar with the term.) I prefer to have a single global control of some sort which indicates whether I'm in "unittest mode" or not. Then all external interfaces (like databases) are accessed through factory objects (a good idea anyhow), and I make my factory objects aware of the "unittest mode" -- in normal mode it may return a database Connection, but in "unittest mode" it returns a MockConnection from the list of MockConnections. These are set up by the unittest (before it starts executing the code) to behave in the expected way. I don't particularly like having the factory functions behave differently under unittesting, but that's the best solution I've come up with. So my typical work process is something like this: (1) Write the code for X in the first place and try it out. (2) Write a unittest for X which will pass (specifying how I expect the external data source to behave). (3) Move on to other things, running my test constantly while refactoring. When I discover a change is needed in the call that X makes, I do this: (4) Change the external source (add new stored procedure or whatever). (5) Change the code for X so it works again. (6) Change the unittest for X to the new behavior. (7) Return to regularly running the test. I use this pattern with lots of kinds of external data sources, databases are one example, but in my current project I have testing mocks for two databases, active directory, and our config file (for tests that need particular configuration settings). -- Michael Chermside From missive at frontiernet.net Fri Mar 28 05:50:07 2003 From: missive at frontiernet.net (Lee Harr) Date: Fri, 28 Mar 2003 10:50:07 GMT Subject: Beginner Question References: <8gSga.236197$L1.65045@sccrnsc02> Message-ID: In article <8gSga.236197$L1.65045 at sccrnsc02>, Kevin Reeder wrote: > On Thu, 27 Mar 2003 20:45:04 -0800, Lee Harr wrote: > >> Well... it is not just the last line, but I think the best way would be: >> >> import random >> def shuffle(self): >> random.shuffle(self.cards) > > This one failed to work with the exception: Attribute error: shuffle. > Probably something I'm not seeing. > Which version of python are you using? I think random.shuffle was added in 2.0 or 2.1 If you are still using 1.5 or 1.6 I would definitely recommend upgrading, especially if you are just starting to learn. There are a lot of great new features that it would be good to learn right from the start (just look how much simpler this example becomes with the new method ;o) >> >> >> How about this: >> >> def shuffle(self): >> import random >> nCards = len(self.cards) >> for i in range(nCards): >> j = random.randrange(i, nCards) >> self.cards.insert(i, self.cards.pop(j)) > > This solution worked great. Is insert a list method? > Try this: dir([]) That will show you most of the list methods. From peter at engcorp.com Tue Mar 25 19:01:05 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 25 Mar 2003 19:01:05 -0500 Subject: Is Python the Esperanto of programming languages? References: <9lBfa.217$Jg1.4622@news1.tin.it> Message-ID: <3E80EDC1.DFE26D19@engcorp.com> Andy Jewell wrote: > > I never intended to provoke a huge off-topic thread, with my little throw-away > remark... Ah, well, then posting anything like that to c.l.p. was surely your _first_ mistake. ;-) > If it's all got too off-topic, maybe we should spawn a new sub-group, maybe > comp.lang.python.esperanto.sux ... ? :-) Hopefully this won't spawn another > 78-odd messages, though! We could always take over an empty > humanities.language sub-group (if there were one)... I think you're looking for the venerable soc.culture.esperanto, and perhaps a proposal for a soc.culture.esperanto.and.python.sux.2.l33t.roolz or something like that! ;-) ;-) -Peter From jlh at cox.net Wed Mar 19 22:46:31 2003 From: jlh at cox.net (Jeff Hinrichs) Date: Thu, 20 Mar 2003 03:46:31 GMT Subject: Novice needs help with py2exe References: Message-ID: Google is your friend http://starship.python.net/crew/theller/py2exe/ -Jeff "Matthew" wrote in message news:b5bb8c$us9$1 at lust.ihug.co.nz... > Hi, > > I've written a simple py program which I want to run under win32 as a > standalaone. the program works fine under pythonwin. Now how-to wrap it > up using py2exe? I've downloaded and installed py2exe and now to be > perfectly frank - What do I do now? There doesn't seem to be any > documentation at all on how to use it - well not that I could understand > anyway. > > D:\Python22\Lib\site-packages\py2exe>python py2exe.py > Traceback (most recent call last): > File "py2exe.py", line 3, in ? > raise RuntimeError, "something's wrong" > > D:\Python22\Lib\site-packages\py2exe>python setup.py py2exe.py --help > python: can't open file 'setup.py' > ^^^^^^^^ >>> doesn't exsist in the py2exe dir > > So, for this novice it's currently "Game Over". > > Any help would be greatly appreciated. > Regards, matthew. > From BPettersen at NAREX.com Sat Mar 1 13:29:31 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Sat, 1 Mar 2003 11:29:31 -0700 Subject: My CTO is learning Python.... Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192022DD860@admin56.narex.com> > From: Nick Vargish [mailto:nav at adams.patriot.net] > > Have you tried showing him the Cookbook, the printed version? [...] Yup. Bought him a copy myself. It was "too clever", "not structured like a tutorial", and generally "not quite what I'm looking for" (*sigh*). I got half of those comments for the effbot's guide to the Standard Library also. Both of which I consider indispensable for any Pythonista... -- bjorn From skip at pobox.com Wed Mar 19 14:43:10 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 19 Mar 2003 13:43:10 -0600 Subject: OT: Recommended Linux Laptops, suppliers? In-Reply-To: <1048100028.1301.98.camel@software1.logiplex.internal> References: <1048100028.1301.98.camel@software1.logiplex.internal> Message-ID: <15992.51278.390163.895099@montanaro.dyndns.org> Cliff> Emacs works best on x86 hardware. vi is best on Apple, but vi Cliff> sucks. Why do you say this? (Not the vi sucks bit, that I pretty much agree with. ;-) I'm typing this using XEmacs on my Mac. Works just as well here as on my Linux laptop. Cliff> Plus, Apples automatically indent Python code with tabs and Cliff> there's no way to change it. Not in Emacs it doesn't. ;-) Skip From user at domain.invalid Mon Mar 17 09:50:59 2003 From: user at domain.invalid (user at domain.invalid) Date: Mon, 17 Mar 2003 16:50:59 +0200 Subject: spreadsheet format References: Message-ID: Steve Holden wrote: > The obvious solution would be XML, at which Python excels (no pun intended > :-). Is there some reason why you haven't mentioned it (other than > completely overlooking it)? Because it's a text-based format you can usually > rely on it arriving at its destination unmangled. Yes, I left it out for a reason: I am not currently aware of any software that can parse/interprete XML spreadsheet without following somespecic schema or dtd. Which means, I may have to write something to write a parser myself -- not a direction I want to go. P.S. I am aware that "gnumeric" has its own xml format. From mis6 at pitt.edu Tue Mar 18 17:34:01 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 18 Mar 2003 14:34:01 -0800 Subject: Can __iter__ be used as a classmethod? References: <60FB8BB7F0EFC7409B75EEEC13E20192022DD8D3@admin56.narex.com> <2259b0e2.0303050740.52a92487@posting.google.com> <89G9a.12708$pG1.332485@news1.tin.it> <2259b0e2.0303061331.2b0b2028@posting.google.com> <25b5433d.0303131213.1c7b38dd@posting.google.com> Message-ID: <2259b0e2.0303181434.721838c@posting.google.com> Alex Martelli wrote in message news:... > Phillip J. Eby wrote: > ... > > I think it would be better to say that staticmethod is the one that > > doesn't give any functionality. I also think staticmethod is poorly > > named, since it does not produce a method, and it definitely doesn't > > do what a 'static method' does in Java or any other language I know > > of. > > Nolo contendere regarding the functionality, but I'm totally puzzled > regarding your objection to the name. Where's the "definitely doesn't > do" -- isn't a Python staticmethod just like e.g. a C++ static method? > > class cpp > { > static void greet() { > std::cout << "Hello, world!\n"; > } > } > > vs > > class py: > def greet(): print "Hello, world!" > greet = staticmethod(greet) > > > What "definite" difference is totally escaping my notice...? > > > Alex I think he is referring to this: >>> class C: ... m=lambda self,x: x ... s=staticmethod(lambda x:x) ... >>> C.m > >>> C.s at 0x402c2d14> >>> C.__dict__['m'] at 0x402c272c> >>> C.__dict__['s'] A staticmethod is not a method, is a function, when called as in the example. On the other hand, if you are doing some metaprogramming such as wrapping the methods in a class by looking at C.__dict__, you must explicitly distinguish static methods (which are descriptors objects in this context) from regular methods(which now are functions). No difference at all in the normal usage, but big difference in metaprogramming applications. Michele From salvatore at wanadoo.fr Sat Mar 1 09:21:11 2003 From: salvatore at wanadoo.fr (Salvatore) Date: Sat, 01 Mar 2003 15:21:11 +0100 Subject: Socket - Fiirewall Message-ID: Hello, I would like to create a little firewall in Python, Does anybody know how to block a port like a FireWall ? Thank you for your help regards Salvatore From mis6 at pitt.edu Tue Mar 25 10:33:54 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 25 Mar 2003 07:33:54 -0800 Subject: closure References: <3XNfa.9332$iE4.3141991@twister.nyc.rr.com> Message-ID: <2259b0e2.0303250733.2b5445e1@posting.google.com> "Max Khesin" wrote in message news:<3XNfa.9332$iE4.3141991 at twister.nyc.rr.com>... > I am looking for some info/tutorial on native closure in py(as of 2.1) - > thanks, You may want to look at David Mertz's articles on functional programming in Python, published by IBM developerWorks (google is your friend) M. From john.abel at pa.press.net Sun Mar 2 18:06:14 2003 From: john.abel at pa.press.net (John Abel) Date: Sun, 2 Mar 2003 23:06:14 -0000 Subject: How to get IP address References: <2a897f11.0303011133.3acdfc8@posting.google.com> <3E620FCE.4080408@freemail.hu> Message-ID: <000001c2e110$9aade850$7601fd0a@hallows> I may be missing something of what you're after here. socket.gethostbyaddr( socket.gethostname() ) will return all the details that you need to know. For example, the output of that command on my machine is : ('hallows', [], ['101.101.101.102', '10.253.1.118']) I have two adapters, one of which is DHCP. The hostname is that, given to your machine during the install. Regards John From rnd at onego.ru Fri Mar 14 00:45:24 2003 From: rnd at onego.ru (Roman Suzi) Date: Fri, 14 Mar 2003 08:45:24 +0300 (MSK) Subject: P.E.P. 3.0.8 ??? Message-ID: (I mangled the subject as I guess people put it into their filters ;-) Hello! So, what is the progress of the subject? I seem to miss voting altogether. And I understood that proposal failed public approval. Has Guido already decided this way or that? Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by Linux RedHat 7.3 From exarkun at intarweb.us Sun Mar 16 02:14:52 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sun, 16 Mar 2003 02:14:52 -0500 Subject: Is " a is b " and " id(a) == id(b) " the same? In-Reply-To: References: Message-ID: <20030316071452.GA18842@meson.dyndns.org> On Sun, Mar 16, 2003 at 02:05:17PM +0800, Chen wrote: > Some one said that " a is b " is the same as " id(a) == id(b) ". But it > seems not always true from the following codes: > > >>> class a: > ... def f(self): > ... pass > ... g=f > > >>> b=a() > >>> print id(a.f), id(b.f), id(a.g), id(b.g) > 6759528 6759528 6759528 6759528 > >>> print a.f is b.f > False > >>> print a.f is a.g > False > >>> print b.f is b.g > False > >>> print a.g is b.f > False > > Then, how to understand this example and the relationship of id() and 'is'? There is a difference in your test that you might not have realized. Consider this interpreter session: >>> class a: ... def f(self): ... pass ... g = f ... >>> b=a() >>> w = a.f >>> x = b.f >>> y = a.g >>> z = b.g >>> print id(w), id(x), id(y), id(z) 135851548 135930988 135691748 136030948 >>> print w is x, w is y, x is y, x is z 0 0 0 0 In your example, the method objects are created, passed to id, and destroyed, each in turn, none existing at the same time as any other. It is an implementation quirk that they all happen to have the same ID, then, because they each occupy the memory that the previous, destroyed instance, occupied as well. However, in the portion of the test where you use "is", two exist simultaniously. This causes them to occupy different memory, and thus have different IDs. If you check the docstring for the id() function, you see that this is how it should be: """This is guaranteed to be unique among simultaneously existing objects.""" Or-at-least-how-it-is-document'ly, Jp -- A sad spectacle. If they be inhabited, what a scope for misery and folly. If they be not inhabited, what a waste of space. -- Thomas Carlyle, looking at the stars -- up 12 days, 23:59, 4 users, load average: 0.05, 0.09, 0.03 From aleax at aleax.it Thu Mar 13 03:39:21 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Mar 2003 08:39:21 GMT Subject: Tuples, what are they: read-only lists or heterogeneous data arrays? References: <15982.24855.181016.568236@montanaro.dyndns.org> <200303111449.42035.fincher.8@osu.edu> <200303120211.h2C2BCH28989@pcp02138704pcs.reston01.va.comcast.net> <6fb43e5d.0303121502.683c615f@posting.google.com> Message-ID: Thomas Wouters wrote: > On Wed, Mar 12, 2003 at 03:02:29PM -0800, Nicola Larosa wrote: > > [ Guido rejects the 'add-list-methods-to-tuples' patch ] > >> Sorry, but this makes no sense. I entirely support the notion that a >> tuple should be *exactly* like a list, apart from the fact that it is >> immutable, so every read-only list method should be available for >> tuples, too. > > You must have missed the posting that started this thread. Tuples *are > not* lists, and should not be used as 'read-only lists' for the sake of > having a read-only list or for the sake of performance. Tuples are more of So what would you propose to do, when somebody needs to use a list as a key into a dictionary -- a list that's not going to be subject to any more changes, but will often need to be subject to non-mutating method calls such as .count ? Peppering the code with type conversion calls tuple(this) and list(that) is then a serious violation of the idea that "practicality beats purity". If tuples are NOT to be used as "frozen lists" for such purposes as indexing into a dictionary, putting into a set, and so on, then we need a separate way to "freeze a list" (or "get a frozen equivalent of a list", that would be fine too) -- perhaps along the same lines by which sets can be "frozen" into immutable-sets in the sets.py module. I think it might be a very nice addition (particularly if done via a protocol that also applied to dicts and that users could implement for their own classes if they wish to). But as long as tuples are the one and only way to "use a list as a dict key" &c, the theoretical arguments about tuples not being just frozen lists are countered by too much practical baggage, IMHO. Alex From fperez528 at yahoo.com Sun Mar 2 03:52:37 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Sun, 02 Mar 2003 01:52:37 -0700 Subject: Code speedup tips References: Message-ID: Sean Richards wrote: > OK this was a big improvement. Using the original nested loop version it > took ~12min for a 500x500 array, using array slices dropped the time to > ~1min. That is a pretty significant reduction. One small thing I needed > to do to get the rule to work correctly was add the line .. > 'workspace[:] += current[1:-1,1:-1]' > when you calculate the workspace. If we don't do this then on step 2 the > centre pixel becomes white instead of staying black. This effect > propagates until the end result is a diamond of alternating black and > white pixels instead of a solid black diamond. > That was a great help Carl, my total Python 'uptime' is only a couple of > hours but it looks like it is going to be an excellent tool. You should take a look at scipy, in particular the weave tool: http://www.scipy.org/site_content/weave Here: http://www.scipy.org/site_content/weave/python_performance.html you'll find a good comparison of various approaches to problems similar to what you have. Numeric is always the right starting point, and Carl's solution was excellent. But you may find situations where it's not enough. And the nice thing about python is that there's still a lot of options. Look also at f2py (http://cens.ioc.ee/projects/f2py2e) if Fortran rocks your boat. As a tool, f2py is just amazing in how easy it makes it to wrap existing fortran codes. Finally, Pyrex and psyco are always options, but I'm not familiar yet with them enough to say more about them. Best, f. From aleax at aleax.it Thu Mar 27 13:33:51 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 27 Mar 2003 18:33:51 GMT Subject: Wishlist: string attributes References: <3E807948.5040401@motorola.com> <6nfga.16983$i26.404601@news2.tin.it> Message-ID: Nicodemus wrote: ... > Why not make this an attribute of the str type? You could access them > using "str.digits". Yes, that's exactly what I'd like to see. It _might_ be neat if, as somebody else suggested, str.digits was of a special type inheriting from str but overring __contains__, e.g.: class specialstr(str): def __new__(cls, initval, checker): return str.__new__(cls.initval) def __init__(self, initval, checker): self.checker = checker def __contains__(self, c) return self.checker(c) # can't set attributes of str, but, if we could...: str.digits = specialstr(string.digits, str.isdigit) str.letters = specialstr(string.letters, str.isalpha) # etc, etc just to speed up idioms such as "if c in str.digits:", rather than asking for them to be recoded as "if c.isdigit():" directly. But I'm not sure the added value would be sufficient to justify such a provision of "more than one obvious way to do it", anyway!-) Alex From andrewsterian at yahoo.com Fri Mar 28 10:48:32 2003 From: andrewsterian at yahoo.com (Andrew Sterian) Date: 28 Mar 2003 07:48:32 -0800 Subject: Copy with __slots__...will it ever work? References: <7754c18e.0303271745.739012cc@posting.google.com> Message-ID: <7754c18e.0303280748.1bbc6d96@posting.google.com> Alex Martelli wrote in message news:... > Andrew Sterian wrote: > > > I've run up against the problem of not being able to call copy.copy() > > on a new-style class that defines __slots__. I found the thread that > > Do you mean on an INSTANCE of the class, or on the class itself as > you say? Doh! Yes, I meant the instance. > I'm not being uselessly pedantic, please note: since classes ARE > "first-class objects" in Python, you can subject them to all > kinds of operations (or at least TRY to;-), so saying "doing > something to a class" and "doing something to instances of a > class" are BOTH valid things, and two VERY different ones. People > whose background is in languages where classes AREN'T "first-class > objects", such as C++, often trip on this terminology issue. I appreciate the distinction and you are not being uselessly pedantic. Coming from C++ (a long time ago...and I'm so glad Python was there to rescue me from the horror that is the STL) I always use object/class/instance interchangeably, even though it's wrong. If people remind me often enough, eventually I'll get it. > They are -- but copying INSTANCES of the class isn't all that > orthogonal, because if the class defines __slots__ then its > instances hold state in a completely different way from how > instances of other kinds of classes hold it. Oh...OK...I didn't know that. > Perhaps this makes it easier to see why "changing the strategy > that instances use to keep their state" can easily interfere > with "how to copy all the state of an instance". Not an intentional > design decision, but a well-understandable bug (now fixed). Thank you for the education. I can certainly wait until Python 2.3 is released to have a fix for this. From ianb at colorstudy.com Fri Mar 14 21:15:50 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 14 Mar 2003 20:15:50 -0600 Subject: Website using Python--what's best architecture? CGI? In-Reply-To: References: Message-ID: <1047694549.4904.259.camel@lothlorien> On Fri, 2003-03-14 at 14:55, Chris wrote: > I would like to create a commercial website using Python. It seems > that straight CGI would be the easiest option, but I'm wondering what > its top capacity would be, and also what other options are commonly > available for a website that I will be hosting through a commercial > host. Here are some specific questions: > > 1. Is there any good ballpark figure on an upper limit of throughput > for Python cgi pages that need to connect to mysql? I realize this > depends on many things, but I guess I am wondering if this is even a > sane option for a "moderately busy" website where almost all pages > will be dynamic and will need to create a db connection? I'm thinking > online store if that helps at all. Mmm... I wouldn't use CGI, though it could be possible. The MySQL connection, for instance, is pretty fast to set up (not necessarily true for other databases), so it's okay that you're reconnecting for every page view. Depending on the CPU power of the host and the traffic it might be fine. But there are ceilings on performance that you can bump up against pretty quickly. One technique for optimizing CGI is to make as few requests use CGI as possible. For instance, Freeform does this to achieve fairly high performance with CGI (http://savannah.nongnu.org/projects/freeform/) -- in this case, it's for publishing news. When an article is posted, the static HTML files are generated for that file. You can use server-side-includes to make this even easier (so you can update the sidebar without updating every page that might include a sidebar). If your site is read-heavy, then this can work. This could aid in an online store, but it would introduce some limitations. > 2. What are other options available via commercial hosts? Is > something like "mod_python" or "Webware" commonly available on > commercial hosts (I know nothing much about either one, btw)? Or some > of the other Python web application frameworks I see mentioned? Seems > like a lot of these would require that you own the hosting machine and > have total control over it, which wouldn't be an option here. Check the Python website. The Python wiki also lists some frameworks: http://www.python.org/cgi-bin/moinmoin/WebProgramming If you don't use CGI, then yes, you have to find a host that specifically supports your chosen framework. Personally I use and am a developer for Webware, but there's several good programs. I don't think Zope is what you're looking for. -- Ian Bicking ianb at colorstudy.com http://colorstudy.com 4869 N. Talman Ave., Chicago, IL 60625 / 773-275-7241 "There is no flag large enough to cover the shame of killing innocent people" -- Howard Zinn From sross at connectmail.carleton.ca Mon Mar 31 21:33:42 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Mon, 31 Mar 2003 21:33:42 -0500 Subject: Parsing C References: Message-ID: Hi. PLY does not generate an AST(although it does include some examples in the documentation on how to make your own). SPARK, however, can be used to generate an AST automatically, but you'll have to code the scanner and parser. The PLY C example will probably be a useful guide for that. I'm using SPARK now for a small language and I've been pleased with how easy it's been to work with. So, I'd like to recommend it. For one thing, you can make your C parser class as a subclass of GenericASTBuilder and the parser will build your tree for you, just specify the grammar(which you can get from PLY). OK, then, good luck, and have fun Sean "Daniel Timothy Bentley" wrote in message news:Pine.GSO.4.44.0303311743400.19083-100000 at amy4.Stanford.EDU... > Hey, > I find myself having to write a C interpreter in Jython. Are there any > useful C compilers that are open-source in python? > > Or compiler-compilers that have files for a C compiler available? > > Or, compiler-compiler-compilers that have files for a compiler-compiler > that have files for a C compiler available available? > > Really, I'm looking for a way to get a C compiler and mildly painlessly > build it to create the AST that my program will look for. > > Oh, and the lexer in addition to the parser would be nice, but I bet it's > all easy and fully of re-goodness in {p|j}ython. > > Thanks in advance, > Dan > From albertbox at sinaman.com Thu Mar 20 02:36:22 2003 From: albertbox at sinaman.com (Albert) Date: 19 Mar 2003 23:36:22 -0800 Subject: Install Python-2.1.3 problem Message-ID: <500532df.0303192336.53c450d0@posting.google.com> I download the open source Python-2.1.3 from Python home page. My platform is RedHat 7.2 .After uncompress, I type " python setup install" The following word displayed : File "setup.py", line 57 extlist = [ext for ext in extlist if ext.name == modname] ^ SyntaxError : invalid syntax how to solve it? From kj_miles at yahoo.com Sun Mar 23 11:50:18 2003 From: kj_miles at yahoo.com (kevinj) Date: 23 Mar 2003 08:50:18 -0800 Subject: Debuging Python w/ multiple threads Message-ID: <7a195931.0303230850.3d4f6768@posting.google.com> I'm attempting to trigger breakpoints set in code that is called from spawned threads using thread.start_new(func,()) My main calls the thread.start_new(func,()) and i want to be able to investigate what is going on in the code that is actuated by the func() being called. I'm using Komodo Pro 2.3.0 ide. From news at scphillips.co.uk Wed Mar 12 05:38:33 2003 From: news at scphillips.co.uk (Stephen C Phillips) Date: Wed, 12 Mar 2003 10:38:33 +0000 Subject: deepcopy problem References: Message-ID: On Tue, 11 Mar 2003 18:44:53 +0000, Jp Calderone wrote: > I think the essense of this problem can be distilled thusly: > > import copy > class Foo(object): pass > f = Foo() > f.foo = f > g = copy.deepcopy(f) > > "f.foo is f" is True, while "g.foo is g" is False. Yes, I get that too. Thanks for making it a simpler example - I hope a solution to this will solve my problem too! > I believe this to be a bug in the pickle module, one which is fixed in > 2.3. There seems to be a work-around in 2.2, though I haven't explored > its behavior very thoroughly: > > import copy > class Foo(object): pass > f = Foo() > f.foo = f > memo = {id(f): f} > g = copy.deepcopy(f) > > Now, "g.foo is g" is True. Did you mean "g = copy.deepcopy(f, memo)" ? If I do that then "g.foo is g" is true but that's only because "g is f" is also true. From what I know about the copy module, the keys in the memo are the id's of the objects being copied and the value of a key is the copy of the object, so passing that memo to deepcopy tells it that the copy of f is f and so g gets pointed at the original f. So what we need is both "g is g.foo" and "g is not f" to be true. I had a look at the SourceForge bug tracker for 2.2.2 and could not see a bug listed for copy or pickle but I may be using it wrongly. Stephen Phillips From skip at pobox.com Thu Mar 6 19:51:16 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 6 Mar 2003 18:51:16 -0600 Subject: bsddb crashes on windows In-Reply-To: References: Message-ID: <15975.60676.77143.612561@montanaro.dyndns.org> Jarek> Will [the new bsddb] be compatible with current bsddb code? There are two components to compatibility you need to consider, the API at the Python level and the format of the bits written to database files. There is a backwards compatibility API in the new bsddb package which is compatible with the previous module's API. The file format will of necessity change, because the version of the underlying library with Python for Windows will jump from 1.85 to 4.1.25. There is a relatively easy way around file format incompatibility across versions, however. In Python 2.3 there are two new programs in the Tools/scripts directory: db2pickle.py and pickle2db.py. To convert an existing database, run db2pickle.py using your currently installed version of Python, something like: python2.1 db2pickle.py mydbfile.db mydbfile.pck rename mydbfile.db mydbfile.dbsave Then generate a new database file using pickle2db.py with Python 2.3: python2.3 pickle2db.py mydbfile.db mydbfile.pck There are options for reading/writing database files generated by bsddb.hashopen, bsddb.btopen, bsddb.rnopen, anydbm.open and dbm.open. (dbhash.open isn't supported separately, since it uses bsddb.hashopen under the covers.) The default is to read/write bsddb.hashopen files. You can also use these scripts to convert databases between file formats (say, between dbm file and an anydbm file). The only restriction is that bsddb recno files have numeric keys and thus can't be interchanged with the other database formats, all of whose keys are strings. (This restriction could be partially wormed around, but it doesn't seem worth the effort, since it is so rarely used.) Skip From tdelaney at avaya.com Mon Mar 17 18:17:17 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 18 Mar 2003 10:17:17 +1100 Subject: No Do while/repeat until looping construct in python? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE2E7BB6@au3010avexu1.global.avaya.com> > From: Thomas Wouters [mailto:thomas at xs4all.net] > > It was a sad occasion too; the killfile was otherwise empty. What - Tim Rue escaped? Tim Delaney From anand at calbay.com Fri Mar 14 20:12:05 2003 From: anand at calbay.com (Anand) Date: 14 Mar 2003 17:12:05 -0800 Subject: Mathlink call from python works with cmd.exe but not with IDEs!! Message-ID: Hi, I am calling a mathematica engine (mathlink) from python. It has a dll interface that gets an instance of this engine and then communicates with the engine and returns the results. Things work fine till this point. When i run the code from c:\python "mathlink.py" i have no problem. After execution the mathlink engine is shutdown. But when i run the code from Idle, the mathlink engine shuts down only when i close idle!. The problem is this same thing happens with other ide's as well. I cannot have more than 2 mathlink kernel loaded. This means after 2 calls my program fails if i dont exit the ide! Is there anyway for me to shutdown the kernel? From max at alcyone.com Mon Mar 10 15:23:38 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 10 Mar 2003 12:23:38 -0800 Subject: The ternary operator: more than one way to do it? References: <23891c90.0303100414.64c2a054@posting.google.com> Message-ID: <3E6CF44A.A2FA1A72@alcyone.com> Paul Boddie wrote: > The whole PEP 308 debate seems to reveal a secret desire in the > community to have more than one way of doing the ternary operator > thing - after all, there wouldn't have been so many creative > suggestions if this were not so. The oft-misquoted Python precept isn't "There's only one way to do it," it's more like, "There's (usually) only one _right_ way to do it." There is always more than one way to do something in any general, powerful, expressive programming language, and Python is no exception. The addition of a conditional operator to Python would resolve the issue of which is the right way to do it (conditional evaluation within an expression with short circuiting), so on the contrary, its addition would not only be not un-Pythonic, but highly Pythonic. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ There I was / There I was / Splitting atoms with my desire \__/ Lamya CSBuddy / http://www.alcyone.com/pyos/csbuddy/ A Counter-Strike server log file monitor in Python. From oren-py-l at hishome.net Wed Mar 12 03:27:09 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Wed, 12 Mar 2003 03:27:09 -0500 Subject: interactive development in python In-Reply-To: <4fd1aa5e.0303111345.58f4c71a@posting.google.com> References: <4fd1aa5e.0303111345.58f4c71a@posting.google.com> Message-ID: <20030312082709.GA10120@hishome.net> On Tue, Mar 11, 2003 at 01:45:17PM -0800, Joseph Heled wrote: > How do I re-load imported modules? reload(module) This re-executes the module body in the module namespace. Some notes: If you have imported any module functions or classes into your local namespace they will still point to the old implementation. Any instances you have created of classes in the module will remain an instance of the old implementation. If the objects methods reference module globals they will get the new implementation so you could get a mixture of the old and new behavior. Reloading does not clear the module namespace first. If globals were added to the module they will not be cleared. It does not reload other modules recursively. With these caveats, it's still useful for a rapid edit-reload-test cycles. I typically use: >>> reload(mymodule); mymodule.sometest() So I can just hit up-arrow+enter to see the effects. Oren From wge at wakalaka.com Fri Mar 21 23:24:52 2003 From: wge at wakalaka.com (wqe) Date: Sat, 22 Mar 2003 04:24:52 GMT Subject: cgitb for the console. Message-ID: I think cgitb is a great tool. Before things like boa came along, I used it heavily for debugging. Anyway, I saw no reason that console error mechanism should be worse than cgitb, so I cosmetically hacked through it to stop outputting html. Anyway, I think the python community process could help improve this code so that it could eventually be part of the normal console error mechanism. Code here: http://home.sus.mcgill.ca/~hperes/contb.py Please send patches and explanations to hunterp at CONFUSESPAMBOTS fastmail.fm From skip at pobox.com Wed Mar 19 12:55:43 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 19 Mar 2003 11:55:43 -0600 Subject: blogging PyCon In-Reply-To: <_42ea.749$iS2.33791@news.uswest.net> References: <_42ea.749$iS2.33791@news.uswest.net> Message-ID: <15992.44831.707489.765229@montanaro.dyndns.org> Kevin> Anyone planning to update their blog while at PyCon? If so, Kevin> please respond to this post. I'd be happy to get a list of URLs for any report pages people plan to maintain while at PyCon. I won't be there, but would like to try and keep up-to-date on what's going on. Thx, Skip From kevin at fonner.net Fri Mar 21 10:04:06 2003 From: kevin at fonner.net (Consistomagus) Date: 21 Mar 2003 07:04:06 -0800 Subject: accessing file properties Message-ID: I want to be able to access the properties of a file. Specifically the Created Date and Time, Modified Date and Time, and Accessed Date and Time. What would you guys figure to be the best most cross platform way of doing this? Thanks, Kevin From LogiplexSoftware at earthlink.net Tue Mar 18 16:54:02 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 18 Mar 2003 13:54:02 -0800 Subject: OT: Recommended Linux Laptops, suppliers? In-Reply-To: <01b901c2ed95$0f7bd940$21795418@dell1700> References: <01b901c2ed95$0f7bd940$21795418@dell1700> Message-ID: <1048024442.1107.361.camel@software1.logiplex.internal> On Tue, 2003-03-18 at 13:26, Brian Quinlan wrote: > > Where do you get this info? USB 2.0 is actually rated higher (480Mb) > > than firewire (400Mb). > > You are comparing 1394 to USB 2.0. 1394b (which is what Apple now uses), > is 800Mb. See: > http://www.1394ta.org/Technology/About/1394b.htm Ah. I knew there was a more recent firewire, but wasn't finding a direct reference to it (Apple's site seems fairly vague, or perhaps it's because it doesn't work right under Mozilla). > > > This is certainly a shortcoming, although most of the devices I've > used > > provide their own power anyway. > > Which sucks. The last thing that I need is more power cables. Granted. > > If I want my USB HDD to sit in a different room than my PC, I'll start > > questioning my sanity . > > But if you want to stream DV to/from your TV then it becomes a problem. Well, perhaps, but not for me (my TV is less than a few feet from my PC), besides I'd probably use the SVideo or composite video ports on my video card for that anyway. My TV lacks both USB and firewire . > > > Did you look at Skip's numbers? > > > > Certainly. I still haven't seen the G4 numbers though. > > He posted G4 numbers! Ah, when I saw Ti I thought Texas Instruments and completely missed the "powerbook" below that. That clears things up a bit ;) > > Skip> Here are some Pystone numbers from my 800 MHz Ti > Skip> Powerbook. > > Skip> Interpreter Best pystone > Skip> 2.1 10482 > Skip> 2.2 11210 > Skip> CVS 13123 > > Scaling his G4 numbers up to 1GHz and scaling his PC down to 2GHz > Celeron levels, the numbers become: > > G4: 14012 > Celeron: 15916 > > Of course this comparison sucks for a bunch of reasons but it is the > best we can do unless we can find people with both types of machines. Mostly it sucks because Skip did it As I mentioned earlier, I doubt using the Cygwin port of Python is going to give very fair numbers on the PC. I haven't used those tools in quite a while, but unless something has changed, you can expect a fairly large performance hit under Cygwin. > > It matters because we are flaming over Apple vs Intel. Every number > > counts at this point . > > Actually, no. You may be flaming Apple but I'm arguing that a G4 laptop > is a reasonable platform for Python development. I never said otherwise. I have no real problem with Apple other than their pricing. I think OSX is a *huge* step forward for them, however I don't see paying twice the price for half the performance (or equal performance, for that matter), unless there is a real need for a particular application that only runs on Mac. Python certainly runs well enough on less expensive platforms that buying a Mac for Python development seems silly (unless the work is specifically for the Mac port of Python). > > > I would guess that writing a non-Apple client would be very > difficult. > > > > And this is why using X11 would have been a benefit (at least to some > of > > us). > > I think that it would be difficult designing a powerful graphics server > that is also easy to implement. Unless I'm mistaken, X still has > problems with anti-aliasing, compositing and 2D transformations (*). My entire GNOME2 desktop is AA. I'm unsure of the others. I certainly haven't noticed a marked difference in performance on my desktop compared to the G4's my gf uses at (art) school. Well, nothing that didn't make mine look faster ;) > Apple has solved all of those problems plus a bunch of problems that the > UNIX graphics people probably don't care about (like multiple-model > device-independent color management). Okay. You've entered graphics-design-land and lost me. This whole time I thought that there were only 256 colors . > (*) in Quartz, if you want to scale a graphics object by 20%, you just > change a transformation matrix (as with OpenGL) and send that to the > server. With X, you resend every graphics command needed to draw the > object, after doing the transformation yourself. Or use a decent graphics library. While X may not provide this capability natively (it's probably considered outside the scope of X) there are enough graphics libraries built on top of X that you shouldn't need to do this sort of thing yourself. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From dcengija_remove_ at inet.hr Sun Mar 16 04:10:35 2003 From: dcengija_remove_ at inet.hr (Davor Cengija) Date: Sun, 16 Mar 2003 10:10:35 +0100 Subject: idle on linux References: <3e73f4fe@duster.adelaide.on.net> Message-ID: <1546399.uzmy0luf9x@lothar.cengija.com> Luke wrote: > Hi, > > I've tried to install idle in RedHat 8.0 > Installed python tools, tcl, tk > But when I start idle at the prompt ('/usr/bin/idle') I get the following > message: ... > ImportError: No module named Tkinter Mandrake (and most likely RedHat, as well) comes with tkinter packed as rpm. You just need to install it. davor at lothar ~ $ rpm -qi tkinter Name : tkinter Relocations: (not relocateable) Version : 2.2 Vendor: MandrakeSoft Release : 9mdk Build Date: Sun 24 Feb 2002 04:24:10 PM CET Install date: Sun 21 Jul 2002 10:01:41 PM CEST Build Host: no.mandrakesoft.com Group : Development/Python Source RPM: python-2.2-9mdk.src.rpm Size : 1626606 License: Modified CNRI Open Source License Packager : Stew Benedict URL : http://www.python.org/ Summary : A graphical user interface for the Python scripting language Description : The Tkinter (Tk interface) program is an graphical user interface for the Python scripting language. You should install the tkinter package if you'd like to use a graphical user interface for Python programming. -- Davor Cengija, dcengija_remove_ at inet.hr From mchermside at ingdirect.com Wed Mar 26 12:43:36 2003 From: mchermside at ingdirect.com (Chermside, Michael) Date: Wed, 26 Mar 2003 12:43:36 -0500 Subject: os.putenv ? Message-ID: <7F171EB5E155544CAC4035F0182093F03CF7CF@INGDEXCHSANC1.ingdirect.com> > > cat > grrr.py > import os > os.putenv("GRRR","This is a late parrot.") > print "GRRR has been set to:", os.getenv("GRRR") > > echo $GRRR > > > python grrr.py > GRRR has been set to: None > > echo $GRRR > > > What am I missing ? While the answer may vary some from OS to OS, in many commonly used OSes (eg: unixes) a process may set its OWN environment, and it may set the environment of its CHILD processes, but it cannot set the environment of its PARENT process. That's why in unix "ls" is written as a separate program, but "setenv" is built into the shell (if it were a separate program, the program could set its own environment, but not that of the shell (its parent)). So what you're asking for is impossible (intentionally) in any language (not just Python). What are you trying to achieve? Perhaps there's a better way. -- Michael Chermside This email may contain confidential or privileged information. If you believe you have received the message in error, please notify the sender and delete the message without copying or disclosing it. From djn at daimi.au.dk Tue Mar 11 09:19:55 2003 From: djn at daimi.au.dk (Daniel Nielsen) Date: Tue, 11 Mar 2003 14:19:55 +0000 (UTC) Subject: Stream Abstractions in python? In-Reply-To: References: <20030311123036.GA5514@daimi.au.dk> Message-ID: <20030311141953.GA21598@daimi.au.dk> On 11/03-03 13.11, Gerhard H?ring wrote: > Daniel Nielsen wrote: [snip] > You might want to take a look at Twisted [1]. It nicely decouples protocol > implementations from the underlying transport, among others. If you're > doing network programming and/or implementing custom protocols it's IMO a > very good framework. I will look into this [1a]. [snip] > Hmm. What about using codecs.EncodedFile for this? [2] Maybe, but a quick gaze over the docs, seems to indicate that I would be better off using pyro/twisted. > [1] http://www.twistedmatrix.com/ -- Argh. Can't connect currently. [1a] Exactly my problem. Reading through some of the posts here recommends twistedmatrix as well, so I look forward to seeing it... > [2] http://www.python.org/doc/current/lib/module-codecs.html /Daniel -- There are no great men, only great challenges that ordinary men are forced by circumstances to meet. -- Admiral William Halsey From sjmachin at lexicon.net Sun Mar 16 16:28:30 2003 From: sjmachin at lexicon.net (John Machin) Date: 16 Mar 2003 13:28:30 -0800 Subject: Strange rounding problem References: <4378fa6f.0303141540.de857b8@posting.google.com> <3E736D6A.42C9355A@engcorp.com> <20030315185608.GB14733@meson.dyndns.org> Message-ID: danb_83 at yahoo.com (Dan Bishop) wrote in message news:... > > If we define the utility of a number base as proportional to the > number of its factors (excluding itself), and inversely proportional > to the magnitude of those factors (and use the Python script at the > end of this message to calculate those factors), we find that the best > bases are 12 (1.562), 6 (1.500), and 24 (1.361), and that bases 14, > 21, 22, 25-28, and 32-35 are worse than the prime bases. > > > def factors(n): > # list of factors of n, including 1 and excluding n > return [i for i in xrange(1, n // 2 + 1) if not n % i] > Wouldn't it be better to exclude non-prime factors of the base? From achrist at easystreet.com Fri Mar 21 11:07:01 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Fri, 21 Mar 2003 08:07:01 -0800 Subject: Object oriented databae for Python References: <3E7A12BA.3A297B2F@easystreet.com> Message-ID: <3E7B38A5.B54F82BE@easystreet.com> Konstantin Knizhnik wrote: > ? This is first release of DyBASE. So I could not call it stable:) > But DyBASE is actually based on GigaBASE core and it is almost five > years old and is stable enough. > Thanks much for the additional info. I was looking at DyBase and GigaBASE and FASTBASE last night, and wondering how hard it would be to get these to talk to Python. I had a little problem with the Dyabase distribution ... The binaries require MSVCR70D.DLL. That's a file that's part of the current MS developer products, but it's not redistributable. So, my programs wouldn't be redistributable if they used the binaries. Worse, I don't even have MSVCR70D.DLL installed on my machine. I expect I'll be trying to re-build this with MSVC++ v6 with debugging off in a couple of hours. Hope that works. Any tips? Al From LogiplexSoftware at earthlink.net Wed Mar 26 17:11:03 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 26 Mar 2003 14:11:03 -0800 Subject: Using poplib to access Yahoo Mail In-Reply-To: <3E81C033.4060801@nonexistento.neto> References: <3E81C033.4060801@nonexistento.neto> Message-ID: <1048716663.22314.299.camel@software1.logiplex.internal> On Wed, 2003-03-26 at 06:58, Alpha Alpha wrote: > Hi, > > I tried using poplib to connect to pop.mail.yahoo.com to connect to my > Yahoo mail account. I get an error saying please check yahoo.com for the > error.. etc. And when I log in to my account (using a web browser), I > get an email saying, "you tried to access Yahoo's pop3 email service, > which is no longer free .. please subscribe ".. etc This is correct. You must pay to access Yahoo mail via pop. > > The point is, when I use a software called poppeeper > (http://www.poppeeper.com), to check _new_ messages in my inbox it works > !! I do not get any email from Yahoo ! The website for poppeeper says that it supports webmail. Most likely it is using that rather than POP. > I wrote to the developer of poppeeper asking how he accessed the yahoo > account, and his approach seems to be the same (via pop.mail.yahoo.com) ! He probably meant that's how it would do it provided you had a POP account at Yahoo. > Is it a problem with the poplib module implementation ? > > That said, my objective is to backup all my yahoo emails (around 212 > messages) onto disk, before I run out of space. Poppeeper does not (yet) > meet my requirements.... There are a few programs that get Yahoo mail by parsing the HTML mail. This site lists several: http://fetchyahoo.twizzler.org/ HTH, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From tim.one at comcast.net Thu Mar 6 18:23:01 2003 From: tim.one at comcast.net (Tim Peters) Date: Thu, 06 Mar 2003 18:23:01 -0500 Subject: bsddb crashes on windows In-Reply-To: Message-ID: [Tim] > You could install a recent Sleepycat release yourself, and use it with > Python via the pybsddb project: > > http://pybsddb.sourceforge.net/ > > In effect, that project is getting folded into the Python core for 2.3. [Jarek Zgoda] > Will it be compatible with current bsddb code? I'm not sure what that question means, but I'm not a bsddb expert regardless. If you can flesh out the question in more detail, perhaps someone else will be able to answer it. From zhitenev at cs.vsu.ru Mon Mar 3 04:57:20 2003 From: zhitenev at cs.vsu.ru (Lexy Zhitenev) Date: Mon, 3 Mar 2003 12:57:20 +0300 Subject: Pls, help me with re References: <3E6324D2.7E76BCB1@alcyone.com> Message-ID: "Erik Max Francis" wrote in message: news:3E6324D2.7E76BCB1 at alcyone.com... > > > > 'Course: 23,95' - matches '23,95' > > '$1 = 23,95 y' - matches '23,95'. > > Why not a regular expression simply like [including both commas and > periods]: > > =.*([0-9,.]+) > This re matches the second example, but it doesn't match the first one. Sorry From aleax at aleax.it Thu Mar 6 06:00:07 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 06 Mar 2003 11:00:07 GMT Subject: c enum - how to do this in python? References: Message-ID: Fernando Perez wrote: > Anna wrote: > >>> Reversing strings with [::-1] is more or less a divertissement, >> >> Actually, the more I play with it, the better I like it. It still looks >> wierd though... and I still want it to have a NAME. I like names. Names >> are a Good Thing. So - what's this mutant smilie called? > > Well, that syntax has actually been valid for lists in python for a long > time. It's just that none of the builtins supported it :) And its name was ("long-form" or "extended") slicing -- and still is. > So now you have it across python. Once you understand the syntax, you > don't need a name for it. But you do -- and the name is, "a long-form slicing of the string". A shorter (nick-)name might help if you must use it often, but that's optional, of course. > Or do you want strings to grow .even(), .odd(), > .odd_skipping_everyother(), .every_prime(), etc methods? Just kidding :) I think you're misreading the OP's request, and that she asked about the name of the [::-1] construct, NOT asked for named _methods_ to be added to string objects to duplicate slicings' functionality. > My point is just that once the syntax becomes second nature to you, it > stops > looking like a smiley and becomes a slice. Trust me, you'll grow to love > it. "A slice" is, e.g., slice(None,None,-1). "A slicing" is the operating which consists in applying a slice object to a container, as in: container[::-1] which is equivalent to: container[slice(None,None,-1)] It's exactly the same distinction as between "an index" and "an indexing": container[foo] this is an indexing, and foo is the index used in this indexing. Yeah, I know, this IS a bit pedantic -- and the distinction between indexing and slicing is fuzzy (if foo=slice(11,22,3) precedes the indexing container[foo], for example;-)... Alex From intentionally at blank.co.uk Tue Mar 4 02:06:22 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 04 Mar 2003 07:06:22 +0000 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <8fb66v8qbv45eatnblq80p131793ej7e3m@4ax.com> <6zK8a.268598$0v.7396380@news1.tin.it> <3E63FE87.D87F59EF@alcyone.com> Message-ID: On Mon, 03 Mar 2003 17:16:55 -0800, Erik Max Francis wrote: >Alexander Schmolck wrote: > >> It isn't a major problem, but I can remember that it did >> (infrequently) cause >> me bugs, so it's not all theoretical. Another minor cause of annoyance >> are >> things like this: >> >> SOME_GLOBAL_CONST = [(y**2, x**2) for (x,y) in >> SOME_OTHER_GLOBAL_CONST] >> del x, y # I could do without this > >But that wouldn't be any different than the explicit for loop form: > > SOME_GLOBAL_CONST = [] > for x, y in SOME_OTHER_GLOBAL_CONST: > SOME_GLOBAL_CONST.append((y**2, x**2)) > del x, y # you could do without this To me, the slight difference is that because I see list comprehensions as functional I don't expect them to have side effects. Of course it is a trivial issue, but it isn't *quite* as benign as the for loop (which is 'supposed to' have side effects). -- steve at ninereeds dot fsnet dot co dot uk From skip at pobox.com Sat Mar 22 10:43:32 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 22 Mar 2003 09:43:32 -0600 Subject: CGI: how to get referer header? In-Reply-To: <3E7C5215.6070209@NOmyrealCAPSbox.com> References: <3E7C5215.6070209@NOmyrealCAPSbox.com> Message-ID: <15996.33956.312958.868798@montanaro.dyndns.org> exnihilo> I am trying to get the referer and user agent headers in a cgi exnihilo> program I'm writing. I haven't been able to find any clear exnihilo> information on how to do this, but I've been trying the exnihilo> following: exnihilo> referer = cgi.parse_header('Referer') exnihilo> agent = cgi.parse_header('User-Agent') They should be available in the environment as HTTP_USER_AGENT and HTTP_REFERER. Take a look at http://www.musi-cal.com/cgi-bin/query for an example. Skip From belred1 at yahoo.com Sun Mar 23 09:42:26 2003 From: belred1 at yahoo.com (Bryan) Date: 23 Mar 2003 06:42:26 -0800 Subject: Defining Python class methods in C References: <2ogfa.143804$zo2.3787485@news2.tin.it> Message-ID: thank you both for your help. i didn't know that classes and types were two different things. i coded it as a type according to the example in "python in a nutshell" and it worked correctly the first time. i wish i never saw the cookbook example... it would have saved me countless hours of agony. classes have data and methods and types have data and methods. in python i write classes all the time, so naturally i gravitated towards the class example in c. i take it from john's posting, that classes are uses to be compatible with older versions of python. bryan From aleax at aleax.it Fri Mar 7 04:16:18 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 07 Mar 2003 09:16:18 GMT Subject: IndentationError: two many levels of indentation References: <3E685D44.FDD5A810@alcyone.com> Message-ID: Erik Max Francis wrote: ... > It would indeed appear there's some sort of limit. I did the following: ... > IndentationError: too many levels of indentation Yes, Parser/tokenizer.h in the Python 2.2.2 sources for example is quite clear about it (grepping in the file...): #define MAXINDENT 100 /* Max indentation level */ int indstack[MAXINDENT]; /* Stack of indents */ int altindstack[MAXINDENT]; /* Stack of alternate indents */ and Parser/tokenizer.c checks for over-indentation: if (tok->indent+1 >= MAXINDENT) { giving an E_TOODEEP error that gets turned into the above exception. 2.3a2 seems to be identical in this respect. I suspect that editing tokenizer.h to use a MAXINDENT of 1000, or whatever, is going to bump up the limit accordingly (at a small memory cost), though I have not experimented with it. Removing the limit altogether would seem to require quite a different approach to tokenization than the one currently used, or else it might be achieved by turning those arrays into dynamically resized ones, if somebody's keen enough to support code-generators to offer patches for the purpose... Alex From gminick at hacker.pl Sun Mar 16 06:22:16 2003 From: gminick at hacker.pl (Wojtek Walczak) Date: Sun, 16 Mar 2003 11:22:16 +0000 (UTC) Subject: small question References: Message-ID: Dnia Sun, 16 Mar 2003 10:25:14 GMT, Ali Dada napisa?(a): > how can i force a script to execute in the user's home directory? > if i know that the user is 'foo' i can say >>os.chdir('/home/foo') > but what is a better and more general way? os.environ["HOME"] ? -- [ Wojtek Walczak - gminick (at) underground.org.pl ] [ ] [ "...rozmaite zwroty, matowe od patyny dawnosci." ] From max at alcyone.com Fri Mar 14 23:58:12 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 14 Mar 2003 20:58:12 -0800 Subject: No Do while/repeat until looping construct in python? References: <3E726623.C2932658@alcyone.com> Message-ID: <3E72B2E4.8BD28AE@alcyone.com> William Sonna wrote: > That simply IS the case. READ THE POST. He called ME names. And just > because you may think its great he did doesn't change THAT FACT one > bit. What name did he call you? Troll? Quite frankly, that looks like it might well be an accurate label, given your behavior so far. > As for what I said to J.P., I stand by what I said. His was a > shit-eating > response. Funny, yes, but shit-eating nonetheless. He suggested that if you hate this Python feature so much, maybe you'd be better off not using Python anyore. Seems like an appropriate response to the tone of your posts up to that point. Your subsequent rudeness only makes that characterization fit better, not worse. > You may call me whatever you feel is appropriate, and as long as you > don't > lie about what I or others have said in this thread I won't respond > and it > ends here. Apparently you think reasoned debate necessarily involves calling people names whenever you feel it "appropriate." That's really too bad, because if you are indeed _not_ a troll, continuing to behave like this is going to continue to get people mad at you, which is counterproductive if your true intent is reasonable discourse. (No doubt you'll now take the opportunity to call _me_ names, just to show how right you are.) -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Who, my friend, can scale Heaven? \__/ _The Epic of Gilgamesh_ The laws list / http://www.alcyone.com/max/physics/laws/ Laws, rules, principles, effects, paradoxes, etc. in physics. From joshway-without-spam at myway.com Fri Mar 14 08:23:07 2003 From: joshway-without-spam at myway.com (jcm) Date: Fri, 14 Mar 2003 13:23:07 +0000 (UTC) Subject: Flying With Python (Strong versus Weak Typing) References: <37a869bc.0303102102.4533973@posting.google.com> <1047398589.950487@yasure> Message-ID: Alex Martelli wrote: ... > I've often daydreamed about having a language where I can offer > such hints and compile my programs in at least two ways: > -- a debugging mode, where hints let the compiler insert checks > for me and raise warnings or errors when my hints don't match > reality, > -- an optimizing mode, where the compiler trusts the hints (at > least to some extent) and uses them to make fast code. Python (the language) basically has this, in the form of assertions. python (the compiler/interpreter) just doesn't have an "optimize-dangerously" mode to take advantage of them. It would be possible to write a compiler for Python to do what you suggest. From artur_spruce at yahoo.com Mon Mar 3 09:14:30 2003 From: artur_spruce at yahoo.com (AdSR) Date: 3 Mar 2003 06:14:30 -0800 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <58q36vgv1ga8ovde5ftub9t8ugaa2pnum5@4ax.com> <3E62778F.EED49083@alcyone.com> Message-ID: Alexander Schmolck wrote: > Erik Max Francis writes: > > > Indeed. I don't see what the tangible benefit is, except by making a > > certain style of lambdas harder to read. One might object to the use of > > lambdas on general grounds, but certainly when you see the keyword > > `lambda' you know what you're in for. PEP 312 attempts to blur that > > distinction, for no other reason than to save keystrokes and make code > > look more impenetrable. I don't see the benefit. Neither do I. > You overlook the fact "that saving keystrokes" (and space) can make a > qualitative change to a language. As can making it less readable. As I understand, Python is, among other things, readability-oriented. Let's keep it like that. As they say, if it ain't broken, don't fix it. Cheers, AdSR From wyojustin at hotmail.com Sun Mar 16 20:19:32 2003 From: wyojustin at hotmail.com (Justin Shaw) Date: Sun, 16 Mar 2003 20:19:32 -0500 Subject: dict.popitem(key) ??? References: Message-ID: "Alex Martelli" wrote in message news:lwVca.92205$zo2.2426955 at news2.tin.it... > Raymond Hettinger wrote: > > > "Justin Shaw" > >> Why doesn't popitem take a key argument that defaults to None? Or how > >> should I pop a particular item out of a dict? > > > > In Py2.3, dict.pop can take an optional default argument: > > > > avalue = mydict(possiblekey, default) > > > > It can also just search for a specified key and return an > > exception if not found: > > > > avalue = mydict(possiblekey) > > Just to clarify (I think a ".pop" just failed to appear here): > > Python 2.3a2+ (#10, Mar 16 2003, 08:10:57) > [GCC 3.2 (Mandrake Linux 9.0 3.2-1mdk)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> ad=dict.fromkeys('ciao') > >>> ad > {'i': None, 'a': None, 'c': None, 'o': None} > >>> ad.pop('z') > Traceback (most recent call last): > File "", line 1, in ? > KeyError: 'z' > >>> ad.pop('z',23) > 23 > >>> ad.pop('a',23) > >>> ad > {'i': None, 'c': None, 'o': None} > >>> > > If you can't use 2.3 (still in alpha stage), then as somebody else > suggested you can still do the job, albeit in two steps: > > >>> ad.get('o',42) > >>> del ad['o'] > >>> ad > {'i': None, 'c': None} > >>> > > > Alex > Thanks for all of your responses. My question is more than answered! Justin From abpillai at lycos.com Fri Mar 7 10:46:08 2003 From: abpillai at lycos.com (Anand B Pillai) Date: 7 Mar 2003 07:46:08 -0800 Subject: urllib2 authentication problems! Message-ID: Hi I am using urllib2 in my application to open a url which needs validation using https username/password. I am using python 2.2.1 on Windows nt 4.0. My code is as follows... authinfo=urllib2.HTTPBasicAuthHandler() authinfo.add_password('realm', 'myurl', 'myusername', 'mypasswd') opener=urllib2.build_opener(authinfo, urllib2.HTTPHandler) urllib2.install_opener(opener) try: streamdata=urllib2.urlopen(myurl).read() except urllib2.URLError, e: msg=str(e) msg+='!\n\n' msg+="Check the URL" print msg It always prints the error message " ! Check the URL" The validation for the realm I am requesting is done through https and not http. What is the mistake I am making here. I cannot understand the error message since I thought that python 2.1 upwards had builtin https url support. Anand Pillai http://members.fortunecity.com/anandpillai From member16943 at dbforums.com Mon Mar 3 00:44:40 2003 From: member16943 at dbforums.com (Tetsuo) Date: Mon, 03 Mar 2003 05:44:40 +0000 Subject: XP or something References: <2593169.1046568078@dbforums.com> Message-ID: <2595856.1046670280@dbforums.com> Alright, I figured it out. It's Lib\site-packages\Pythonwin\pythonwin.exe -- Posted via http://dbforums.com From mwh at python.net Mon Mar 17 09:26:13 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 17 Mar 2003 14:26:13 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 17) References: <3E75D574.8EF68D97@engcorp.com> Message-ID: <7h31y16jchm.fsf@pc150.maths.bris.ac.uk> Peter Hansen writes: > Mike Meyer wrote: > > > > QOTW: "We will perhaps eventually be writing only small modules which are > > identified by name as they are used to build larger ones, so that devices > > like indentation, rather than delimiters, might become feasible for > > expressing local structure in the source language." --Donald E. Knuth, > > "Structured Programming with goto Statements", Computing Surveys, Vol 6 > > No 4, Dec. 1974 > > Wait a sec... think about that for a minute. Is he saying that one > will be able just to list a simple series of commands which draw on > functionality defined in specialized, application-specific modules? > > That the resulting language will be so high level that, for the most > part, control flow and complicated nested structures will be unnecessary? 93. When someone says "I want a programming language in which I need only say what I wish done," give him a lollipop. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html Cheers, M. -- C++ is a siren song. It *looks* like a HLL in which you ought to be able to write an application, but it really isn't. -- Alain Picard, comp.lang.lisp From tdelaney at avaya.com Mon Mar 24 18:29:28 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 25 Mar 2003 10:29:28 +1100 Subject: [Python-Dev] How to suppress instance __dict__? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE3DC955@au3010avexu1.global.avaya.com> > From: Michael Hudson [mailto:mwh at python.net] > > "Delaney, Timothy C (Timothy)" writes: > > [__init__ vs. __new__] > > > Because most of the time we want to work with fully-constructed > > objects. You can't use overridden methods in a constructor - only > > from an initialiser. > > What makes you say that? > > Doing too much C++ lately? Unfortunately, yes :( How about this then ... using __init__ is simpler in most cases ;) Tim Delaney From max at alcyone.com Mon Mar 10 15:33:07 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 10 Mar 2003 12:33:07 -0800 Subject: What is this 'u' in my list References: Message-ID: <3E6CF683.3F074F45@alcyone.com> Antun Karlovac wrote: > I just created a list and when I printed it out to the console, I > got:- > > [u'name', u'size', u'expression', u'number', u'reference', u'string', > u'color'] > > What is the u before the string? It means it's Unicode. Use the .encode method of the Unicode objects to convert them to some other encoding. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ There I was / There I was / Splitting atoms with my desire \__/ Lamya CSBuddy / http://www.alcyone.com/pyos/csbuddy/ A Counter-Strike server log file monitor in Python. From someone at invalid.com Mon Mar 10 04:24:41 2003 From: someone at invalid.com (Sean Richards) Date: Mon, 10 Mar 2003 09:24:41 GMT Subject: How to return fractional part from array of floats? References: Message-ID: On Mon, 10 Mar 2003 09:01:53 GMT, Sean Richards wrote: > The subject says it all. I have a Numeric array of type Float. How do I > return an array of the fractional parts of the Floats. I know I can > apply modf() to a single float but is there some function I am missing > that I can apply to a complete array? Typical - spend a lot of time trying to work something out and find the answer minutes after you post. Sorry for the wasted bandwidth. asarray(floatarray).astype('l') seems to do the trick. Sean :) -- +---------------------------------------------------------------+ | All spelling errors are intentional and are there to show new | | and improved ways of spelling old words. | +---------------------------------------------------------------+ From cah7k at virginia.edu Mon Mar 17 15:51:20 2003 From: cah7k at virginia.edu (Charles Harrison) Date: 17 Mar 2003 12:51:20 -0800 Subject: does anyone know why the os.path.walk() function would fail in the middle of reading the names of a directory under windows? I call it from the ineractive interpreter and it prints a portion of the names list that should get sent to the visit() func Message-ID: does anyone know why the os.path.walk() function would fail in the middle of reading the names of a directory under windows? I call it from the ineractive interpreter and it prints a portion of the names list that should get sent to the visit() function, but the list ends in the middle of one of the names and there is no ']' on the end of the list, but it doesnt return an error From tjreedy at udel.edu Tue Mar 11 09:38:09 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Mar 2003 09:38:09 -0500 Subject: A possible lazy evaluation system? References: Message-ID: "Stephen Horne" wrote in message news:lmmr6vgoc01vkbvkp6vmbo8d9dnboljunl at 4ax.com... > It occured to me that, instead of a fully lazy parameter system, a > simpler approach may be to lable parameters as lambdas. > > You could then write something like... > > def IF (c, lambda x, lambda y) : > if c : > return x () > else : > return y () > > ...and call it with... > > IF (y != 0, x/y, 1000000) > > The 'lambda' asserts that the parameters expression gets converted to > a parameterless lambda instead of being evaluated immediately. > > The same notation in declarations of __call__ could provide the same > capability to all callables. > > The question is - is this a sane suggestion? As Python is currently defined, no. If there is to be a pre-interpretation compile phase, this requires that the compiler know at *compile* time what function object will be bound to name IF at *runtime*. This is currently impossible. It requires that the function object exist at runtime, which it does not, or that the linkage info be accessible at compilie time through another access method, which it currently is not and which could be very difficult to impossible. It also assume that namespace name IF will always be bound to the same function object! This is currently not necessarilyt true. Definition names, when present, are not the same as namespace binding names. In addition, the function called can be the result of an arbitrarily complicated expression, with a value not calculable at compile time. Consider as just one example: print eval("lambda x: " + raw_imput("Enter 'x expression': "))(2.5) Terry J. Reedy From exarkun at intarweb.us Sun Mar 2 23:44:35 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sun, 2 Mar 2003 23:44:35 -0500 Subject: Strange regex problem In-Reply-To: References: Message-ID: <20030303044435.GA17848@meson.dyndns.org> On Sun, Mar 02, 2003 at 10:30:38PM +0100, Rene Pijlman wrote: > > Also, this definitely proofs that Python's weak typing is not a > good idea. The standard reply "unit testing" obviously doesn't > work when a function/method behaves correctly, but is called > with wrong parameters. This would never have happened in Java. > ;-) > -1 -- up 22 days, 8:30, 9 users, load average: 0.17, 0.20, 0.25 From aleax at aleax.it Thu Mar 13 02:54:32 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Mar 2003 07:54:32 GMT Subject: Can __iter__ be used as a classmethod? References: <2259b0e2.0303111203.3b8147ae@posting.google.com> Message-ID: Aahz wrote: ... >> """Subclasses of Frozen are frozen, i.e. it is impossible to add >> new attributes to them and their instances, except via inheritance""" ... > Why the heck didn't you use __slots__?!?!?! Just using __slots__ (without a custom metaclass) would NOT "freeze" any subclass: just by subclassing, you'd get instances to which attributes could freely be added. A custom metaclass might well be a more suitable approach, of course, and it could, in particular. use __slots__ to optimize things. Alex From martin.vonloewis at hpi.uni-potsdam.de Thu Mar 27 11:32:14 2003 From: martin.vonloewis at hpi.uni-potsdam.de (Martin v. Löwis) Date: Thu, 27 Mar 2003 17:32:14 +0100 Subject: improved pickle References: Message-ID: > First, to whom can I write suggestions for the next versions of python? Depends on how formal you want the suggestions to be. You could write a Python Enhancement Proposal (PEP), see http://www.python.org/peps/pep-0001.html Alternatively, you can submit wishes at sf.net/projects/python. > I have improved the binary pickle module to be able to memorize existing > objects. Please understand that the pickle module is meant to be version-independent. Any improvements to it are unacceptable if they break backwards compatibility, i.e. if old pickles can't be read anymore with new releases. (emitting pickles that can't be read in old versions may be acceptable, depending on how desirable the change is). > For example if you have a global instance that you don't want to store into > the persistence but you do want to restore references to it. I would think this is supported today, by means of the persistent_id/persistent_load functions. Regards, Martin From dg96057 at teledomenet.gr Wed Mar 12 05:37:06 2003 From: dg96057 at teledomenet.gr (Dimitris Garanatsios) Date: Wed, 12 Mar 2003 12:37:06 +0200 Subject: Does ScientificPython run on Windows? References: Message-ID: <3E6F0DD2.7050400@teledomenet.gr> Gary Pajer wrote: > The docs seem to imply that it only works on Unix-like systems. > If so, is it necessary to compile it? I ain't got no stinkin' compilers on > Windows. :) > > Thanks, > Gary > > Hoping that we are talking about the same package, it works fine under windows too. To install it just unzip/untar the downloaded file and run python setup.py install from the directory you unzipped/untared it, as the README file instructs you... You won't have to compile anything, either on windows or on a *nix system (i think... at least i didn't) Regards, Dimitris From mathie at wossname.org.uk Thu Mar 27 10:20:58 2003 From: mathie at wossname.org.uk (Graeme Mathieson) Date: Thu, 27 Mar 2003 15:20:58 +0000 Subject: alternative manuals References: Message-ID: >>>>> "Marko" == Marko Faldix writes: Marko> Hi there, I would like to ask if someone uses other functions Marko> and library references then these at www.python.org. Maybe Marko> web references, maybe real books. Python in a Nutshell[1]. Well, it turned up from Amazon on Friday along with Learning Python and Programming Python which I'm currently working through. I fully intend to use it. On the other hand, the documentation on the main website looks pretty good. Footnotes: [1] http://www.oreilly.com/catalog/pythonian/ -- Right now, there are scr1pt k1dd13s plotting to DDoS my network, my co-lo server is not responding to pings and the people that I IRC with may be involved in both. I'm sysadmin Graeme Mathieson and this is the longest day of my life. http://www.wossname.org.uk/ From aleax at aleax.it Thu Mar 13 13:05:23 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Mar 2003 19:05:23 +0100 Subject: Tuples, what are they: read-only lists or heterogeneous data arrays? In-Reply-To: <20030313122020.GE2112@xs4all.nl> References: <15982.24855.181016.568236@montanaro.dyndns.org> <200303131207.09183.aleax@aleax.it> <20030313122020.GE2112@xs4all.nl> Message-ID: <200303131905.23782.aleax@aleax.it> On Thursday 13 March 2003 01:20 pm, Thomas Wouters wrote: ... > Notice how I said it didn't require modification of the interpreter or of > builtin types; *that* kind of work can get rejected by Guido. A separate > module to accomplish a task is never wasted, as long as it's useful (and if > it's not useful, it shouldn't be added, right?) There are plenty of Kludges to work around the lack of __as_immutable__ in built-in lists &c would make near-useless any "separate module to accomplish the task" of using (frozen copies of) lists as dict keys &c -- just as: > Not quite an analogous example. The iteration protocol requires interpreter > changes to be generally useful, as having to write 'for item in > iterator(object)' or 'for item in object.iterator()' almost negates the What makes you think that having to do somedict[freeze(somelist)]=xx and then check by "if tempfreeze(somelist) in somedict:" etc would be any more "generally useful" than having to write "for item in iter(x):" ...? > Yes, PR is as important in selling an idea to Guido (or most people, in > fact) as code is. But *without* code, it becomes that much harder to sell, > even if it's just half-working, proof-of-concept, pseudo-code. And nothing > makes accepting more easy than having a working, community-accepted, > widely-used implementation ready and working. :-) There is ZERO chance of having a "community-accepted implementation" for something that needs to be in the core to be useful -- and this holds for a "freezing protocol" just as much as it holds for iterator. When the needed changes are obvious (and that is clearly so for "freezing", even more than for iterators), developing a patch to implement the obvious is a just-as-obvious utter waste of time and energy that (if one IS keen to have the change in the core) should instead be entirely deployed in "PR work". Do you think that it makes ANY difference whether there's one or a million patches to implement ternary operators -- will the existence of those patches make ANY difference to the likelihood of Guido introducing a ternary op into Python?! *PAH*. It's *STRICTLY* a matter of creating an upswell of popular support -=- enough to get Guido to decide to hold a popular consultive vote on the issue, AND enough to get (hypothetically) overwhelming support for the change. Ternary proponents managed the first but not the second -- we'll see what happens. But NO MATTER how many patches they might have written, all of them together would have been completely useless in swinging a single popular vote, and thus a total waste of effort. I think you're confusing the issue of changes that appear to present any amount at all of technical difficulty, with that of changes which are entirely obvious and bereft of any difficulty EXCEPT that of convincing Guido. Working to develop patches is just as obviously "utterly useless" for the latter kind, as it's "potentially useful" for the former kind. And since a "freezing protocol" is quite clearly in the latter category, thus do I believe that your advice in the matter is totally wrong, misplaced, and misleading. Alex From me at privacy.net Sun Mar 16 20:27:12 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Mon, 17 Mar 2003 13:27:12 +1200 Subject: No Do while/repeat until looping construct in python? In-Reply-To: References: <4017400e.0303130007.5762bf65@posting.google.com> <3bXba.70188$zo2.1844793@news2.tin.it> Message-ID: Steven Taschuk wrote: > But they're not equivalent, logical massage or no. > while not clean > rinse > lather > doesn't rinse and lather if already clean, while > repeat > rinse > lather > until clean > rinses and lathers at least once in all cases. And both of them leave my clothes lathered at the end of the process. :-( Glad-you're-not-programming-MY-washing-machine-ly, -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From tim_one at email.msn.com Thu Mar 27 23:38:06 2003 From: tim_one at email.msn.com (Tim Peters) Date: Thu, 27 Mar 2003 23:38:06 -0500 Subject: Copy with __slots__...will it ever work? In-Reply-To: <7754c18e.0303271745.739012cc@posting.google.com> Message-ID: [Andrew Sterian] > I've run up against the problem of not being able to call copy.copy() > on a new-style class that defines __slots__. If you can, try current CVS Python. Guido reworked a lot of this code after the 2.3a2 release, as part of our introduction of a new pickle protocol. New-style classes that define __slots__ can be pickled in current CVS Python, and copy.copy() may have inherited relevant new abilities too. > ... > * Will copy.copy() ever work with __slots__? Is it in the pipe for a > future version? > > * If not, why not? Is there a good technical reason? or just not > enough demand? Nobody who knows has time to write about this stuff. If you can't try it yourself, please post specific examples you care about, and I'm sure someone else will try them and report back. if-it-were-obvious-you-wouldn't-have-asked-ly y'rs - tim From mwh at python.net Fri Mar 7 09:06:37 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 7 Mar 2003 14:06:37 GMT Subject: Concerns about performance w/Python, Pysco on Pentiums References: <3E660EB3.4065D81F@engcorp.com> <3E66BA3F.7691C3B0@engcorp.com> <3e677433$0$87747$edfadb0f@dread11.news.tele.dk> <7h3bs0oh25s.fsf@pc150.maths.bris.ac.uk> <3E6784AD.E4D523BD@engcorp.com> <7h3y93sfldh.fsf@pc150.maths.bris.ac.uk> <3E67A2F2.187785EA@engcorp.com> Message-ID: <7h3llzrff5g.fsf@pc150.maths.bris.ac.uk> Peter Hansen writes: > Tentative conclusion: although it's at the bottom of the range of > claimed improvements from Psyco, I'll take my 36% and run. I'll > switch to lists, because dicts have zero advantages in this case, > though the speedup is minor. Have you tried Python 2.3a2? You might like what you see (pymalloc is probably the main reason for the improvement, but there have been many, many little performance tweaks). Cheers, M. -- In short, just business as usual in the wacky world of floating point . -- Tim Peters, comp.lang.python From paul at boddie.net Fri Mar 21 08:03:21 2003 From: paul at boddie.net (Paul Boddie) Date: 21 Mar 2003 05:03:21 -0800 Subject: Website using Python--what's best architecture? CGI? References: Message-ID: <23891c90.0303210503.3728d5ae@posting.google.com> Andy Robinson wrote in message news:... > > > >So, don't CGI ! Programming a CGI highly dynamic site is a hassle, even with > >the help of a templating or HTML generator package (like HTMLGen and > >others). > > I disagree. Several years of making reporting 'add-ons' to other > people's app servers, which are usually CGI scripts, has taught > me something very interesting. I'm guessing that your "add-ons" are CGI scripts, as opposed to the application servers of those other people. Clarification is necessary here because CGI scripts can act as the "gateway" to application servers - eg. Webware's WebKit.cgi. > Our apps consistently respond several times faster than the big Websphere or > ASP systems that talk to them. The other systems have usually been written by > large numbers of smart programmers over time and tend to get big and slow as > they add more features, or maybe just because they have a heck of a lot of > code to execute in their main loops.. I can understand this, and I can see how it's interesting to use as much of Apache's infrastructure (for example) as possible to do application server type activities. > I also think that how the process is initiated (which is what CGI is > about) has absolutely nothing to do with the framework you use or > don't use. You can make a simple, clean dispatch mechanism > and a few utilities to preserve state with tokens in very few lines > of code. And if your web frame work is <1000 lines of Python > code, which is plenty, there won't be a big startup overhead. Indeed, there's a lot to be said for making use of the capabilities of the operating system. Start-up of Python processes doesn't necessarily involve heavy I/O, and as far as things like session storage and persistence are concerned, modern filesystems certainly have something to offer in competition to relational database systems. Moreover, the traditional separate process model can be quite compelling with Python and the issues the current interpreter has with distributing threads across multiple CPUs - this being an element in recent discussions of Python's performance in Web applications. > Please measure for yourself the actual time taken to execute a > 'hello world' type page which does one query and formats > the output on the different frameworks you are considering. And then contribute the results to the WebProgramming section of the PythonInfo Wiki. :-) [...] > >In addition, playing with CGI means creating a new DB connector for each > >request when (most) Web application servers handle open DB connections pools > >for you. > > True, but...please measure the connection overhead. [...] > OTOH I was told once that Oracle could take seconds and allocate > megabytes of RAM for each connection. Yes, it apparently depends on the database system concerned. Previous involvement in Oracle-based applications tended to result in avoidance of "straight CGI" for this very reason. > This would be a really fun topic for a Python conference: > set a simple task and actually test and benchmark all those > web frameworks. ;-) Indeed. However, I think that performance obsessions obscure the reason for the existence of most of these frameworks: to provide high-level APIs to the information and "transactions" involved in Web applications. One could argue that the diversity of the high-level APIs currently employed in the various frameworks is a major obstacle to portability of applications (ie. right now you write your application for either Zope, Webware, SkunkWeb, etc. and have to commit to that choice), but one could also argue that one also has the freedom to choose a paradigm that feels comfortable. Another possibility, of course, is to undermine the need to employ an application server in various cases by enhancing the 'cgi' module in the standard library, but the last time such improvements were proposed, the response was less than lukewarm. Paul From johnroth at ameritech.net Fri Mar 21 18:28:43 2003 From: johnroth at ameritech.net (John Roth) Date: Fri, 21 Mar 2003 18:28:43 -0500 Subject: What's up with rebinding assignment? References: Message-ID: "Ulrich Petri" wrote in message news:b5fse2$294l9f$1 at ID-67890.news.dfncis.de... > > "Jp Calderone" schrieb im Newsbeitrag > news:mailman.1048270535.12131.python-list at python.org... > > > > Why is rebinding a variable from a nested scope a design flaw, if > reading > > it is not? > > > > In my unit tests, I tend to have a lot of things like this: > > > > [snip unittest] > > > > Why should assignment to an attribute of a name in an outer scope be any > > different from assignment to an actual outer name? Or does this code > > have a serious design flaw? ;) > > Perhaps i didn't made myself very clear. > I your case you are changing an attribute of self, not self-the-thing. > > What i wanted to say is that no deeper scope should be able to change a > higher level variable. It depends on what you're doing. I've had cases where I actually wanted to do that. Having to work around not being able to change variables in the immediately enclosing scope resulted in a non-obvious mess. Of course, that occurs very rarely. In general, that kind of side effect is a rather noxious code smell. John Roth If there are things you can't do, there will be results you can't get. From spam+py at magnetic-ink.dk Mon Mar 3 01:22:22 2003 From: spam+py at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Mon, 3 Mar 2003 06:22:22 +0000 (UTC) Subject: Using an operator as an object References: <8d3e714e.0303021819.24f1aa38@posting.google.com> Message-ID: <0ddf43fd-e2ed-414b-a8f2-711d1d1c275f@news.szn.dk> Tony C wrote: > What I'd like to do is this > > > def docalc( operator, num1, num2): > > return (num1 operator num2 ) Perhaps you could use: #v+ def docalc(operator, num1, num2): return eval( repr(num1) + operator + repr(num2) ) end def docalc #v- or its lambda equivalent: #v+ docalc = lambda op, n1, n2: eval( repr(n1) + op + repr(n2) ) #v- Please beware of security issues re eval. // Klaus -- ><> vandag, m?re, altyd saam From someone at invalid.com Sat Mar 1 23:05:45 2003 From: someone at invalid.com (Sean Richards) Date: Sun, 02 Mar 2003 04:05:45 GMT Subject: Code speedup tips References: <3E6146A9.30607@heimsnet.is> Message-ID: On Sat, 01 Mar 2003 23:47:53 +0000, Dagur P?ll Ammendrup wrote: > Hi > > If you haven't already, I recommend reading this: > > http://manatee.mojam.com/~skip/python/fastpython.html > > -Dagur > Great stuff, thankyou :) Sean -- +---------------------------------------------------------------+ | All spelling errors are intentional and are there to show new | | and improved ways of spelling old words. | +---------------------------------------------------------------+ From missive at frontiernet.net Thu Mar 27 23:45:04 2003 From: missive at frontiernet.net (Lee Harr) Date: Fri, 28 Mar 2003 04:45:04 GMT Subject: Beginner Question References: Message-ID: In article , Kevin Reeder wrote: > I'm working through the online Python beginner's guide "How to Think Like a > Computer Scientist" and am stumped on one of the exercises. A > function to shuffle cards within a class definition called Deck appears > as follows: > > def shuffle(self): > import random > nCards = len(self.cards) > for i in range(nCards): > j = random.randrange(i, nCards) > self.cards[i], self.cards[j] = self.cards[j], self.cards[i] > > The problem is to rewrite the last line without using a sequence > assignment. Everything I've thought of has the result of only inserting > the random integer j at each index which doesn't solve the problem. I'm > not really asking for the "right" answer as much as something to jog my > thought in the right direction! > Well... it is not just the last line, but I think the best way would be: import random def shuffle(self): random.shuffle(self.cards) How about this: def shuffle(self): import random nCards = len(self.cards) for i in range(nCards): j = random.randrange(i, nCards) self.cards.insert(i, self.cards.pop(j)) From staschuk at telusplanet.net Tue Mar 18 02:42:45 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 18 Mar 2003 00:42:45 -0700 Subject: Linux password manipulation in Python In-Reply-To: <1047951824.19558.21.camel@helot>; from jkrukoff@ltgc.com on Mon, Mar 17, 2003 at 06:43:44PM -0700 References: <200303171030.05262.gherron@islandtraining.com> <1047951824.19558.21.camel@helot> Message-ID: <20030318004245.A16419@tibia.amotlpaa.bogus> Quoth John Krukoff: > You probably want to look at man 3 crypt. [...] But not, note, the crypt(3) that comes in the man-pages package, which describes only the DES hashing method; I presume you're referring to one which comes with glibc. > On my box (gentoo): > > # grep jkrukoff /etc/shadow > jkrukoff:$1$TR8v8QBY$/RuCh8wlK.aHczufkXFbZ/:12129:0:99999:7::: > > # python > >>> from crypt import crypt > >>> crypt( 'bob', '$1$TR8v8QBY$' ) > '$1$TR8v8QBY$/RuCh8wlK.aHczufkXFbZ/' > > Where the salt begins with '$1$', is a maximum of eight characters and > is optionally terminated by a '$'. Needless to say, this probably isn't > very portable. The important thing for the OP is, I think, that the salt for the MD5 method includes everything up to the third '$', and not just the first two characters (as in the DES method). I think this '$1$...$' business is more portable than you think: the glibc sources have comments which suggest that they're duplicating an existing implementation from elsewhere; the shadow suite seems to have taken it from FreeBSD. It's not *just* a GNU extension. Certainly, if you look in /etc/passwd or /etc/shadow and find a hash that starts with '$1$' (which is not permissible with Unix crypt), then it's a good guess that it's an MD5-based hash as above and that the local system's crypt() will do the Right Thing if you separate out the salt properly. In case anybody's interested, I include below a na?ve reimplementation in Python of glibc's md5_crypt. It's an entertainingly bizarre algorithm. #!/usr/bin/env python """Reimplementation of MD5-based crypt(), based on glibc 2.2.4.""" import md5 import string def md5_crypt(key, salt): assert salt.startswith('$1$') assert salt.endswith('$') salt = salt[3:-1] assert len(salt) <= 8 hash = md5.new() hash.update(key) hash.update('$1$') hash.update(salt) second_hash = md5.new() second_hash.update(key) second_hash.update(salt) second_hash.update(key) second_hash = second_hash.digest() q, r = divmod(len(key), len(second_hash)) second_hash = second_hash*q + second_hash[:r] assert len(second_hash) == len(key) hash.update(second_hash) del second_hash, q, r # Comment in glibc 2.2.4 source: # "The original implementation now does something weird: for every 1 # bit in the key the first 0 is added to the buffer, for every 0 # bit the first character of the key. This does not seem to be # what was intended but we have to follow this to be compatible." # But this is *not* what their code does. The code alternates # between '\0' and key[0] based *not* on the bits of the key, # but on the bits of the representation of the *length* of the # key. Weirdness on top of weirdness. i = len(key) while i > 0: if i & 1: hash.update('\0') else: hash.update(key[0]) i >>= 1 hash = hash.digest() for i in xrange(1000): nth_hash = md5.new() if i % 2: nth_hash.update(key) else: nth_hash.update(hash) if i % 3: nth_hash.update(salt) if i % 7: nth_hash.update(key) if i % 2: nth_hash.update(hash) else: nth_hash.update(key) hash = nth_hash.digest() # a different base64 than the MIME one base64 = './0123456789' \ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \ 'abcdefghijklmnopqrstuvwxyz' def b64_three_char(char2, char1, char0, n): byte2, byte1, byte0 = map(ord, [char2, char1, char0]) w = (byte2 << 16) | (byte1 << 8) | byte0 s = [] for _ in range(n): s.append(base64[w & 0x3f]) w >>= 6 return s result = ['$1$', salt, '$'] result.extend(b64_three_char(hash[0], hash[6], hash[12], 4)) result.extend(b64_three_char(hash[1], hash[7], hash[13], 4)) result.extend(b64_three_char(hash[2], hash[8], hash[14], 4)) result.extend(b64_three_char(hash[3], hash[9], hash[15], 4)) result.extend(b64_three_char(hash[4], hash[10], hash[5], 4)) result.extend(b64_three_char('\0', '\0', hash[11], 2)) return ''.join(result) def _test(): assert md5_crypt('bob', '$1$TR8v8QBY$') == \ '$1$TR8v8QBY$/RuCh8wlK.aHczufkXFbZ/' if __name__ == '__main__': _test() -- Steven Taschuk "The world will end if you get this wrong." staschuk at telusplanet.net -- "Typesetting Mathematics -- User's Guide", Brian Kernighan and Lorrinda Cherry From zhitenev at cs.vsu.ru Tue Mar 18 09:50:15 2003 From: zhitenev at cs.vsu.ru (Lexy Zhitenev) Date: Tue, 18 Mar 2003 17:50:15 +0300 Subject: script filename and autorun References: <3e77229a$1@newsflash.abo.fi> Message-ID: "Simon Dahlbacka" wrote in message news:3e77229a$1 at newsflash.abo.fi... > Hi, > Hi, also. > > 1) how do I get the filename of the current script running? (I want to > detect location at runtime) As I have solved this problem, the result that works anyhow this script is executed is import sys, os print os.path.abspath(sys.argv[0]) > 2) is it enough with just a key "python > c:\whateverthepathistomyprogram\prog.py" in ...\Run or do I also need full > path to python? It is enough on WinNT, 2000 and XP, but it won't work on Win9x branch. You will have to write full path to interpreter. Of course it has to be installed. Lexy From me at privacy.net Mon Mar 10 22:42:01 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 11 Mar 2003 16:42:01 +1300 Subject: Can __iter__ be used as a classmethod? In-Reply-To: <2259b0e2.0303061227.6f7934fb@posting.google.com> References: <3e649aa3_4@news.bluewin.ch> <2259b0e2.0303041023.43e8b81f@posting.google.com> <4B89a.6715$zo2.218162@news2.tin.it> <3e65273f$1_3@news.bluewin.ch> <2259b0e2.0303050855.1eece801@posting.google.com> <2259b0e2.0303061227.6f7934fb@posting.google.com> Message-ID: Michele Simionato wrote: > It seems I must define a dummy class > >>>>class C(object): pass > > bound the classmethod to it > >>>>C.c=c > > and then retrieve the original function via im_func > >>>>C.c.im_func > > It there must be a better way! It seems like you should be able to do c.__get__(None).im_func. I just tried that and I got Python 2.2 (#1, Jul 11 2002, 14:19:37) [GCC 3.0.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def f(x): return x ... >>> c=classmethod(f) >>> d = c.__get__(None) Segmentation fault (core dumped) Oops! But it would probably have worked if I had a less buggy version of Python... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From abulka at netspace.net.au Tue Mar 18 04:36:52 2003 From: abulka at netspace.net.au (Andy Bulka) Date: 18 Mar 2003 01:36:52 -0800 Subject: A fun tool for demonstrating or teaching python? References: <9s7ba.2698$4q6.305236@news20.bellglobal.com> Message-ID: <13dc97b8.0303180136.3e78548a@posting.google.com> I have a page dedicated to OO / software Visualisation at http://www.atug.com/andypatterns/egg.htm which might provide some ideas on how visual python debuggers and/or development environments might work. -Andy Bulka http://www.atug.com/andypatterns From peter at engcorp.com Mon Mar 17 16:34:54 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 Mar 2003 16:34:54 -0500 Subject: Rudeness (was: Re: OT: Aspergers link) References: Message-ID: <3E763F7E.43E2FDA5@engcorp.com> Eric Stechmann wrote: > > At 07:08 PM 3/17/03 +0000, Carl Banks wrote: > >Please accept my apologies for suggesting that you're not really > >mentally ill. > > It appears that Mr Banks has little or nothing of worth to contribute. And it appears that with the massive 21 or so lines of useless cruft that makes up your signature, your own signal-to-noise ratio is even less impressive. Carl we know: he _adds_ content. Who are you? -Peter From pinard at iro.umontreal.ca Mon Mar 3 16:21:00 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois_Pinard?=) Date: 03 Mar 2003 16:21:00 -0500 Subject: diff for (text only) manuscripts In-Reply-To: References: Message-ID: [Jon Slavin] > This is not Python specific, but it seems that Python offers hope for a > solution. [...] a diff that is word as opposed to line oriented. [...] > Any suggestions welcome. This is not really a Python solution, but there is a little tool called `wdiff', which does a word oriented diff, merely as a C fronted to `diff'. It is part of GNU, and written at a time I did not know Python. :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From staschuk at telusplanet.net Tue Mar 18 02:44:09 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 18 Mar 2003 00:44:09 -0700 Subject: PEP 312 (and thus 308) implemented with a black magic trick In-Reply-To: ; from sross@connectmail.carleton.ca on Mon, Mar 17, 2003 at 08:38:22PM -0500 References: <2259b0e2.0303171358.5a6fe337@posting.google.com> <3E766255.5D06489A@alcyone.com> Message-ID: <20030318004409.C16419@tibia.amotlpaa.bogus> Quoth Sean Ross: [...] > '~' just happens to be easier than ':' to intelligently isolate and replace > in Python code because it > has fewer possible uses/meanings. Imho the more important factor is that the code using ~ in the black magic way can be compiled by the stock compiler as is (though the result of that compilation is never used). -- Steven Taschuk o- @ staschuk at telusplanet.net 7O ) " ( From tomchance at gmx.net Sun Mar 16 05:37:03 2003 From: tomchance at gmx.net (Tom Chance) Date: Sun, 16 Mar 2003 10:37:03 +0000 Subject: Closing pipes References: <1047787460.506561@yasure> Message-ID: Donn Cave wrote: > Quoth Tom Chance : > | I've got a bit of code that opens a new pipe with os.popen, to start > | mencoder. When I call the close() function on it, it takes an > | unacceptably long time to close the pipe and return to the main thread. > | > | I've tried using popen2.popen2 to open and close the thread, and this > | will close the thread instantly, but rather than killing the process, it > | simply seems to detach itself from the thread and return python to its > | main thread. > | > | Is it simply an unavoidable feature of python and its pipe support that > | it will take quite a while to kill a process? Is there any way I can > | kill the process more quickly? > > You would kill the process with the kill() function (posix or os.kill()) > It sends your choice of signal to the process; you might use SIGTERM. But to use the kill() function I need to know the process ID of the pipe, and afaik popen() doesn't return that, and neither does fork(). How can I get the pid? Tom From nospam at horvath.com Mon Mar 3 19:58:00 2003 From: nospam at horvath.com (Bob Horvath) Date: Tue, 04 Mar 2003 00:58:00 GMT Subject: affordable Zope hosting References: <9lR8a.383154$Yo4.12760797@news1.calgary.shaw.ca> Message-ID: On Mon, 03 Mar 2003 17:14:13 -0600, John E. Barham wrote: > Shameless plug: Lane Street Labs at www.LaneStLabs.com Shameless plugs are fine by me, but feel free to email them if you feel it is in appropriate to post here. I am surprised there weren't more responses. Is there a better place for me to have asked? From v.wehren at home.nl Tue Mar 4 12:15:54 2003 From: v.wehren at home.nl (vincent wehren) Date: Tue, 4 Mar 2003 18:15:54 +0100 Subject: IME withTix on multilanguagesupported system ? References: <34e4328e.0303020911.7c7ed0c9@posting.google.com> <3E64A0BA.9080604@v.loewis.de> Message-ID: "Martin v. L?wis" schrieb im Newsbeitrag news:3E64A0BA.9080604 at v.loewis.de... > vincent wehren wrote: > > Exactly my point. I don't know about 8.4, with in 8.3 there's no way I can > > *input* German and Russian in the same widget by switching the keyboard > > layout and have them both rendered correctly with the same underlying > > codepage (pasting cyrillic alongside German is no problem). It sure seems > > like Tk doesn't do anything with the WM_INPUTLANGCHANGE notification (yet). > > I just tried, and it works better than we think it does. I installed the > Vietnamese keyboard on an English XP installation with German MUI. > Switching the keyboard to Vietnamese in IDLE of Python 2.2.1 (Tk 8.3), I > can happily enter characters not supported in my codepage (1252), such > as "a" (U+0103, LATIN SMALL LETTER A WITH BREVE). Are you sure that's what you're seeing? Turning up the font size in config-win.txt tells me it's a small a with tilde ("?") not with breve! Regards, Vincent > Regards, > Martin > From ycal at grapevine.net Sat Mar 1 12:00:23 2003 From: ycal at grapevine.net (Phil Lacy) Date: Sat, 1 Mar 2003 11:00:23 -0600 Subject: how to debug a python program normally run in windows console Message-ID: <3e60e5a4_1@newsfeed> I have a program that has a bug but it is run from a windows console. If I start program from idle it doesn't read my environment variables that I have to preset in the console before running the python file. if I type python I have no idea where to go from the command-line python typing help just gives me some prompt unknown to me. Any idea where to get help on debugging from a windows console -- - Phil -reverse ycal for email- -For MSACCESS, comments are made -regarding vers9.0 (2000) UON - From jack at performancedrivers.com Mon Mar 24 04:16:25 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 24 Mar 2003 04:16:25 -0500 Subject: Python 2.3 True = False In-Reply-To: ; from anand@calbay.com on Sun, Mar 23, 2003 at 10:58:14PM -0800 References: Message-ID: <20030324041625.H6746@localhost.localdomain> On Sun, Mar 23, 2003 at 10:58:14PM -0800, Anand wrote: > >>> True = False > >>> True > False > > has anyone tried this before? Yes, in FORTRAN. And it has the same effect. -jackdied From axel at pizza.home.kosnet.com Fri Mar 21 09:15:25 2003 From: axel at pizza.home.kosnet.com (Axel Straschil) Date: 21 Mar 2003 15:15:25 +0100 Subject: Parsing HTML-Code to readable References: Message-ID: Hallo! > Perhaps mxTidy is what you need? > Yes, exactly!!! Thanks, AXEL. From aleax at aleax.it Wed Mar 12 13:21:51 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 12 Mar 2003 18:21:51 GMT Subject: deepcopy problem with new-style classes in Python 2.3a2 References: Message-ID: <3VKba.46563$pG1.1102880@news1.tin.it> Stephen C Phillips wrote: > Hi, > I am having a problem using deepcopy on a complex data structure. I > think it can be distilled down to a basic difficulty shown below (thanks > to Jp Calderone). > With Python 2.3a2 (or Python 2.2.2) I get this: > >>>> class Foo(object): > ... pass > ... >>>> f = Foo() >>>> f.foo = f >>>> g = copy.deepcopy(f) >>>> g is not f > True >>>> f is f.foo > True >>>> g is g.foo > False > > Obviously I would like "g.foo is foo" to be True. > g.foo is not f either, it is some other empty object. > With old-style classes I get the desired behaviour. Can anyone explain > what the problem is? Module copy is currently not able to install a "proper" deep-copier function that works automatically and correctly for instances of new-style classes, in good part because it has no way to identify "instances of new-style classes" as such (as opposed to, e.g., instances of subclasses of list, or dict, etc -- they're all much the same thing, but need very different approaches to deep-copying). I suggest you submit this as a bug, and if you need a workaround you can ensure your new-style classes contain a __deepcopy__ that satisfies your needs, such as: def __deepcopy__(self, memo): x = Foo.__new__(Foo) memo[id(self)] = x for n, v in self.__dict__.iteritems(): setattr(x, n, copy.deepcopy(v, memo)) return x for new-style classes whose instances hold all of their state in __dict__, and so on. Alex From trentm at ActiveState.com Fri Mar 7 18:35:55 2003 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 7 Mar 2003 15:35:55 -0800 Subject: upload file via web form In-Reply-To: ; from jdhunter@ace.bsd.uchicago.edu on Fri, Mar 07, 2003 at 04:24:52PM -0600 References: Message-ID: <20030307153555.A27234@ActiveState.com> [John Hunter wrote] > > I want to automatically upload some data to a password protected web > server where some form variables must be filled out and a file must be > uploaded. > > I know how to do it directly with httplib. Is there a better way? I don't think so. Normally urllib.urlopen() (or urllib2.urlopen()) would be what you should use here however then do not handle HTTP POST requests properly when a file upload is involved. Uploading form data when a file is involved means that the HTTP POST body must be encoded as multipart/form-data. .urlopen() is hardcoded to use a Content-Type header of application/x-www-form-urlencoded (which is what you want if _no_ file is involved). Here is a method that I have been working on to do this. I suppose a bug should be logged on urlopen for this as well. Trent -- Trent Mick TrentM at ActiveState.com -------------- next part -------------- """Some httplib helper methods.""" def httprequest(url, postdata={}, headers={}): """A urllib.urlopen() replacement for http://... that gets the content-type right for multipart POST requests. "url" is the http URL to open. "postdata" is a dictionary describing data to post. If the dict is empty (the default) a GET request is made, otherwise a POST request is made. Each postdata item maps a string name to either: - a string value; or - a file part specification of the form: {"filename": , # file to load content from "content": , # (optional) file content "headers": } # (optional) headers is used to load the content (can be overridden by ) and as the filename to report in the request. is a dictionary of headers to use for the part. Note: currently the file part content but be US-ASCII text. "headers" is an optional dictionary of headers to send with the request. Note that the "Content-Type" and "Content-Length" headers are automatically determined. The current urllib.urlopen() *always* uses: Content-Type: application/x-www-form-urlencoded for POST requests. This is incorrect if the postdata includes a file to upload. If a file is to be posted the post data is: Content-Type: multipart/form-data This returns the response content if the request was successfull (HTTP code 200). Otherwise an IOError is raised. For example, this invocation: url = 'http://www.perl.org/survey.cgi' postdata = { "name": "Gisle Aas", "email": "gisle at aas.no", "gender": "M", "born": "1964", "init": {"filename": "~/.profile"}, } Would generate a request similar to this (your boundary and ~/.profile content will likely be different): POST http://www.perl.org/survey.cgi Content-Length: 388 Content-Type: multipart/form-data; boundary="6G+f" --6G+f Content-Disposition: form-data; name="name" Gisle Aas --6G+f Content-Disposition: form-data; name="email" gisle at aas.no --6G+f Content-Disposition: form-data; name="gender" M --6G+f Content-Disposition: form-data; name="born" 1964 --6G+f Content-Disposition: form-data; name="init"; filename=".profile" Content-Type: text/plain PATH=/local/perl/bin:$PATH export PATH --6G+f-- Limitations: - I don't think binary files are handled properly. And I don't think Unicode files will be handled properly. We will have to get smart on allowing the mimetype and (if text) charset to be specified. By default we try to guess: text/plain or application/octet-stream. If text/* then try to guess the charset. See Lib/email/Charset.py for inspiration here. There are also a couple of Python Cookbook recipes for encoding guessing. - This doesn't do HTTP error handling for some code as does urllib.urlopen() for error codes 301, 302 and 401. - I don't know if the return semantics are good. For instance the reponse headers are not accessible. Inspiration: Perl's HTTP::Request module. http://aspn.activestate.com/ASPN/Reference/Products/ActivePerl/site/lib/HTTP/Request/Common.html """ import httplib, urllib, urlparse from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart if not url.startswith("http://"): raise "Invalid URL, only http:// URLs are allow: url='%s'" % url if not postdata: method = "GET" body = None else: method = "POST" # Determine if require a multipart content-type: 'contentType'. for part in postdata.values(): if isinstance(part, dict): contentType = "multipart/form-data" break else: contentType = "application/x-www-form-urlencoded" headers["Content-Type"] = contentType # Encode the post data: 'body'. if contentType == "application/x-www-form-urlencoded": body = urllib.urlencode(postdata) elif contentType == "multipart/form-data": message = MIMEMultipart(_subtype="form-data") for name, value in postdata.items(): if isinstance(value, dict): # Get content. if "content" in value: content = value["content"] else: fp = open(value["filename"], "rb") content = fp.read() fp.close() # Create text part. Do not use ctor to set payload # to avoid adding a trailing newline. part = MIMEText(None) part.set_payload(content, "us-ascii") # Add content-disposition header. dispHeaders = value.get("headers", {}) if "Content-Disposition" not in dispHeaders: #XXX Should be a case-INsensitive check. part.add_header("Content-Disposition", "form-data", name=name, filename=value["filename"]) for dhName, dhValue in dispHeaders: part.add_header(dhName, dhValue) else: # Do not use ctor to set payload to avoid adding a # trailing newline. part = MIMEText(None) part.set_payload(value, "us-ascii") part.add_header("Content-Disposition", "form-data", name=name) message.attach(part) message.epilogue = "" # Make sure body ends with a newline. # Split off the headers block from the .as_string() to get # just the message content. Also add the multipart Message's # headers (mainly to get the Content-Type header _with_ the # boundary attribute). headerBlock, body = message.as_string().split("\n\n",1) for hName, hValue in message.items(): headers[hName] = hValue #print "XXX ~~~~~~~~~~~~ multi-part body ~~~~~~~~~~~~~~~~~~~" #import sys #sys.stdout.write(body) #print "XXX ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" else: raise "Invalid content-type: '%s'" % contentType # Make the HTTP request and get the response. # Precondition: 'url', 'method', 'headers', 'body' are all setup properly. scheme, netloc, path, parameters, query, fragment = urlparse.urlparse(url) if parameters or query or fragment: raise "Unexpected URL form: parameters, query or fragment parts "\ "are not allowed: parameters=%r, query=%r, fragment=%r"\ % (parameters, query, fragment) conn = httplib.HTTPConnection(netloc) try: conn.request(method, path, body, headers) response = conn.getresponse() # Process the reponse. Here is a summary of HTTP responses: # http://www.btinternet.com/~wildfire/reference/httpstatus/index.htm if response.status == 200: return response.read() else: #print "XXX http error:" #print " status:", response.status #print " reason:", response.reason #print " msg:", response.msg raise IOError, ('http error', response) finally: conn.close() From thomas at xs4all.net Sat Mar 8 13:51:30 2003 From: thomas at xs4all.net (Thomas Wouters) Date: Sat, 8 Mar 2003 19:51:30 +0100 Subject: Bug or wart? You make the call. In-Reply-To: <698f09f8.0303081039.a2b69dd@posting.google.com> References: <2e363c08.0303051256.58c94b08@posting.google.com> <20030307180524.GF9018@siliconimage.com> <698f09f8.0303081039.a2b69dd@posting.google.com> Message-ID: <20030308185130.GL2112@xs4all.nl> On Sat, Mar 08, 2003 at 10:39:28AM -0800, Jeremy Fincher wrote: > Jp Calderone wrote in message news:... > > There is one very practical reason. Method objects (not "class methods" - > > those are something else) are created anew every time they are fetched! > What's the rationale behind this behavior? It doesn't have an official rationale, but it's easily considered. Python is a very dynamic language. An instance's __class__ and a class's __bases__ can be dynamically changed. It is part of how Python Works. -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! From ken at perfect-image.com Tue Mar 11 11:21:11 2003 From: ken at perfect-image.com (Ken Godee) Date: Tue, 11 Mar 2003 09:21:11 -0700 Subject: Extend with Java/Printing? In-Reply-To: Message-ID: <3E6DAA87.1795.8F1F75@localhost> > > Is it possible to extend python to use Java? > > Jython is perhaps what you're looking for ! > > www.jython.org > > * Python interpreter written in Java > * Access to all Java packages > * Compile Python to Java bytecode (.class) > > --Gilles I've seen it and seems popular, it just seemed backwards to what I wanted to do. I'll read up on it. From godoy at metalab.unc.edu Wed Mar 5 20:14:48 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Wed, 05 Mar 2003 22:14:48 -0300 Subject: How to get IP address References: <3E63138B.6000304@pa.press.net> <3E631721.1020003@freemail.hu> <1o9ij-ov2.ln1@beastie.ix.netcom.com> Message-ID: <86bs0ps3cn.fsf@ieee.org> Dennis Lee Bieber writes: > My dial-up address doesn't show at all (though the KPPP stats does > show both ends: local 165.247.213.30 remote 168.121.1.1 > > Of course, I only have the one machine in place, no idea what would > result if I hooked my laptop to the ethernet card and tried from it. I've made a really ugly hack as my first Python implementation of something web related. ---------------------------------------------------------------------- #! /usr/bin/env python # # Pattern we're looking for: # #

Your IP address is
# 200.181.178.165 #

# # Address: # # http://www.lawrencegoetz.com/programs/ipinfo/ # import urllib import re import sys from HTMLParser import HTMLParser class ProcessContents(HTMLParser): def handle_data(self, data): # Debug # print data ip_address = re.compile("\d+\.\d+\.\d+\.\d+").search(data) if ip_address: print ip_address.group() def start(): # Open and read website... sock = urllib.urlopen('http://www.lawrencegoetz.com/programs/ipinfo/') pagina = sock.read() sock.close() process = ProcessContents() process.feed(pagina) if (__name__ == '__main__'): start() ---------------------------------------------------------------------- I know I could do that in a much simpler way, but it was a toy to attach to a bigger thing... It will show you your IP address that is connected to the Internet. See you, -- Godoy. From paoloinvernizzi at dmsware.com Tue Mar 4 11:22:29 2003 From: paoloinvernizzi at dmsware.com (Paolo Invernizzi) Date: Tue, 04 Mar 2003 16:22:29 GMT Subject: what exactly is "None" ? In-Reply-To: References: Message-ID: <9p49a.176455$YG2.5342713@twister1.libero.it> Andrei Doicin wrote: > I know that "None" is the Boolean false value that > gets thrown out when there's nothing to return or a > function doesn't manage to reach the end of itself and thus "return > whatever", but *what* (in Python terms) exactly is equal to "None" ??? The *equality* can be implemented using the special __eq__ method, so *what* is *equal* to *None* can be driven in the direction you want... Strictly speaking only None==None because None *is* None! > I ask this as I'm trying to set up some conditional statements that do > something if "whatever" is equal to "None". Then you must implement in *whatever* the __eq__ operator... But, IMHO, you are looking at the problem in the wrong way... Paolo From kendall at monkeyfist.com Tue Mar 18 12:07:48 2003 From: kendall at monkeyfist.com (Kendall Clark) Date: Tue, 18 Mar 2003 11:07:48 -0600 Subject: Witch globalizacion (was: RE: Recommended Linux Laptops, supp liers?) In-Reply-To: References: Message-ID: <20030318170748.GA1914@monkeyfist.com> On Tue, Mar 18, 2003 at 04:39:12PM +0000, Alex Martelli wrote: > >> ...And to think there are people busy > >> protesting against "globalization"... *WICH* globalization?!... [snip] > Hmmm, I _am_ in favour of globalizing witches, too, but > as it happens it was an H I dropped here, not a T... While I concede this isn't the forum for this discussion, the antiglobalization protest movement is pretty clear what kind of globalization it opposes and what kind it favors. The World Social Forum at Porto Alegre is a good place to get a handle on these issues, are are the writings of Walden Bello, Vandana Shiva, or Noam Chomsky. In the interests of fairness and accuracy... Kendall Clark -- Jazz is only what you are. -- Louis Armstrong From gerard.breiner at ias.u-psud.fr Mon Mar 17 06:48:51 2003 From: gerard.breiner at ias.u-psud.fr (Gerard Breiner) Date: Mon, 17 Mar 2003 12:48:51 +0100 Subject: how to send a form html by email ? References: Message-ID: My form is a html form. My server apache is configured with mod-python and here is a part of my http.conf : ------------------------------ Alias /python "C:/Program Files/Apache Group/Apache/htdocs/python" AddHandler python-program .py PythonHandler email PythonDebug on --------------------------------- and here is my email.py file that i am trying to test. -------------------------------- import smtplib # Import the email modules we'll need from email.MIMEText import MIMEText # Open a plain text file for reading. For this example, assume that # the text file contains only ASCII characters. fp = open(textfile, 'rb') # Create a text/plain message msg = MIMEText(fp.read()) fp.close() # me == the sender's email address # you == the recipient's email address msg['Subject'] = 'The contents of %s' % textfile msg['From'] = me msg['To'] = you # Send the message via our own SMTP server, but don't include the # envelope header. s = smtplib.SMTP() s.connect() s.sendmail(me, [you], msg.as_string()) s.close() ------------------------------------------- Here is the error from my navigator : Mod_python error: "PythonHandler email" -------------------------------- Traceback (most recent call last): File "C:\Python22\Lib\mod_python\apache.py", line 181, in Dispatch module = import_module(module_name, _req) File "C:\Python22\Lib\mod_python\apache.py", line 335, in import_module module = imp.load_module(mname, f, p, d) File "c:/program files/apache group/apache/htdocs/python\email.py", line 2, in ? ImportError: No module named MIMEText --------------------------- Maybe, this module isn't implemented in apache module ? Best regards gerard "Gerhard H?ring" a ?crit dans le message de news: slrnb7ba24.1fo.gerhard.haering at haering.opus-gmbh.net... > Gerard Breiner wrote: > > Hello, > > > > Is someone has already made a script python so that to send a form by > > email from the web server ? [...] > > You can send email using the smtplib module. I'm not sure what kind of > "form" you might want to send by email, though. > > -- Gerhard From edream at tds.net Tue Mar 4 16:26:23 2003 From: edream at tds.net (Edward K. Ream) Date: Tue, 04 Mar 2003 21:26:23 GMT Subject: ANN: Leo 3.11b1 outlining editor References: <3E64A5ED.3060708@tin.it> Message-ID: <3S89a.1646$ES3.1150562@kent.svc.tds.net> Thanks for this contribution. Could you put it in a small .leo file and send it to me at my email address below? Thanks. In the future, please send your correspondence re Leo to one of Leo's Forums on SourceForge: http://sourceforge.net/forum/?group_id=3458 I monitor all those forums regularly. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From djn at daimi.au.dk Thu Mar 27 05:05:25 2003 From: djn at daimi.au.dk (Daniel Nielsen) Date: Thu, 27 Mar 2003 10:05:25 +0000 (UTC) Subject: signal module? In-Reply-To: References: <20030327092336.GB17524@daimi.au.dk> Message-ID: <20030327100523.GC17524@daimi.au.dk> On 27/03-03 10.55, Martin v. L?wis wrote: > > I'm using threads, so I'd like ctrl-c to actually terminate the > > program. If my memory serves me, ctrl-c is SIGINT, so in my code, in > > the main thread, I write: > > Notice that Python already binds SIGINT, to install a handler that raises > a KeyboardInterrupt. > I realise this, but that handler doesnt get the signal either... From: http://www.python.org/doc/current/lib/module-thread.html "Threads interact strangely with interrupts: the KeyboardInterrupt exception will be received by an arbitrary thread. (When the signal module is available, interrupts always go to the main thread.)" I don't know what to make of this, except that KeyboardInterrupt isn't always raised in the main thread, unless you use the signal module somehow. /Daniel -- There are no great men, only great challenges that ordinary men are forced by circumstances to meet. -- Admiral William Halsey From claird at lairds.com Thu Mar 6 18:46:39 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 06 Mar 2003 23:46:39 -0000 Subject: help! advocacy resources needed fast References: Message-ID: In article , Steve Holden wrote: >"Geoff Gerrietts" wrote in message >news:mailman.1046819836.25704.python-list at python.org... . . . >> One of the guys who's been with the organization for a long time wants >> to go to a Java-based approach. The long term viability, he maintains, >> is better, and the short term boost in performance per box in the cage >> is also better. >> >I assume here he is arguing that Java is long-term "more viable" than Python >because of the huge marketing slush-fund that Sun have thrown at the >language. Ignore that it's object-oriented Cobol. Ignore that programmer >productivity will go down: compare > > SAXParserFactory factory = SAXParserFactory.newInstance(); > >with > > factory = xml.sax.make_parser() > >Worse than the fact tha the declarations aren't necessary is the fact that >common Java style actually hides the name of the variable as a tiny word in >the middle of a humungous declaration text like the above. I liked Java when >it was small. Since it scaled up to match its overblown plans for world >domination it's almost as bad as any other piece of bloatware. The API is >just too big and too all-encompassing. . . . There is sooooo much to say on these topics. I don't know where to begin. On alternate hours, I feel like giving up the fight. Struts with, say, Tomcat, is an entirely realistic ap- proach. This isn't because Sun says so, or because Java is something other than object-oriented Cobol. It's more that Struts gives a lot of serious function- ality, and people who like Struts are unlikely to get the point of Python's far more light-weight (in a good sense) style. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From simonb at webone.com.au Tue Mar 11 21:41:03 2003 From: simonb at webone.com.au (Simon Burton) Date: Wed, 12 Mar 2003 13:41:03 +1100 Subject: A fun tool for demonstrating or teaching python? References: <9s7ba.2698$4q6.305236@news20.bellglobal.com> Message-ID: On Mon, 10 Mar 2003 23:19:02 +0000, Tim Gahnstr?m /Bladerman wrote: > > > I am doing a similar project and have had some thoughts about using pygame > as part of the project to give the students a good ground for building their > games and stuf but my current questions is if it is overkill? > > Are al the features of pygame more confusing then helping to a beginner? Is > that maybe later on for more advanced students? It is an interesting > question that I havn' t yet answered. "Wat features are begginer looking for > (or able to grasp) in the graphics departement". The answer might ofcourse > depend on their age but my curren opinion is geared towards that they really > don't ask fore more then the basics, thats what I wanted when I started I > think. > > Tim yes, i agree. Not using pygame directly; but interfacing to classes (eg. Turtle) that do. But, to learn basics one needs examples, etc, and i want to steer clear of math/algorithm examples, and use sound/animation/multi-m as soon as possible. eg. x+y concatenating sound objects x and y. Simon. From reply.in at the.newsgroup Sat Mar 22 08:44:55 2003 From: reply.in at the.newsgroup (Rene Pijlman) Date: Sat, 22 Mar 2003 14:44:55 +0100 Subject: String to int newbie question References: Message-ID: Boris Genz: >I want to convert a number string ( '3211' for example ) to a number, >( actually integer ) preserving the original number Is there any other way? >( the exact number being string and integer ) Que? >but if my number string starts with one or more zeroes, >then the numbers won't be same... Yes they will. '0027' and '027' both convert to 27. >For example, if I have string = '0027' then int(string) would give 27. >How can I add leading zeroes to that number? By not converting it to an integer. It already had leading zeroes before you converted it :-) 0027 == 027 == 27 -- Ren? Pijlman From uwe.schmitt at procoders.net Thu Mar 13 16:05:18 2003 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 13 Mar 2003 21:05:18 GMT Subject: SandBox.py new version References: Message-ID: Uwe Schmitt wrote: > Hi, > I updated SandBox.py to version 0.5. SandBox.py allows > executing python code in a restricted environment. Sorry but Jason Harper discovered some bugs in the new code, there is no problem with the overall design but I'll have to spend some hours on code fixing. The interface will not change so you can try Sandbox but do *not* use it in a productive environment. It is stil v0.5. Greetings, Uwe -- Dr. rer. nat. Uwe Schmitt Computer science is no more about Computers, uwe.schmitt at num.uni-sb.de than astronomy is about telescopes. (Dijkstra) http://www.procoders.net From staschuk at telusplanet.net Mon Mar 17 13:07:30 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 17 Mar 2003 11:07:30 -0700 Subject: No Do while/repeat until looping construct in python? In-Reply-To: ; from me@privacy.net on Mon, Mar 17, 2003 at 01:27:12PM +1200 References: <4017400e.0303130007.5762bf65@posting.google.com> <3bXba.70188$zo2.1844793@news2.tin.it> Message-ID: <20030317110730.A186@tibia.amotlpaa.bogus> Quoth Greg Ewing (using news.cis.dfn.de): > Steven Taschuk wrote: > > But they're not equivalent, logical massage or no. > > while not clean > > rinse > > lather > > doesn't rinse and lather if already clean, while > > repeat > > rinse > > lather > > until clean > > rinses and lathers at least once in all cases. > > And both of them leave my clothes lathered at > the end of the process. :-( > > Glad-you're-not-programming-MY-washing-machine-ly, Heh. One little bug... (What I had in mind was actually not washing clothes but hair; it is (or was once) not uncommon for shampoo bottles in this part of the world to have instructions "Lather, rinse, repeat".) -- Steven Taschuk Aral: "Confusion to the enemy, boy." staschuk at telusplanet.net Mark: "Turn-about is fair play, sir." -- _Mirror Dance_, Lois McMaster Bujold From irmen at -NOSPAM-REMOVE-THIS-xs4all.nl Wed Mar 19 16:29:19 2003 From: irmen at -NOSPAM-REMOVE-THIS-xs4all.nl (Irmen de Jong) Date: Wed, 19 Mar 2003 22:29:19 +0100 Subject: Does Python do try: except: finally: ? In-Reply-To: References: Message-ID: <3e78e12f$0$49107$e4fe514c@news.xs4all.nl> Jerry Seutter wrote: > Does Python do a block like: > > try: > do_something() > except: > do_something_else() > finally: > do_cleanup() > > Python gives me an error when I try to do this and the > online documentation only gives examples with try-except > and try-finally blocks. Correct, you have to do it like you did in your other code snippet. Read more in http://groups.google.com/groups?threadm=3967d908.363887342%40news.online.no As I understand it, it has to do with ambiguity. --Irmen. From mwm at mired.org Thu Mar 27 10:34:47 2003 From: mwm at mired.org (Mike Meyer) Date: Thu, 27 Mar 2003 15:34:47 GMT Subject: Const in python? References: Message-ID: mwilson at the-wire.com (Mel Wilson) writes: > In computer fonts I've looked at the numeric digits > usually seem to be more 'upper-case' than 'lower-case' in > size. That's true in most fonts. For lower-case-like digits, you want "non-lining" or "old style" digits, which are hard to find. I haven't seen those for fixed width fonts, but haven't gone looking for them either. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From mis6 at pitt.edu Fri Mar 7 11:24:28 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 7 Mar 2003 08:24:28 -0800 Subject: Can __iter__ be used as a classmethod? References: <3e649aa3_4@news.bluewin.ch> <2259b0e2.0303041023.43e8b81f@posting.google.com> <4B89a.6715$zo2.218162@news2.tin.it> <3e65273f$1_3@news.bluewin.ch> <90oe6vccthidi7h443od1ndrls8h5oakr5@4ax.com> <3e67cc71_2@news.bluewin.ch> Message-ID: <2259b0e2.0303070824.2eef082b@posting.google.com> "Samuele Pedroni" wrote in message news:<3e67cc71_2 at news.bluewin.ch>... > > Although it is an underdocumented feature, e.g. the pure python version of > super here > > http://www.python.org/2.2.2/descrintro.html#cooperation > > would not work. Here's how the feature was added: > > www.python.org/sf/535444 > > and for a normal method: > > >>> class C(object): > ... def f(self): pass > ... > >>> class D(C): pass > ... > >>> D.f > > >>> super(D,D).f > > > > super(D,D) appear to misbehave. Another minor inconsistency (IMHO) is that "metamethods" i.e. regular methods in the metaclass are not retrieved by "dir": >>> class M(type): ... def mm(cls): ... "This is a metamethod" ... return cls ... class C(object): ... __metaclass__=M ... def pm(self): ... "This is plain method" ... return self ... >>> dir(C) #retrieves the plain method 'pm', not the metamethod 'mm' ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__metaclass__', '__module__', '__new__', '__reduce__', '__repr__', '__setattr__', '__str__', '__weakref__', 'pm'] In order to retrieve 'mm' I need to invoke dir(M): this is slightly inconsistent because usually when 'dir' is invoked on an instance, it automatically retrieves the methods of its class, therefore I would expect that invoked on a class it would retrieve the methods of its metaclass. On the other hand, this could be done by design, in order to avoid cluttering of the output of 'dir'. 'dir' is not meant to retrieve everything. It is also a documented behaviour: >>> print dir.__doc__ dir([object]) -> list of strings Return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it: No argument: the names in the current scope. Module object: the module attributes. Type or class object: its attributes, and recursively the attributes of its bases. Otherwise: its attributes, its class's attributes, and recursively the attributes of its class's base classes. Michele From jsaul at gmx.de Tue Mar 11 02:39:30 2003 From: jsaul at gmx.de (jsaul) Date: Tue, 11 Mar 2003 08:39:30 +0100 Subject: time.strftime() In-Reply-To: References: <20030310092838.GB695@jsaul.de> Message-ID: <20030311073930.GA686@jsaul.de> * Anders Hammarquist [2003-03-11 00:15]: > If you don't have a particular reason not to, it's probably better > to use email.Utils.formatdate() to get an rfc-822 timestamp. email.Utils.formatdate(time.time(), 1) That's it! Thanks for the hint! Cheers, jsaul -- Palo pa'que aprenda que aqu? s? hay honor! [Rub?n Blades] From ericmattes at yahoo.com Tue Mar 11 14:14:18 2003 From: ericmattes at yahoo.com (Eric Mattes) Date: Tue, 11 Mar 2003 14:14:18 -0500 Subject: Pygame and Tk References: Message-ID: Well, the problem with that is that I need these GUI components up the entire time, it's not just for config. Regarding PyUI, I did notice it and it looks very promising. I'll look into that more. -E "Syver Enstad" wrote in message news:uy93mkd89.fsf at online.no... > "Eric Mattes" writes: > > > Hi everyone. > > > > I'd like to know if Pygame and Tk can be used for the same window. Can > > I > > > > have a pygame window with a Tk GUI surrounding it? > > > > If not, is it difficult to create a mouse-driven GUI in pygame? anyone > > know > > > > of a good example/tutorial? > > > > Thank you so much!!! > > -Eric > > An idea Eric... > > How about using an ordinary Tk application to > configure the game, pickling the configured objects to disk, and > starting the PyGame application (with os.system or something) that > just consists of the game, which unpickles the objects and uses them > > -- > > Vennlig hilsen > > Syver Enstad From tim.one at comcast.net Fri Mar 28 13:35:34 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 28 Mar 2003 13:35:34 -0500 Subject: Locking error (?!?) In-Reply-To: Message-ID: [Scott Pigman] > is this a bug in my code or my brain: It looks like a bug in your code, but not in the code you showed us. > ------------------------------------- class Agent: > > assert self.lock.locked() > > self.OUT_SOCKET.send(message) > assert self.lock.locked() > > response = self.OUT_SOCKET.recv(Agent.MESSAGE_BUFFER_SIZE) > assert self.lock.locked() ## FAILS > > > -------------------------------------- > > self.lock is an object of type threading.Lock, which was previously > acquired ( lock.acquire() ). The first two assertions pass, the > third one fails. can anybody give me some insight why? Some other thread called lock.release(). > I had thought that once aquired, the lock will remain lock until That part's right. > the locking thread releases it. But that part's not -- any thread can release the lock. It's impossible to guess what's in the rest of your app, but it *may* be that you wanted a threading.RLock here instead of a threading.Lock (for the relevant difference here, read the docs -- they're really quite clear about this distinction). From sholden at holdenweb.com Sun Mar 23 12:16:34 2003 From: sholden at holdenweb.com (Steve Holden) Date: Sun, 23 Mar 2003 12:16:34 -0500 Subject: Invitation to PyCon Message-ID: <00ee01c2f15f$f6070ec0$6300000a@holdenweb.com> Well, looks like it's PyCon weekend in DC, folks, and here we are amid the cherry blossom (sadly not a feature of this year's cherry blossom festival). The registrations have been smoothly handled by our colleagues of Yet Another Society, for which we thank them. Those who have had to request a refund should expect a formal response shortly before or after PyCon ends. If you do not receive such a response by email, please contact me to ensure your details have been received. I look forward to putting faces to many names, and extend the hand of friendship to all pythonistas, whether attending PyCon or not. There's a goodly crowd attending, barring any travel-related problems such as weather (which featured in my missing the first Python conference I booked). The sprinters are already converging to begin work on Monday, and if you aren't sprinting then think about coming in on TUESDAY AFTERNOON to register early and avoid the morning rush on Wednesday. PyCon's organizers are all interested in hearing your feedback on the conference, and this will be the theme of a session late in the agenda, where your feedback (negative and, hopefully, ;positive)can be made more publicly. Over all we are trying to provide an interesting week with access to Python talent, humor, conceit, and all else that we consider positive about the language. If you aren't already registered then it will cost you $250 at the door (again, if you want to register AT THE CONFERENCE we recommend that you register ON SITE TUESDAY AFTERNOON with your credit card). There has apparently been a good response to our call for gophers, and I'd like to thank all our volunteer gophers in advance for helping to keep the wheels rolling. Ladies and gentlemen, welcome to PyCon DC 2003 week -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Register for PyCon Tuesday March 25 at GWU's Cafritz Conference Center From BPettersen at NAREX.com Mon Mar 3 14:23:45 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Mon, 3 Mar 2003 12:23:45 -0700 Subject: Finally figured out member generators... Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192022DD883@admin56.narex.com> In case anyone else has struggled to make their class iterable by making a generator produce the individual items... Here's the doc-report I filed: This should probably go at the end of 2.2.5 (LibRef). """If you are designing a class that should be iterable, i.e. you want to be able to say "for x in myClass:...", and, you also want the convenience of using a member function that is a generator to provide the items, your class' __iter__() method should return "MyClass.myGenerator(self)". The object returned from this call is an iterator-generator that implements both of the required __iter__() and next() methods. Example: class Range10: def __init__(self): self.scale = 5 def __iter__(self): return Range10.generateItems(self) def generateItems(self): for i in range(10): yield i * self.scale There are a couple of subtleties here. First, only "user-defined functions" are converted to methods when accessed through a class or instance, i.e.myObject.foo() will extract the foo function wrap it up as a method object, insert myObject in the argument list and call it (LibRef: 3.2/Callable types/User-defined methods). [thanks to Alex M. for clarifying this issue for me] This automatic conversion does not happen for any other type of objects defined inside class scope. In our case, generateItems() will be a generator-iterator, i.e. not a "user-defined function". Thus the conversion to an instance method does not happen, and it is left as a static method of the class. [this seems like it might be a bug to me...]. To get around this irregularity, make sure your __iter__() calls generateItems() as a static method, and explictly pass self. """ -- bjorn From mrs at myrealbox.com Mon Mar 17 08:29:29 2003 From: mrs at myrealbox.com (Marcio Rosa da Silva) Date: Mon, 17 Mar 2003 14:29:29 +0100 Subject: import with variable In-Reply-To: <4hbb7voqtuov11i78t330462ca72vuhik5@4ax.com> References: <87el569rih.fsf@bvt40171.gbf-braunschweig.de> <4hbb7voqtuov11i78t330462ca72vuhik5@4ax.com> Message-ID: Rene Pijlman wrote: > Marcio R. da Silva: > >>I'm trying to import a file using the name stored in a variable. For example: >> >> r = "module" >> import r >> >>I know this didn't work, but I would like to know how I can do this. I >>need to create a module "on the fly" and use it in my program. > > > See __import__ on > http://www.python.org/doc/current/lib/built-in-funcs.html > Thanks! That's exactly what I need! Marcio From gerhard.haering at opus-gmbh.net Mon Mar 17 05:51:30 2003 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 17 Mar 2003 10:51:30 GMT Subject: how to send a form html by email ? References: Message-ID: Gerard Breiner wrote: > Hello, > > Is someone has already made a script python so that to send a form by > email from the web server ? [...] You can send email using the smtplib module. I'm not sure what kind of "form" you might want to send by email, though. -- Gerhard From usenet2002 at krap.dk Wed Mar 12 16:50:04 2003 From: usenet2002 at krap.dk (Svenne Krap) Date: Wed, 12 Mar 2003 22:50:04 +0100 Subject: ReportLab, PDF and Latin-1 characters References: <5b016ac1-8f81-4fdc-b8fb-a7c0934494e3@news.szn.dk> Message-ID: <7rav6vsrffms5n63hd8n1053kt01m6ga7k@4ax.com> Does the #v- and #v+ do anything ? Maybe it's a problem with the windows version ? Maybe it's a locale-problem.. I am still a newbie :) On Wed, 12 Mar 2003 21:34:41 +0000 (UTC), Klaus Alexander Seistrup wrote: >Svenne Krap wrote: > >> Still same error > >Are you sure there's nothing wrong with yout python setup? > >It works here if I use > >#v+ > >>>> c.drawString(10, 10, unicode('bl?b?rgr?d', 'iso-8859-1')) > >#v- > >where 'iso-8859-1' is my input charset. > >My environment: > >#v+ > >$ python >Python 2.2.2 (#1, Jan 18 2003, 10:18:59) >[GCC 3.2.2 20030109 (Debian prerelease)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> ^D >$ > >#v- > > // Klaus From sholden at holdenweb.com Mon Mar 17 08:55:15 2003 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 17 Mar 2003 13:55:15 GMT Subject: calling a program without waiting for it to finish References: <6b9f8eda.0303170520.534f53f4@posting.google.com> Message-ID: <7tkda.69218$JE5.22506@news2.central.cox.net> "mnietz" wrote ... > Hey Guys, > > I looking for a way to execute a command-line programm from Pyhton > without having to wait for it to finish. > AFAIK i can't use os.popen() or os.system() because these methods wait > for a return-value. Or can I use the unix command exec in way like > start in windows os.system("start ping -t www.google.com")? > That does exactly what i need. > You need to look at os.fork and os.spawn* and choose the method that suits you best. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Register for PyCon now! http://www.python.org/pycon/reg.html From david at no.westcontrol.spam.com Tue Mar 25 10:49:12 2003 From: david at no.westcontrol.spam.com (David Brown) Date: Tue, 25 Mar 2003 16:49:12 +0100 Subject: Const in python? References: Message-ID: "Dave Brueck" wrote in message news:mailman.1048602718.20497.python-list at python.org... > On Tue, 25 Mar 2003, David Brown wrote: > > > > LIKE_THIS > > > > > > otherwise it is spelled > > > > > > likeThis > > > > There is just one little problem with ALL CAPS conventions - they look ugly, > > To you, perhaps. This is a very widely used, understood, and accepted > convention - I quite like it. > > > Conventions that make code obvious are generally a good thing, but ALL CAPS > > distracts the reader and changes the emphasis of the code, which is contrary > > to the spirit of Python > > Not really - it's a cheap way to provide more insight into how the > developer sees the code and to convey more info to the reader. To me it > helps code readability quite a bit. > > > Assigning to constants should not really be a problem - after all, you don't > > assign to variables unless you know what the variable is, and that the > > assignment is correct in the program. Why treat constants any other way? > > Well, one reason is that the value is only part of the information > associated with it. Another key piece of info is that you as the developer > do not consider, for example, MAX_FD to be a runtime fluctuating input to > your program. > > But, if you don't like the convention, don't use it of course. Many, many, > many people do like and do use it though. At my current company we have a > very simple spelling standard the gist of which is: > > MyClass, MyFunction, myVariable, MY_CONST > > and we have yet to find that any of the spellings "distract" or "change > the emphasis" in some negative way - rather they convey more information > and improve readability. > Yes, I know it's a common convention - both in Python and in other languages - and that many people use it. It's a matter of personal taste, I suppose. I just tend to find that writing in all caps stands out too much, and takes up too much visual space in the code. I tend to use "MyClass, myFunction, myVariable, myConst" for Python, and other high-level languages, but I'm not always strict about it. For assembly programming, I am strict about capitals for code, small letters for data - it pays to be stricter there! > > in Python, the run-time typing and binding means that you can make so > > many silly mistakes (it's the price you pay for the power and > > flexibility) that assigning to constants is a minor issue. > > Oh, I defintely agree that assigning to constants is a minor issue - I > didn't bring this topic up, ya know. :) I use the ALL_CAPS spelling > because of the extra information it gives far more than as a safeguard > against accidental assignment, although the latter is still helpful. > > -Dave > Well, if it adds to the readability of your code - great! I always like to keep in mind that the computer will spend milliseconds reading the code, while humans might be looking at it for hours, days, weeks or years, and it's important to write accordingly. David From logistix at zworg.com Sun Mar 30 17:47:03 2003 From: logistix at zworg.com (logistix) Date: 30 Mar 2003 14:47:03 -0800 Subject: Is Python overhyped (just like Java)? References: Message-ID: No. From avail at uponrequest.org Fri Mar 28 01:49:40 2003 From: avail at uponrequest.org (Kevin Reeder) Date: Fri, 28 Mar 2003 06:49:40 GMT Subject: Beginner Question References: Message-ID: <8gSga.236197$L1.65045@sccrnsc02> On Thu, 27 Mar 2003 20:45:04 -0800, Lee Harr wrote: > Well... it is not just the last line, but I think the best way would be: > > import random > def shuffle(self): > random.shuffle(self.cards) This one failed to work with the exception: Attribute error: shuffle. Probably something I'm not seeing. > > > How about this: > > def shuffle(self): > import random > nCards = len(self.cards) > for i in range(nCards): > j = random.randrange(i, nCards) > self.cards.insert(i, self.cards.pop(j)) This solution worked great. Is insert a list method? Kevin From justin at gnubia.net Sat Mar 29 18:19:05 2003 From: justin at gnubia.net (Justin Ryan) Date: 29 Mar 2003 17:19:05 -0600 Subject: HTML / DOM In-Reply-To: <200303282232.20641.b.maryniuk@forbis.lt> References: <200303282232.20641.b.maryniuk@forbis.lt> Message-ID: <1048979945.8165.31.camel@qutang.gnubian.org> If you can do what you need with XML, why not do that and use an XSLT stylesheet to render as HTML? On Fri, 2003-03-28 at 14:32, Bo M. Maryniuck wrote: > Hello, all. > > Can anybody drop me a real code how to work with DOM in _HTML_ which is even > not XHTML? I took a look over 4DOM but unfortunately documentation there is > too silly. :( Well, for example, I have a HTML string: > >

Text here bar

> > Now, how to build a DOM from this chunk to do the following: > 1. Fetch somehow a "name" attribute from the "" tag > 2. Change it (not a "bar", but a "foo" value!) > 3. Push it back to the same place > 4. Return modified HTML back as string without doctype and so on. > > Any ideas? I know how to work with XML, but HTML-stuff drives me crazy since > it does not XML. Yes, I've tried to RTFM and STFW, but now I gave up -- this > all does not work as I need. > > What I need to do with it. I have a HTML's where I need to found all the tags > which contains Unicode data in the "name" attribute and > urllib.quote() it than return this HTML back. But how to do it with DOM in > HTML -- I have no idea, since this is not XML... :( > > Thank you for any help and any *working* ideas and examples. :) > > -- > Regards, Bogdan > > If vegetarians eat vegetables, what do humanitarians eat? > From pan-newsreader at thomas-guettler.de Thu Mar 20 02:23:04 2003 From: pan-newsreader at thomas-guettler.de (Thomas Guettler) Date: Thu, 20 Mar 2003 08:23:04 +0100 Subject: Rookie: Parsing the nth table out of an html doc References: Message-ID: On Thu, 20 Mar 2003 05:15:23 +0100, footnipple wrote: > Hello All, > > I've "googled" and "rtfm'ed", and I'm just not getting how to do this > from the python documentation... There are two ways: - you can try to parse it yourself with regular expressions. If the table is created from a database and a script, this might be easy. - You can use a html parser. E.g. HTMLParse (look at the module index) thomas -- Thomas Guettler http://www.thomas-guettler.de From npetry at accesscomm.ca Tue Mar 11 10:58:12 2003 From: npetry at accesscomm.ca (Norman Petry) Date: 11 Mar 2003 09:58:12 -0600 Subject: Condorcet analysis of Official PEP308 Ballots In-Reply-To: <200303111318.h2BDIrH26328@localhost.localdomain> References: <1047367657.1029.297.camel@chomsky> <200303111318.h2BDIrH26328@localhost.localdomain> Message-ID: <1047398293.1015.115.camel@chomsky> On Tue, 2003-03-11 at 07:18, Anthony Baxter wrote: > > >>> Norman Petry wrote ... > > Of course, the fact that the status quo is clearly preferred by a > > majority in both votes does not necessarily mean that the ternary should > > not be implemented. It is likely that many features that have been > > added to Python would not have received the support of a majority when > > they were first introduced. For this reason, the SOCIAL RANKING is > > probably a much more useful result than the SINGLE WINNER when trying to > > decide how to resolve this issue. > > Um, huh? A vote was held, a majority said "no change", and suddenly now > you're claiming that "obviously a vote isn't the important thing"? No, I never claimed that. I think that holding this vote, as well as properly tallying and analyzing the results was very important, otherwise I wouldn't have gone to the trouble of doing it. My point was that the status-quo option, which a majority clearly prefers to every other alternative, won't necessarily be the most useful piece of information for Guido. If this was a democratic decision, then yeah, the single winner result should be used. It's clearly not, though. GvR isn't known as the "Benevolent _Dictator_ for Life" for nothing! Only Guido can decide how much support is needed for the ternary to justify adding it to the language, and he can set the bar wherever he wants. He might require a simple majority. However, if he is hostile to the idea of a ternary, he might require a supermajority, as some of the opponents of the ternary expected when voting methods were being discussed. On the other hand, he may decide that adding a feature that would be useful to a large minority of users is a good enough reason to add it -- only Guido knows. > I ended up not caring whether it goes in or not. But to turn around after > the vote with this sort of comment "well, not everything that went into > python would have won a vote, that's not the important thing" seems like > sour grapes of the worst sort. Nonsense. Personally, I'd be perfectly happy if Guido decides to accept the majority decision and NOT implement the ternary, since the ternary syntax proposals with the most community support are worse than the status-quo, imo. If you look at my ballot, you'll see that the only proposal that I think would make Python a better language is: x if C else y which came in 4th in the collective rankings -- a strong showing, but clearly one with many opponents. The most likely alternative for implementation based on the vote is: (if C: x else: y) which is clumsy and inelegant, but at least readable. I'd prefer not to see this in Python. It won't appear in my code, and I'd rather not have to read other people's code that uses this. The third ranked option was: C ? x : y which I detest. If too much of this C-style syntax garbage gets added to Python, I'll be looking elsewhere for a language! Therefore, you'll find no "sour grapes" here. Of course, the social ranking, like the single winner are only a guide -- Guido may freely choose to implement any, all, or none of the syntax proposals, regardless of their level of support within the programmer community. Who knows? Maybe he'll reveal himself as the MDFL (Mad Dictator For Life) and decide to implement: C -> (x, y) ;-) -- Norman Petry From amir at clockwise3d.com Thu Mar 27 11:06:36 2003 From: amir at clockwise3d.com (Amir Hadar) Date: Thu, 27 Mar 2003 18:06:36 +0200 Subject: improved pickle Message-ID: Hi All First, to whom can I write suggestions for the next versions of python? Anyway here is one: I have improved the binary pickle module to be able to memorize existing objects. For example if you have a global instance that you don't want to store into the persistence but you do want to restore references to it. you should first memorize the instance and then dump some object. When you want to unpickle then first memorize the global object with the same key and then unpickle. All references to the global object that was memorize in the dump will be restored to the global object that was memorized in the load. First Run of an application: ... ... g = SomeGlobalInstance() # instance 0x123456 c = SomeClass(g) # c.Value = g pickler.memo_inst(g ,"The global instance") #<-- NEW pickler.dump(c) ----------------------------------------------------------- Second Time the application runs: ... ... g = SomeGlobalInstance() # instance 0xFEFEFEFE unpickler.memo_inst(g ,"The global instance") #<-- NEW c = unpickler.load() assert c.Value == g I have added them method memo_inst to the pickler and the unpickler. If there is another way to do it please tell me. I know that one can modify the memo dictionary but the structure of this dictionary is not trivial. If anyone want the source code please contact me. Regards, Amir From do-not-spam-ben.hutchings at businesswebsoftware.com Tue Mar 18 05:13:22 2003 From: do-not-spam-ben.hutchings at businesswebsoftware.com (Ben Hutchings) Date: 18 Mar 2003 10:13:22 GMT Subject: command line arguments processing: an ugly lpr wrapper References: Message-ID: In article , morden wrote: > os.execv("/usr/bin/lpr", new_arg) > > # should I exit(os.execv("/usr/bin/lpr", new_arg)) instead? No. The exec family of functions *replaces* your program with the one you specify. They never return successfully, and in Python, they raise an exception when they fail. From gb at cs.unc.edu Tue Mar 18 13:55:31 2003 From: gb at cs.unc.edu (Gary Bishop) Date: 18 Mar 2003 13:55:31 -0500 Subject: How can I use an existing COM object pointer with win32com? Message-ID: In my C++ extension that wraps the Microsoft Active Accessibility API I can get a pointer to a IWebBrowser2 COM interface from an IAccessible representing the browser. I'd like to hand this pointer back to my Python code and use it just like I would use the object I'd get from ie = DispatchWithEvents("InternetExplorer.Application", IEEvents) Can I do that? I don't want to create a new instance of Internet Explorer. I want to connect to a particular instance already running. I have looked for an example of "adopting" a COM pointer but haven't found one. Thanks Gary Bishop Associate Professor Computer Science University of North Carolina at Chapel Hill From gerhard.haering at opus-gmbh.net Wed Mar 5 10:34:44 2003 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 5 Mar 2003 15:34:44 GMT Subject: Concerns about performance w/Python, Pysco on Pentiums References: <3E660EB3.4065D81F@engcorp.com> Message-ID: Peter Hansen wrote: > [hardware simulator in Python] > On a Pentium 266 MMX, the simulator executes roughly 15000 > simulated HC12 clock cycles per second. On a P3 866 MHz > chip, it can do about 85000 cycles per second. On a P4 2GHz > it can do about 115000 cycles per second. The real CPU > runs 8 million of these clock cycles per second, and we > were hoping for significantly better performance than we've > seen so far. > > More interesting to me, however, is the poor relative performance > of the faster machines. I can believe the P3 866 should be about > 5.5+ times faster than the old P266, but the P4 is only 35% > faster than it! It may well be that the real bottleneck of your simulator is memory access and not CPU. In this case you could try rewriting your Python code so that it uses continuous memory blocks. If for example you use lists for simulating the RAM, you could try to use the buffer module instead. (Note, the P3 is running Win98SE, the P4 is running > Redhat 7.3, both with their "vanilla" Python 2.2 installations, > in the case of Linux that being the RPM from python.org.) These use different compilers. Microsoft Visual C++ vs. (most likely) gcc 2.9.5.x. It should be possible to squeeze more performance out of the P4 by using gcc 3.2 or the Intel compiler instead. You should rather expect -5 to 15 % improvement rather than an order of magnitude, though ;-) Still this sounds like memory is the bottleneck ... You could try to look at the cache misses for your process, if that is at all possible. -- Gerhard From none at of.your.business Tue Mar 11 12:07:11 2003 From: none at of.your.business (lynx) Date: Tue, 11 Mar 2003 12:07:11 -0500 Subject: Flying With Python (Strong versus Weak Typing) References: <37a869bc.0303102102.4533973@posting.google.com> Message-ID: On Mon, 10 Mar 2003 21:02:34 +0000, Hasoob ahs wrote: > In an interview at http://www.artima.com/intv/strongweak4.html Guido > van Rossum was asked if "he would be comfortable enough with the > robustness of Python systems to fly on an airplane in which ALL the > control software was written in Python". Guido's answer was clear but > I would like to hear from other Python programmers. i know something about your average civilian airplane, and how hard/easy it is to control even if it were to lose most of its electronics. i'd be comfortable, yes. i've also read some stories about what sort of certification process avionics software has to go through, and what sort of development processes and documentation demands are placed on such; i think i might be comfortable flying even were the plane programmed in QBasic. well, under VFR conditions, anyway. ;-) -- PGP/GnuPG key (ID 1024D/3AC87BD1) available from keyservers everywhere Key fingerprint = FA8D 5EA4 E7DC 84B3 64BC 410C 7AEE 54CD 3AC8 7BD1 "...if you can fill the unforgiving minute with sixty seconds' worth of distance run..." From Padraig at Linux.ie Tue Mar 4 11:12:17 2003 From: Padraig at Linux.ie (Padraig at Linux.ie) Date: Tue, 04 Mar 2003 16:12:17 +0000 Subject: Sorting lists of lists by columns In-Reply-To: <3E64BF02.9040901@motorola.com> References: <3E64BF02.9040901@motorola.com> Message-ID: <3E64D061.6060601@Linux.ie> Stephen Boulet wrote: > Is there any list method available to sort lists of lists by columns? > I'm thinking of a spreadsheet-type function where you might sort rows by > the column x, y, and then z. http://tardis.linux.ie/727/ From max at alcyone.com Tue Mar 4 17:43:10 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 04 Mar 2003 14:43:10 -0800 Subject: what exactly is "None" ? References: Message-ID: <3E652BFE.C96E3424@alcyone.com> Mark McEahern wrote: > None is a singleton. I don't know whether it's correct to say that > it's a > Boolean false value. Well, it certainly evaluates to false in a Boolean context, just as 0, 0.0, 0L, [], (), etc. do. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ The people are to be taken in very small doses. \__/ Ralph Waldo Emerson Alcyone Systems / http://www.alcyone.com/ Alcyone Systems, San Jose, California. From cce at clarkevans.com Tue Mar 4 21:47:53 2003 From: cce at clarkevans.com (Clark C. Evans) Date: Wed, 5 Mar 2003 02:47:53 +0000 Subject: PEP 308: an additional "select/case" survey option In-Reply-To: <20030305005906.GA56890@doublegemini.com> References: <882b0a41.0303020225.3caf0334@posting.google.com> <20030305005906.GA56890@doublegemini.com> Message-ID: <20030305024753.GA58310@doublegemini.com> After some encouragement by Raymond, I'd like to add one more item to the survey, if you like what follows perhaps you can even *change* your vote (Raymond?) to include: Q accept switch-case Z deny everything else! Dedication: To those who hate the terinary operator beacuse it isn't pythonic... Background: After looking over much of my Python source code, I found that where I thought I needed a terinary operator, I ended up taking one of two paths: if 0 == quantity: exit = 'no exit' elif 1 == quantity: exit = 'a door' else: exit = '%s doors' % quantity Or, the more concise mapping-idiom: exit = { 0: 'no exit', 1: 'a door' }.get(quantity, '%s doors' % quantity) The latter construct has two advantages over the if/else statement level solution: 1. It's clear that I'm making an assignment to exit; in effect the "exit =" isn't duplicated and this aids in authoring/maintenance/reading. 2. The ugly '== quantity' isn't duplicated for each line, once again improving maintenance. However, the mapping-idiom has three problems: 1. The conditional switch isn't exactly "obvious" here unless you're a Python vetran, this hurts in the maintenance arena; besides the 'else' case is ugly. 2. It doesn't short-circut cleanly, to do a short-circut you need to use lambda's... ick; further, it results in the construction of a mapping which may not really help out optimizations. 3. It really doesn't facilitate the use whitespace/indentation to re-inforce a visual representation of the program's structure. Philosophy: The whole rationale for this construct is to reduce data duplication (both the assignments and conditional tests) to increase maintenance. The goal is not to save on vertical screen realistate by enabling multi-line constructs to be "jumbled" into a single line. It seems that many people are asking for the terinary option for the latter. Instead, this proposal seeks to engage Python's unique approach to syntax by using whitespace to enhance the visual representation of the program's structure. Many Python converts are here exactly beacuse Python is very readable and thus maintainable. This proposal is here soley to re-enforce this "pythonic" approach to coding. Proposal: The proposal introduces a 'select' or 'switch' keyword which creates an indented expression block. Instead of the following, exit = { 0: 'no exit', 1: 'a door' }.get(quantity, '%s doors' % quantity) You could write, exit = select quantity case 0: 'no exit' case 1: 'a door' else: '%s doors' % quantity This proposal gives you the power of the mapping-idiom without the uglyness. It expresses the intent of the construct in a very human readable manner using whitespace smartly. While the above is "good", it assumes an equality operator. So that the structure is more generic, his proposal allows an optional operator (a function taking 2 or more value and returning a boolean) immediately following the 'case' label, z = 1.0 + select abs(z) case < .0001: 0 case > .5: .5 else: -sigma / (t + 1.0) Note that the examples given in the proposal are thus very easily expressed using this notion: data = select hasattr(s,'open') case true: s.readlines() else: s.split() z = 1.0 + select abs(z) case < .0001: 0 else: z t = v[index] = select t case <= 0: t - 1.0 else: -sigma / (t + 1.0) return select len(s) case < 10: linsort(s) else: qsort(s) The 'operator' need not be binary, one could, for example, provide a terinary operator, such as: def between(cmp,rhs,lhs): return cmp >= rhs and cmp <= lhs score = select die case 1: -2 case 2: -1 case between 3,4: 0 case 5: +1 case 6: +2 else: raise "invalid die roll %d " % roll Summary: The proposal thus creates a flexible mechanism for avoiding the excessive duplication of assignment and equality fragments within a conditional assignment nest; it does so through a new expression structure which, like the rest of Python, uses indentation for structure. This proposal thus provides the pratical benefit of a terinary operator, while at the same time opening the door to a rich (and quite readable) conditional assignment mechanism. In particular, this proposal rejects the rationale for 'terinary' operator as a way to trade horizontal screen realestate for vertical space; as this rationale is in direct opposition to the fundamental principle of readability. And as such, the proposal explicitly does not include a way to include multiple case labels on the same line. Credits: Alex Martelli for validating the elimination of needless-duplication of code as the primary goal for the construct; and Carel Fellinger for presenting the idea of a plugable predicate/operator Raymond Hettinger for asking me to write this up more or less formally From max at alcyone.com Sat Mar 1 19:38:51 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 01 Mar 2003 16:38:51 -0800 Subject: UnicodeError: ASCII encoding error: ordinal not in range(128) References: <5PucnTryQrw00PyjXTWc3A@speakeasy.net> Message-ID: <3E61529B.40F580E2@alcyone.com> Hasan Diwan wrote: > I have a script to parse RSS feeds into HTML. Some of these RSS feeds > contain characters outside the 7-bit ASCII range, and the page is set > to > display in utf8. My question is how to force the script below to > output > strings in UTF8 as opposed to ASCII: Try S = U.encode('utf-8') -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ There's this perfect girl / Living inside the shell \__/ Lamya Fauxident / http://www.alcyone.com/pyos/fauxident/ A "faux" ident daemon in Python. From mhammond at skippinet.com.au Wed Mar 5 01:56:51 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Wed, 05 Mar 2003 06:56:51 GMT Subject: Code to recognize MS-Word document files? In-Reply-To: <3e64d3c3$0$52915$a1866201@newsreader.visi.com> References: <3e64d3c3$0$52915$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: > I'm looking for a snippet of python that I can use to determine > if a file is a MS-Word document. People around here seem to > have gotten into the habit of attaching MS-Word files without a > ".doc" on the name. > > Even with the .doc, the mimetypes module doesn't seem to get it > right. :( This code, from ppw32, will extract information from MS Office documents. I'm not sure what other properties are available. Mark. # DumpStorage.py - Dumps some user defined properties # of a COM Structured Storage file. import pythoncom from win32com import storagecon # constants related to storage functions. # These come from ObjIdl.h FMTID_UserDefinedProperties = "{F29F85E0-4FF9-1068-AB91-08002B27B3D9}" PIDSI_TITLE = 0x00000002 PIDSI_SUBJECT = 0x00000003 PIDSI_AUTHOR = 0x00000004 PIDSI_CREATE_DTM = 0x0000000c def PrintStats(filename): if not pythoncom.StgIsStorageFile(filename): print "The file is not a storage file!" return # Open the file. flags = storagecon.STGM_READ | storagecon.STGM_SHARE_EXCLUSIVE stg = pythoncom.StgOpenStorage(filename, None, flags ) # Now see if the storage object supports Property Information. try: pss = stg.QueryInterface(pythoncom.IID_IPropertySetStorage) except pythoncom.com_error: print "No summary information is available" return # Open the user defined properties. ps = pss.Open(FMTID_UserDefinedProperties) props = PIDSI_TITLE, PIDSI_SUBJECT, PIDSI_AUTHOR, PIDSI_CREATE_DTM data = ps.ReadMultiple( props ) # Unpack the result into the items. title, subject, author, created = data print "Title:", title print "Subject:", subject print "Author:", author print "Created:", created.Format() if __name__=='__main__': import sys if len(sys.argv)<2: print "Please specify a file name" else: PrintStats(sys.argv[1]) From gunnar.kongsrud at hoyre.no Fri Mar 14 05:12:49 2003 From: gunnar.kongsrud at hoyre.no (Gunnar Kongsrud) Date: Fri, 14 Mar 2003 11:12:49 +0100 Subject: Python code! Message-ID: Hi, I have a question about a code in pyhton. If the code below make my articals sort automatacly articals after 01.01.2003 ho do i get it to sort articals from 01.01.2001 to 01.01.2002 by using a simular code? python:object.portal_catalog(meta_type='Artikkel', level=object.level(), sort_on='Date', Date=['2003-01-01'],sort_order='reverse', Date_usage='range:min') Best regards from, Gunnar Kongsrud From m.schubert at sh.cvut.cz Tue Mar 11 20:45:48 2003 From: m.schubert at sh.cvut.cz (Marian Schubert) Date: Wed, 12 Mar 2003 02:45:48 +0100 Subject: libglade-2.0-0.dll References: Message-ID: "Steven Taschuk" wrote in message news:mailman.1047425449.5458.python-list at python.org... > Quoth Marian Schubert: > > "Steven Taschuk" wrote in message > > news:mailman.1047367817.14451.python-list at python.org... > [...] > > > Have you looked at ? > > > > sure, no compiled .dll there :/ > > There's source, though. Why not build it yourself? Well I don't have compiler and devel libs on this win box so i can't compile it myself... There are some older versions of libglade so it's highly possible that someone have this new ver. cu, maio From staschuk at telusplanet.net Wed Mar 12 22:08:18 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 12 Mar 2003 20:08:18 -0700 Subject: GCD in standard library? In-Reply-To: ; from blakeg@metalink.net on Wed, Mar 12, 2003 at 08:06:55PM -0500 References: Message-ID: <20030312200818.A2382@tibia.amotlpaa.bogus> Quoth Blake Garretson: > [...] I'm just guessing it is very common > for people to have to add this to their programs: > > def gcd(x,y): > if x % y == 0: return y > else: return gcd(y,x%y) I for one haven't needed this in Python yet, but if I did I'd do it this way: def gcd(a, b): while b: a, b = b, a % b return abs(a) which (1) avoids the unnecessary recursion, (2) gives the right answer for zero operands, and (3) gives a predictable and defensible, if not obviously right, answer for negative operands. I don't know why it's not in the standard library as you inquire; one reason may be simply that it's not in the standard C math library. -- Steven Taschuk staschuk at telusplanet.net "What I find most baffling about that song is that it was not a hit." -- Tony Dylan Davis (CKUA) From penguinista at DONTmail.SPAMnet.mk Wed Mar 5 14:52:41 2003 From: penguinista at DONTmail.SPAMnet.mk (=?UTF-8?B?0LTQsNC80ZjQsNC9INCzLg==?=) Date: Wed, 05 Mar 2003 20:52:41 +0100 Subject: Few ZODB questions Message-ID: <3e665589@news.mt.net.mk> I have several questions about ZODB: 1. is ZODB multithread safe (like the Queue class) 2. is the ZODB multiprocess safe (meaning that two separate python processes can access it, like some of the file databases can) 3. What kind of operations are possible on the ZODB? 4. Why isn't it more popular outside of the ZOPE project? -- ?????? (jabberid:damjan at bagra.net.mk) C/C++ you can't kill them , still can't live with them. From dagurp at heimsnet.is Sun Mar 2 07:43:19 2003 From: dagurp at heimsnet.is (=?ISO-8859-1?Q?Dagur_P=E1ll_Ammendrup?=) Date: Sun, 02 Mar 2003 12:43:19 +0000 Subject: Strange regex problem In-Reply-To: References: <33803989.0303020048.10c8fc09@posting.google.com> Message-ID: <3E61FC67.8070705@heimsnet.is> This code is enough to reproduce it for me: #!/usr/bin/env python import re file = ''' <{F_ACTIVE}> $total $birth_lang
$birthusers $active[TOTAL] {ibf.lang.active_users} [.. A lot of HTML ..] ''' locations = [] p = re.compile('') m = p.search(file) while m: begin = m.end() match = m.group(1) n = re.search('' % match,file,begin) m = p.search(file,begin) If i change the 2n line from the bottom to this: q = re.compile('' % match) n = q.search(file,begin) this problem does not happen. Is there any change in speed because of this? Not that it matters much for the script I'm making. -Dagur Rene Pijlman wrote: > Miki Tebeka: > >>OP: >> >>>literal 45 >>>literal 73 >>>literal 66 >>>literal 70 >>>literal 95 >>>literal 71 > > > It looks like debug output. Are you running in some sort of > debug mode? > > >>2. Can you give us a sample input file? > > > And some complete code we can run to reproduce the problem. > From tebeka at cs.bgu.ac.il Sun Mar 16 04:04:26 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 16 Mar 2003 01:04:26 -0800 Subject: dict.popitem(key) ??? References: Message-ID: <33803989.0303160104.228cfd20@posting.google.com> Hello Justin, > Why doesn't popitem take a key argument that defaults to None? Or how > should I pop a particular item out of a dict? item = mydict[key] del mydict[key] Miki From BPettersen at NAREX.com Tue Mar 4 13:54:17 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Tue, 4 Mar 2003 11:54:17 -0700 Subject: Finally figured out member generators... Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192022DD8C6@admin56.narex.com> > From: Steven Taschuk [mailto:staschuk at telusplanet.net] > > Quoth Bjorn Pettersen: > [...] > > >>> class D: > > ... def __init__(self): self.v = 5 > > ... def __iter__(self): return self > > ... def next(self): > > ... for i in range(10): > > ... yield i + self.v > > ... > > >>> d = D() > > >>> list(d) > > > > which will recurse infitely. That __iter__ should return > > self.next(), thus creating and returning an iterator > > object because of generator semantics didn't occur to > > me since the whole point was to have the class > > be it's own iterator... Oh, well, it was fun anyways :-) > > Um. I think you're conflating iterators with iterables. In the > code above [...] Well, yes, I guess I gave it away when I said "the whole point was to have the class be it's own iterator" . Although it would certainly cause problems with multiple simultaneous iterations over the same container, there shouldn't be anything wrong with doing it when you know there can only be one for loop (etc.) working on the container. The way I read the docs, the iterator protocol was simply (a) an iterable container must have a method __iter__(self), which (b) returns an object having a method next(self), which when repeadtedly called will return successive items of the container, and finally (c) next() will raise StopIteration when all items in the container have been returned. Here's an example: >>> class E: ... def __init__(self): ... self.value = range(10) ... self.scale = 5 ... def __iter__(self): ... self.cur = 0 ... return self ... def next(self): ... pos = self.cur ... self.cur += 1 ... if pos < len(self.value): ... return self.value[pos] * self.scale ... else: ... raise StopIteration ... >>> e = E() >>> list(e) [0, 5, 10, 15, 20, 25, 30, 35, 40, 45] The problem with the exmple the top, was simply that by specifying self as the __iter__, I was implying that d.next() would return the next item in D [which I think is perfectly reasonable, I mean it says it's going to "yield" the value right there, you'd almost think there were some magic wrapping going on -- who was it that said it wouldn't confuse us to reuse 'def' to declare generators?..... (tim?) ] The reality is, of course, that d.next() returns not an item in D, but an (generator-)iterator (an object containing next() that will produce the items). [... how to use separate iterator classes..] I agree that separate iterator classes are very explicit and have a number of good qualities, they seem heavy-handed when it comes to Python though (remember we came from the __getitem__ protocol...) Also, I would probably make the iterator an inner class (doesn't pollute the namespace, and just have a look at the C++ stl for what you can do when common parts of classes are named the same :-): class MyContainer: class iterator: def __init__(self):... def __iter__(self): return iterator(self) def next(self): ... etc. [...] > A generator function, as you say, is handy here, because it lets > you avoid writing a separate iterator class: > > class WithGenerator: > def __init__(self, scale): > self.scale = scale > def __iter__(self): > for i in range(5): > yield i*self.scale Agreed. I haven't used generators much until now (at least not in Python :-), but I think we're going to move to 2.3 final where they're standard, etc., etc. Thanks, -- bjorn From me at privacy.net Sun Mar 16 21:05:31 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Mon, 17 Mar 2003 14:05:31 +1200 Subject: Another Pyrex Question In-Reply-To: References: Message-ID: Ganesan R wrote: > Is it possible to setup a > class variable?. Say, some thing like > > cdef class Shrubbery: > static cdef int count No, but you don't really need it -- just use a module-level variable, e.g. cdef int Shrubbery_count outside of the class definition. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From reply.in at the.newsgroup Mon Mar 17 21:33:26 2003 From: reply.in at the.newsgroup (Rene Pijlman) Date: Tue, 18 Mar 2003 03:33:26 +0100 Subject: It feels so good, so quick and not C! References: Message-ID: BB: >I then decided to do a simple project to write a "reverse string" >routine. Guido has already done this simple project when he was learning Python. He recently recovered it when cleaning up his hard disk and now he is making it available to us through a special syntax as of Python 2.3: "desrever eb ot stnaw taht gnirts"[::-1] Towers of Hanoi is in the works, but the PEP debates about its syntax have not yet reached a final conclusion. A recent attempt to force a solution through a vote failed unexpectedly. Presumably because voters were required to solve the 8-disks-on-3-towers puzzle in an interactive applet to prove they truly understood the issue. -- Ren? Pijlman From opengeometry at yahoo.ca Thu Mar 13 16:09:01 2003 From: opengeometry at yahoo.ca (William Park) Date: 13 Mar 2003 21:09:01 GMT Subject: Has anyone created a simple POP3 and SMTP server using TWISTED? References: Message-ID: Zoo Keeper wrote: > Or by any other means for that matter. > > I have two domains, one for me, one for my wife, for our web sites. I > want our own mail servers because our ISP has changed names 3 times in 4 > years. Right now I am using a great product (my server is BeOS, btw) > but it is a trial version and the minimal license is for 50 users and > costs too much. So, I figured I'd write one in Python, but I wanted to > check here first to make sure it hasn't already been done so that I am > not wasting time researching and writing something that already > exists... Everything is easy if there is no errors, but handling all possible details that may arise is very time-consuming. Also, unnecessary, since Fetchmail/Sendmail already exist in many platforms. -- William Park, Open Geometry Consulting, Linux solution for data management and processing. From Vincent.Raaijmakers at ge.com Thu Mar 27 13:57:29 2003 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (IndSys, GE Interlogix)) Date: Thu, 27 Mar 2003 12:57:29 -0600 Subject: NewBie: Python script as a service in linux Message-ID: <55939F05720D954E9602518B77F6127F011E9085@FTWMLVEM01.e2k.ad.ge.com> Yep! Thanks a lot! Vincent -----Original Message----- From: Brian Quinlan [mailto:brian at sweetapp.com] Sent: Thursday, March 27, 2003 1:35 PM To: Raaijmakers, Vincent (IndSys, GE Interlogix); python-list at python.org Subject: RE: NewBie: Python script as a service in linux > Can someone explain to me?what the best way is in Linux > to "convert" a python script into a service. Is this what you are looking for? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 Cheers, Brian From mis6 at pitt.edu Mon Mar 17 16:58:28 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 17 Mar 2003 13:58:28 -0800 Subject: PEP 312 (and thus 308) implemented with a black magic trick Message-ID: <2259b0e2.0303171358.5a6fe337@posting.google.com> Today I had an illumination on how to implement both PEP 312 and 308 in current Python. I think I will share the idea, even if I would *not* recommend to use such a dirty trick in production code. Notice that instead of the proposed colon notation for PEP 312 (:x as a shortcut for lambda :x) I use a tilde notation: ~x as a shortcut for lambda :x This means that I am changing the semantics of the unary operator "~", which is a Bad Thing: but as I said, this is dirty trick ;) I am not suggesting it. This is simply a proof of concept. Here there is an example of usage: ------------------------------------------------------------------ # example.py; will not work from the interpreter from ternary import if_, RecognizesImplicitLambdas from math import sqrt class C(RecognizesImplicitLambdas): def safesqrt(self,x): return if_( x>0, ~sqrt(x), ~0) #short-circuiting ternary operator c=C() print c.safesqrt(4), c.safesqrt(-4) -------------------------------------------------------------------- The output of this script is 2.0 and 0, therefore if_( x>0, ~sqrt(x), ~0) is short-circuiting, as wanted. Here there is the ternary module: -------------------------------------------------------------------- # module ternary.py "PEP 308 and 312 implemented via a metaclass-powered dirty trick" import inspect,__main__ # the ternary operator: def if_(cond,f,g): "Short circuiting ternary operator implemented via callable expressions" if cond: return f() else: return g() # an utility function: def dedent(block): "Dedent a block of code, if need there is""" lines=block.splitlines(); firstline=lines[0] spaces=len(firstline)-len(firstline.lstrip()) if not spaces: return block return '\n'.join([line[spaces:] for line in lines]) # the metaclass black magic: class DirtyTrick(type): """Cooperative metaclass that looks at the source code of its instances and replaces the string '~' with 'lambda :' before the class creation""" def __new__(meta,name,bases,dic): for attr in dic.values(): if inspect.isfunction(attr): code=inspect.getsource(attr) if code.find('~')==-1: continue # no '~' found, skip code=code.replace('~','lambda :') code=dedent(code)+'\n' exec code in __main__.__dict__,dic # modifies dic return super(DirtyTrick,meta).__new__(meta,name,bases,dic) # a convenient base class: class RecognizesImplicitLambdas: "Children of this class do recognize implicit lambdas" __metaclass__=DirtyTrick -------------------------------------------------------------------------- I am aware of the limitation of this approach, still it is quite cool: notice that the metaclass changes the source code on the fly *before* the class creation and automagically will be invoked for any subclass of RecognizesImplicitLambdas. Quite impressive, IMHO. Of course, changing the semantics of the language is never a good idea, still it is impressive that it is a so easy to perform such a black magic. Skipping the comments, the ternary module is only 20 lines long! Python-is-not-as-simple-as-you-could-imagine-ly yours, -- Michele Simionato - Dept. of Physics and Astronomy 210 Allen Hall Pittsburgh PA 15260 U.S.A. Phone: 001-412-624-9041 Fax: 001-412-624-9163 Home-page: http://www.phyast.pitt.edu/~micheles/ From usenet at voygr.com Tue Mar 11 17:04:04 2003 From: usenet at voygr.com (Dave Bates) Date: Tue, 11 Mar 2003 16:04:04 -0600 Subject: Curses - Win/dos Message-ID: <3e6e62b7$1@nntp01.splitrock.net> Hello Everyone, I was trying to play around with curses .. and the docs say to import curses (ofcourse) and run a few methods to setup the screen and such.. Problem is, when I do this on a WIN type of system I get: >>> import curses Traceback (most recent call last): File "", line 1, in ? File "C:\Python22\lib\curses\__init__.py", line 15, in ? from _curses import * ImportError: No module named _curses >>> However, it works just fine on Linux (of course, curses is installed by default on *nix) Is there a "Curses" package I need to install for win.. or am I missing something here? From peter at engcorp.com Thu Mar 27 14:04:37 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 27 Mar 2003 14:04:37 -0500 Subject: How can I test if a reference is null ? References: <2e3d7019.0303271101.11d00cdf@posting.google.com> Message-ID: <3E834B44.E6CAD3A8@engcorp.com> smac wrote: > > cudjoe at europe.com (cudjoe) wrote in message news:... > > On a Java GUI, I need to test if a label contains an Icon, I wrote > > those few lines in Jython (similar): > > > > > > tabComp = panel.getComponents() > > trouve = false > > for com in tabComp: > > if isinstance(com, JLabel): > > icon = com.getIcon() > > if( icon != NULL ): ##### doesn't work ! > > trouve = true > > > > I know that there are no types in python, but how can we test if a > > variable is empty ? > > > > Thanks you everybody, > > > > Mathieu > > if vars().has_key('icon'): > print 'not empty' This is surely not the same thing as what the OP intended. If the com.getIcon() routine doesn't manage to return anything, even None, then it must have raised an exception and your test would never be executed anyway. Alex was indubitably on the right path as usual... -Peter From tottinge at indy.rr.com Fri Mar 7 12:59:20 2003 From: tottinge at indy.rr.com (Tim Ottinger) Date: Fri, 07 Mar 2003 17:59:20 GMT Subject: Perl Vs Python References: Message-ID: <3E68DC7B.3020706@indy.rr.com> Anand B Pillai wrote: > The disadvantages I think is probably speed, poor documentation among > other things. I'm not sure that I would characterize the documentation as "poor". I think I would characterize it by saying that the documentation we have ranges from good to excellent, but that we don't have as much of it as the Perl community does. We've got great tutorials, and most of the library doc is pretty good. I really like some of our documentation, and I use it freqently when looking for a wheel to avoid reinventing. If one has web access, the python wiki and web sites are quite good. But you don't see as many python books as perl books at the local shop. Maybe we don't need as many. It would be good to have one authoritative volume for each major release maybe, and a few targeted at web development or numeric processing or GUI apps. That would really be enough. Waiting-for-a-really-good-wxPython-book-ly yours, Tim Ottinger (not the other Tim) -- +---------------------------+--------------------------+ | Tim Ottinger | OpenOffice Mozilla Samba | | Indianapolis, IN USA | Python, C++, Whatever | | I promote Free Software | Linux! (MS if I have to) | |---------------------------+--------------------------| | OO Architecture, Design, Teacher/Mentor | +------------------------------------------------------+ From ldwhitley at charter dot net Mon Mar 24 13:18:47 2003 From: ldwhitley at charter dot net (ldwhitley at charter dot net) Date: Mon, 24 Mar 2003 12:18:47 -0600 Subject: PyNetTestUser Message-ID: I found a directory on my XP laptop named c:\Documents and Settings\PyNetTestUser\ Looks like a python related directory, anyone know whose, why, etc? Larry From theller at python.net Fri Mar 14 14:36:21 2003 From: theller at python.net (Thomas Heller) Date: 14 Mar 2003 20:36:21 +0100 Subject: do it yourself listbox control References: <59e5b87.0303141104.30ba5e5@posting.google.com> Message-ID: mirandacascade at yahoo.com (Miranda Evans) writes: > Win2K operating system. > Python 2.2 > > Constraint:not able to use any of the various applications (e.g. > Tkinter, wxPython, PythonCard) that simplify the process of handling a > UI. > > Looking for sample code that handles a listbox control. Hopefully, > the sample code will illustrate: > - how to accept a list of information passed to it and display that > list in something that looks like a listbox control > - how to detect whether an entry in the list has been selected (where > selected means the user has clicked on a row in the list) > - if a list entry has been selected and the user has clicked the OK > button, how the code that gets excuted when OK button is clicked can > reference the various columns of information in the selected row of > the list > - how to detect whether the cancel button has been clicked > > Although this application cannot make use of the various UI tools (see > constraint above), this application can import various classes/modules > that might be regarded as UI-related, e.g. > > import win32ui > import win32api > import win32con > from pywin.mfc import dialog > Isn't MFC a UI tool by your definition? > I'm guessing that this 'do it yourself' listbox is available > somewhere, but I'm not sure where to look. IMO the activestate distribution contains a help search/browse facility which demonstrates this. If you really want to do it without a prefabricated UI toolkit, just using the raw win32 api, welcome to ctypes: http://starship.python.net/crew/theller/ctypes.html. Also anygui contains backends using ctypes and win32gui (not win32ui or mfc). Thomas From brian at sweetapp.com Tue Mar 18 21:16:23 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 18 Mar 2003 18:16:23 -0800 Subject: OT: Recommended Linux Laptops, suppliers? In-Reply-To: <1048033446.1108.398.camel@software1.logiplex.internal> Message-ID: <01cf01c2edbd$89e62b40$21795418@dell1700> > No doubt they have some nice features. They also lack some I consider > essential. I don't think we're going to reach an agreement on what a > good price/performance ratio is. Using Skip's numbers, the 1GHz Powerbook scores about 10% less pystones. I think that 10% less performance, for a similar price, is reasonable. > Perhaps you get a bigger paycheck or > are happy with the same PC for longer than I am. I spend around $400 a > year to upgrade my PC (new mobo, CPU and RAM, occasionally an additional > amount for a larger HDD) and easily double my performance every year. > With a Mac I'd have to shell out $2000/year to maintain the same > situation (and given their glacial processor improvements *if* it could > be done remains questionable). To me that's unacceptable in today's > commodity PC market. We were talking about laptops here. What PC laptops have upgradeable motherboards? > > Are your fonts antialiased or is every graphic object antialiased? And I > > am talking about client graphics, not window manager constructs. > > Everything. The fonts are AA by X (Xft extensions), but the desktop is > AA by the video driver (nVidia), which, IMHO, is where it ought to be > done (most modern video cards support fullscreen AA in hardware). I'd > be surprised if Apple doesn't leverage this same hardware support. Cliff, I don't think that you understand how the X architecture works. Here is a diagram: http://www.x.org/X11_protocol.html If you look at the protocol, there is no way for a client to specify that it wants to draw a line terminating at subpixel locations. This is actually true of all the X functions that I am aware of. The server can chose to render the line using antialiasing, if it wishes, but precision is lost between client and server (because the protocol specifies integers for coordinates). There is also no way to assign blending values when drawing. Your point about your desktop being antialiased is irrelevant because your desktop is a window manager artifact and your window manager is not an X client. Where the pixel calculations are actually done is irrelevant to the X (and Quartz) client. > > There are OpenGL extensions for X windows. Why do you think that is? > > Because it would be way too expensive to convert OpenGL constructs into > > X primitives and send those across the network. > > But at least they *can* be sent across the network . Well, they can't because no one is insane enough to do this. But you *could*, I guess. Just like you could just send the entire window buffer over in Cocoa. Doing that with a 1024x768 window @ 60fps would cost you 4MB/s of network bandwidth. And you'd lose a bunch of information (like color correction data) and optimization opportunities. > I've done > little research and it appears that Apple's remote desktop is very > similar to VNC or PCAnywhere. Apple doesn't have a remote desktop product, do they? They just have hooks to allow others to develop them. > Undoubtedly Apple figures this type of thing isn't > too interesting to their target market (and perhaps they'll add it > later, if their architecture allows) but to me it's an essential aspect > of my computing environment. The architecture allows it and any interested party is free to implement it. > I have 4 PC's here at work, one in another > room, and I routinely run monitor apps, editors and whatnot remotely. I do this too. I just use ssh, which I'll admit is less cool. Cheers, Brian From antonmuhin at sendmail.ru Fri Mar 14 11:59:40 2003 From: antonmuhin at sendmail.ru (Anton Muhin) Date: Fri, 14 Mar 2003 19:59:40 +0300 Subject: please comment - my first classes In-Reply-To: References: Message-ID: I quite agree with Sean about naming conventions too. Some more notes. > class bookmark: > def __init__(self,group,name,url): > self.group=group > self.name=name > self.url=url > > def Print(self): > print self.group,':',self.name,':',self.url it might be written as: print ':'.join([self.group, self.name. self.url]) if all are strings. This solution is quite understanable (at least for me ;) and might be a bit more effecient. > > def AsTuple(self): > return( (group,name,url) ) > > class bookmark_group_db: > def __init__(self): > self.lastKey = -1 > self.groups = {} > > def Add(self,name): > self.lastKey += 1 > self.groups[self.lastKey]=name Or self.groups[len(self.groups)] = name This seems to eliminate need for lastKey. BTW, why not to use lists? self.groups = [] self.groups.append(name) ? > > def Has(self,key): > if self.groups.has_key(key): > return 1 > else: > return 0 Maybe just: return self.groups.has_key(key) or (for lists) return 0 <= key < len(self.groups) > > def PrintAll(self): > for i in self.groups.keys(): > print i,':',self.groups[i] For dict: for i, value in self.groups.iteritems(): print i, ':', value For lists (in Python2.3, but it quite easy for Python2.2 too): for i, value in enumearte(self.groups): print... > > class bookmark_db: > def __init__(self): > self.lastKey = -1 > self.bookmarks = {} > > def Add(self,group,name,url): > self.lastKey += 1 > self.bookmarks[self.lastKey]=bookmark(group,name,url) See above > > def AddBookmark(self,src): > self.lastKey += 1 > self.bookmarks[self.lastKey]=src See above > > def PrintAll(self): > for i in self.bookmarks.keys(): > self.bookmarks[i].Print() See above BTW, if you need this functionality often, why not abstract it into a class? > > def Find(self,sub): > matches = bookmark_db() > for i in self.bookmarks: > if self.bookmarks[i].name.find(sub)>-1 or > self.bookmarks[i].url.find(sub)>-1: > matches.AddBookmark(self.bookmarks[i]) > return (matches) I personally don't like () in returns, but it's a matter of taste Does this code work? Don't you mean: for bookmark in self.bookmarks: if bookmark.name.find(sub) ....? You may introduce function or method for bookmark matching: def doesBookmarkMatch(bookmark, sub): return bookmark.name.find(..) or bookmark.url.find(...) And use it. BTW,several more compact forms: matches = [bookmark for bookmark in self.bookmarks if doesBookmarkMatch(sub)] or matches = filter(doesBookmarMatch, self.bookmarks) > > def Size(self): > return (len(self.bookmarks)) In some context, you might want to override __len__ method to use something like len(bookmark_db()) BTW, your bookmark_db seems to be just a list. Maybe you need several functions and stick to a simple list. > [snipped] HTH, Anton. From robin at execulink.com Fri Mar 28 15:29:13 2003 From: robin at execulink.com (robin) Date: Fri, 28 Mar 2003 15:29:13 -0500 Subject: session information in cgi scripts References: Message-ID: James Gregory wrote: >Simple qn: Is there a module that implements session data? Or rather, >what is the module that implements session data? I'm using python as a >CGI so storing stuff in my own webserver isn't really an option. I >looked on http://python.org/doc/current/modindex.html and nothing leapt >out at me. You could try my Wasp: http://www.execulink.com/~robin/wasp/readme.html It has a session module that stores info server-side in a regular pickle file, keyed to a cookie id. Expiry time, etc. can be set and the programmer can store arbitrary data in the session. -- robin From aleax at aleax.it Tue Mar 4 12:14:35 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 04 Mar 2003 17:14:35 GMT Subject: Vote on PEP 308: Ternary Operator References: <882b0a41.0303020225.3caf0334@posting.google.com> <2259b0e2.0303040823.f8c8974@posting.google.com> Message-ID: <%959a.5216$zo2.160354@news2.tin.it> Michele Simionato wrote: ... > This is a very confusing votation system :-( Not on a par with Italian electoral laws (which you may have already blissfully forgotten from your Pennsylvania home, as far as I know...), but, yes, pretty bad, I agree. Alex From martin.vonloewis at hpi.uni-potsdam.de Mon Mar 24 04:32:41 2003 From: martin.vonloewis at hpi.uni-potsdam.de (Martin v. Löwis) Date: Mon, 24 Mar 2003 10:32:41 +0100 Subject: type function does not subtype References: <3E7E81EF.1992BFD4@alcyone.com> Message-ID: > Why would you want to sub-class a function object? > > * To provide methods on the object allowing OO-style API's for > introspection? That won't work. If you create a function through the def statement, it will be of type function, not of a subclass thereof. So on all function objects, your introspection methods won't be available. > * Experimenting with meta-programming mechanisms Same counter-argument: How do you create such specialized function objects? > The question then becomes, is it appropriate to allow the > sub-classing approach? Not unless accompanied with some other change to conveniently create specialized function objects. One proposal (originally proposed to create class methods) might work: def foo(args)[enhanced_cleanup]: code This would create a function object first, then invoke the callable enhanced_cleanup, which returns a modified (or wrapped) object. However, if this extension were available, specializing the function type is still not necessary, since you could just as well create wrapper objects in all usage scenarios you have given. > Which comes back to Tim's post, suggesting that a volunteer creating a > sub-classable version of the function object would be sufficient to > introduce such a thing to the core. I suspect any volunteer would notice quickly that this is not sufficient. Regards, Martin From max at alcyone.com Wed Mar 5 02:33:35 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 04 Mar 2003 23:33:35 -0800 Subject: PEP 308: an additional "select/when" survey option References: <882b0a41.0303020225.3caf0334@posting.google.com> <20030305005906.GA56890@doublegemini.com> <3E6571C1.78DC4489@alcyone.com> Message-ID: <3E65A84F.A2E1874E@alcyone.com> "Clark C. Evans" wrote: > Quite right. A switch/case statement isn't at issue for PEP 308, > and I was incorrect to label this proposal as such -- switch/case > is a block level construct which contains statements. I'm not > proposing that. I understand that. I (on autopilot) retyped what you wrote, but I understood what you were suggesting. As I said, it is really beyond the scope of PEP 308; it should be in another PEP. > This proposal is for a select/when *expression* which is simply > a generalization of a terinary operator, and equivalent to > some of the "elif" like options on the table. So, this > proposal fits right in with the spirit of the PEP. It's something that could degenerate to a ternary (or trinary, but not terinary) operator, but it in and of itself is a more generalized construct and so is not appropriate for a PEP 308 vote. If you want to suggest a generalized select/when (or whatever you want to call it) and propose that, that's fine, but it would be for another PEP. Take people who wanted to implement ternary operators in terms of a special syntax for zero-argument lambdas and a new builtin; this degenerates to a ternary (or can be used as one), but really deserved to be suggested under another PEP; and, indeed, it was. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ I like young girls. Their stories are shorter. \__/ Thomas McGuane Crank Dot Net / http://www.crank.net/ Cranks, crackpots, kooks, & loons on the Net. From aleax at aleax.it Fri Mar 21 04:11:44 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 21 Mar 2003 09:11:44 GMT Subject: Raising an exception in the caller's frame References: Message-ID: Thomas Heller wrote: ... > Hopefully I can explain it: check_result() is not the 'cause' of the > error, it's purpose is simply to detect the error. The 'exception' > really occurrs in dosomething(). Yes, your purpose is very clear to me and I agree there _should_ be a way to achieve it, but I can't think of one. > The situation is similar to what is explained for the warn() function, > see the stacklevel parameter. Maybe I should look into the warnings > module. If you're satisfied with a warning, yes, but when you turn the warning into an error the stacklevel doesn't seem to work, e.g.: >>> import warnings as w >>> class mywa(Warning, ValueError): pass ... >>> w.filterwarnings('error', category=mywa) >>> def checkeven(value): ... if value%2: w.warn("Value not even", mywa, 2) ... return value ... >>> def somework(value): ... return checkeven(value+1) ... >>> somework(23) 24 >>> somework(42) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in somework File "", line 2, in checkeven File "/usr/local/lib/python2.3/warnings.py", line 49, in warn warn_explicit(message, category, filename, lineno, module, registry) File "/usr/local/lib/python2.3/warnings.py", line 84, in warn_explicit raise message __main__.mywa: Value not even >>> Alex From mruiz at safa.es Tue Mar 25 06:15:23 2003 From: mruiz at safa.es (Manuel Ruiz) Date: Tue, 25 Mar 2003 12:15:23 +0100 Subject: Executing Python scripts in Python? References: <3e800fb6$1@mail.hmgcc.gov.uk> Message-ID: El Tue, 25 Mar 2003 08:13:41 +0000, Richard escribi?: Hi, Python has several way of execute other python code. Take a look at eval(), exec and execfile() in you python documentation. If you have problems understanding this functions don't hesitate and contact with me by email. Regards Manuel Ruiz > Hi, > > I am currently writing an application in Python that (amongst other things) > processes incoming data from multiple socket network connections. The > incoming data on each socket is in a different format, although they all > convey the same data. > > I want my Python program to execute other Python scripts (in threads), > passing to them (or making available to them) an object containing a > connected socket and a ton of data fields for it to populate from the > received (and processed) socket data. These scripts cannot be hard-coded > into the appliocation as I need to be able to change the scripts while the > main program is running. > > I have seen in the Python Library Reference the 'code' module and think that > this might be able to help me. However I can't find any examples of its use > that applies to my situation. > > Has anyone got any ideas? > > Thanks > > Richard From claird at lairds.com Wed Mar 5 15:01:08 2003 From: claird at lairds.com (Cameron Laird) Date: Wed, 05 Mar 2003 20:01:08 -0000 Subject: Perl Vs Python, Associative arrays, regex, and other considerations. References: Message-ID: In article , Bob X wrote: >"Cameron Laird" wrote in message >news:v5sgg22lphoh1f at corp.supernews.com... >> In article , Mike Meyer >wrote: >> . >> . >> . >> >About equal. Both can be interfaced to other languages through C, you >> >can wrap C and C++ libraries for both with SWIG, and both have a >> >number of guis available, with tcl/tk being popular on both. >> . >> . >> . >> Mike, we disagree. While I think enough of GUIfied Perl >> to maintain the authoritative FAQ for Perl/Tk, my view is >> that there's no comparison with the breadth of toolkit >> bindings Python offers. PyQt, wxPython, ... make for a >> stronger effective range of choices than I see from any >> other language, including C. >> -- >Not that I am arguing one way or another, but Perl has binding to those >(mentioned) as well. True? > > Nope. PerlQt's usable with release 3, but juvenile compared to PyQt. wxPerl is at version 0.12. The FLTK binding's no more than an exper- iment. Perl/Tk never worked under MacOS. I admit that Gtk-Perl's more active than I used to predict. I've lost track of the maturity of Perl XPCOM; I know it used to be a bit fragile. And so on. It could be that I'm not current. As of a couple of years ago, Python bindings were considerably more *serious* than their Perl homologues; Pypeople constructed working applications with them. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From tjreedy at udel.edu Sat Mar 29 16:55:04 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 29 Mar 2003 16:55:04 -0500 Subject: Metaphors and politics References: <1MudnTyOEK1mauGjXTWcqg@speakeasy.net> <3E835DC2.3678BD7F@engcorp.com> Message-ID: "Terry Reedy" wrote in message news:L9ecnVASabhrlxujXTWcpQ at comcast.com... > Here is another from Australia's Sunday Mail (another right-wing rag?) > that combines the UPI info (I presume) with a local source. They > quote from 3!! separate disillusioned (by reality) 'human-shield' > returnees. Given people's general reluctance to reexamine deeply held > beliefs even in the face of strong contrary evidence, this is pretty > remarkable. I have also seen Rev. Joseph interviewed live on a TV news program and he said the same things reported by UPI, so UPI (and its subscribers) quoted him correctly. Dismissing his powerful testimony by slamming a news organization he has no connection with and probably dislikes himself is an evasive non sequitor. Terry J. Reedy From grisha at apache.org Mon Mar 17 10:49:27 2003 From: grisha at apache.org (Gregory (Grisha) Trubetskoy) Date: Mon, 17 Mar 2003 10:49:27 -0500 (EST) Subject: ANNOUNCE: Mod_python 3.0.3 In-Reply-To: <20021127135855.Q36516-100000@eden.ispol.com> Message-ID: <20030317103105.X92188-100000@eden.ispol.com> The Apache Software Foundation and The Apache HTTP Server Project are pleased to announce the release of mod_python 3.0.3. Mod_python is an Apache HTTP Server module that embeds the Python interpreter within the server. With mod_python you can write web-based applications in Python that will run many times faster than traditional CGI and will have access to advanced features such as ability to retain database connections between requests, access to httpd internals and provide content filter as well as connection handlers. This release fixes numerous bugs identified after last release (3.0.1). It is highly recommended that you upgrade to version 3.0.3 for improved stability and performance. Mod_python is available for download from: http://httpd.apache.org/modules/python-download.cgi For more information about mod_python visit: http://www.modpython.org/ Regards, Grisha Trubetskoy From bkc at Murkworks.com Sat Mar 1 12:21:19 2003 From: bkc at Murkworks.com (Brad Clements) Date: Sat, 1 Mar 2003 12:21:19 -0500 Subject: xforms (W3C) intepreter in Python? References: <3e393e41_1@spamkiller.newsgroups.com> Message-ID: <3e60ec9c_1@spamkiller.newsgroups.com> "Gerald Bauer" wrote in message news:c4a49f85.0302282351.5cbcdc71 at posting.google.com... > > Anyone else looking at xforms? > > Yes. XForms is my top priority and I plan to add it over the next > couple of weeks/months to the Luxor XUL toolkit. Thanks for the response, I've been all over your site in the past, and all the sites you linked to and on and on. Luxor, xwt, thinlet and xsmiles websites all get a daily visit from me looking for "news". (that, and Vamp.. ) Some of the luxor-family sites appear to be out-dated. I suspect your hands are full. --- Clearly, xul and xforms isn't simple. I'm considering re-writing thinlet in Python to dirty my fingers. From max at alcyone.com Wed Mar 12 23:08:40 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 12 Mar 2003 20:08:40 -0800 Subject: GCD in standard library? References: <3E6FE2A7.DCDE0C96@alcyone.com> Message-ID: <3E700448.ACAB311C@alcyone.com> [I already replied to this by email since it wasn't clear that it was cc'd to the newsgroup/list.] Blake Garretson wrote: > Right. Maybe I'm doing something wrong, but the recursive version > appears > faster. Here's my little test: You've only done one trial each, so this really doesn't say much. Other effects (such as load or caching) can easily swamp these results. Instead you should be running with very large test numbers and run the test many, many times (like hundreds of thousands or millions). -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ That which is resisted persists. \__/ Camden Benares ZOE / http://www.alcyone.com/pyos/zoe/ A simple Python OpenGL rendering engine. From aleax at aleax.it Thu Mar 6 17:50:41 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 06 Mar 2003 22:50:41 GMT Subject: Python in a Nutshell: Real Soon Now! References: Message-ID: <5hQ9a.22180$zo2.647510@news2.tin.it> Steve Holden wrote: > I thought US readers, at least, might be interested to know that UPS have > just delivered my complimentary copy of "Python in a Nutshell". By using a > fine, almost onion-skin, paper they have made an excellent volume that is > quite manageable to read and carry around. Nice job, Alex ... should be > on the bookshelves any time now! Thanks! I was impressed by UPS and ORA this time -- *my* copy also arrived today, and I heard from an Italian guy who reviews technical books for an important local site -- HE also got his review copy today... Alex From aleax at aleax.it Tue Mar 11 09:28:05 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 11 Mar 2003 14:28:05 GMT Subject: Can __iter__ be used as a classmethod? References: <3e649aa3_4@news.bluewin.ch> <2259b0e2.0303041023.43e8b81f@posting.google.com> <4B89a.6715$zo2.218162@news2.tin.it> Message-ID: Greg Ewing (using news.cis.dfn.de) wrote: > Alex Martelli wrote: >> Aren't these reasons enough? How else would you code a method that >> you can indifferently call either on any instance or on the class >> object itself? > > How often do people actually *need* that functionality, Not often! The same could be said of MANY other things, I believe, including of course staticmethod. How many of the features introduced in Python 1.6 and later are actually NEEDED, considering that 1.5.2 was already quite usable to write large and complicated applications in? "NEED" is a very strong word, after all. > though? Smalltalkers don't seem to be bothered by the > need to know whether to call a method on a class or an > instance. Can someone provide a compelling use case > for this in Python? If you provide any compelling use case for staticmethod's ability to perform the same thing, I think a parallel can surely be drawn that shows a similar use case for classmethod's slightly richer abilities with exactly the same context. >> And _having_ to write a custom metaclass as the >> only way to get classmethods would be somewhat of an overkill. > > What if there were some syntactic support, such as > > class C: > > def class foo(cls): > ... > > which would trigger the automatic creation of a > suitable metaclass. Would there still be a pressing > need for classmethod()-style class methods then? I think that using a custom metaclass has implications that may be considered a bit too strong to sneak one in "by black magic" -- what happens if you're multiply inheriting from a class C and a class D and both have class methods? Should we have a FURTHER custom metaclass generated then? Magic gets blacker and blacker... What do you find so horrible with classmethod as it stands that would come close to justifying such an excursion into exhoterism in order to get rid of it? Alex From rtconstant at sbcglobal.net Mon Mar 17 12:16:47 2003 From: rtconstant at sbcglobal.net (Constant) Date: Mon, 17 Mar 2003 17:16:47 GMT Subject: windll and structure passing to Win32 API function Message-ID: <3qnda.341$ic4.192600243@newssvr30.news.prodigy.com> I cannot find good tutorial or reference info on Sam Rushing's windll related procedures. I have read the books and searched the web very well. Here is my specific prolem. I am working with the Win32 API function CreateProcess(), as the example for this posting. Some of its parameters are structures. I will use the last two, lpStartupInfo and lpProcessInformation to explain my problem. First, I can create the two structures using Oracle(). I can receive information returned from a Win32 API function, such as, lpProcessInfomation. Second, what I cannot figure out is how to pass information in a structure, like lpStartInfo. I can create it. But I do not know how to populate the structure with data to be passed. For example, I would like to set the elements dwX, dwY, dwXSize, and dwYSize to position the window created by the new process. I set the appropriate dwCreationFlags of the CreateProcess() function. My only problem (I hope) is how to set the appropriate members of the StatupInfo structure that I create and then pass this populated structure to CreateProcess(). My first desire is an answer to how to do what I just described, pass info in structures. I have successfully used similar structures in Win32 API functions that return info in structures. My second desire is to know the location of any good tutorial and/or reference information on using windll. I have searched the example scripts and the web and the books, but such documentation, as I have found, is woefully inadequate. Terry From troy at gci.net Fri Mar 7 16:40:42 2003 From: troy at gci.net (Troy Melhase) Date: Fri, 07 Mar 2003 21:40:42 +0000 Subject: tal template engine in python out of zope References: Message-ID: You don't need a separate implementation of TAL or PageTemplates -- the ones that are distributed with Zope work outside of Zope with a little help. Try looking thru the Zope mailing list archives for details on how to get the PageTemplate package available on its own. It's actually quite easy; download Zope, unpack the archive and copy some directories around. I have a recipe in the cookbook that explains how to use PageTemplates with the Medusa web server (no Zope involved). You could probably adapt the recipe to fit your needs. The recipe is here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157501 Good luck. -troy Antonio.P wrote: > I am looking for an implemetation of the zope "tal" template engine but > out of zope. > I can only use python not zope, but I'd like to use a template engine like > the tal of zope. > > Thank you From ark at research.att.com Mon Mar 24 09:54:00 2003 From: ark at research.att.com (Andrew Koenig) Date: Mon, 24 Mar 2003 14:54:00 GMT Subject: Python 2.3 True = False References: Message-ID: >> has anyone tried this before? Jack> Yes, in FORTRAN. And it has the same effect. No, not really. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From pball at umich.edu Mon Mar 10 20:12:56 2003 From: pball at umich.edu (pball) Date: 10 Mar 2003 17:12:56 -0800 Subject: JOB POST - short term consulting Message-ID: We're a data analysis shop and we're looking for a pythonista for 2-3 weeks to help us clean up and advance a project. The code does this: query engine -> python data ----^--> page renderer--- |----graph maker <--| where the query engine is whatever slurps & processes data (probably SQL, but other engines are possible); the data then live in python objects and get handed to a page-generation engine which makes "pages" (PDF, HTML, etc); The page-generation engine calls the graph maker to make graphs that are laid out on the page. Lots of graphs. Hundreds of graphs, laid out on nice-looking but complicated pages that represent tables and other data structures. Currently we use reportlab for the PDF page renderer and ploticus for the graph engine (ploticus returns SVGs). Lots of other graph engines are possible (R, gnuplot, SciPy, etc). We've designed it like this to keep things that vary separated - different data reading tools, different page renderers, different graph makers. Right now, the code is done enough that we can make a bunch of graphs. However, we want to do the following: - render the design in formal UML notation - write a test framework for every little thing - refactor the not-very-well-thought-out pieces (hopefully a minority) - check & possibly fix the patterns - add a load of features. We're short-handed, and we need some seriously experienced python help, ideally someone who loves testing and refactoring, for approx 2-3 weeks. Washington DC-area is probably best. Even more ideally, we want someone with ideals - we build databases and do data analysis of large-scale human rights atrocities. We use only free software (though with a bit looser definition than FSF uses). The pay is pretty miserable by private sector standards ("we put the 'non' in non-profit"). But the tech is nifty and the substance of the application will make you feel good about what you're doing. Plus, it's really interesting ;) check us out http://shr.aaas.org/hrdag If you're interested, drop me an email with some sample code and let me know what you think: pball-AT-NOSPAM-aaas-dot-org. thanks - PB. From basu at mahiti.org Thu Mar 27 01:19:43 2003 From: basu at mahiti.org (Basalingamma) Date: Thu, 27 Mar 2003 11:49:43 +0530 (IST) Subject: XML generation Message-ID: <35330.192.168.0.232.1048745983.squirrel@192.168.0.254> HAI, How can I generate xml by extracting Zope's ZCLASS instances properties. ------------------------ Basalingamma, Volunteer, Mahiti Infotech Private Limited 314/1, Vijay Kiran, II Floor, 7th Cross, Domlur Layout, Domlur, Bangalore - 560 071 From peter at engcorp.com Fri Mar 21 15:04:13 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Mar 2003 15:04:13 -0500 Subject: Is Python the Esperanto of programming languages? References: <7i65qe953z.fsf@enark.csis.hku.hk> <3E7A9C89.D5D01F85@engcorp.com> <7i4r5w7i7u.fsf@enark.csis.hku.hk> Message-ID: <3E7B703D.D3EB19E@engcorp.com> Isaac To wrote: > > To Chinese, the whole inflection thing, let alone agreement, is plain > stupid. I don't know if "stupid" is exactly the word you should use here, unless you're trying to incite antagonism. Perhaps you meant "unnecessary"? [...] > BTW, Yes, Chinese is indeed *much more* resistent in noisy environments (but > for a very different primary reason: it's louder). Ah... do you have any evidence of this, or are you just theorizing? [...snip lots of good stuff on some of Esperanto's warts...] > That's why I said that Esperanto is inelegant. Well, it's hard to argue with some of what you say. Nevertheless, I believe the main point is simply that Esperanto is provably *much* easier to learn than most natural languages, and easier to at least some extent than probably all of them. Few people will argue convincingly that Esperanto is trivially easy to learn, and a discussion of "elegance" reduces quickly to personal opinion anyway, and so is largely pointless. -Peter From aleax at aleax.it Fri Mar 7 10:42:08 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 07 Mar 2003 15:42:08 GMT Subject: automatic (un-)pickling / overwriting self References: <6c492956.0303070109.2e51963e@posting.google.com> Message-ID: Clemens Hermann wrote: > Hi, > > while working on a cgi-admin interface i got a little problem with > pickle. > I use a hierarchical class structure to keep users, permissions, etc. > As the amount of data is quite small i just pickle the top class > instance that references the rest. So far so good... > I am looking for a way to automatically pickle the top class whenever > one of the referenced object changes. That's pretty hard indeed, to put it mildly; you'd basically have to wrap every "referenced object" into the Observed side of an Observed/Observer patter, catch EVERY change (a VERY tall order indeed, with the amount of indirections being unbounded) and do a callback to the top-class Observer. I would urge you to look for a much easier and less-general approach. > Furthermore I want a class > instance to unpickle the data automatically on creation. > A self = unpickledObject in __init__ does not work (probably a bad > idea anyway :). You can code the class's __new__ method to return the unpickled object, and leave its __init__ empty (it's called anyway after __new__, unless you go for custom metaclasses or play some strange tricks such as returning something that's NOT actually an instance of that class). > So how is automatic/implicite serialization(on changes) and Too hard to bother with in the general case, IMHO. > de-derialization(in __init__) from *within* a class instance done? > Furthermore: How can I make sure that there can only be one instance > of the top class active at a time? You want the Singleton design pattern -- but it's not a good idea, use Borg instead (let there be as many instances as there happen to be, as long as they all share the same state). See for example http://www.aleax.it/Python/5ep.html for an in-depth essay on that. Alex From lorenzo at mysurname.net Fri Mar 14 13:12:12 2003 From: lorenzo at mysurname.net (L. B.) Date: Fri, 14 Mar 2003 18:12:12 GMT Subject: Python and IBM Message-ID: <0Yoca.13018$7y3.379291@twister1.libero.it> Hi all, found that developer's work on the IBM site is full of Python articles... i was just curious to know how Python fits in IBM... what is it used for? Thank You, Lorenzo From martin at v.loewis.de Fri Mar 7 03:14:30 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 07 Mar 2003 09:14:30 +0100 Subject: G++3.2.1 and static decls. in C++ Modules References: Message-ID: "Riendeau, Mike" writes: > If any python guru has a more elegant workaround than the following, > please let me know. Just ignore staticforward and statichere; use static all the time. Those macros were introduced to work around a bug in the Irix compiler (I believe); this compiler is no longer in use, and it is pointless to preserve them. Regards, Martin From kp at kyborg.dk Mon Mar 3 02:16:08 2003 From: kp at kyborg.dk (Kim Petersen) Date: Mon, 03 Mar 2003 08:16:08 +0100 Subject: I like Unicode more than I used to... References: <2nZ4a.10942$_c6.1134088@newsread2.prod.itd.earthlink.net> <15961.28266.229005.462017@montanaro.dyndns.org> Message-ID: <3E630138.9040700@kyborg.dk> Martin v. L?wis wrote: > Skip Montanaro writes: > > >>The only obvious way to announce the encoding would be by exporting >>an environment variable to the child program. > > > On Unix, the convention is that the terminal should follow the > locale's encoding; it is the user's responsibility to declare the > locale so that it matches the terminal. Actually that depends on the Unix version (and we might be talking major versions (eg. SysV vs. BSD)) - the import of STREAMs into SysV made it possible to change the encoding on the stream - not on the program (this works on at least one SysV i have - using mapchan(M) on SCO). > > On Win32, there is API to determine the input and output encoding of a > console window (yes, they can be different), provided you have a > "console handle". > > Regards, > Martin > -- Med Venlig Hilsen / Regards Kim Petersen - Kyborg A/S IT - Innovationshuset Havnepladsen 2 7100 Vejle Tlf. +4576408183 || Fax. +4576408188 From grante at visi.com Fri Mar 28 17:00:55 2003 From: grante at visi.com (Grant Edwards) Date: 28 Mar 2003 22:00:55 GMT Subject: Determining if program executing in shell background? References: Message-ID: <3e84c617$0$83870$a1866201@newsreader.visi.com> In article , Kevin Perrott wrote: > I'm trying to find a function that will tell me if a pyton > program is executing in the background when launched using the: > > & > > shell syntax. > > I'm trying to utilize the curses module to output messages to > 'windows' and the system seems to stop the program when I try > to get it to run in the background. I'm assuming it has > something to do with the curses module requiring control of a > proper stdout or something along those lines. > > I wrote a small test program using the isatty() function: > > #!/usr/bin/python > import sys > import os > isatty = os.isatty(sys.stdout.fileno()) > if isatty == 1 : > print("isatty") > else : > print("isnotatty") > > that I thought would do the trick but "isatty" always prints > whether launched by > > > or > & That's correct. Either way, stdout is connected to the terminal where the program was started. > I must be missing something somewhere and would appreciate any > help you guys/gals could give me. I'm guessing that the program is trying to query stdin for a character or status and has been stopped since stdin is not available. I'm not really sure how to programmatically check for that condition. You may want to add a command-line option to your program to tell it that it's to run in "daemon" mode so that it won't try to use ncurses. If you really want to use ncurses when run in the background, you should ask about it in a group where Thomas Dickey is likely to see the question. Try comp.os.linux.development.apps, and make sure that ncurses is in the subject line. -- Grant Edwards grante Yow! I KAISER ROLL?! What at good is a Kaiser Roll visi.com without a little COLE SLAW on the SIDE? From sandorlevi at yahoo.com Tue Mar 4 15:35:24 2003 From: sandorlevi at yahoo.com (Levente Sandor) Date: 4 Mar 2003 12:35:24 -0800 Subject: Help with wxPython BoxSizers References: <33803989.0303040753.1c47eefc@posting.google.com> Message-ID: <8b5e42a6.0303041235.6cad845d@posting.google.com> You've added twice the button 'b', first to the horizontal, then again to the vertical sizer. [...] hsizer.Add(b) # <--- topsizer.Add(hsizer) EVT_BUTTON(self, ID_BROWSE, self.on_select_defect) topsizer.Add(b) # <--- delete this line [...] ---- levi tebeka at cs.bgu.ac.il (Miki Tebeka) wrote in message news:<33803989.0303040753.1c47eefc at posting.google.com>... > Hello All, > > Can someone tell me what I'm doing wrong in the following code? > I'd like to get the [...] button next to the text control and not below it. > > 10x. > > --- client.py --- > from wxPython.wx import * > > ID_READ_DATA = NewId() > ID_QUIT = NewId() > ID_DEFECT = NewId() > ID_BROWSE = NewId() > > FILE_FILTER = 'Defect Files|*.001;*.002;*.003;*.cmp;*.kla' > RECIPE_NAME = '' > > class Client(wxFrame): > def __init__(self, parent, id): > wxFrame.__init__(self, parent, id, 'Compass Client') > topsizer = wxBoxSizer(wxVERTICAL) > # Top Read Data button > b = wxButton(self, ID_READ_DATA, 'Read Data') > EVT_BUTTON(self, ID_READ_DATA, self.on_read_data) > topsizer.Add(b) > # Defect file > #FIXME: Why doesn't layout work? > topsizer.Add(wxStaticText(self, -1, 'Defect file:')) > hsizer = wxBoxSizer(wxHORIZONTAL) > self.defect = \ > wxTextCtrl(self, ID_DEFECT, '', size=(200, -1)) > hsizer.Add(self.defect) > b = wxButton(self, ID_BROWSE, '...', size=(20, -1)) > hsizer.Add(b) > topsizer.Add(hsizer) > EVT_BUTTON(self, ID_BROWSE, self.on_select_defect) > topsizer.Add(b) > > q = wxButton(self, ID_QUIT, 'Quit', wxPoint(0, 70)) > EVT_BUTTON(self, ID_QUIT, lambda e: self.Close(1)) > topsizer.Add(q) > self.SetSizer(topsizer) > self.SetAutoLayout(1) > topsizer.Fit(self) > > def on_read_data(self, event): > print event > > def on_select_defect(self, event): > dlg = wxFileDialog(self, 'Select a Defect File', '', '', FILE_FILTER, \ > wxOPEN) > if dlg.ShowModal() != wxID_OK: > return > self.defect.SetValue(dlg.GetPath()) > > > if __name__ == '__main__': > app = wxPySimpleApp() > frame = Client(None, -1) > frame.Show(1) > app.MainLoop() > > --- client.py --- From ouj at aludra.usc.edu Mon Mar 3 23:47:40 2003 From: ouj at aludra.usc.edu (ouj) Date: Mon, 3 Mar 2003 20:47:40 -0800 Subject: Help! Cannot open a file in a class Message-ID: Hi, I am new to Python. I write a class that opens a file and reads the data from the file. class Cvdoc: def __init__(self): ...... fd = file('vdoc.dat', 'wr') print dir(fd) fd.readlines() I used the following code to use this class: a = Cvdoc() And I got the following response: $ python vdoctest.py ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init_ ...... ritelines', 'xreadlines'] Traceback (most recent call last): File "vdoctest.py", line 12, in ? a = Cvdoc() File "vdoctest.py", line 8, in __init__ fd.readlines() IOError: [Errno 9] Bad file descriptor I can get access to the attributes of fd, such as fd.mode. However, I cannot invoke the methods associated with fd, such as fd.read(), etc. Can any one tell me help me out? Thanks a lot! Best regards, Jingzhao From remi at python-hosting.remove-me.com Mon Mar 17 13:02:22 2003 From: remi at python-hosting.remove-me.com (Remi Delon) Date: Mon, 17 Mar 2003 19:02:22 +0100 Subject: Website using Python--what's best architecture? CGI? References: Message-ID: <3e760db1$0$7894$626a54ce@news.free.fr> > I would like to create a commercial website using Python. It seems > that straight CGI would be the easiest option, but I'm wondering what > its top capacity would be, and also what other options are commonly > available for a website that I will be hosting through a commercial > host. Here are some specific questions: > > 1. Is there any good ballpark figure on an upper limit of throughput > for Python cgi pages that need to connect to mysql? I realize this > depends on many things, but I guess I am wondering if this is even a > sane option for a "moderately busy" website where almost all pages > will be dynamic and will need to create a db connection? I'm thinking > online store if that helps at all. You can also check out CherryPy (http://www.cherrypy.org), which has an original approach to website development. The threshold to get started is very low, but it is nonetheless quite powerful. > 2. What are other options available via commercial hosts? Is > something like "mod_python" or "Webware" commonly available on > commercial hosts (I know nothing much about either one, btw)? Or some > of the other Python web application frameworks I see mentioned? Seems > like a lot of these would require that you own the hosting machine and > have total control over it, which wouldn't be an option here. What do you think I'm running http://python-hosting.com for :-)) > Any words of advice appreciated. I really would like to develop it in > Python and don't want to go down a path that is unrealistic. Regards. Remi. From rc127 at yandex.ru Sat Mar 29 23:17:55 2003 From: rc127 at yandex.ru (Egor Bolonev) Date: Sun, 30 Mar 2003 15:17:55 +1100 Subject: how to hide text window when in GUI Message-ID: <3855690338.20030330151755@yandex.ru> Tkinter,windowsXP From martin at v.loewis.de Fri Mar 7 03:17:51 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 07 Mar 2003 09:17:51 +0100 Subject: IndentationError: two many levels of indentation References: Message-ID: Two Inches writes: > We've got this error when we tried to execute code that was created > with a generator tool. The code had about 500 levels of indentation > (nested if blocks). It is no problem for us to change the generator. > > However, I couldn't find this limitation in the language > reference. Shouldn't it be in there? What is the exact limit? > > Is there any technical rational for this limit? There is no limit in the compiler that I know of. Instead, IndentationError indicates a genuine error in your Python code. It is, for example, generated if you write print x print y This is a IndentationError (which is a SyntaxError), as you shall not indent the second line more than the first one. Regards, Martin From me at privacy.net Wed Mar 12 20:12:35 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Thu, 13 Mar 2003 14:12:35 +1300 Subject: lambda question In-Reply-To: References: Message-ID: David Bear wrote: > Still I am > wondering if this is a valid use of the lambda function. Anyone have > comments on where lambda's are most usefull? There's nothing wrong with it, but it's rather unusual style-wise, and it's no more (or less) efficient than using a def. Lambdas are most useful when you can embed them in another expression. Typical uses include creating callbacks for plugging into GUI widgets, e.g. import Tkinter, sys win = Tkinter.Tk() def make_button_which_prints(s): b = Tkinter.Button(win, text = s, command = lambda: sys.stdout.write(s + "\n")) b.pack() make_button_which_prints("Hello") make_button_which_prints("Goodbye") make_button_which_prints("Ftang!") win.mainloop() -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From donn at u.washington.edu Fri Mar 28 18:37:02 2003 From: donn at u.washington.edu (Donn Cave) Date: 28 Mar 2003 23:37:02 GMT Subject: Determining if program executing in shell background? References: Message-ID: Quoth "Kevin Perrott" : | I'm trying to find a function that will tell me if a pyton program is | executing in the background when launched using the: | | & | | shell syntax. You might try this: if os.tcgetpgrp(0) == os.getpid(0): print 'foreground' else: print 'background' This is basically asking if the current process is the process leader of the foreground process group for tty device unit 0 (standard input.) Donn Cave, donn at u.washington.edu From skip at pobox.com Tue Mar 4 21:23:46 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 4 Mar 2003 20:23:46 -0600 Subject: Code to unserialize Perl's Storable format? Message-ID: <15973.24498.13269.13088@montanaro.dyndns.org> Is there some Python code out there which can decipher Perl's Storable format? Thx, Skip From gerrit at nl.linux.org Wed Mar 5 14:52:49 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 5 Mar 2003 20:52:49 +0100 Subject: All this voting needs a pep In-Reply-To: References: Message-ID: <20030305195249.GA4402@nl.linux.org> phil hunt schreef op woensdag 5 maart om 20:26:27 +0000: > On Wed, 5 Mar 2003 14:10:45 +0000, Robin Becker wrote: > >Any body interested in starting a PEP 100000666 on new voting module for > >python lib? :) > > > >Well I guess not, as the Popular Front for the Liberation of Pythonistan > >now proposes to support the Pythonistan dictatorship unlike the > >reactionary Pythonistan People's Liberation Army who have instituted > >competing voting proposals on all sorts of new things. > > Splitter! > > All right-thinking people agree with the resolution passed by the > congress of the Pythonistan Peoples Front that voting should be by > Condorcet. I take it you mean left-thinking people? ;) yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From martin at v.loewis.de Sat Mar 22 17:17:55 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 22 Mar 2003 23:17:55 +0100 Subject: Shouldn't __init__ return self instead of None? (Was: Re: [Tutor] Why error if method __init__ does not return none) In-Reply-To: References: <200303221653.41190.ahimsa@onetel.net.uk> <5.2.0.9.0.20030322095904.0280dab8@66.28.54.253> Message-ID: Gerrit Holl schrieb: > This raises an interesting question. Shouldn't it say: __init__ should > return self...? Because _that_ is what it really does... That is debatable. If you have class Foo: def __init__(self): pass then this is *really* equivalent to having a function def Foo(*args): result = class("Foo",(),body_of_Foo) init = getattr(result, __init__) if init: init(*args) return result So the object is returned from calling Foo, not from calling __init__. It is an initalizer, not a constructor (only Python 2.2 supports constructors). An initializer is a procedure; it returns nothing. Regards, Martin From dave at boost-consulting.com Sat Mar 22 21:00:41 2003 From: dave at boost-consulting.com (David Abrahams) Date: Sat, 22 Mar 2003 21:00:41 -0500 Subject: BOOST help again ... References: Message-ID: Jim writes: > Hi ... > I have a new boost question ... how do convert a tuple to a c struct > ... my half brained attempt is below ... but it has some obvious > compile problems ... Please post Boost.Python questions to the c++-sig: http://mail.python.org/mailman/listinfo/c++-sig > void BOOSTED_cosim_define_board(boost::python::tuple t) > { > double x60_clk, pwm_clk, utx_clk, urx_clk, local_ref_clk, > pcr_ref_clk, mod_ref_clk, demod_ref_clk; > long mod_utopia, demod_utopia, dac_type, adc_type; > > if (!PyArg_ParseTuple(t, "(ddddddddllll)", > &x60_clk, > &pwm_clk, > &utx_clk, > &urx_clk, > > &local_ref_clk, > &pcr_ref_clk, > &mod_ref_clk, > &demod_ref_clk, > > &mod_utopia, > &demod_utopia, > > &dac_type, > &adc_type)) > { > PyErr_SetString( PyCosim_Error, "invalid args" ); > return; > } use extract(t[0]) extract(t[8]) etc., to get the values out. Your approach won't interact properly with exception-handling. > theboard.x60_clk=x60_clk*1e6; > theboard.pwm_clk=pwm_clk*1e6; > theboard.utx_clk=utx_clk*1e6; > theboard.urx_clk=urx_clk*1e6; > > theboard.local_ref_clk=local_ref_clk*1e6; > theboard.pcr_ref_clk=pcr_ref_clk*1e6; > theboard.mod_ref_clk=mod_ref_clk*1e6; > theboard.demod_ref_clk=demod_ref_clk*1e6; > > theboard.mod_utopia=static_cast(mod_utopia); > theboard.demod_utopia=static_cast(demod_utopia); > > theboard.dac_type=static_cast(dac_type); > theboard.adc_type=static_cast(adc_type); > > return; > } Your compile problems are not "obvious" from what you posted. If you need help with compilation errors, it helps to show us a few. Reproducible test cases are also good. -- Dave Abrahams Boost Consulting www.boost-consulting.com From aleax at aleax.it Tue Mar 4 11:39:44 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 04 Mar 2003 16:39:44 GMT Subject: Sorting lists of lists by columns References: <3E64BF02.9040901@motorola.com> Message-ID: Stephen Boulet wrote: > Is there any list method available to sort lists of lists by columns? I'm > thinking of a spreadsheet-type function where you might sort rows by the > column x, y, and then z. The Decorate-Sort-Undecorate idiom, which ends up playing the main role in the Sorting and Searching chapter of the Python Cookbook, is perfect for this task. E.g.: def sortByColumns(list2d, column_indices, in_place=False): aux = [ [ sl[i] for i in column_indices ] + [sl] for sl in list2d ] aux.sort() aux = [ sl[-1] for sl in aux ] if in_place: list2d[:] = aux else: return aux This is MUCH faster, as well as simpler, than passing a comparison function to the sort method. Alex From sholden at holdenweb.com Sun Mar 16 21:26:07 2003 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 17 Mar 2003 02:26:07 GMT Subject: Has anyone created a simple POP3 and SMTP server using TWISTED? References: Message-ID: <3nada.62946$JE5.33528@news2.central.cox.net> "Zoo Keeper" wrote ... > Or by any other means for that matter. > > I have two domains, one for me, one for my wife, for our web sites. I > want our own mail servers because our ISP has changed names 3 times in 4 > years. Right now I am using a great product (my server is BeOS, btw) > but it is a trial version and the minimal license is for 50 users and > costs too much. So, I figured I'd write one in Python, but I wanted to > check here first to make sure it hasn't already been done so that I am > not wasting time researching and writing something that already > exists... > I'm sure you will get lots of technical answers to your problem. However, surely it would be simpler to move to an ISP who will let you manage your own domain. Many such ISPs exist, and even if they change their names you will be able to continue using your own domain name.You should even be able to continue using the same domain name when you move from one ISP to another. So this isn't really a Python problem (IMHP). regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Register for PyCon now! http://www.python.org/pycon/reg.html From jpaish at freenet.edmonton.ab.ca Fri Mar 21 10:15:12 2003 From: jpaish at freenet.edmonton.ab.ca (Joseph Paish) Date: Fri, 21 Mar 2003 08:15:12 -0700 Subject: a couple of newbie questions Message-ID: <20030321.081510.2111331352.12265@localhost.localdomain> i am in the process of converting a perl script to python and have a couple of questions : --- 1. is there a way to comment out a large block of code in python? the reason i ask is that i would like to comment out the entire perl script and convert it piece by piece into python, uncommenting each function as it is converted so i can test if it does what i want. --- 2. is there a way to read a datafile whose records are space separated so that the second field becomes the key to a dictionary and the value portion is the entire record. for example, 01/01/2003 abc 1234.56 789.98 12332.98 <<< the original record the key would be : abc the value would be : 01/01/2003 abc 1234.56 789.98 12332.98 i have managed to read the datafile into a list of lists and would like to loop through this collection of records and convert it to a list of dictionaries keyed on the second field. i have already looked everywhere i can think of, but i haven't had any luck finding how to convert a list of lists into dictionaries. an alternative would be to bypass the list of lists altogether and populate the dictionary as i read each record. this would be even simpler. suggestions? thanks joe From gerrit at nl.linux.org Fri Mar 14 09:29:29 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Fri, 14 Mar 2003 15:29:29 +0100 Subject: newbie Pygame question In-Reply-To: References: Message-ID: <20030314142929.GB4055@nl.linux.org> [FUP: pygame-users at seul.org] Kristofer Wouk schreef op vrijdag 14 maart om 06:41:32 +0000: > I've been looking all over and can't figure out a way to do this, I know > it's something simple. > > How can a make a sprite(a bullet, to be exact) travel from point A(the > player sprite's position) > to point B(the mouse position)? > > Any help would be appreciated. Thanks. Have a look at Pygsear: http://nongnu.savannah.org/pygsear yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From rballard_99 at yahoo.com Tue Mar 4 12:55:54 2003 From: rballard_99 at yahoo.com (Bob Ballard) Date: Tue, 4 Mar 2003 11:55:54 -0600 Subject: md5 for large files References: <3E64E467.B64551E2@engcorp.com> Message-ID: Large is any file that I want to transfer around. For example the gpg library for windows that I just downloaded is a little over 1 mb and has a defined md5 value that I'd like to compare. This for a starter but for a specific purpose, i'd like to include the hash val in a separate file and upload or download with the target file, no matter the size. Any clues? Bob "Peter Hansen" wrote in message news:3E64E467.B64551E2 at engcorp.com... > Bob Ballard wrote: > > > > Can someone provide me with a snippet or pointer to usinging Python to > > verify the md5 value for a large file? All examples I've seen are for a > > small string. I'm not yet using GPG for NT and I need to verify or generate > > md5 values for file xfers. > > Define "large"... From news at titanic.co.uk Wed Mar 5 15:19:18 2003 From: news at titanic.co.uk (Simon Faulkner) Date: Wed, 05 Mar 2003 20:19:18 +0000 Subject: Parsing a conf file Message-ID: Hello All, Is there a simple / recommended way of parsing a setting from a conf file? For eample, I have a file /etc/program.conf which might have a setting like >> #My conf file server = Stafford << How do I parse out the name Stafford for the key server?? Simon From me at privacy.net Mon Mar 10 23:30:38 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 11 Mar 2003 17:30:38 +1300 Subject: PEP 308 use case (Re: A suggestion for a possible Python module) In-Reply-To: References: Message-ID: If anyone's collecting potential use cases for conditional expressions, here's one. Jp Calderone wrote: > def commaize(s): > P = len(s) % 3 > st = s[:P] + (len(s) > 3 and P and ',' or '') # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > return st + ','.join([s[i:i+3] for i in range(P, len(s), 3)]) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From mis6 at pitt.edu Wed Mar 19 11:22:27 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 19 Mar 2003 08:22:27 -0800 Subject: Aspergers link (was Re: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad...) References: <4fm07vg66gr4o4c74gb7ie5v85vlom1vhf@4ax.com> <0vv17v4vn4khffgr2io0otrnni8sc6rug7@4ax.com> <%dica.80722$zo2.2065641@news2.tin.it> <7f2b571b.0303161642.320e0997@posting.google.com> Message-ID: <2259b0e2.0303190822.58f369dd@posting.google.com> Carl Banks wrote in message news:... > I think people with Asperger's "syndrome" just violated someone's > arbitrary and very narrow idea of what they think is normal. > Here's my advice: forget all this crap about Asperger's syndrome. > Instead, go read about Myers-Briggs personality typing. _Please > Understand Me_, by David Kiersey, is a good reference. Kiersey would > probably dismiss Asperger's "syndrome" as nothing but a strong > introverted and thinking personality. This is a quite rude way of making the point, but still I think there is some merit in what Carl is saying. I see that this is an unpopular view in the newsgroup, so let me be clear in what I mean. I think there is a tiny line dividing the syndrome from the strong personality type, but still the line exists. I would put the line here: or you have the control of your life, or the syndrome has the control of your life. If (to make a simple example) you don't enjoy social life and you would rather go to the library than to the party, this does not means that you have the syndrome: however, if you CANNOT go to the party, then you have the syndrome. I agree that there are people that really are on the bad side of the line: you cannot say to them "oh, be a good boy, make a little effort an go to the party", because they *cannot*. It would denote complete incomprehension for them (and besides, rudeness and stupidity) to follow this approach. However, I don't think Carl is addressing his words to the really sick persons, that are the minority. I think he is addressing his words to the persons with "a strong introverted and thinking personality", as he says, that do not have the syndrome but they think they have. And they think they have the syndrome because of the strong social pressure (which is stronger in the USA than in Europe, as I can tell having lived in both countries, BTW): unfortunately, the society is trying to convince people that they are sick if they don't follow a very strictly defined "normal" behavior, where "normal" means conformism with the society stereotypes. > Frankly, it sickens me that there are people out there who consider > traits such as introversion, and reliance on thought instead of > feeling, to be "diseases." Well said Carl! The problem is more with "normal" people than with the "non-normal". I think Carl does not like weenies and a victimism philosophy: I don't like it either. More on philosophical terms, I am against the modern society when is trying to convince people that "life is (always) wonderful", and that there is something like the "right to happiness". Historically speaking, these concepts are extremely recent and they were unthinkable in earlier epoch. According to the Ancient Greek, the aim to pursue was avoiding the pain, not reaching the "happiness". Happiness was thought to be a transient state, not a rightful expectation for a normal life. If I look at my "normal" friends of my age (I am 33) they are all in existential crisis: they all had big dreams of a great or at least happy life whereas they are discovering now that they have just a plain, ordinary life that sucks (in the best cases) or not a life at all (many of the people I know, alone, with bad sentimental stories, an horrible job, etc). They say: look at me, I am still young, still sane, I have some money, I should be happy, why I am not so? I must be sick!! Which, of course, it is a completely absurd point of view. The reality, as Lacan says, is that "life is hard". Carl is slapping people that have no reason of thinking to be sick, not the people that really are! It really disturbs me to see people (not referring to people on the mailing list here, but some people I know) complaining, wondering about their psychological status, when they are entirely and absolutely normal, plain and ordinary: it is their life that it is not okay, not them! On the other hand, surprisingly maybe, people with "a strong introverted and thinking personality" (notice: I am not saying people with the syndrome) are quite advantaged with respect to the "normals". I hadn't big expectations for my life at the age of seven: actually I was never thinking about the future, all my effort were concentrated on surviving in the present. I couldn't be fooled by society propaganda (at least not so completely fooled as others): I did not want a great life, I only wanted a life. I must say that I never heard about Asperger's before this threat: anyway, I wasn't surprised to have a score of 32. Nevertheless, as the test says "many who score above 32 and even meet the diagnostic criteria for mild autism or Asperger's report no difficulty functioning in their everyday lives." I would go further and says that having "a strong introverted and thinking personality" is helping me in my life now (of course it was *not* helping me when I was a child :-(). Let me give a single example. I am a physicists: I must give seminars and lectures at international congress. This would be a scary task for most normal people, but for me it is not very hard: I am trained. For me, it was hard even go the local shop and buy milk and bread for my mother: if I survived to that, I can easily give a seminar to an audience of international scientists. I also have a fiance' and a life that I think is much more interesting of the lives of my friends who stayed in our original little village in the countryside. I would say that I am happier than I was and even more happier than I expected to be. Final thought: normality strongly depends on the milieu where you live. I am sure the average score on the test for people on the mailing list is much higher than 16.4, the "normal" average (according to http://www.wired.com/wired/archive/9.12/aqtest.html) As I often say to my fiance' "I have always thought to be a little strange when I was younger, but now, if I compare myself with my colleagues physicists, I am one of the most normal!" Whereas for most people life is easy when they are young and difficult when they are grown up, for people with "a strong introverted and thinking personality" it is probably the opposite. My advice to the youngest people of the mailing list is simply "wait". I think this is the best advice I can give. Of course, IANAP and I referring to people in the safe side of the line. When you pass the line things get harder and harder, and I don't think anybody has a good advice in those cases. That's all for today, it was an interesting thread, -- Michele Simionato - Dept. of Physics and Astronomy 210 Allen Hall Pittsburgh PA 15260 U.S.A. Phone: 001-412-624-9041 Fax: 001-412-624-9163 Home-page: http://www.phyast.pitt.edu/~micheles/ From dmetzler.nospam at partner.auchan.fr Fri Mar 21 10:54:56 2003 From: dmetzler.nospam at partner.auchan.fr (Damien Metzler) Date: Fri, 21 Mar 2003 16:54:56 +0100 Subject: DCOracle2 Message-ID: Hello, i have a problem regarding the module DCOracle2: i'd like to map an Oracle stored procedure with a python function (like in the documentation). I do the following : ########################### import DCOracle2 print "Connecting to Database..." db=DCOracle2.connect('admindc/dcadmin at dbks.linux') c=db.cursor() findMag=c.procedures.ADMINDC.TEST.FINDMAG findMag(2,mag) print mag ######################### and here is what i have as a result : #########################" Connecting to Database... Traceback (most recent call last): File "C:\Documents and Settings\f997x055.F8889\Bureau\PyOracle.py", line 22, in ? findMag=c.procedures.ADMINDC.TEST.FINDMAG File "D:\Python22\DCOracle2\DCOracle2.py", line 1637, in __getattr__ AttributeError: TEST ########################### The schema admindc exists, the package TEST and the procedure FINDMAG too. Does anyone have the same problem... Is it a bug ? From max at alcyone.com Wed Mar 12 20:50:21 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 12 Mar 2003 17:50:21 -0800 Subject: I don't understand PEP 308. References: <2635252.1047490747@dbforums.com> <2636657.1047515159@dbforums.com> Message-ID: <3E6FE3DD.9D9D8E68@alcyone.com> Tetsuo wrote: > Originally posted by Jp Calderone > > > It proposes an if-then expression. > > What's the difference? More importantly, what is the benefit? Python makes a distinction between expressions and statements. That's why things like if x = 1: ... are illegal, since assignment is a statement and not an expression. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Life is an effort that deserves a better cause. \__/ Karl Kraus The laws list / http://www.alcyone.com/max/physics/laws/ Laws, rules, principles, effects, paradoxes, etc. in physics. From fb at frank-buss.de Sun Mar 9 09:41:30 2003 From: fb at frank-buss.de (Frank Buss) Date: Sun, 9 Mar 2003 14:41:30 +0000 (UTC) Subject: Code speedup tips References: Message-ID: Frank Buss wrote: > But I think for the calculation of the sum of all 1's, it could be > faster. Currently it is implemented like this: > > # print the number of '1's for all automaton steps > for step in range(length / 2): > print reduce(lambda x, y: x+y, rule30.current) > rule30.step() > > Where 'current' is a Numeric's array. Any tips? Changjune Kim sent me the idea, to use ".count(1)". This doesn't work with the Numeric array (perhaps it should be added to the Numeric array-class), but after ".tolist()" it is 5 times faster: 11 seconds for 5000 arrays of size 10000 with tolist().count(1) and 52 seconds for my lambda construct. for step in range(length / 2): print(rule30.current.tolist().count(1)) rule30.step() -- Frank Bu?, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From tim.one at comcast.net Tue Mar 18 20:05:01 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 18 Mar 2003 20:05:01 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 17) In-Reply-To: Message-ID: [Greg Ewing] > Just out of curiosity, has any other irrational > number (other than ones specially constructed to > be so) been proved normal? Last I heard (a few years ago), no. Note two meanings for "normal": the original definition required normality in all bases simultaneously, and that's usually called "absolutely normal" now. Also, AFAIK, no absolutely normal number is known (constructed or not). This is curious because the set of non-normal reals has measure 0 ("almost all" reals are absolutely normal). > And what are the grounds for suspecting pi to > be normal? Is it just "we don't have any particular > reason to think it isn't", or is there more to > it? Billions of digits of pi have been computed, and this tiny string of digits has passed extensive statistical tests for equidistribution (of single digits, pairs, triples, ..., up to something like 16-tuples). By induction, it must be normal . From aleax at aleax.it Mon Mar 3 10:32:43 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 03 Mar 2003 16:32:43 +0100 Subject: Books Database References: Message-ID: Eliran Gonen wrote: > I want to ask you what do you think is the best way to keep > a list of books with other data (such as year and author) in a > file ? That depends on your purposes and on the size the database is likely to grow to. > And what way should be used to parse it ? That depends on what format you're keeping it in. > Is something like: > > <.database> > > name=Example > author=Somedood > year=1969 > > name=Wuffy > author=Puffy > year=2010 > > ....etc > > > Is alright ? I don't like it at all -- neither fish nor fowl, and you're likely to have to write your own parser for it -- not trivial, though not a really big deal -- naah. XML is probably OK: and you can parse it easily with SAX, for example. Or if the fields you want to record for each book are fixed and you "know" they'll never contain (e.g.) newlines and vertical bars, you could use a one-line-per-record, fields- separated-by-vbars format: Example|Somedood|1969 Wuffy|Puffy|2010 and "parse" this with [ rec[:-1].split('|') for rec in afile ]. Alex From sjmachin at lexicon.net Wed Mar 26 17:01:46 2003 From: sjmachin at lexicon.net (John Machin) Date: 26 Mar 2003 14:01:46 -0800 Subject: writing to file very slow References: <41538.164.15.134.155.1048690460.squirrel@http://moritz.homelinux.or g> Message-ID: Jack Diederich wrote in message news:... > On Wed, Mar 26, 2003 at 03:54:20PM +0100, Moritz Lennert wrote: > > for x in range(results.ntuples()): > > var = "" > > for y in range(len(results.listfields())-1): > > var+=str(results.getresult()[x][y])+'|' > > var+=str(results.getresult()[x][len(results.listfields())-1]) > > f.write(var) > > f.write('\n') > gotten_result = results.getresult() # we only call this once > field_str = '|'.join(map(str, gotten_result[0])) > for row in gotten_result: > f.write(field_str) > f.write(row[-1]) # is this really what you want? translation of below line > # var+=str(results.getresult()[x][len(results.listfields())-1]) > f.write('\n') No, it's not what he wanted, and it's not a correct translation but the original is so god-awfully-obscure that you are forgiven :-) Here's his original, with two substitutions, and removing the str() -- this makes it much clearer what is going down ... for row in gotten_result: var = "" for y in range(numfields-1): var += row[y] + '|' var += row[numfields-1] f.write(var) f.write('\n') From intentionally at blank.co.uk Sun Mar 9 17:03:41 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Sun, 09 Mar 2003 22:03:41 +0000 Subject: OT: Programmers whos first language is not English References: <74ij6vcebl67dto60dun42hd625qrkmcv7@4ax.com> Message-ID: <6gen6v86h0313dkc4btqngm4r631m6i9gb@4ax.com> On Sun, 9 Mar 2003 22:05:50 +0100, Grzegorz Adam Hankiewicz wrote: >On Sat, Mar 08, 2003 at 11:21:36AM +0000, Stephen Horne wrote: >> One thing I'm considering is the use of a non-ASCII source code. > >Be aware, you face a terrible death. > >> I'm quite curious what other people think about this kind of idea - >> particularly people whose first language is not English. > >Your ideas periodically appear somewhere around me, both >in unofficial and official proposals even from well known >organizations. The result is that these ideas suck, and I talk from >seing failing projects, not from personal preference: > >1) You may need special tools depending on your language, forcing >people to a specific environment. > >2) Code written in a language looks bad mixed with another >one. Where's the advantage of using a keyword in your native language >when 85% of the code is calls to a library written in english you >don't have control over? > >3) You prevent people not able to speak the language from >contributing it. Certainly this happens with english too, >but nowadays it is the lowest common denominator for computer >programming. Esperanto might want to change that, a herculean effort, >an even then it's not your native language. > >4) It doesn't matter what language you choose: soon programmers >start using abbreviatures in function/variable names which don't >mean anything even to other native programmers. > >Your idea is nice in that the source code would store the identifiers >and the editor would show them in your preferred language. The bad >thing is that it won't be able to do that with the function/variable >names a programmer will write. From eddie at holyrood.ed.ac.uk Mon Mar 3 16:57:48 2003 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Mon, 3 Mar 2003 21:57:48 +0000 (UTC) Subject: Expect on window (from python script) References: Message-ID: eddie at holyrood.ed.ac.uk (Eddie Corns) writes: >enough and maybe sending 'tester\n' might work. I think a telnet client is Duh, I meant 'tester\r' of course, the CR vs LF vs CRLF issue. >Eddie From sjmachin at lexicon.net Fri Mar 7 10:57:11 2003 From: sjmachin at lexicon.net (John Machin) Date: 7 Mar 2003 07:57:11 -0800 Subject: Concerns about performance w/Python, Pysco on Pentiums References: <3E660EB3.4065D81F@engcorp.com> <3E66BA3F.7691C3B0@engcorp.com> <3e677433$0$87747$edfadb0f@dread11.news.tele.dk> <7h3bs0oh25s.fsf@pc150.maths.bris.ac.uk> <3E6784AD.E4D523BD@engcorp.com> <7h3y93sfldh.fsf@pc150.maths.bris.ac.uk> <3E67A2F2.187785EA@engcorp.com> Message-ID: Pedro Rodriguez wrote in message news:... > On Thu, 06 Mar 2003 20:35:14 +0100, Peter Hansen wrote: > > > def step(self): > > opcodeByte = self.readByte(self.PC) > > try: > > opcode = self.opcodes[opcodeByte] > > except KeyError: > > raise UnimplementedOpcode('$%02X %s' % (opcodeByte, > if you are using a dictionnary for opcodes, wouldn't you gain > time by not putting a try/except clause but by going straight > with self.opcodes.get(...) and checking the returned value > against None. Rule 1: optimize for frequent events, not for infrequent events. In emulating a CPU, which is more frequent, valid opcode or invalid opcode? In your get-versus-try example, you do "valid" 256 times and "invalid" (1000000 - 256) times. Below is a slightly more realistic test, which seems to indicate that the try-except caper is about 50% faster than dict.get() if you never hit the "except" clause. Cheers, John 8<------ import time def getter(q): l = {} for i in range(256): l[i] = i t0 = time.time() npass = nfail = 0 lget = l.get for i in xrange(1000000): x = lget(q) if x is None: nfail += 1 else: npass += 1 t1 = time.time() print "get", q, t1 - t0, npass, nfail def tryer(q): l = {} for i in range(256): l[i] = i t0 = time.time() npass = nfail = 0 for i in xrange(1000000): try: x = l[q] except KeyError: nfail += 1 else: npass += 1 t1 = time.time() print "try", q, t1 - t0, npass, nfail for q in (0, 1, 255, -1, 256, 257): getter(q) tryer(q) 8<------- === output (Python 2.2 Windows 32 bit version, on a 1.4Ghz Athlon) get 0 1.30199992657 1000000 0 try 0 0.871000051498 1000000 0 get 1 1.27199995518 1000000 0 try 1 0.881000041962 1000000 0 get 255 1.36199998856 1000000 0 try 255 0.950999975204 1000000 0 get -1 1.31200003624 0 1000000 try -1 7.77199995518 0 1000000 get 256 1.32100009918 0 1000000 try 256 7.77199995518 0 1000000 get 257 1.30200004578 0 1000000 try 257 7.79100000858 0 1000000 From thomas at xs4all.net Tue Mar 11 04:02:41 2003 From: thomas at xs4all.net (Thomas Wouters) Date: Tue, 11 Mar 2003 10:02:41 +0100 Subject: The ternary operator: more than one way to do it? In-Reply-To: <3E6D3C3D.675C1DE4@alcyone.com> References: <23891c90.0303100414.64c2a054@posting.google.com> <3E6CF44A.A2FA1A72@alcyone.com> <3E6D3C3D.675C1DE4@alcyone.com> Message-ID: <20030311090241.GQ2112@xs4all.nl> On Mon, Mar 10, 2003 at 05:30:37PM -0800, Erik Max Francis wrote: > Any language feature can be abused. The writer of the abuse is to blame > for such misuses, not the language. Then why is Python any better than C, C++, Java, Perl, *LISP, etc ? Why are we using indentation for blocks, if we can trust the writer not to mis-use indentation ? Many people will answer to the first by explaining Python is small, simple, easy to learn. Some may say (as they have in the past) 'it fits your brain'. Where does adding features from other languages stop ? I've seen my share of 'bad' Python, which was split into two camps: incorrect use of whitespace, and not enough object-oriented code. Cases of the first were suprisingly easy to fix using a few search-and-replaces, and cases of the second were suprisingly easy to fix with some minor refactoring. -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! From aleax at aleax.it Sat Mar 29 13:07:33 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 29 Mar 2003 18:07:33 GMT Subject: Profiling Embedded Code References: <3e84bf28$0$59852$65c69314@mercury.nildram.net> Message-ID: Andrew Wilkinson wrote: > Hi, > > I've got some Python code that is embedded into a C application, and I'd > like to profile it. Unfortunatly I can't get the standard profile module > to work. > > My C code imports a module, and then at the appropriate time calls the > UpdateGameData function. When the module is imported I'd like to do a > 'test' run of the function, with the profiler on to perform a simple check > on it. (I know this is not a particually good way to profile the code, but > I'd like to get it working and then move on...) > > The module is given (slightly trimmed) here... > --- > def UpdateGameData(time): > ... > > > import profile > p = profile.Profile() > p.run('UpdateGameData(0)') > -- > > With this code I get the following exception... > Traceback (most recent call last): > File "./python/core.py", line 28, in ? > p.run('UpdateGameData(0)') > File "c:/programming/python/lib/profile.py", line 403, in run > return self.runctx(cmd, dict, dict) > File "c:/programming/python/lib/profile.py", line 409, in runctx > exec cmd in globals, locals > File "", line 1, in ? > NameError: name 'UpdateGameData' is not defined > > Now this seems very silly to me as 'UpdateGameData' obviously is defined. Yes, but it's not defined in the __main__ module. > I had a look in the code for profile and it seems to mess around with > __main__, but I'm not sure that it's pointing at the right place. > > Any suggestions for how to get this to work would be much appreciated, If your module is named foo, use: p.run('import foo; foo.UpdateGameData(0)') or else use p.runctx instead, but the above may be simpler. Alex From franz.steinhaeusler at utanet.at Sat Mar 22 07:26:00 2003 From: franz.steinhaeusler at utanet.at (Franz Steinhäusler) Date: Sat, 22 Mar 2003 12:26:00 GMT Subject: Text Editor with wxPython Message-ID: <3e7c561a.8718311@news.utanet.at> Hello Newsgroup, I'd like to write a small text editor with wxPython. How would you program a simple, but extensible editor? Would you suggest a data strcture of one string per line? A tree structure for the data elements?? Which relativ simple editor would you suggest me to use as a template or pattern? Perhaps Frogedit from wxPython Sample Applications or Python idle? Does anybody know a website, where it is described, how to design and implement an editor? (sorry for my english) Many thanks in advance From reply.in at the.newsgroup Sun Mar 2 09:58:45 2003 From: reply.in at the.newsgroup (Rene Pijlman) Date: Sun, 02 Mar 2003 15:58:45 +0100 Subject: Strange regex problem References: <33803989.0303020048.10c8fc09@posting.google.com> <3E61FC67.8070705@heimsnet.is> <112dnb44I66fhP-jXTWc2Q@speakeasy.net> Message-ID: A.M. Kuchling: >re.search()'s arguments are (pattern, string, flags). With re.search(), >there's no way to specify a starting point within the string, so you're >going to have to use a precompiled regex. Ah, re.search() on http://www.python.org/doc/current/lib/node99.html had me confused as well. Especially since the description of compile() on the same page says: "Compile a regular expression pattern into a regular expression object, which can be used for matching using its match() and search() methods, described below." ^^^^^^^^^^^^^^^ But I guess this refers to search() on another page of the documentation: http://www.python.org/doc/current/lib/re-objects.html. -- Ren? Pijlman From cce at clarkevans.com Tue Mar 4 19:59:06 2003 From: cce at clarkevans.com (Clark C. Evans) Date: Wed, 5 Mar 2003 00:59:06 +0000 Subject: Towards a more Pythonic "Ternary Operator" In-Reply-To: References: <882b0a41.0303020225.3caf0334@posting.google.com> Message-ID: <20030305005906.GA56890@doublegemini.com> Alex, Gustavo, and Carel, Thank you for commenting. Below is follow up to your response and an improved "operator" mechanism for the case/switch statement due to musings on Carel's option. On Tue, Mar 04, 2003 at 04:05:12PM +0100, Alex Martelli wrote: | Good points -- basically similar to arguments for having | such augmented-assignment operators as += in the language | (avoiding = | redundancy both in reading and writing the code). Yes. | > So, really, we have two categories of duplication: | > | > (a) the left hand side of the assignment | > (b) the left hand side of the conditional | | Yes, but they're orthogonal -- i.e. the second case might | just as well be: | | if a == X: | c = Q | elif a == Y: | d = R | else: | e = S | | which only shows redundancy kind [b], not kind [a]. Why | are we assuming the two redundancies go together? Correct. However, empirically from my production code (in production at 20+ companies), both types of redundancy tend to cluster together. Thus, it makes sense to me to try and think of a mechanism which allows us to treat them together. Think of it as an 80/20 optimization. For example, I often have code like... if 0 == quantity: exit = 'no exit' elif 1 == quantity: exit = 'a door' else: exit = '%s doors' % quantity which I often re-write with the "mapping-idiom" as: exit = { 0: 'no exit', 1: 'a door' }.get(quantity, '%s doors' % quantity) This gains the advantage of normalizing both type [a] and type [b] redundancies, however, it comes at a cost: 1. the code isn't "obvious" to newbies making it harder to maintain -- making my code obscure 2. the code doesn't short-circuti; Yes, you can have function pointers returned from the mapping and then invoke the function... but this isn't any more obvious or easy to read! Thus, a new syntax-level construct which combines this pattern in a easy to understand manner /w short-circuts would be useful... exit = select quantity case 0: 'no exit' case 1: 'a door' else: "%s doors" % quantity The examples given in the survey are very cleanly expressed with this syntax. data = select hasattr(s,'open') case true: s.readlines() else: s.split() z = 1.0 + select abs(z) < .0001 case true: 0 else: z t = v[index] = select t <= 0 case true: (t-1.0) else: -sigma / (t + 1.0) return select len(s) < 10 case true: linsort(s) else: qsort(s) | > Perhaps we can scratch two itches at the same time? The syntax | > really doesn't matter now; what matters is that we agree on the | > problem. Then we can throw up our best syntaxes and let Guido | > choose and work his magic... | | I like this analysis, but I do not understand the reason to | assume the two redundancy problems should occur together. I've found a slight hybrid of the combination common, where [a] and [b] occur, but the 'operator' differs. In this situation, we could allow an optional boolean function/operator right after the case statement. The first argument to the operator would be the item selected, and the remaining arguments are used up to the colon. If the operator is missing, it is assumed to be the '==' operator. z = 1.0 + select abs(z) case < .0001: 0 case > .5: .5 else: -sigma / (t + 1.0) score = select die case 1: -2 case 2: -1 case between 3,4: 0 case 5: +1 case 6: +2 else: raise "invalid die roll %d " % roll For a die roll of 8, for example, the 'between' function would be called with the tuple (8,3,4) and would clearly return false. On Tue, Mar 04, 2003 at 09:09:52AM -0600, sismex01 at hebmex.com wrote: | Yes, there is a lot of duplicated "text" in the first | case, and the second case corrects that. But you don't | need new syntax to be able to make it better, you already | have dictionaries: | | b = { Q:X, R:Y }.get(a,S) | | At least to me, it's a lot more readable, doesn't involve | new syntax, and can grow to a larget amount of options | if needed. While it may be common, this idiom isn't very intuitive for newbies. It took several examples before I caught on... and even then I'm not really happy with the result. | In the above example, imagine evaluating A, B or C could | have side-effects; in that case, upon constructing the | selection dictionary, all side-effects would have been | triggered, so this construction would be no good. It | could be adapted, by changing the function chooser() | like so: | | >>> def chooser(option): | try: | return { a:lambda:A, | b:lambda:B, | c:lambda:C }[option]() | except KeyError: | return default Yes, but once again, this isn't obvious to newbies nor is it very readable. In short, ick. On Tue, Mar 04, 2003 at 04:27:47PM +0100, Carel Fellinger wrote: | | I think you missed | | (c) it takes up too much precious screen estate | Exactly. I purposefully left his one out. I think that much of the Python community would disagree with you here. Python isn't and shouldn't be horizontally efficient (like C or Java). | otherwise I agree, and I think a general switch expression might | be more interesting, but as you propose the beast it only deals | with straight comparision. What about enhancing it like: | | b = (if a : | on X: Q | on Y: R | else: S) I merged your idea of the operator with my idea of the predicates, see above. Thanks. This seems to be an improvement. I'm not yet certain that it is worth the complexity, but it is nice. | And a possible shortening syntactic sugaring could produce: | | b = (if a ; on X: Q; on Y: R; else: S) Here is where you add your (c) requirement, and I think it is also the point where a good part of the Python community (who came to Python for clearly indented logical structures) disagrees. | Anyway, by now it looks so troublesome that I rather not have it in:) No doubt. But I think where you went wrong is that (c) isn't a requirement. Python need not be horizontally efficient. Best, Clark From max at alcyone.com Thu Mar 27 21:57:18 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 27 Mar 2003 18:57:18 -0800 Subject: __import__ woes References: <20030328011801.24753.33823.Mailman@mail.python.org> Message-ID: <3E83BA0E.117C3CAF@alcyone.com> Rich Davis wrote: > When I try to "__import__" from the command-line like > > >>> __import__("test") > > >>> test.doIt("test string") > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'test' is not defined Yes, this is expected behavior. __import__ does not behave the same way that the import statement does. __import__ _returns_ the imported module without inserting it anywhere in the namespace. You want testModule = __import__('test') testModule.doIt(...) -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ It's soulful music. It doesn't necessarily sound like ... soul ... \__/ Sade Adu Bosskey.net: Quake III Arena / http://www.bosskey.net/q3a/ A personal guide to Quake III Arena. From johnroth at ameritech.net Thu Mar 27 18:38:29 2003 From: johnroth at ameritech.net (John Roth) Date: Thu, 27 Mar 2003 18:38:29 -0500 Subject: Proposed standard python module: ieee754 References: Message-ID: Submit a PEP asking for the functionality, and then go to the Python-Dev list to discuss it. I think the basic request has got a fairly good chance, based on the reception for several other "features" that varied in different C libraries. On the other hand, the BDFL may not agree with the implementation. However, he might. The next step is to submit a PEP. John Roth "Gregory R. Warnes" wrote in message news:mailman.1048805562.27862.python-list at python.org... > > I've written a small pure-python module for handling IEEE 754 special > values that I would like to propose as an addition to the standard python > library. I've included the README file which describes the module > below. > > 1) What is the mechanism for submitting this for inclusion? > 2) Also, can others please inspect the code? > > Thanks > > -Greg > > > From the README: > > INTRODUCTION > > [The ieee754 python module] implements constants and functions for > working with IEEE754 double-precision special values. It provides > constants for Not-a-Number (NaN), Positive Infinity (Inf), and Negative > Infinity(-Inf), as well as functions to test for these values. > > WHY THIS MODULE IS NEEDED: > > Handling of IEEE 754 special values in python depends on the > underlying C library. For instance, on some systems "float('Inf')" > will properly return the IEEE 754 value for infinity. On other sytems > (notably MS-Windows) this generates an error. > > Likewise the string represenation of an IEEE 754 special value > generated from a floating point value also varies by platform. For > example, the command "float(1e3000)", returns 'inf' on Python 2.1.3 on > Debian Linux ('testing'). On Solaris 8 with python 2.2.1, this > returns 'Infinity', and on MS-Windows 2000 with Active Python 2.2.1, > this returns '1.#INF'. > > > In the past, it has been recommendations to use > > Inf = 1e300**2 > NaN = Inf/Inf > > to define positive infinity and not-a-number. However, the first > expression generates an error on all of the python interpreted I > have available, and is not easily understandable even if it works. > In addition, this does not permit detection of NaN values, since > the IEEE 754 standard requires that > > NaN != x > > for all possible values of x, including NaN. > > Consequently, it is impossible to consistently set or detect IEEE > 754 floating point values in normal python code without resorting > to manipulating bit-patterns directly. > > The ieee754 module performs the necessary bit-pattern manipulation > to directly set and test for the patterns that define IEEE 754 > special values, relieving the programmer of this burden. > > CONSTANTS > > NaN I > IEEE 754 'Not a Number' value > > Inf > IEEE 754 Positive Infinity value > > NegInf > IEEE 754 Negative Infinity value > > PosInf > IEEE 754 Positive Infinity value > > > FUNCTIONS > > is_NaN(value) > Determine if the argument is a IEEE 754 NaN (Not a Number) value. > > is_Inf(value) > Determine if the argument is a IEEE 754 positive infinity value > > is_NegInf(value) > Determine if the argument is a IEEE 754 negative infinity value > > > > is_Finite(value) > Determine if the argument is an finite IEEE 754 value (i.e., is > not NaN, positive or negative inifinity) > > > is_Infinite(value) > Determine if the argument is an infinite IEEE 754 value (positive > or negative inifinity) > > > > sign(dval) > Extract the sign bit from a double-precision floating point value > > mantissa(dval) > Extract the mantissa bits from a double-precision floating > point value. > > exponent(dval) > Extract the exponentent bits from a double-precision floating > point value. > > Note that for normalized values, the exponent has an offset of > 1023. As a consequence, the actual exponent is obtained by > subtracting 1023 from the value returned by this function. > > EXAMPLE > > (Run under Python 2.2.1 on Solaris 8) > > >>> import ieee754 > >>> val = 1e30000 # should be cause overflow and result in 'Inf' > >>> val > Infinity > >>> ieee754.is_Inf(val) > 1 > >>> ieee754.Inf > Infinity > >>> nval = val/val # should result in NaN > >>> nval > NaN > >>> ieee754.is_NaN(nval) > 1 > >>> ieee754.is_NaN(val) > 0 > > IMPLEMENTATION > > The code is implemented in pure Python by taking advantage of the > 'struct' standard module to directly set or test for the bit patterns > that define IEEE 754 special values. Care has been taken to generate > proper results on both big-endian and little-endian machines. > > The current implementation is pure python, but some efficiency could > be gained by translating the core routines into C. > > REFERENCES > > See > for reference material on the IEEE 754 floating point standard. > > Further information on this package is available at > . > > From monkey at greyledge.net Fri Mar 28 11:15:27 2003 From: monkey at greyledge.net (Andy Chase) Date: Fri, 28 Mar 2003 11:15:27 -0500 Subject: Can PIL be installed under Cygwin? Message-ID: Well, this appears to be a Cygwin issue. I downloaded and ran the standalone Python 2.2 installer for Windows, copied the PIL files to the appropriate directories in the new installation, and everything worked right off the bat - moreover, 'import Image' works correctly; I don't have to use 'from PIL import Image' as I did under Cygwin. Still, I'd be interested to know *why* PIL won't work under Cywgin's build of Python, if anyone happens to know. :) -Andy From bob at rsballard.com Sun Mar 9 12:08:45 2003 From: bob at rsballard.com (Bob Ballard) Date: Sun, 09 Mar 2003 11:08:45 -0600 Subject: OT: Recommended Linux Laptops, suppliers? References: <3e6a571b$1_1@spamkiller.newsgroups.com> Message-ID: <3E6B751D.60708@rsballard.com> You should check here and see what they say... http://www.linux-laptop.net/ Bob Brad Clements wrote: > Sorry this is OT > > I'm looking to buy a notebook/laptop. I would like to run Linux on it. I > don't want to buy a notebook with Windows installed. I don't want to pay for > that OS since I'm just going to discard it. > > I see that Microsoft still has a lock on the big-brand manufacturers, and I > haven't found any (Dell, Toshiba, Sony, HP, etc..) that will ship a notebook > with Linux on it (or no OS at all). > > Apple's are pretty much out of the price range, and I prefer an Intel/AMD > box anyway. Though, I do like the new Apple notebooks :-( > > So, can anyone suggesting a white-box manufacturer of notebooks that aren't > crap, don't weigh more than 8 lbs, run more than 2 hours on battery? > > Or . a big-name notebook that comes with Linux (or no OS) > > -- > > I have a Toshiba Tecra 720CDT that I'd like to replace, I paid an incredible > amount for it years ago.. cutting edge, etc. :-( > > -- > Novell DeveloperNet Sysop #5 > > _ > > From nospam at garen.net Sat Mar 29 21:34:12 2003 From: nospam at garen.net (Garen Parham) Date: Sat, 29 Mar 2003 18:34:12 -0800 Subject: Is Python overhyped (just like Java)? References: Message-ID: Ajay na wrote: > Can some-one please explain why one would want to use Python? What is wrong > with C++? > > In my opinion, the problem with C++ has nothing to with the language > semantics. The problem is that when people are confronted with a powerful > language like C++, they tend to want to optimize everything to death. > That's when they get themselves in trouble. > > Those who use Python know they are sacrificing a lot in terms of memory and > speed. But if they took the same attitude toward C++, they can actually get > a lot of flexibility, code reuse, simplicity, and all the other benefits of > OO programming at over half the cost of using Python! The problem is that > people who don't understand C++, are afraid to use the 'virtual' features of > that language because it's 'too expensive'. But that's stupid...because > Python's 'virtualness' is even more expensive! > > Nope...I'm not trolling...I want someone to give a solid and intelligent > argument about why I should switch from C++ to Python! The two languages have quite divergent design goals so they aren't strictly comparable. However in areas where they overlap you may want to choose python because it has a fairly economical notation and is typically more 'productive' with its more interactive environment. As for people wanting to optimize things to death, well, I've noticed that there is a culture of that kind of attitude with C and C++ -- which makes sense given that they're widely used for 'systems programming', but that kind of behavior can occur with any language. It's also a bit strange that you spend so much time talking about C++. There is no either-or thing going on. You can use both languages for whatever task you like. The universe doesn't require hegemony. From timr at probo.com Wed Mar 5 02:55:18 2003 From: timr at probo.com (Tim Roberts) Date: Tue, 04 Mar 2003 23:55:18 -0800 Subject: cgi FieldStorage strangeness References: Message-ID: m at idelix.com (Mark Tigges) wrote: > >I'm at a loss here, therefore the post. > >I'm writing a CGI that uploads a file from the client using method >POST in an html form submit. Unfortunately I can't seem to get the >form fields. When the page loads up, using FieldStorage.print_form it >says "No form fields". Uploading a file requires a different data type from standard form processing. You need to use the enctype field in the
header: -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From yvan_charpentier at hotmail.com Mon Mar 31 23:42:38 2003 From: yvan_charpentier at hotmail.com (yvan) Date: 31 Mar 2003 20:42:38 -0800 Subject: SimpleParse and LookAhead Message-ID: <9ee55987.0303312042.47b3283e@posting.google.com> Hi, I must be missing something here. I was expecting the following script to get me: 'root', it outputs 'oot' Reading the docs, my understanding what that if '?' is a prefix, then the parser object returns to the previous location. Is that right? If not, how do i get that behaviour? declaration = r'''line := ?([a-z], root) root:= char ''' testdata = '''root - Dir ''' from simpleparse import generator from mx.TextTools import TextTools parser = generator.buildParser(declaration).parserbyname('line') taglist = TextTools.tag(testdata, parser) for tag, beg, end, parts in taglist[1]: print testdata[beg:end] Any help appreciated, -Yvan From irmen at -NOSPAM-REMOVE-THIS-xs4all.nl Fri Mar 7 14:30:26 2003 From: irmen at -NOSPAM-REMOVE-THIS-xs4all.nl (Irmen de Jong) Date: Fri, 07 Mar 2003 20:30:26 +0100 Subject: distutils changes my scripts when installing (python 2.2) In-Reply-To: References: <3e67f6c2$0$49111$e4fe514c@news.xs4all.nl> Message-ID: <3e68f352$0$49104$e4fe514c@news.xs4all.nl> Steve Holden wrote: > I wouldn't worry too much as long as everything works: if you really have a > /usr/bin/python then it's quicker than using /bin/env python. Thanks guys. I'm not worried anymore about my scripts being changed by distutils. I was just curious why it did this. :) Irmen From simonb at webone.com.au Mon Mar 24 03:22:30 2003 From: simonb at webone.com.au (Simon Burton) Date: Mon, 24 Mar 2003 19:22:30 +1100 Subject: n-ary tree widget References: Message-ID: On Sun, 23 Mar 2003 11:16:24 -0800, student wrote: > > I could write one myself, but I'm hoping i don't have too :) .. notice why? > also taht i'm not looking for a file structure type tree widget. I > need to display it in a method similar to the tree above and it should > be able to expand / collapse the nodes interactively go for it! i'd recommend using tkinter's canvas (for a quick start), Simon Burton From dave at boost-consulting.com Sun Mar 23 22:01:14 2003 From: dave at boost-consulting.com (David Abrahams) Date: Sun, 23 Mar 2003 22:01:14 -0500 Subject: [Python-Dev] How to suppress instance __dict__? References: Message-ID: "Delaney, Timothy C (Timothy)" writes: >> From: David Abrahams [mailto:dave at boost-consulting.com] >> >> Guido van Rossum writes: >> >> > So I don't think __new__ is preferred over __init__, unless >> you need a >> > feature that only __new__ offers (like initializing an >> immutable base >> > class or returning an existing object or an object of a different >> > class). >> In other words, TIMTOWTDI? <0.3 wink> > > [Moved to python-list as I think it's gone well beyond python-dev]. > > I wouldn't say that. Use __init__ unless you *must* use __new__. And > when you use __new__, still use __init__ for initialisation. > > And if you are going to use __new__, you are expected to be able to > explain *why*. > > Pretty straightforward to me. Why should that be the rule? Why not the opposite? FWIW, if everyone used the opposite policy (__new__ unless you must use __init__), the problem of __del__ operating on uninitialized objects could be substantially relieved. However, tradition has us working the other way. -- Dave Abrahams Boost Consulting www.boost-consulting.com From j0hnfr0g at yahoo.com Thu Mar 13 09:37:40 2003 From: j0hnfr0g at yahoo.com (JohnFrog) Date: 13 Mar 2003 06:37:40 -0800 Subject: Stupid Python Questions Message-ID: <16008e62.0303130637.4235626d@posting.google.com> I have never used Python, and I am wondering about this following things (OS=Win2K): 1) Can I call and run DOS executables from a Python script? 2) Can I easily create a standalone program (1 file) that runs under DOS (command prompt) that contains my script and the Python interpreter (or just what is needed for my script), so that from an end-user perspective it just looks like a DOS executable? 3) Is there a preferred place to download a Python interpreter from? Thanks, John From ibarg at as.arizona.edu Thu Mar 20 16:58:11 2003 From: ibarg at as.arizona.edu (Irene Barg) Date: 20 Mar 2003 13:58:11 -0800 Subject: Tkinter displaying 300 records sluggish References: Message-ID: Everyone, Thanks for your comments. The fix was to just break the result set into chunks, then provide navigation buttons (<<, <, >, >>) to page between the chunks. Having to display smaller chunks at a time gives it a more robust feeling. Cheers, --irene Paul M wrote in message news:... > Anand B Pillai wrote: > > Hi > > > > Probably this is out of context. But you should strongly > > consider using wxPython for these kind of tasks. Speed is not > > a virtue of tkinter. I am not familiar with tkinter though I > > can tell you that wxPython would be surely faster than tkinter > > for most performance intensive apps. > > > > How are you able to make such definitive statements about the speed and > appropriateness of tkinter when you're "not familiar with tkinter"? > > --Paul From aleax at aleax.it Thu Mar 27 06:33:11 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 27 Mar 2003 11:33:11 GMT Subject: doing hundreds of re.subs efficiently on large strings References: <3E80CE1D.1000200@NOmyrealCAPSbox.com> <3e818b47$0$31942$edfadb0f@dread12.news.tele.dk> <3E82911D.3030807@NOmyrealCAPSbox.com> <3e82b7e9$0$31932$edfadb0f@dread12.news.tele.dk> Message-ID: Anders J. Munch wrote: > "nihilo" wrote: >> How do I use finditer to find the unmatched parts also (the stuff >> between the matches)? It looks to me like it just gives you access to >> the stuff that is matched, but maybe I'm missing something. > > Look at start() and end(). > >>>> s = 'hi nihilo' >>>> for m in re.finditer('(n)|(o)', s): > ... print m.start(), m.end() > ... > 3 4 > 8 9 >>>> s[:3], s[3:4], s[4:8], s[8:9], s[9:] > ('hi ', 'n', 'ihil', 'o', '') >>>> Yeah, but having to keep track of "one after the latest .end" in the loop to accumulate the fragments is fussy and may be a bit error-prone. I'm not sure performance advantages justify that. Let's check -- performance should ALWAYS be measured, NEVER guessed at...!!! Here's a module ms.py with both approaches: import re # simulate a copy of dozen needed substitutions from string import lowercase uppercase = lowercase.upper() # say allres is a list of RE's (without groups!), and # allsub a parallel list of strings to substitute for # each corresponding RE when it matches allres = list(lowercase) allsub = ['(%s!)'%c for c in allres] # a biggish string, about 10K char, on which to do substitutions bigstr = (lowercase+uppercase) * 200 # join the many REs (which have no groups) into one big RE bigre = re.compile( '(' + ')|('.join(allres) + ')' ) def sub_1(bigre=bigre, bigstr=bigstr, allsub=allsub): "substitutions with delicate, tricky approach" pieces = [] prev = 0 for m in bigre.finditer(bigstr): pieces.append(bigstr[prev:m.start()]) pieces.append(allsub[m.lastindex-1]) prev = m.end() pieces.append(bigstr[prev:]) return ''.join(pieces) def sub_2(bigre=bigre, bigstr=bigstr, allsub=allsub): "substitutions with simple, straightforward approach" def onesub(m): return allsub[m.lastindex-1] return bigre.sub(onesub,bigstr) assert sub_1() == sub_2() And the winner is...: [alex at lancelot alex]$ python timeit.py -s 'import ms' 'ms.sub_1()' 10 loops, best of 3: 1.28e+05 usec per loop [alex at lancelot alex]$ python timeit.py -s 'import ms' 'ms.sub_2()' 10 loops, best of 3: 9.92e+04 usec per loop ...the simple, straightforward approach, with 99 milliseconds per loop, versus 128 milliseconds per loop for the fussy, tricky one! Don't guess -- MEASURE...!!! Alex From brian at sweetapp.com Sat Mar 29 18:54:50 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Sat, 29 Mar 2003 15:54:50 -0800 Subject: Is Python overhyped (just like Java)? In-Reply-To: Message-ID: <000401c2f64e$963409f0$21795418@dell1700> > Python hides all the low-level stuff and lets you concentrate on the > problem you are trying to solve. This might even lead to Python apps > running faster than C++ apps. There is a C++ vs. Java example of this phenomenon: the Xalan-C XSLT processor consistently benchmarks slower than the Xalan-J XSLT processor. Much of the Xalan-C development effort is focused on fixing memory problems, ensuring that the project builds on all platforms, etc. Most of the algorithmic performance optimizations and new features appear first in Xalan-J and are then moved into Xalan-C when the developer resources are available. Cheers, Brian From MFranklin1 at gatwick.westerngeco.slb.com Thu Mar 20 04:31:35 2003 From: MFranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 20 Mar 2003 09:31:35 +0000 Subject: PMW ScrolledFrame References: Message-ID: <3E798A77.3050900@gatwick.westerngeco.slb.com> Irene Barg wrote: > > The problem is this. My top window is a PMW ScrolledFrame. If I > display the 'pages' of data in Column (tabluar format), things work > great. For the tabular data, I use the grid geometry, and simple > Tkinter calls. If RowsPerPage is set to 10, I can page through my > results, and the interior of the ScrolledFrame gets refreshed > properly. However, if the data are displayed in Row (record format), > I use PMW.Group to create my 'record or card' look and PMW.EntryField > to display the fields in each 'record'. With RowsPerPage=10, when > I press the 'nextpage' icon, instead of 'refreshing' what inside > the ScrollFrame interior, it 'appends' to it. > Irene I suspect it is because you are using pack to put the Row (record format) pages in. When you use gird it will 'draw over' widgets in the same grid position however pack will not in fact it will just pack them below (as you are seeing) you have two choices... change to the grid or pack_forget the Row data before pack'ing the next / prev page..... Martin From altis at semi-retired.com Sun Mar 16 18:03:20 2003 From: altis at semi-retired.com (Kevin Altis) Date: Sun, 16 Mar 2003 15:03:20 -0800 Subject: wxPython question References: Message-ID: In general, you'll want to bring questions like this up on the wxPython-users mailing list. http://www.wxpython.org/maillist.php You'll get a much larger audience of wxPython programmers looking at your problem that way. Offhand, I would say you have two options. One as someone else has suggested is to use HTML, but this may only be good for the output. With wxPython you'll have the option of using the wxHtmlWindow class or if you only care about working on the Windows platform you can use the much more capable wxIEHtmlWin class. The latter can basically do anything that you can do in Internet Explorer, including support for plug-ins since it simply wraps the IE ActiveX component. You can even use it for HTML WYSIWYG editing using one of the many bits of HTML and JavaScript available around the web such as: http://www.insidedhtml.com/tips/contents/ts12/page1.asp I just verified that it works with the PythonCard simpleIEBrowser sample. http://pythoncard.sourceforge.net/samples/simpleIEBrowser.html The problem with using that for input is that currently, I don't think the individual events for keystrokes and mouse clicks are propogated up from the ActiveX wrapper to wxPython. It is probably possible to do so, in the future more capabilities will likely be added to the wrapper. That means if you were careful about how you position the input HTML window, the UI might be workable, simply putting a button outside the HTML for "Send". Another possibility, is to create your own font or find one on the web that contains smileys or anything else you want to display. Then you can use the wxTextCtrl with the wxTE_RICH2 style to display the smileys intermingled with your other text. That is how people often mix small graphics and text in other applications and it should work for wxPython too. ka --- Kevin Altis altis at semi-retired.com http://radio.weblogs.com/0102677/ http://www.pythoncard.org/ "Scott" wrote in message news:mpq97vg5n5020m4n2thcpq80divpl287b9 at 4ax.com... > On Sun, 16 Mar 2003 18:43:59 +0100, "Nikolaus Wagner" > wrote: > > >On Sun, 16 Mar 2003 00:06:46 -0600, Scott wrote: > > > >> Is there a wxPython control (or wxWindows control that I could wrap) > >> out there anywhere that behaves like a wxTextCtrl, except that it > >> allows inclusion of images, eg. "smileys?" I've had no luck finding > >> such a beast. Can anyone help? Thanks. > > > >Do you want do display something containing text and graphics too > >or do you want a text editor that can handle pictures too? > > > >If you just want to display text with images you could use the HTML > >control (dont know the name, just look at the demo) > > I want to make something like a "chat window," which would be a small > editor control that can display small images amongst the text. Know > of anythiing like that? > From syver-en+usenet at online.no Thu Mar 20 14:12:28 2003 From: syver-en+usenet at online.no (Syver Enstad) Date: 20 Mar 2003 20:12:28 +0100 Subject: win32: exposing python scripts as .dll's Message-ID: Now and then I need to interface with something by writing a .dll (example: simple mapi provider, controlpanel applet, isapi extension). It would have been nice to be able to write these .dll's in python instead of C++. What would be cool would be a tool that generated a dynamic link library from a python module. As far as I can see, such a tool would have to generate exported functions, import the python module and dispatch function calls to their python versions. It would be kind of like ctypes only the other way round. Is there any prior art in this area? -- Vennlig hilsen Syver Enstad From sdahlbacSPAMSUX at abo.fi Wed Mar 19 04:51:24 2003 From: sdahlbacSPAMSUX at abo.fi (Simon Dahlbacka) Date: Wed, 19 Mar 2003 11:51:24 +0200 Subject: py2exe problem References: <3e773d0b@newsflash.abo.fi> <3e777fdd$1@newsflash.abo.fi> Message-ID: <3e783df1@newsflash.abo.fi> "Mike C. Fletcher" wrote in message news:mailman.1048021362.865.python-list at python.org... > Most likely you have used the Unicode version of wxPython. To make it > work on Win98 you need to have the unicode extensions for Windows, which > is an extra DLL not needed on Win2K/XP. ..first time, yes I used the unicode version of wxpython, then I recalled I had seen a notice about possible trouble with unicode on win9x so I tried to uninstall the unicode version and installed the non-unicode version of wxpython, but still not working.. :( > > The DLL is called unicows.dll > > See the thread from last month: "wxAssert on Win98, can't get Log Font" > on the wxPython users list. > > HTH, > Mike > > Simon Dahlbacka wrote: > > >"Thomas Heller" wrote in message > >news:znns65oy.fsf at python.net... > > > > > >>"Simon Dahlbacka" writes: > >> > >> > ... > > >..hmm, on my computer it works nicely.. winxp,python22,wxpython,win32all > >however it fails with some wx assertion errors on a friend's machine win98, > >no python installed.. > > > >..is it wx that is bugging or.. ? > > > >/Simon > > > > > > > > > > -- > _______________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://members.rogers.com/mcfletch/ > > > > From aleax at aleax.it Thu Mar 13 14:13:51 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Mar 2003 19:13:51 GMT Subject: Flying With Python (Strong versus Weak Typing) References: <37a869bc.0303102102.4533973@posting.google.com> <95cs6vo5k8rm15cd1iv0389kqfa2d2k7ht@4ax.com> Message-ID: Max wrote: ... > Python tends to be less visible, so perhaps there is some substance to a Number of Google hits: Java 32 M Perl 12.7 M C++ 7.6 M Python 4.9 M Fortran 1.6 M Eiffel 810 K Ada 227 K there are lots of false hits in most of these, of course (Monty Python, American with Disabilities Act, ...), but still, I _do_ wonder -- less visible than WHAT?-) Alex From hemanth_sethuram at yahoo.com Mon Mar 3 02:13:08 2003 From: hemanth_sethuram at yahoo.com (Hemanth P.S.) Date: 2 Mar 2003 23:13:08 -0800 Subject: PEP309 - built-in curry class (revisions) References: <78f45bd8.0302270702.74f2eae4@posting.google.com> <18s7a.35798$ep5.10090@nwrddc02.gnilink.net> <78f45bd8.0302280212.76bb9d62@posting.google.com> <3e5fa164$1@nntp0.pdx.net> <78f45bd8.0303021441.24b4beb7@posting.google.com> Message-ID: <9be5e130.0303022313.11f525a8@posting.google.com> In IBM DeveloperWorks Python series, David Mertz wrote a series of articles on functional programming in Python. He used examples from xoltar toolkit. It may help to take a look into it before developing something from scratch. --Hemanth P.S. "Ben Wolfson" wrote in message news:... > On Sun, 02 Mar 2003 14:41:42 -0800, Peter Harris wrote: > > > Scott David Daniels wrote in message news:<3e5fa164$1 at nntp0.pdx.net>... > >> Peter Harris wrote: > >> > Carl Banks wrote in message news:<18s7a.35798$ep5.10090 at nwrddc02.gnilink.net>... > >> >>Peter Harris wrote: > >> >>>How about the following? > >> >>> Module to be called "functional" (it can be a home for > >> >>> operations on higher-order functions in general.) > >> >>Good idea. > >> > >> I agree as well. > >> > > OK, 2 independent seconds for that, it's going in the PEP. > > There already exist some higher-order functional modules; the Xoltar > toolkit is a good one (sf.net/projects/xoltar-toolkit) though it doesn't > look like it's been updated in a while. From hinsen at cnrs-orleans.fr Tue Mar 25 12:37:29 2003 From: hinsen at cnrs-orleans.fr (Konrad Hinsen) Date: Tue, 25 Mar 2003 18:37:29 +0100 Subject: Interfacing Python & Fortran In-Reply-To: References: Message-ID: <200303251837.29098.hinsen@cnrs-orleans.fr> On Monday 24 March 2003 08:37, Amit Keney wrote: > I am interested in interfacing Python & Fortran . Searching the > net, I came up with Pyfort & F2PY. > I use a MIPS pro fortran 90 compiler on an IRIX platform. Should I go > forward with Pyfort or F2PY That depends on your applications. The two interface generators are optimized for different situations. Pyfort does more of the work for you, but can silently introduce array copies that might turn out to be a problem for you. Try both on a simple project and decide then. Konrad. From stuart at bmsi.com Sat Mar 8 12:25:08 2003 From: stuart at bmsi.com (Stuart D. Gathman) Date: Sat, 08 Mar 2003 17:25:08 GMT Subject: OT: Programmers whos first language is not English References: <74ij6vcebl67dto60dun42hd625qrkmcv7@4ax.com> Message-ID: On Sat, 08 Mar 2003 06:21:36 -0500, Stephen Horne wrote: > One thing I'm considering is the use of a non-ASCII source code. Use unicode. This works very well in Java - although it is "fun" to read Java code written in India with identifiers displayed in beautiful non-Latin characters - matching the identifiers feels like playing MahJong. > In particular, I'm thinking of using XML - not as an AST representation, > but merely as a way of marking up source code. This would require > special editors, of course, but if WYSIWYG editors can be created for > HTML I don't see why programmers are still stuck in the plaintext age. Ack! Yuck! Don't use XLM! > One possible use of XML might be that 'keywords' and 'symbols' could be > stored as XML elements specifying non-language-specific tokens - the > editor could have a local language table to recognise keywords as the You don't need XLM for this. I am reminded of a college prank. On April 1st, 1978 (or some year close to that), the sysadmin at GMU replaced the keyword table for the HP2000 Basic system used by all the beginning computer science students. For instance, "PRINT" was now "SCRIBBLE", "INPUT" became "LISTEN FOR", "LET" became "MAKE", "NEXT" became "INCREMENT", "FOR" became "VARY", "IF" became "WHEN", "GOSUB" became "DIVE", "RETURN" became "SURFACE". Actually, I thought the new keywords were more intuitive than the original. The programs were stored and interpreted tokenized, so everything worked flawlessly as it always had. But program listings were, "amusing", and you had to use the new keywords to enter or edit programs. The funny thing was, all the real computer nerds immediately realized what was happenning and took only a minute or two to familialize themselves with the new keywords, with no need for outside help. Pity the poor newbie coming into the lab. All around, dozens of students were busily doing their work (or "working" on the multi-player spacewar game that was popular then) with no apparent problems. But every attempt to execute any of the examples in the textbook resulted in complete frustration. When they appealed for help to those in the know, there were some pretty fanciful explanations of why the textbook was wrong - I wish I could remember some of the stories. -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From mis6 at pitt.edu Wed Mar 5 10:40:33 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 5 Mar 2003 07:40:33 -0800 Subject: Can __iter__ be used as a classmethod? References: <60FB8BB7F0EFC7409B75EEEC13E20192022DD8D3@admin56.narex.com> Message-ID: <2259b0e2.0303050740.52a92487@posting.google.com> Alex Martelli wrote in message news:... > Michele Simionato wrote: > ... > > Anyway, I can emulate classmethods with regular methods in the > > metaclass: > > > >>>> class meta(type): > > ... def call_f(cls): cls.f() # a perverse way of calling f > > ... def f(cls): print "%s.f" % cls.__name__ > > > >>>> class A(object): > > ... __metaclass__ = meta > > ... > >>>> class B(A): pass #notice: B inherits the metaclass of A > > ... > > > >>>> A.call_f() > A.f > >>>> B.call_f() > > B.f > > Not quite -- try A().call_f()... would work just fine if call_f > were a static method, but won't work for a metaclass method. > > Not a decisive advantage, but there can be some elegance in > being able to call A.f() and A().f() similarly. > > > Alex True, but my point was that this very little convenience does not justify (IMHO) the introduction of classmethods in the language. There are two typical cases: 1) I want to be able to call A().f(). Then I can use a regular method defined in A and inside the method I extract the class with type(self); 2) A is not meant to be instantiated, and I want to use the notation A.f(). Then I can define a regular method in the metaclass. Then, there is a limit case, where f is defined in the metaclass of A, but I want to call it from an instance of A. In this case it is enough to write type(A()).f(). Therefore in any case, simply by typing few characters more, I can emulate the classmethod effect (if not the precise syntax and some subtility). If Python had no metaclasses, I would think classmethods are useful; but since Python has metaclasses, I think they are redundant and a possible source of confusion. Just my $0.02, Michele From BPettersen at NAREX.com Sat Mar 1 05:30:55 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Sat, 1 Mar 2003 03:30:55 -0700 Subject: My CTO is learning Python.... Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192022DD85D@admin56.narex.com> ...time to run screeming from the building . His problem, is that "There doesn't seem to be any good books on Python". Pressed a little more, it was refined to "either the documentation assumes you've never programmed before, and spends volumes of text introducing loop constructs etc." (that was the commentary on the Tutorial ), "or, the author seems to be in love with the language purely for its advanced and obscure features" (he'd hoped 'Thinking in Python' would be like the C++/Java equivalent...). Pressed a little bit further, he commented: "what I'm really looking for is a quick introduction for someone that allready knows C++ or Java". So on the positive side, our CTO is voluntarily learning Python -- on the other hand, every time I show him the pydiomatic way of doing something, his eyes get really big and he comments "you can do that? Why isn't that in the documentation?" Followed by me pointing out where in the docs it is, followed by "well, that's not very obvious..." In case you were wondering, he's a self-admitted contrarian who expects things to be the way he thinks they should be. He's also my boss (he say, I do), and also probably one of the most brilliant analytical minds I've ever met (i.e. I think he could do amazing things with Python if I can manage to get him behind it instead of tripping over it :-) Does anyone have a writeup or a reference to "pydiomatic problem solving" especially for an audience of expert, large scale C++ and SQL programmers? (I must admit I'm having problems getting people to think of a Python solution, instead of first going 'how do I do this in C++', and then 'how do I translate my C++ to Python?' -- advice graciously accepted) If I have to start from scratch, I would (so far) summarize from FAQ 6 (Python's design), 4 (Programming in Python), 8 (Python on Windows), Selected sections from "Dive into Python", Python Cookbook?, DB API 2.0 (although I'm not sure I can justify $1200/devel for mxODBC yet...), Intro to Numeric (we do numerical models), PIL/Piddle/PDFGen, Automating Office from Win32 Programming, selected topics that have modules in the stdlib (probably borrowing from effbot's work), Gordon's Installer/Py2Exe, ??? Am I missing anything? What I've been looking for, and not found, is examples of how dynamic typing and interface polymorphism make your code shorter, simpler, and easier. I will of course compare them to C++ templates (with the bonus of seeing your code instead of all the type declarations), but I was hoping for a couple of good examples. The one I have so far, is from one of my projects (a "full" justifier for ascii text of various paragraph types): # match space and markup before the actual text. class BulletItems: match = re.compile('r(\s*)([*\-+])(\s*)').match def __init__(self, match, lines): ... class NumericList: match = re.compile(r'(\s*)(\d+\s*[.\-]?)(\s*)').match def __init__(self, match, lines): ... class PlainText: match = re.compile(r'(\s*)').match # always matches def __init__(self, match, lines): ... def getParagraph(paragraph): """Return an object of the appropriate Paragraph class, depending on what text looks like. """ # PlainText always checks as true, so we won't fall off the end lines = paragraph.split('\n') for klass in [BulletItems, NumericList, PlainText]: m = klass.match(line[0]) if m: return klass(m, lines) I'm looking for code that's similarly clear and straight forward in Python and requires much more typing in C++... -- bjorn ps: I was sort of wondering why I didn't need to do "match = staticmethod(match)" in the various paragraph classes? I know re.compile(..).match is a bound method with self bound to the re object, what I don't understand is why a bound method is special and can be used as a staticmethod, while regular functions (def/lambda) cannot? Anyone? From clpl.19.ghum at spamgourmet.com Sat Mar 22 15:56:05 2003 From: clpl.19.ghum at spamgourmet.com (Harald Armin Massa) Date: Sat, 22 Mar 2003 21:56:05 +0100 Subject: Text Editor with wxPython References: <3e7c561a.8718311@news.utanet.at> Message-ID: Franz, > I'd like to write a small text editor with wxPython. > How would you program a simple, but extensible editor? Scintilly is included with wxPython. It's a complete programmers editor. www.scintilla.org If you want to study just a simple editor with wxPython, go to site- packages/wxPython/lib/editor. You can test it within the demo of wxPython There were some rumours about documentation for the scintilla textcontrol, check wxPython mailinglist on aspn.activstate.com Best wishes Harald From sav at ulj.menatepspb.com Tue Mar 11 18:57:08 2003 From: sav at ulj.menatepspb.com (Alexander Semenov) Date: Wed, 12 Mar 2003 02:57:08 +0300 Subject: "is" and "==" References: Message-ID: <3e6e77ce$1@post.ulj.menatepspb.com> > >>> "spam" is "spam" > 1 > >>> "spam" is "sp" + "am" > 0 But in case of rare insertion and often comparing one can use intern(): >>> a = 'spam' >>> b = 'sp'+'am' >>> a is b 0 >>> a == b 1 >>> a = intern(a) >>> b = intern(b) >>> a is b 1 Alexander Semenov. From sismex01 at hebmex.com Tue Mar 11 18:07:19 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 11 Mar 2003 17:07:19 -0600 Subject: clear derived list Message-ID: > From: John Hunter [mailto:jdhunter at ace.bsd.uchicago.edu] > Sent: Tuesday, March 11, 2003 5:08 PM > > I have a class derived from a list. I want to be able to set the list > from another list, first clearing the existing members. I don't see > an analog to the clear method of dictionaries. > > Here is what I am doing now > > class mylist(list): > def set(self, seq): > # flush the old list > [self.pop() for i in range(len(self))] > self.extend(seq) > > l = mylist() > l.append(1) > l.append(2) > > x = [3,4,5] > l.set(x) > print l > > This prints [3,4,5], which I want. But my gut tells me there is a > better way. > > John Hunter > Ugh. You want something like this: > class mylist(list): > def set(self, seq): > self[:] = seq To delete all items of a list: self[:] = [] -gustavo From achim.domma at syynx.de Wed Mar 12 18:25:02 2003 From: achim.domma at syynx.de (Achim Domma) Date: Thu, 13 Mar 2003 00:25:02 +0100 Subject: void pointers with SWIG References: <66f88664.0303121451.53598af1@posting.google.com> Message-ID: I don't know much about SWIG and if it's possible at all, but I would not export such an interface to a nice language like python. I would write a small OO wrapper in C++ around your API and export this interface to Python. I use boost.python for such things, but using SWIG should also be quite easy in this case. regards, Achim From tanzer at swing.co.at Wed Mar 12 12:05:28 2003 From: tanzer at swing.co.at (Christian Tanzer) Date: Wed, 12 Mar 2003 18:05:28 +0100 Subject: Flying With Python (Strong versus Weak Typing) In-Reply-To: Your message of "Wed, 12 Mar 2003 05:37:50 EST." <3E6F0DFE.4AFA8037@engcorp.com> Message-ID: Peter Hansen wrote: > Dennis Lee Bieber wrote: > > > > laotseu fed this fish to the penguins on Tuesday 11 March 2003 06:41 pm: > > > Second thing : > > > Ariane crashed because of a bug in an ADA module. ADA is very strongly > > > *and* statically typed. > > > > > The module was fine -- for the previous generation of Ariane. > > > > If I read correctly, one of the reports available on-line, the closest > > one can come to is that the module which failed was not coded to trap > > an exception condition and recover. > > There was a lengthy discussion of this in the Extreme Programming > mailing list at one point. I can't recall the conclusion, but > after rereading your quotations it seems to me that this is a > case where adequate testing could have "easily" identified the problem. > > It would be interesting to know what tests where actually done, > but my guess is that unit tests for the individual routines > involved was not one of them, or that those tests where quite > inadequate (not checking behaviour in the case of an out-of-bounds > value, for example). The real story is much more complicated. I don't remember all the details, but here are some that I do remember: - The developers looked at the code that later failed and decided that it was safe to skip the exception handling -- this saved some CPU cycles they needed. - When the Ariane 5 was developed, the code was reused but ESA didn't want to spend money on a full system test. - If they had used the same level of paranioa during the porting of the code as during initial developmont they'd most probably found the bug in time. Disclaimer: my memory used to be better. If you want to know what really happened go read the original report (most commentators interpreted the facts in the light of pushing their own silver bullet ;-) -- 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 aleax at aleax.it Mon Mar 31 09:02:58 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 31 Mar 2003 14:02:58 GMT Subject: PyFloat_AsDouble C/API function References: Message-ID: Kostyantyn Teplynskyy wrote: > > Hellow, can somebody explain me why PyFloat_AsDouble converts only to 3 > decimal places. Example It does nothing of the kind -- the symptom you report is no doubt partly mis-observation on your part (e.g., you're seeing "6 signigicant digits" and erroneously believing it matters at all which of those digits are "decimal places") and partly due to some OTHER part of your C code that you don't show us. For example, if you were at any time converting that C double into a C float (single-precision, thus about 6 significant digits) that might explain things. But the PyFloat_AsDouble C/API function, per se, has nothing to do with the problem you see. Alex From max at alcyone.com Thu Mar 20 05:42:41 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 20 Mar 2003 02:42:41 -0800 Subject: Is Python the Esperanto of programming languages? References: <3E79946D.2060400@Linux.ie> Message-ID: <3E799B21.9BB4F13C@alcyone.com> Padraig at Linux.ie wrote: > I would say python is more like lojban Nah, that'd be APL. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Who's not sat tense before his own heart's curtain? \__/ Rainer Maria Rilke CAGE / http://www.alcyone.com/pyos/cage/ A cellular automaton simulation system in Python. From vze4rx4y at verizon.net Tue Mar 25 19:32:48 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 26 Mar 2003 00:32:48 GMT Subject: Wishlist: string attributes References: <3E807948.5040401@motorola.com> Message-ID: "Stephen Boulet" wrote in message news:3E807948.5040401 at motorola.com... > Being a big fan of string methods, here's what I'd like to see for python strings: > > I can access string methods like (str.lower) but I would like to be able to > access all string module attributes without importing the string module (like > str.ascii_lowercase, str.whitespace, etc.). The plan is to use functions like str.isascii() instead of attributes. I had already written the patch. The next step is to extend it so that parallel functions are available for Unicode. Raymond Hettinger From opengeometry at yahoo.ca Fri Mar 14 20:33:02 2003 From: opengeometry at yahoo.ca (William Park) Date: 15 Mar 2003 01:33:02 GMT Subject: Has anyone created a simple POP3 and SMTP server using TWISTED? References: <0001HW.BA9660EB0012EC36F0407600@netnews.attbi.com> <1047595161mnewscandiazoo@attbi.com> <1047621015.523173@yasure> Message-ID: Donn Cave wrote: > Ask on comp.lang.python, has anyone implemented SMTP or POP servers in > Python? Who's obtuse here? You are, for implying that SMTP/POP3 daemon can be written on toilet paper while in bathroom. > > So, download Fetchmail/Sendmail/Gnu-pop3d, and compile. Lots of > > details have been worked out in these programs over the years by > > many people. > > Oh, right. Sendmail wouldn't work for sure, and it's a terrible > choice for a 3 person site anyway. Don't know about the other two, > but I'd guess very strong odds of some platform incompatibility that > would be the end for someone who only knows Python. A simplistic SMTP > and POP3 implementation isn't a huge undertaking, might be a fun > project. You can send email using Telnet, and that may be good for learning SMTP handshaking. But, to make it bullet-proof (which email server should be), is not trivial. What SMTP/POP3 program are you running on your machine? I'll bet it's not written in Python. -- William Park, Open Geometry Consulting, Linux solution for data management and processing. From newsgroups1 at bitfurnace.com Wed Mar 5 22:38:48 2003 From: newsgroups1 at bitfurnace.com (Damien Morton) Date: Wed, 5 Mar 2003 22:38:48 -0500 Subject: building python under windows Message-ID: Im building python 2.3a2 using MSVC 6.0 under windows 2000. The projects in the pcbuild directory builds python.exe and python23.dll I want to build several versions of python, with various profiling options and optimisations turned on, and am trying to figure out how to build a statically linked version of python.exe I would have, for example, python.exe (2.3a2 unchanged) python_dxp.exe (2.3a2 with dynamic profiling turned on) etc etc Any help, suggestions, etc greatly appreciated. From mertz at gnosis.cx Tue Mar 18 19:06:48 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Tue, 18 Mar 2003 19:06:48 -0500 Subject: OT: Recommended Linux Laptops, suppliers? References: <01b901c2ed95$0f7bd940$21795418@dell1700> Message-ID: Cliff Wells wrote previously: |I have no real problem with Apple other than their pricing. I think you are still on a wrong track here, Cliff. I've followed all the links posted in this thread, and I have not seen anything listing a lower priced Intel/AMD/Transmeta PC than an equivalent Apple. The key thing here is to look at what is EQUIVALENT. For me, Pystones (or other benchmarks) are very low on my list of desired laptop features. It is quite true that you simply cannot buy an Apple laptop with the CPU performance of even a moderately-priced x86. And the closest you can come is to buy Apple's extremely pricey top end. But it is also true that you CANNOT buy an x86 laptop that weighs less than 5lbs and has a battery that lasts 4 hours for less than $1500[*]. Especially not one that includes an internal CD drive. If those are your criteria, an iBook is your least expensive choice. The ultralight PCs though, do also have somewhat lower performance than their heavier siblings (i.e. closer to Apples). It's not mostly CPU speed that costs money. Weight costs money (inversely), and battery life costs money. And screen size (where Apples only do moderately well per dollar). Yours, Lulu... [*] I have the strange feeling someone is going to quote me a year from now, when my numbers are dramatically inaccurate. Blah, blah, I mean new price, today's date, etc. -- mertz@ _/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: \_\_\_\_ n o gnosis _/_/ Postmodern Enterprises \_\_ .cx _/_/ \_\_ d o _/_/_/ IN A WORLD W/O WALLS, THERE WOULD BE NO GATES \_\_\_ z e From donovan at passion-pictures.com Wed Mar 5 13:28:01 2003 From: donovan at passion-pictures.com (Donovan Hide) Date: Wed, 5 Mar 2003 18:28:01 -0000 Subject: Using win32api.GetTickCount() over the network Message-ID: <3e6641b1$0$19301$afc38c87@news.easynet.co.uk> Hi pythonists, is there a way to connect to a remote machine and use win32api.GetTickCount() call to measure how long a machine has been up, in a smilar way to the MS utility uptime.exe. Also does anyone know how to control services and processes on remote machines without using other .exe utilities such as those from sysinternals. I am writing a wxPython utility to monitor and control a 3d renderfarm and your assistance would be gratefully received. Cheers, Donovan Hide. From kevin at cazabon.com Sun Mar 2 10:54:27 2003 From: kevin at cazabon.com (Kevin@Cazabon.com) Date: Sun, 02 Mar 2003 15:54:27 GMT Subject: XP or something References: <2593169.1046568078@dbforums.com> Message-ID: I know that ActivePython used to install Tcl/Tk at the same time, but I believe that the current releases no longer do that (for some unknown reason). I'm pretty certain that if you install Tcl/Tk separately you'll be good to go. Try ActiveState's Tcl installer at: http://www.activestate.com/Products/Download/Register.plex?id=ActiveTcl Kevin. "Tetsuo" wrote in message news:2593169.1046568078 at dbforums.com... > > I bought a new computer with WinXP Pro, 2.8, 512, better than I could > have dreamed. Just one significant problem so far. Python GUI refuses to > work. This happened with the old comp, too, but ActiePython fixed it > (regular still didn't work). Now both are broken. The shell works fine, > of course, but I don't care about the shell. > > -- > Posted via http://dbforums.com From gerrit at nl.linux.org Mon Mar 17 14:43:50 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 17 Mar 2003 20:43:50 +0100 Subject: OT: Aspergers link In-Reply-To: <7f2b571b.0303161642.320e0997@posting.google.com> References: <0bkv6v8akrd0db5i66eu685t5pmviuf0bk@4ax.com> <4fm07vg66gr4o4c74gb7ie5v85vlom1vhf@4ax.com> <0vv17v4vn4khffgr2io0otrnni8sc6rug7@4ax.com> <%dica.80722$zo2.2065641@news2.tin.it> <7f2b571b.0303161642.320e0997@posting.google.com> Message-ID: <20030317194350.GA2639@nl.linux.org> [removing (Was: ...3.0.8...) from Subject to get this out of filters ;] Tim Randolph schreef op maandag 17 maart om 01:47:30 +0000: > Alex Martelli wrote in message news:... > > Stephen Horne wrote: > > > I have Aspergers disorder, Cool! > > > and as a result I have a strong tendency to > > > overpedantic use and interpretation of language. Back at school in Yes, me too. In English however, this problem is smaller because my vocabulary is smaller. When I just started being active on the internet, I made a lot of noise and a lot of argument/dispute, for example, I though some website should be W3C AAA, while others disagreed, and I was being unreasonable. At itself, this is not Asperger but rereading it astonisheh myself about by obstinacy, although that is not Aspergers either. I find it cool that more Aspergers are using Python, any others reading this? Let's make an Aspergers Python User Group ;) I have been active in nl.comp.programmeren, n.politiek and n.c.os.linux long ago. However, I could not withhold there, because of the atmospehere, since I am very bad at withholding "critics" (read: people saying a 13-year-old-boy would never get a job because he is busy flaming) (well I still am). Please don't say that's normal: it is, but that's because this is an extreme example, and the less extreme examples aren't noticed by myself ;). > > While I've never been diagnosed with any such disorder, I can certainly > > identify with many (not all) of the symptoms you mention. Many people say so, but they often do not know what Asperger truly means. It can be very difficult for Aspergers to have contacts, and for others to have contacts with Aspergers. Aspergers have difficulties in making social contacts, it could be called some sort of social blindness. Actually, it is sort of the default-reflex-reaction. Everyone, from my Physics teacher to my dad to the man who brought me into a health-program on TV said so. *Please* don't, because it isn't True...! Being an Asperger is not _bad_, however, at least, for me it isn't. I often get comments on my website (see .sig), and a lot of people are in situations far worse that I and probably far worse than Steve's; isolated, without family, denying their Aspergers, depressive... I have been on a special school and very lucky in having so. > Harper's mag ran (May 2002) a fascinating biography of someone with > Aspergers last year. It has a lot to say about the disorder and the > NYC Subway System. > > Can be found on the web here: > > http://www.findarticles.com/cf_0/m1111/1824_304/85882845/print.jhtml Interesting. For the Dutch, which are around here a lot, a biography in Dutch by a Python-user can be found at: http://people.nl.linux.org/~gerrit/ ; ) BTW, a friend of mine knows the periodic system out of his head. I'm thinking of going to learn this as well, just to train my memory. Haven't done that for a loooong time, since I left Gymnasium. yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From anthony at interlink.com.au Tue Mar 11 10:02:58 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Wed, 12 Mar 2003 02:02:58 +1100 Subject: Condorcet analysis of Official PEP308 Ballots In-Reply-To: <3E6DF10A.ADF57FD9@engcorp.com> References: <3E6DF10A.ADF57FD9@engcorp.com> <1047367657.1029.297.camel@chomsky> Message-ID: <200303111502.h2BF2wl27511@localhost.localdomain> >>> Peter Hansen wrote > Let's try this approach: the vote was NOT binding. That could be a > reason to call it "not the most important thing" (thought I can't find > those words, or the ones you quoted, in Norman's posting). My bad. I tried to do the short summary thing, and fouled it up. Bad anthony, bad anthony. Apologies to Norman. > Not only that, but even if a "majority" said "no change", weren't there > a larger number collectively asking for a change, but not agreeing on > the specifics? If that's so, and since the decision is entirely up to > Guido, he could well conclude from the results that there should be > a change, but that it should be (for example) his original proposal > as it's elegant and clean and easily implemented. And while there may > be some, uh, "discussion" of this, it would be the *right* thing > since he is, after all, the BDFL. Dunno. It seems to me that with the (to me, anyway) overly confusing voting process, all that's really possible to say from the voting results was "some people like it. a similar sized group of people don't like it", for various values of "it", and a generous value of the word "similar" to mean "around the same, a bit more, or a bit less". At the end of the day, it doesn't feel like the voting process gave us much new information. But with the voting results as they are, pretty much everyone can pick-n-choose their results - this would be useless. The vote's happened, punt the whole lot to Guido, don't try to specify this way or that way to interpret the results to give a chosen outcome. As you said, it's Guido's call. I'm comfortable he'll make a decision that'll be something we can live with. nobody-mention-the-lambda-ly yrs Anthony From a.schmolck at gmx.net Sun Mar 2 18:48:00 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 02 Mar 2003 23:48:00 +0000 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <58q36vgv1ga8ovde5ftub9t8ugaa2pnum5@4ax.com> <3E62778F.EED49083@alcyone.com> Message-ID: Erik Max Francis writes: > Indeed. I don't see what the tangible benefit is, except by making a > certain style of lambdas harder to read. One might object to the use of > lambdas on general grounds, but certainly when you see the keyword > `lambda' you know what you're in for. PEP 312 attempts to blur that > distinction, for no other reason than to save keystrokes and make code > look more impenetrable. I don't see the benefit. You overlook the fact "that saving keystrokes" (and space) can make a qualitative change to a language. Certain styles of doing things only become viable if they don't involve too many keystrokes. For example, thanks to its lightweight lambda-syntax, smalltalk has a very simple syntax and powerful methods. If ``[x]`` became ``lambda : x``, it would be completely unusable. Compare: Smalltalk: Python: ... someBool ifTrue: [1] ifFalse: [2] apparently needs a ternary operator... ... someContainer at: 3 ifAbsent: [0] try: ... someContainer[3] ... except IndexError, KeyError: ... 0 ... # easy ... someDict at: 3 ifAbsent: [0] ... someDict.get(3, 0) # oops ... someDict at: 3 ifAbsent: [val compute] if someDict.has_key(3): ... else: ... val.compute() ... alex From martin at v.loewis.de Fri Mar 28 02:13:33 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 28 Mar 2003 08:13:33 +0100 Subject: Proposed standard python module: ieee754 References: Message-ID: "Warnes, Gregory R" writes: > Not at all. As it stands now, most common platforms have IEEE 754 compliant > hardware, unfortunately, the C library routines are inconsistent in how and > whether they deal with these special values. It's worse than that: The hardware is usually *not* (strictly) IEEE 754 compliant, and even if it is, it is inconsistent across platforms in being so. IEEE supports different rounding modes and exception modes (this is probably wrong terminology), so whether computations give INF or an exception is vendor-defined (either is IEEE 754 compliant). Regards, Martin From skip at pobox.com Tue Mar 18 12:40:26 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 18 Mar 2003 11:40:26 -0600 Subject: OT: Recommended Linux Laptops, suppliers? In-Reply-To: <016501c2ece6$219373e0$21795418@dell1700> References: <1047944775.1108.51.camel@software1.logiplex.internal> <016501c2ece6$219373e0$21795418@dell1700> Message-ID: <15991.23050.692543.16320@montanaro.dyndns.org> >> A similarly configured iBook or PowerBook (*if* they had one at 2GHz) >> would cost well over $2000. Brian> Are you sure that a 1GHz G4 is slower than a 2GHz Celeron? I'm Brian> not. I sort of doubt the 1GHz G4 would outspin a 2GHz Celeron, but who knows? Here are some Pystone numbers from my 800 MHz Ti Powerbook. I ran the CVS pystone three times with each version of the interpreter, and report the highest number here: Interpreter Best pystone 2.1 10482 2.2 11210 CVS 13123 The CVS is as of a few minutes ago, which includes Raymond Hettinger's rather cool "branch prediction" macros. Skip From bokr at oz.net Wed Mar 26 22:28:43 2003 From: bokr at oz.net (Bengt Richter) Date: 27 Mar 2003 03:28:43 GMT Subject: Integer arithmetic References: <5bhga.17993$i26.423807@news2.tin.it> Message-ID: On Wed, 26 Mar 2003 12:38:25 GMT, Alex Martelli wrote: >Daniel Timothy Bentley wrote: [...] > >> Basically, if you're going to say ints and longs are separate types, I >> think there should be a way to makes ints from longs fairly reliably. I >> don't think that's a niche, I think it's something a consistent language >> should provice. > >Well, your proposed expression DOES "make ints from longs fairly reliably", >it's just that I think the ints it makes are probably not the ones you'd >like to get (except for 0<=foo >I think you want something like: int(cmp(foo,0)*(abs(foo) & sys.maxint)). > >Me, I think it's better to incapsulate the "conversion to int ignoring >overflow" in a function, using an if/else: > >def toint(foo): > if foo>=0: return int(foo&sys.maxint) > else: return -int(-foo&sys.maxint) > The above doesn't match typical hardware and C-style int behavior: >>> import sys >>> def toint(foo): ... if foo>=0: return int(foo&sys.maxint) ... else: return -int(-foo&sys.maxint) ... >>> hex(-sys.maxint-1) '0x80000000' >>> -sys.maxint-1 -2147483648 >>> type(-sys.maxint-1) >>> toint(-sys.maxint-1) 0 Bug, ISTM. [...similarly...] Because two's complement "minint" is not -sys.maxint, (it is -sys.maxint-1) Regards, Bengt Richter From max at alcyone.com Tue Mar 4 22:38:26 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 04 Mar 2003 19:38:26 -0800 Subject: os.execv References: Message-ID: <3E657132.95658970@alcyone.com> Ulrich Petri wrote: > Thanks that did it. > Kinda stupid behaviour (imho) It's simply mimicking the underlying exec... functions' behavior. Each argument to the function is an argument that gets passed to the executable. There's no reason arguments themselves can't contain whitespace, so there's no way your preference can work properly. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ And your daddy died for you / And I'll do the same \__/ India Arie Bosskey.net: Counter-Strike / http://www.bosskey.net/cs/ A personal guide to Counter-Strike. From student00 at angelfire.com Thu Mar 13 09:08:43 2003 From: student00 at angelfire.com (student) Date: 13 Mar 2003 06:08:43 -0800 Subject: Tkinter Text widget scrolling Message-ID: Hi, I'm fairly new to python, and just started working with Tkinter I want to know if theres a way to change the scroll range in the text widget. When text gets larger than the viewable size of the text widget, the scroll is automatically resized, however i want to override this so theres a little white space underneath insted of having the last liine at the bottom. Due to the nature of the application i'm writing, simply adding space at the bottom won't do, i need away to work with the scroll range.... any ideas? thanks From erwin at andreasen.com Thu Mar 6 11:49:09 2003 From: erwin at andreasen.com (Erwin S. Andreasen) Date: 06 Mar 2003 17:49:09 +0100 Subject: linking with shared library, undefined reference to Py_BuildValue References: <3607e8e4.0303041621.78803015@posting.google.com> Message-ID: <8765qwzbi2.fsf@andreasen.org> jkpangtang at yahoo.com (JW) writes: > I have 2 files: > 1) spam.c > int gcd(int x, int y) > 2) spamwrapper.c > #include "Python.h" > > extern int gcd(int, int); > extern void print_data(char *, char *, char *); > > PyObject* spam_gcd(PyObject *self, PyObject *args) > When i try compiling and linking main.c with spammodule.so and libpython2.2.a, > i get the following error messages: > -->./spammodule.so - undefined reference 'Py_BuildValue' > --> ./spammodule.so - undefined reference 'Py_InitModule4' Why do you want to link the Python part of your module if you are going to call only the plain C method directly? I'd suggest compiling spam.c to spam.so separately if that's all you want to do. Your undefined reference however is caused by the linker discarding all of libpython2.2.a. When you link with a *static* library (which is really a collection of .o files with an index) the linker will decide on a .o file basis whether that .o file is really needed -- and it does that based what unsatisfied undefind references are pending so far. If nothing needs that .o file inside the .a, it is not linked in. Since nothing in your program needs anything in libpython2.2.a, no part of it actually gets included into your main program. With a real appliation that embeds Python, you woud call various Python interpreter initiliazation functions, as described in http://www.python.org/doc/current/ext/embedding.html -- this would pull in the necessary Python functions from the library. If you absolutely want to force inclusion of the .a file in its entirety (which would be a waste if you aren't actually going to embed Python), you can use the GNU ld --whole-archive option: $ gcc -rdynamic test.c -o test -Wl,--whole-archive /usr/lib/python2.2/config/libpython2.2.a -Wl,--no-whole-archive -lutil -lm -ldl -lpthread $ ls -la test -rwxr-xr-x 1 erwin users 899268 Mar 6 17:45 test . or use a shared libpython2.2, if available. Don't forget the -rdynamic option, as Martin mentioned. -- =============================================================== Herlev, Denmark <*> =============================================================== From yourmom at hotmail.com Sat Mar 29 20:56:27 2003 From: yourmom at hotmail.com (Your Mom) Date: Sun, 30 Mar 2003 01:56:27 GMT Subject: import package w/ all subpackages? Message-ID: There doesn't seem to be a built-in way to import a package w/ all it's subpackages & modules. Does anyone else see value in adding a statement like "import fully foolib"? I've developed a package that (in trying to keep its contents organized properly) has ended up with a number of modules & subpackages. Currently, a typical program attempting to use my package needs to run 'import foolib.foo, foolib.bar, foolib.baz' for each component to be used. I've determined that i *could* make things easier by adding 'import foo, bar, baz' in the __init__.py file; however, this forces all programs using a single component from the package to import them all, requiring that any depency of any of those components be installed. Wouldn't it be nice to for scripts that want everything in a package to be available for use to say something along the lines of "import fully foolib", while letting other scripts pick modules ala cart? Just a thought, anyway... - Michael From djn at daimi.au.dk Fri Mar 28 03:13:39 2003 From: djn at daimi.au.dk (Daniel Nielsen) Date: Fri, 28 Mar 2003 08:13:39 +0000 (UTC) Subject: signal module? In-Reply-To: <3E839CF5.F5F1EDBA@alcyone.com> References: <20030327092336.GB17524@daimi.au.dk> <7h3ptodm377.fsf@pc150.maths.bris.ac.uk> <20030327132010.GA440@daimi.au.dk> <3E839CF5.F5F1EDBA@alcyone.com> Message-ID: <20030328081338.GC12097@daimi.au.dk> On 27/03-03 16.53, Erik Max Francis wrote: > Dennis Lee Bieber wrote: > > > Pardon, but I've never seen so many ";" in a Python file > > before. They > > aren't really needed /unless/ you are putting multiple statements on a > > single line. > > And it would be one thing if it were done consistently. It's not; some > statements have semicolons as (redundant) terminators, but some don't. > What can I say? I'm used to placing all those ; , but then sometimes I remember that is is not needed in Python and I don't place them... But becides stating the obvious... Any other comments on my thread + signal problem? /Daniel -- There are no great men, only great challenges that ordinary men are forced by circumstances to meet. -- Admiral William Halsey From martin at v.loewis.de Wed Mar 26 16:15:24 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 26 Mar 2003 22:15:24 +0100 Subject: Simple change of python's behaviour References: Message-ID: "Tim Gahnstr?m /Bladerman" writes: > Another way would be to add loop as a native keyword in my python > interpreter, is it a feasible idea or is it just overworking something > simple? Where would I start for this? It is feasible, and it shouldn't be that hard. You have to implement the following steps: 1. Modify the lexer to recognize the new keyword. 2. Modify the grammar to incorporate it, adding non-terminals as necessary. 3. Modify the compiler to recognize the non-terminals Changes to the byte code are not needed for this feature (as you plan to represent it with existing statements). Optionally, you can implement 4. Add a __future__ statement, making your extension optional. I'm not sure whether the list of keywords is generated; it might be that you just have to modify the grammar. So I recommend to start with 2), editing Grammar/Grammar. Make sure you build on Unix, so that the compiler generator is invoked. For 3), look at Python/compile.c > Is there a better way? I'd personally consider "don't extend the language" better, but you haven't actually given a rationale for this extension, so this is a weak objection. Regards, Martin From blakeg at metalink.net Wed Mar 12 21:44:11 2003 From: blakeg at metalink.net (Blake Garretson) Date: Wed, 12 Mar 2003 21:44:11 -0500 Subject: GCD in standard library? References: Message-ID: "Skip Montanaro" wrote: > Depends on what field you're in. I have been programming in Python for nine > or ten years and have never once had the need for a gcd function. True. I'm an engineer so I often use Python for number crunching. > As for adding it to the math module, that goes against the typical grain of > Python's core extension modules. They generally expose functions in a > corresponding Unix C library. Good point. I didn't think of that. Thanks for the response, Blake G. From mh at pixar.com Wed Mar 12 17:47:34 2003 From: mh at pixar.com (Mark Harrison) Date: Wed, 12 Mar 2003 22:47:34 GMT Subject: embedded program questions Message-ID: newbie alert... your patience is appreciated. Can someone loan me a clue on these questions? 1. Is it possible to detect an error from Py_Initialize? I basically want something like if (Py_Initialize() has an error) log error and restart things as necessary 2. How can I capture errors from the PyRun_ functions? I would like to something like if ((rc = PyRun_SimpleString("a = 10 10")) != 0) { processerror(rc); } but catch and report the result or error myself. It seems that I can call Py_CompileString, but I can't figure out what to do with the object returned. :-/ 3. Can I instantiate multiple interpreters in the same program? E.g., I have a server and I would like each client to have its own dedicated interpreter. 4. Is there such as thing as Tcl's safe interpreter model? Many TIA, Mark -- Mark Harrison Pixar Animation Studios From peter at engcorp.com Wed Mar 26 08:40:18 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 Mar 2003 08:40:18 -0500 Subject: about time References: Message-ID: <3E81ADC2.7416C46D@engcorp.com> Byron Morgan wrote: > > The time.py module seems to have no straightforward method to produce a time > display with seconds expressed in floating point precision, even though > clock() will produce microseconds. Am I missing something in the docs? This is unclear to me. time.time() returns a float, with the fractional part representing a fraction of a second, therefore certainly something that could be called "floating point precision" (whatever that means). What about it don't you like? From peter at engcorp.com Fri Mar 7 08:40:41 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 07 Mar 2003 08:40:41 -0500 Subject: Concerns about performance w/Python, Pysco on Pentiums References: <3E660EB3.4065D81F@engcorp.com> <3E66BA3F.7691C3B0@engcorp.com> <3e677433$0$87747$edfadb0f@dread11.news.tele.dk> <7h3bs0oh25s.fsf@pc150.maths.bris.ac.uk> <3E6784AD.E4D523BD@engcorp.com> <7h3y93sfldh.fsf@pc150.maths.bris.ac.uk> <3E67A2F2.187785EA@engcorp.com> Message-ID: <3E68A159.608B2585@engcorp.com> CezaryB wrote: > > Tuples are faster then lists. Try this: > self.opcodes = tuple( Opcode.opcodes ) An interesting point, if true. I'm surprised by that. I would have thought that the difference, if any, would be so small as to be immeasurable in anything but code which only did tuple lookups... I'll have to experiment to see, if only to prove your point to myself. > > def step(self): > > > if newPC is not None: > > self.PC = newPC > > else: > > self.PC += deltaPC + opcode.length > > > > self.cycles += opcode.cycles > > ... > Inline "step" in your main loop, use local variables instead od self.PC, self.opcodes > self.resolveAddress. It should help Psyco. That's a possibility, of course, although then the step() method is not available for use when I actually want it available, unless I modify run() (which currently calls step()) so I can ask it to stop after only one instruction (and then rewrite step() to call run() with that flag, of course). If performance were really that important, these changes would be exactly the route I would consider taking. Performance isn't that important, however, and maintainability is far more important than the smallish gains that would be found so far. I appreciate the suggestions, though, and may play with a few just for kicks. The real issue regarding Psyco for me was simply what I could get *without* hand-tuning the code first. In my mind, Psyco would provide negligible value if I could get significant speed gains only by inlining code, using locals, and so forth. What's needed is something that lets me write the code in the most straight- forward maintainable fashion, without much regard to performance (except in basic algorithmic terms), and then slap in a bind() or two and see a big speedup. If that's not feasible, then I'm personally happy with staying vanilla Python as it's lots "fast enough" in even this case. But tuples faster than lists? Hmmm.... ;-) -Peter From anton at vredegoor.doge.nl Sat Mar 8 16:33:21 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 08 Mar 2003 22:33:21 +0100 Subject: TextPad and Python References: <8a0bb987.0303062118.201471b8@posting.google.com> <24944f78.0303070516.44ffe642@posting.google.com> <37aaa.131$Tv4.1919@news-server.bigpond.net.au> Message-ID: On Fri, 07 Mar 2003 23:41:51 GMT, "Neil Hodgson" wrote: > SciTE's interactive output window isn't all that interactive as, for >example, the backspace key is interpreted within the window and not sent >through to the running program. Maybe it's a feature :-). At the moment I am sitting in front of 3 monitors, each connected to a different computer. The computers are connected via network cards. I have a mouse and a keyboard connected to a little switch box so I can control which computer is receiving mouse and keyboard input. Now it would be nice to read the news on one monitor, edit a script on another monitor and have the output of the script on the third monitor. I guess on unix this would be easy but on windows it's a lot harder. (I probably reinvented the wheel as the next poster will kindly point out.) However scite is very good for these kind of things! On one computer I have scite running a little XMLRPC script: (the script has its output window maximized) #echoserver.py import SocketServer from SimpleXMLRPCServer import SimpleXMLRPCServer def echo(s): print s, return s if __name__ == '__main__': server = SimpleXMLRPCServer(("dummy", 8000)) server.register_function(echo) server.serve_forever() (this could also be a cygwin rxvt window running the python script) One another computer I have this script somewhere: #echoclient.py import xmlrpclib import os import sys svr = xmlrpclib.Server('http://dummy:8000') def runcmd(cmd): i,f = os.popen4(cmd) d = svr.echo(f.read()) if __name__=='__main__': runcmd('pythonw -u %s' %sys.argv[1]) The finishing touch is to have a scite on this second computer that has this extra info in its python.properties: command.name.2.*.py=net echo command.2.*.py=pythonw -u echoclient.py $(FileNameExt) Now if I am editing a python script there's an extra menu option under 'tools' that runs the script and displays the output on the computer running the server script. So the output is on another monitor. Also, not so long ago I configured scite to run the mingw c-compiler for c-files, had pychecker installed as another menu option etc. Of course these things could also be done using cygwin or some other way, but scite doesn't fix things too much for me and it's very configurable. Scite rocks ! Anton. whishlist: - now if somebody would just write a python lexer-generator for scite, I have some IRC-logs that could use better syntax coloring ... - recursive grepping From rmunn at pobox.com Sat Mar 29 18:43:34 2003 From: rmunn at pobox.com (Robin Munn) Date: Sat, 29 Mar 2003 23:43:34 GMT Subject: bug ??? References: Message-ID: Franck Bui-Huu wrote: > Hey > > I don't understand a weird behavior of python > > I ve got two functions: > > def function1(var1, var2): > ... > function2(var1, var2) # first call to function2 > function2(var1, var2) # second call to function2 > > def function2(var1, var2, var3 = []): > ..... > > At the start of function2 during its first call var3 = [] -> OK > but during the second call (always at its starting) var3 = [97,3] which is > the value of var3 when first call of function2 was ending ??? > > if I call function2 by : function2(var1, var2, []) all works fine.... > > Anyone can help me ? You probably haven't gotten a response yet because so many people have been away at PyCon 2003... Basically, when the "def function2" line is executed, function2 is defined. In the same line, an empty list object is created and set as the default parameter to var3. Then in the body of function2, you modify that list object -- so the first time you call function2 without a third parameter, the default parameter (a list object that is currently empty) is assigned to var3. During execution of function2, that list object is modified. Then the second time function2 is called with no third parameter, that same list object (no longer empty) is assigned to var3 as its default parameter. What you actually wanted to do was something like this: def function2(var1, var2, var3 = None): if var3 is None: var3 = [] # Rest of function2 here... Read http://www.python.org/doc/FAQ.html#6.25 for more information. P.S. Notice the distinction I'm making between *names* and *objects*. If you're coming to Python from a language like C, you may not be used to this distinction -- but once you grok that names are just pointers to objects, several things that used to be confusing may start to make more sense. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From dwelch91 at no.spam.attbi.com Sat Mar 29 20:33:36 2003 From: dwelch91 at no.spam.attbi.com (djw) Date: Sun, 30 Mar 2003 01:33:36 GMT Subject: namespace problems in pyqt In-Reply-To: <%2rha.70$6U5.65818@newsfep2-win.server.ntli.net> References: <%2rha.70$6U5.65818@newsfep2-win.server.ntli.net> Message-ID: You might have better luck (and a faster response) if you post to the PyKDE mailing list here: http://mats.gmd.de/mailman/listinfo/pykde /Don/ From edo4 at emich.edu Mon Mar 3 11:24:43 2003 From: edo4 at emich.edu (Ngoc) Date: 3 Mar 2003 08:24:43 -0800 Subject: Numarray Python extension in debug mode Message-ID: <99457f2.0303030824.475883ce@posting.google.com> Is there anyway I can install numarray in debug mode? python_d setupall.py install is not working. Ngoc From sholden at holdenweb.com Sat Mar 8 14:32:06 2003 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 08 Mar 2003 19:32:06 GMT Subject: Fixes to zipfile.py [PATCH] References: <87heae244i.fsf@christoph.complete.org> <3E6A4322.9010908@rsballard.com> Message-ID: "Bob Ballard" wrote in message news:3E6A4322.9010908 at rsballard.com... > You should try using python to control winzip from the command line as > you can any other shell too. should do what you want. See, > > http://www.winzip.com/xcmdline.htm > > Bob > A good idea for Windows, but sadly not portable to Unix. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Register for PyCon now! http://www.python.org/pycon/reg.html From sismex01 at hebmex.com Tue Mar 18 11:13:16 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 18 Mar 2003 10:13:16 -0600 Subject: PEP 312 (and thus 308) implemented with a black magic trick Message-ID: > From: Chermside, Michael [mailto:mchermside at ingdirect.com] > Sent: Tuesday, March 18, 2003 10:07 AM > > I just wanted to say that I'm really impressed. > > It's pure evil, of course, but nonetheless very beautiful and > astoundingly simple. > > For some reason I'm more disturbed by the mis-use of operator > overloading than by the metaclass which modifies code... > perhaps because I've been burned by the former before (in C++). > > -- Michael Chermside > Perhaps, instead of using "~" as a marker for "lazy-evaluation", "~~" can be used. It's easy to see, not too "noisy", it's syntacticly correct, and very improbable to be used like that. :-) -gus From martin at v.loewis.de Fri Mar 14 18:21:52 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 15 Mar 2003 00:21:52 +0100 Subject: calling a method using a variable name? References: <3E724077.1020003@nowhere.com> Message-ID: Patrick Price writes: > class X: > def method(): > pass > > > z=X."method"() > > How would I do this? Notice that writing z = X.method() wouldn't work, either, since you cannot call an unbound method without an instance. So you would have to write x = X() z = x.method() If you want to use a string, write z = getattr(x, "method") () HTH, Martin From no at email.com Mon Mar 17 13:08:01 2003 From: no at email.com (Anthony Paul) Date: Mon, 17 Mar 2003 19:08:01 +0100 Subject: username cgi References: Message-ID: Gerhard H?ring wrote: > > What about using a Cookie for this? This approach will work > cross-platform. I can't because I'm using mandatory profiles... > You mean "Windows authentification" (NTLM)? That should be possible if > you use Internet Exploder, IIS and your users are authenticated > against a domain. Don't ask me how to do it in Python, though. I'm using Apache2 on a linux server. However, I don't think REMOTE_USER variable needs a Microsoft server. Only a .htaccess is needed I think (?). -- Anthony Paul ============ C'est au pied du mur qu'on voit le mieux le mur. From aleax at aleax.it Mon Mar 3 03:38:54 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 03 Mar 2003 09:38:54 +0100 Subject: XP or something References: <2593169.1046568078@dbforums.com> <2595838.1046668716@dbforums.com> Message-ID: Tetsuo wrote: > Okay, now I feel stupid. Or maybe I am. > > I clicked the link in Start, and it works fine. Before, I tried to open > the file "pythonw.exe" directly. But I can't figure out the path that > link points to... I guess it isn't too important, but it'd be nice. Can't you "Explore" the Start button in Win/XP to find out all the details of such things as the shortcuts found in its sub-folders? That used to be possible in older Win releases, after right-clicking on the button. Alex From anton at vredegoor.doge.nl Fri Mar 28 07:20:41 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 28 Mar 2003 13:20:41 +0100 Subject: OT: Re: Prime number algo... what's wrong? References: <1MudnTyOEK1mauGjXTWcqg@speakeasy.net> <3E835DC2.3678BD7F@engcorp.com> Message-ID: Lulu of the Lotus-Eaters wrote: >I've mentioned to Phil (the site maintainer for the prime number >resources) that I think he is overbroad in his block--only three >countries (USA, UK, Australia) are engaging in direct aggression. The Some antidote against the "country as person metaphor" - not implying any signs of you being poisoned by it - : Metaphor and War, Again George Lakoff, AlterNet March 18, 2003 http://www.alternet.org/story.html?StoryID=15414 An older text from the same author is providing more detail and introduces subtle terminology such as the "ruler for state" metonym. Sorry, no webpage here, just some info to google it up: from: Dave Touretzky (dst at dst.boltz.cs.cmu.edu) subject: George Lakoff on "Metaphor and War" newsgroups: comp.ai date: 1990-12-31 03:54:52 PST >Just to attempt a slight thread connection, perhaps one could filter >access by the primality of incoming IP addresses. I'll have to check >the site for efficient techniques. Nah, just post some magma code, that will keep them busy trying to implement the functionality in python :-) Anton. ps. the magma code (Not sure where I found it, so I'm posting the code instead of the link, also I've edited it a bit in order to avoid line breaks): /* Magma implementation of AKS primality proof algorithm, by Allan K. Steel (note my initials -- nice coincidence :-)), <[Allan's first name]@maths.usyd.edu.[Australia]>, 8/8/02. The power test is done at the beginning in polynomial time (with a log factor). Note that I use NextPrime to loop through the values of r. This is faster than testing whether each new r is prime: NextPrime(r) computes with proof the first prime greater than r (and in deterministic polynomial time for r < 3.4*10^14). This is ironic of course, in that we have can prove any number < 3.4*10^14 prime in deterministic polynomial time (and in < 0.001 secs in practice), which is way above the reasonable testing range for the AKS algorithm. */ function AKS(n) if IsPower(n) or n gt 2 and IsEven(n) then return false; end if; logn := Log(2, n); r := 3; while r lt n do if GCD(n, r) ne 1 then return false; end if; q := D[#D] where D := PrimeDivisors(r - 1); if q ge 4*Sqrt(r)*logn and Modexp(n, (r - 1) div q, r) \ ne 1 then break; end if; r := NextPrime(r); end while; P := PolynomialRing(IntegerRing(n)); for a := 1 to Floor(2*Sqrt(r)*logn) do if Modexp(x - a, n, x^r - 1) ne x^(n mod r) - a then return false; end if; end for; return true; end function; From martin at v.loewis.de Wed Mar 26 16:08:33 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 26 Mar 2003 22:08:33 +0100 Subject: Simple Python web development References: Message-ID: Afanasiy writes: > * Uses the Apache web server > * Does not depend solely on CGI or FastCGI > * Requires only an Apache daemon, and no others > * Does not require editing of *.conf or .htaccess every > time you want to add another page to your web application. I *think* mod_python meets all these requirements. Regards, Martin From sismex01 at hebmex.com Mon Mar 17 13:28:51 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 17 Mar 2003 12:28:51 -0600 Subject: Linux password manipulation in Python Message-ID: > From: Gary Herron [mailto:gherron at islandtraining.com] > Sent: Monday, March 17, 2003 12:30 PM > > Hi, > > This may be more of a Linux than Python question, but I'll try asking > it here first. > > How does one deal with encrypted passwords on a Linux system which > uses shadow passwords? > > The 'crypt' module has an example in its documentation of encrypting a > password (and then comparing to the contents of the /etc/passwd file), > but that example explicitly states it does not support shadow > passwords. And when I use crypt to encrypt a known password, I do not > get anything like the contents of the /etc/shadow file. > > Thanks for any help, > > Gary Herron IIRC, shadow passwords might be using MD5 to hash them, instead of crypt(). -gus From rzrtkxlp at qxqsjvlo.com Mon Mar 31 14:26:31 2003 From: rzrtkxlp at qxqsjvlo.com (lorabanks) Date: Mon, 31 Mar 2003 19:26:31 GMT Subject: What a Deal << 2GB and 1GB >> USB Flash Memory Drive Message-ID: <23c792e99172f4592374b34ae05431a7@news.teranews.com> Great Deals on USB Flash Memory Drive >>>>> Price: 2GB - $779 >>>>> Price: 1GB - $389 with and with Free Shipping *%$ http://www.ebestshoppers.com #%& From ckea25d02 at sneakemail.com Mon Mar 31 21:06:52 2003 From: ckea25d02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 01 Apr 2003 14:06:52 +1200 Subject: To get text in a Text widget. In-Reply-To: <3E8896A1.83C2621@emi.u-bordeaux.fr> References: <3E8896A1.83C2621@emi.u-bordeaux.fr> Message-ID: denis gaultier wrote: > I just want to know how to do to get text typed in a Text widget. > I don't know what kind of parameter I must give to the "get" function. If you're talking about Tkinter, from memory I think something like get(0, 'end') will get you all the text. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From UNZRCHUYBTAS at spammotel.com Sun Mar 30 08:01:09 2003 From: UNZRCHUYBTAS at spammotel.com (Jens Gelhaar) Date: 30 Mar 2003 05:01:09 -0800 Subject: A default in the __init__ is like a class variable? Message-ID: <35404b41.0303300501.27ae4054@posting.google.com> Is this a feature? >>> class test: ... def __init__(self,t=[]): ... self.t=t ... >>> t1=test(); t2=test() >>> t1.t.append("feature?") >>> print t1.t ['feature?'] >>> print t2.t ['feature?'] >>> I know why both t has the same list, but I would not expect this. Each instance should have it's own list. From me at privacy.net Tue Mar 18 22:29:31 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Wed, 19 Mar 2003 15:29:31 +1200 Subject: Python and Nuclear Safety (Re: PEP 312 (and thus 308) implemented with a black magic trick) In-Reply-To: References: Message-ID: Tim Churches wrote: > Are you the Greg Ewing of Pyrex fame, from Canterbury University in New > Zealand? If so, I didn't think New Zealand had a nuclear arsenal. I am, but on that occasion the PSU was using me to channel their thoughts (they frequently pick random people from around the world for that, to better obfuscate their identity, or lack thereof). It seems that "our country" in their announcement is meant to refer to the USA. > I see your email address is from Germany. Is it? That's news to me! I always thought .nz referred to New Zealand... Has the PSU been messing around with the domain name system again? Things got terribly confused last time they did that. > Please tell me that those four Python programmers are not now sitting with their > fingers hovering over the Enter key, waiting for the word from you-know-who. I certainly hope not, but... only George and the PSU know... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From john.burton at jbmail.com Sun Mar 9 07:16:24 2003 From: john.burton at jbmail.com (John Burton) Date: Sun, 9 Mar 2003 12:16:24 -0000 Subject: DNS lookup References: Message-ID: "Alessio Pace" wrote in message news:eTFaa.3697$Fc.114939 at tornado.fastwebnet.it... > Is there a portable way to do a DNS lookup? I am developing in Unix (Linux) > but I would prefer avoiding the use of Unix specific command line tools. I > need both translation from machine name to IP and from IP to machine name. > Thanks. import socket print socket.gethostbyname("example.com") print socket.gethostbyaddr("192.168.0.1") From mhammond at skippinet.com.au Tue Mar 18 17:12:33 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 18 Mar 2003 22:12:33 GMT Subject: How can I use an existing COM object pointer with win32com? In-Reply-To: References: Message-ID: Gary Bishop wrote: > In my C++ extension that wraps the Microsoft Active Accessibility API > I can get a pointer to a IWebBrowser2 COM interface from an > IAccessible representing the browser. I'd like to hand this pointer > back to my Python code and use it just like I would use the object I'd > get from > > ie = DispatchWithEvents("InternetExplorer.Application", IEEvents) > > Can I do that? I don't want to create a new instance of Internet > Explorer. I want to connect to a particular instance already running. > > I have looked for an example of "adopting" a COM pointer but haven't > found one. There are 2 steps you must go through: 1) Convert the C++ interface pointer to a PyObject 2) Convert this PyObject to a "nice" win32com instance 1) is a matter of calling PyCom_PyObjectFromIUnknown(), defined in PythonCOM.h 2) is really a matter of calling the functions yourself from the C++ code using the Python API - eg, PyImport_ImportModule() to get win32com.client, PyObject_GetAttr() to get the function from the module, and PyEval_CallObject() to make the call. (The exact names may not be correct there) I am not sure how you hope to get DispatchWithEvents working, given that the second param is a class object - however, I am sure you have some plan :) Further, I suggest that (2) actually be put in Python code. Your C++ code should do (1), then delegate to your own Python code. This code then does (2), and anything else necessary. Mark. From rmunn at pobox.com Mon Mar 31 13:04:56 2003 From: rmunn at pobox.com (Robin Munn) Date: Mon, 31 Mar 2003 18:04:56 GMT Subject: Application Error --- Dr. Waston References: <860fca46.0303310631.4240f8c2@posting.google.com> Message-ID: KT wrote: > Hi, > We are using python 1.5.2 version on windows NT 4.0 server, > and from last week we are facing an issue, > > "While publishing files using python to the replication server we get > the below mentioned error. > > The application,./Python.exe, generated an application error. The > exception generated was c0000005 at address 1e128983 (PyArg_VaParse)" > > We tried re-installing the software but it didn’t help. > > Any help on this would be much appreciative While many people would be glad to try and help, there's not enough information in your post for anyone to be able to solve this problem for you. What data files are generating this error? What is the "replication server" you're talking about? Most importantly, what is the Python code you're running that is crashing? I see you're running 1.5.2 -- that's a very old version by now. Does the problem persist in version 2.2? What about 2.3a2? Thanks for posting the exact error message. That's at least something. I see that the error seems to be occurring in PyArg_VaParse, which at least gives a glimmer of a clue as to what might be wrong, but please give us more information or we won't be able to solve your problem. For an idea of how to phrase your questions better, to supply the kind of information we might need to help, see "How to Ask Questions the Smart Way": http://www.catb.org/~esr/faqs/smart-questions.html -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From gharik at comcast.net Tue Mar 25 01:26:52 2003 From: gharik at comcast.net (G) Date: Tue, 25 Mar 2003 01:26:52 -0500 Subject: Understanding sockets? References: Message-ID: Hi Dennis, thanks, your code works. however, it does not work if the client is indefinitely running. i would like to have a client that is always running and continually sending and receiving messages from the server. i do not know how to do this using sockets. thanks. g From reply.in at the.newsgroup Mon Mar 3 12:09:28 2003 From: reply.in at the.newsgroup (Rene Pijlman) Date: Mon, 03 Mar 2003 18:09:28 +0100 Subject: Books Database References: Message-ID: A.M. Kuchling: >the format is quite nicely readable and near-trivial to parse. [...] >%K mystery, sherlock holmes > >The only problem is with adding additional fields; you have to >come up with a single character that isn't already used. "26 fields ought to be enough for everybody." And in this case, I agree :-) -- Ren? Pijlman From puccio_13 at yahoo.it Sun Mar 9 06:42:33 2003 From: puccio_13 at yahoo.it (Alessio Pace) Date: Sun, 09 Mar 2003 12:42:33 +0100 Subject: DNS lookup Message-ID: Is there a portable way to do a DNS lookup? I am developing in Unix (Linux) but I would prefer avoiding the use of Unix specific command line tools. I need both translation from machine name to IP and from IP to machine name. Thanks. From m at idelix.com Mon Mar 3 16:16:34 2003 From: m at idelix.com (Mark Tigges) Date: 3 Mar 2003 13:16:34 -0800 Subject: cgi FieldStorage strangeness Message-ID: I'm at a loss here, therefore the post. I'm writing a CGI that uploads a file from the client using method POST in an html form submit. Unfortunately I can't seem to get the form fields. When the page loads up, using FieldStorage.print_form it says "No form fields". Now, I have written such a script before to do something very similar, and it works fine ... on the same server. I know the client is actually doing a post, since mozilla warns that it will POST the data again when I hit reload. cgi.print_environ shows the appropriate values are in CONTENT_LENGTH and CONTENT_TYPE. Has anybody else experience anything like this?? I'm about to pull my hair out. Thanks, Mark. From max at alcyone.com Mon Mar 3 14:45:09 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 03 Mar 2003 11:45:09 -0800 Subject: Why no RE match of A AND B? References: <3E6270DC.3060904@tiscali.co.uk> <_Fw8a.106840$Hl6.9851028@news010.worldonline.dk> <3E629E43.D8661813@alcyone.com> <3E62A8BD.BB7A7CA6@alcyone.com> <3e6317e7$0$16108$edfadb0f@dread11.news.tele.dk> <3E6321E3.C43FBAF2@alcyone.com> <3e63441f$0$16163$edfadb0f@dread11.news.tele.dk> Message-ID: <3E63B0C5.EEA2A1EC@alcyone.com> "Anders J. Munch" wrote: > Taking statistical evidence from a hypothetical scenario, hm. It's a judgement call. > How can one miss what one doesn't know? Well, since I keep saying in the parts that you're clipping, I won't bother repeating myself again. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Strange is our situation here upon earth. \__/ Albert Einstein Esperanto reference / http://www.alcyone.com/max/lang/esperanto/ An Esperanto reference for English speakers. From pc451 at yahoo.com Fri Mar 28 09:33:22 2003 From: pc451 at yahoo.com (Peter Clark) Date: 28 Mar 2003 06:33:22 -0800 Subject: Python USB interface. References: Message-ID: Grzegorz Dostatni wrote in message news:... > Hi. > > I will be playing with a digital camera: Mustek Gsm at rt Mini 3. > Unfortunately it comes with drivers for windows only... and I'd > prefer to use it under linux. > > Is there an interface in python to the USB? Python interactive mode could > be perfect way to figure out how to interface to this gadget. Under Linux, you can basically interface with USB like any other serial port; i.e., everything is a file, just open it up and watch it. However, in your case, you probably would be better off with using gphoto; http://gphoto.sourceforge.net/proj/libgphoto2/support.php says that the level of support for your camera is "testing." Who knows what that means, but it's probably a lot further along in functionality than what you would get with a quick Python script. For instance, the current KDE release supports gphoto2 right out of the box (Control Panel -> Peripherals -> Digital Camera) and I'm sure there's something for GNOME, too. :Peter From aleax at aleax.it Sat Mar 22 05:51:45 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 22 Mar 2003 10:51:45 GMT Subject: What's up with rebinding assignment? References: Message-ID: <5fXea.138371$zo2.3599417@news2.tin.it> Des Small wrote: ... >> My question is: is there a chance this will make it into Python? >> Nobody seems to have noticed it... Will a PEP help? > > I don't know how the politics works, but Alex Martelli has said that > the best way to get stuff in is to make an idea visible and hope > that Someone Important adopts it like unto their own brainchild. Heh -- I wouldn't recommend anybody to accept my perceptions of group-politics... it's definitely not my area of expertise;-). > Naively, if we hang around discussing this ("Operator, Lisp luser!" > "Keyword, C++ buffoon!") for a bit maybe we'll attract some attention. I think that we're at the stage at which a PEP or two might help, and in fact even patches to implement lexical vs := well might. A PEP should (as I see things) pick one alternative and discuss the others (including existing possibilities and alternate changes, e.g. if the PEP focused on 'lexical' it should mention := as an alternative and why it's rejected). Having a patch would let the speedups, claimed as one important advantage wrt the existing possibilities, be MEASURED (always more convincing) rather than GUESSED AT. Finding places in the standard Python library where the new construct would help would be a real boon, too. As it's clearly too late for this to get into Python 2.3, the time available is quite long -- say 6+ months until the first likely glimmerings of a future Python 2.4 start appearing. Alex From pajer at iname.com Tue Mar 11 15:11:42 2003 From: pajer at iname.com (Gary Pajer) Date: Tue, 11 Mar 2003 15:11:42 -0500 Subject: Does ScientificPython run on Windows? Message-ID: The docs seem to imply that it only works on Unix-like systems. If so, is it necessary to compile it? I ain't got no stinkin' compilers on Windows. :) Thanks, Gary From tjreedy at udel.edu Sat Mar 8 09:52:42 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 8 Mar 2003 09:52:42 -0500 Subject: Perl Vs Python References: <7i1y1i479u.fsf@enark.csis.hku.hk> Message-ID: "Isaac To" wrote in message news:7i1y1i479u.fsf at enark.csis.hku.hk... > I'd rather say that Python is developed much later than Perl, so it learns > from all the ugliness of Perl. =) Say what you want, I believe Python and Perl were both developed about the same time, around 1990. Perl became famous sooner because it filled a 'hot' new web nitch -- that of writing CGI programs. Terry J. Reedy From mwm at mired.org Sat Mar 15 11:33:28 2003 From: mwm at mired.org (Mike Meyer) Date: Sat, 15 Mar 2003 16:33:28 GMT Subject: Strange rounding problem References: <4378fa6f.0303141540.de857b8@posting.google.com> Message-ID: mnations at airmail.net (Marc) writes: > GAP IN ROUTINE 9.6e-007 > GAP BEFORE CONVERSION 9.6e-007 > GAP AFTER CONVERSION 959 > gapList = [[], 9.5999999999999991e-007, '3'] > > This appears to be confusing. The variable is set to .00000096 but is > passed through as 9.5999999999999991e-007. It appears accurate when > printed before the value is returned, is inaccurate when the full > return list is printed, accurate when it's printed by itself after the > return, and then inaccurate again when the division is made. Why does > it do this, and how can I avoid it? Actually, all the numbers are the same. What you are seeing is the difference between str and repr. Repr is used on the elements of a list when it is printed. But here's what happens when you do things by hand: >>> print repr(9.6e-7) 9.5999999999999991e-07 >>> print str(9.6e-7) 9.6e-07 >>> print str(9.5999999999999991e-07) 9.6e-07 >>> http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From aleax at aleax.it Sat Mar 1 17:19:08 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 01 Mar 2003 22:19:08 GMT Subject: Can you create a class from a string name References: <3E611ABE.2050102@verizon.net> Message-ID: Anna wrote: ... > def factory(aClass, *args): > return apply(aClass,args) Note that this needs aClass to be a class object, not a class name. And in today's Python, apply's rather redundant -- the body of this factory function might just as well be: return aClass(*args) since the * form can now be applied on calling, symmetrically to its application in def (it expands any sequence of arguments). So you might equally well define, in modern Python: factory = aClass Alex From Paul.Moore at atosorigin.com Fri Mar 28 04:22:38 2003 From: Paul.Moore at atosorigin.com (Moore, Paul) Date: Fri, 28 Mar 2003 09:22:38 -0000 Subject: [Spambayes] Non-email use of the spambayes project Message-ID: <16E1010E4581B049ABC51D4975CEDB880113D9CA@UKDCX001.uk.int.atosorigin.com> From: Skip Montanaro [mailto:skip at pobox.com] > I've successfully applied the Spambayes code (http://spambayes.sf.net/) > to a non-email application today and thought I'd pass the concept along > to others. This is a lovely idea! Based on this description, I'm sure I can think of a number of "data cleaning" exercises I'd like to do which might benefit from this sort of approach. Makes me wonder if there's a case for taking the algorithmic guts out of spambayes, and making a standalone library module from it... Thanks for posting this. Paul. From LogiplexSoftware at earthlink.net Wed Mar 19 16:26:51 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 19 Mar 2003 13:26:51 -0800 Subject: OT: Recommended Linux Laptops, suppliers? In-Reply-To: <15992.53581.64027.578138@montanaro.dyndns.org> References: <1048100028.1301.98.camel@software1.logiplex.internal> <15992.51278.390163.895099@montanaro.dyndns.org> <1048104887.1118.9.camel@software1.logiplex.internal> <15992.53581.64027.578138@montanaro.dyndns.org> Message-ID: <1048108364.1343.5.camel@software1.logiplex.internal> On Wed, 2003-03-19 at 12:21, Skip Montanaro wrote: > Cliff> Returning to the topic of disorders, IANAP, but it appears you've > Cliff> got that one where you just don't get it. > > Ah, I see. The missing smileys fooled me. Well, based upon previous discussions, since you eventually got it, you just have a personality problem, not an actual disorder > explicitness-is-next-to-cleanliness-ly, y'rs, One more thing usenet and porn have in common. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From tjreedy at udel.edu Thu Mar 6 00:14:44 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Mar 2003 00:14:44 -0500 Subject: Bug or wart? You make the call. References: <2e363c08.0303051256.58c94b08@posting.google.com> Message-ID: "Paul Miller" wrote in message news:2e363c08.0303051256.58c94b08 at posting.google.com... > Just out of curiosity, I tried something like this: > > Python 2.2 (#1, Apr 12 2002, 15:29:57) > [GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-109)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> class Spam (object): > ... def eggs (self): > ... pass > ... > >>> Spam.eggs > > >>> Spam.eggs.attr = 0 > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'instance method' object has no attribute 'attr' > >>> spam = Spam() > >>> spam.eggs.attr = 0 > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'instance method' object has no attribute 'attr' > >>> spam.__dict__ > {} > >>> Spam.__dict__['eggs'].attr = 1 Try Spam.__dict__['eggs'] without assignment, as you did with 'Spam.eggs' above and see what type of object you are assigning to. This should answer your question. > >>> spam.eggs.attr > 1 > >>> Spam.eggs.attr > 1 > >>> > > In other words, when I try to set a nonexistent attribute of a method, > either in a class or an instance, I get an AttributeError, Correct. >but if I access it through the class __dict__, I can do it. You are making an invalid assumption. See note above. >Which of these is the correct behavior? Both Terry J. Reedy From nav at adams.patriot.net Mon Mar 24 09:07:10 2003 From: nav at adams.patriot.net (Nick Vargish) Date: 24 Mar 2003 09:07:10 -0500 Subject: a couple of newbie questions References: <20030321.081510.2111331352.12265@localhost.localdomain> Message-ID: sjmachin at lexicon.net (John Machin) writes: > Unless you give a damn about data integrity, in which case you might > like to check things like (1) do lines have the minimum 2 fields and > the presumably desirable 5 fields [based on the OP's example] (2) are > there any duplicate keys. Geez, excuse me for trying to supply an illustrative example. The guy was _lost_. I wanted to show the way without obscuring the solution to the problem with a lot of type checking. And where's your solution, smart guy? Nick -- # sigmask.py || version 0.2 || 2003-01-07 || Feed this to your Python. print reduce(lambda x,y:x+chr(ord(y)-1),'Ojdl!Wbshjti!=obwAqbusjpu/ofu?','') From max at alcyone.com Mon Mar 24 17:46:26 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Mar 2003 14:46:26 -0800 Subject: Python 2.3 True = False References: <3E7EB0C1.FB2A76EB@alcyone.com> Message-ID: <3E7F8AC2.E636CA24@alcyone.com> Rene Pijlman wrote: > You have got to be kidding :-D > > What did it assign True and False to? And why? Probably 1 and 0, respectively. If you want True/False sentinels and can't be sure you have Python 2.3, you have to make them yourself. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ It is only to the individual that a soul is given. \__/ Albert Einstein Lsystem / http://www.alcyone.com/pyos/lsystem/ A Lindenmayer systems explorer in Python. From matt at teaphoo.fsnet.co.uk Fri Mar 21 04:51:33 2003 From: matt at teaphoo.fsnet.co.uk (Matt Russell) Date: 21 Mar 2003 01:51:33 -0800 Subject: MockObject Suport For unittest.TestCase References: Message-ID: <459f9b68.0303210151.1f6eb064@posting.google.com> Many appologies for getting yout name wrong Michael, I am all over the place this morning :( mcherm at mcherm.com wrote in message news:... > Matt: > > GREAT CONTRIBUTION! > > I think that mock objects is a feature that could be very useful, and > a handy way to build them inside the unittest module sounds like a > greate idea. And we appreciate your effort to contribute! > > I haven't finished looking over your patch yet, but I have a couple > of suggestions right fron the beginning. > > (1) I would change self.called (which is private storage for the mock > object) to something like self.__mockObject_called to reduce the chance > of an unfortunate name collision. > > (2) In MockFactory.__new__ I would try to check for classes implementing > custom __getattr__, and __getattribute__ methods, and handle those > specially (probably by raising an exception claiming that the class > can't be mocked). > > I'm sure there'll be other suggestions from other people, and perhaps > some more from me if I get more time. > > -- Michael Chermside From gerhard.haering at opus-gmbh.net Tue Mar 11 08:38:16 2003 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 11 Mar 2003 13:38:16 GMT Subject: Silly Question References: Message-ID: Clint Bailey wrote: > I've been studying Magnus Lie Hetland's book, Practical Python, for some > time now. For some time something has struck me. Is there such an object as > an ARRAY in the Python language. An array is a low-level construct that you hardly ever need. So it's hidden away in the array *module*. What you most probably want is a list type, that can hold an arbitrary number of elements. This one is part of core Python. You use it like this: l1 = [3, 4, 5] # A list of integers l2 = ["s1", "s2"] # A list of strings l_misc = [3, 5.0, "asdfsdf"] # A list of misc. stuff print l1[0] # print first list element l1.append(6) # append another element to the list etc. Have a look at the methods lists support in order to learn how to use them. They're a little hard to find, because they're hidden here: http://www.python.org/doc/current/lib/typesseq-mutable.html Uhm. Better read your tutorial than this. I hardly understand it myself ;-) -- Gerhard From aleax at aleax.it Tue Mar 4 17:28:08 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 04 Mar 2003 22:28:08 GMT Subject: Sorry ... References: Message-ID: Lance LaDamage wrote: > If I shocked you by my various errors, it's because one thing ... and > prepare for the shock ... : > > I am an 11 year old child who enjoys to program in Visual Basic and have I'm impressed! You're definitely a far better programmer than I was at your age... > recently learned Python because a chat friend had a chatbot (written in > Python) and I was required to develop most of it. I'm very interested in > programming and I rely on the help of other programmers to help you > (because my mother and father can't.) If anyone can offer me any tips or > help, I would appreciate it. While it may be a bit "old stuff" for you, I'd recommend starting with http://www.livewires.org.uk/python/ -- it gives a nice tour of Python, including how to use it to write videogames, which is an interesting take on things, I believe. Alex From graham__fawcett at hotmail.com Mon Mar 10 14:08:35 2003 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 10 Mar 2003 11:08:35 -0800 Subject: pep 308: why doing (almost) nothing suffices References: Message-ID: "Edward K. Ream" wrote in message news:... > > How about repr(s)? > > I don't think so. > > >>> s = 'a' > >>> repr(s) > "'a'" > > >>> s = "a" > >>> repr(s) > "'a'" Try again... >>> a = 'xyz' >>> print repr(a) 'xyz' >>> a == eval(repr(a)) 1 >>> b = "wxy" >>> print repr(b) 'wxy' >>> b == eval(repr(b)) 1 The double-quoting in your example is a result of "repr'ing a repr", since the interactive read-eval-print loop will repr() the results of any expression, including the results of a repr() call. By explicitly printing the results we avoid this behaviour. -- Graham From manus at diplom.org Mon Mar 3 20:13:46 2003 From: manus at diplom.org (Manus Hand) Date: 3 Mar 2003 17:13:46 -0800 Subject: Dumb question on assignment chaining Message-ID: <984e2f1d.0303031713.3ad6e931@posting.google.com> Okay, first of all, I know that for clarity's sake I should write statements like a = a.b = c in two statements, but in playing around.... :-) class Node: def __init__(self, val): self.val, self.next = val, None def __repr__(self): return `self.val` walker = zero = Node(0) walker = walker.next = Node(1) print zero.next # this prints None # ...hmm. Okay, start over... walker = zero = Node(0) walker.next = walker = Node(1) print zero.next # this prints 1 So it seems that in the construction x = y = z, the assignments take place in left-to-right order (i.e., x = z and then y = z; the opposite of how the C language implements its assignment operation). I checked the Python documentation to see if this is etched in stone and can be depended upon, but I saw nothing (am I just missing it?) in section 6.3. ...In fact, I saw nothing about chained assignments in that section (where I would have thought it would be) at all. So to my "dumb question" -- is this behavior indeed etched in stone? And if so, where can I find the stone tablet? (Not in section 6.3 of the language reference, unless I am mistaken.) Just curious, Manus From peter at engcorp.com Sat Mar 22 09:28:20 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 22 Mar 2003 09:28:20 -0500 Subject: Converting time from GMT to another timezone References: <17aafe08.0303211412.1bf76abb@posting.google.com> <3E7B92CA.360821AD@engcorp.com> Message-ID: <3E7C7304.627A6DA2@engcorp.com> William Park wrote: > > Peter Hansen wrote: > > Really, it's unclear what you are trying to do. > > Yet, you gave an answer. God, it's amazing that Python can even raise > one's telepathetic powers. I think you forgot a smiley. From ycal at grapevine.net Sat Mar 1 12:46:45 2003 From: ycal at grapevine.net (Phil Lacy) Date: Sat, 1 Mar 2003 11:46:45 -0600 Subject: how to debug a python program normally run in windows console References: <3e60e5a4_1@newsfeed> Message-ID: <3e60f082_3@newsfeed> vincent wehren posted in news:b3qqd7$h37$1 at news1.tilbu1.nb.home.nl > > Maybe you could try setting the environment from within the python > file, using os.environ I thought about that, thanks for the language help, saves a newby some time. - Phil -reverse ycal for email- -For MSACCESS, comments are made -regarding vers9.0 (2000) UON - From tweedgeezer at hotmail.com Wed Mar 19 18:43:54 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 19 Mar 2003 15:43:54 -0800 Subject: Incomparable abominations (was: python-dev Summary) References: Message-ID: <698f09f8.0303191543.46ab8e5a@posting.google.com> mertz at gnosis.cx (David Mertz, Ph.D.) wrote in message news:... > [snip] > Yours, David... I can't say much more than, "I concur." It seems completely un-Pythonic to me to restrict comparisons to happen only between "compatible" types. Jeremy From ejy712 at comcast.net Fri Mar 14 17:43:31 2003 From: ejy712 at comcast.net (Ed Young) Date: Fri, 14 Mar 2003 17:43:31 -0500 Subject: Authentication Using Rotor Message-ID: I am writing a distributed application in Python which uses sockets to transfer data. I would like to authenticate the sender when a socket connection is made. The best I have come up with so far is to have identical keys at both the sender and the receiver. The receiver would send a random integer challenge to the sender. The sender would encrypt the challenge and return it. The receiver would also encrypt the challenge integer and compare it with what the sender returned. If they compare the connection would be allowed to continue. The Python supplied encryption module is 'rotor', which I propose to use for encrypting the challenge. This mechanism will have to work across all platforms on which Python runs. Is this a reasonable approach to authentication? Is there a standard, builtin, or better way to do this? If this is a resonable approach, any ideas for key generation, or for that matter generating a truely random challenge integer? I recognize the need to authenticate, but I haven't quite figured out how to practically accomplish it yet. Thank you for your thoughs on this problem... From skip at pobox.com Thu Mar 20 17:37:25 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 20 Mar 2003 16:37:25 -0600 Subject: Am I misusing socket.setdefaulttimeout here? In-Reply-To: References: <15994.253.243228.801114@montanaro.dyndns.org> <15994.2526.608123.910861@montanaro.dyndns.org> <15994.8937.625199.527667@montanaro.dyndns.org> Message-ID: <15994.17061.481529.877840@montanaro.dyndns.org> Syver> I was under the definite impression that timeoutsocket also Syver> worked by putting the socket in blocking mode. You meant non-blocking mode, yes? Syver> And httplib doesn't use the file interface to the socket library Syver> as far as I can remember. >From httplib.py: class HTTPResponse: def __init__(self, sock, debuglevel=0, strict=0): self.fp = sock.makefile('rb', 0) ... Then later: def _read_status(self): # Initialize with Simple-Response defaults line = self.fp.readline() Later still: def read(self, amt=None): if self.fp is None: return '' if self.chunked: return self._read_chunked(amt) if amt is None: # unbounded read if self.will_close: s = self.fp.read() else: s = self._safe_read(self.length) self.close() # we read everything return s Need I continue? ;-) Syver> The point I am trying to make here is that I don't see why things Syver> that worked with timeoutsocker should stop working on the new Syver> socket with timeout mode. Timeoutsocket implements a file-like abstraction (TimeoutFile) directly on top of the socket without calling the socket's makefile method. It implements write, read, readline, readlines and flush methods. I suspect this would work for the socket module as well, though there are probably some subtle semantic differences between how TimeoutFile the file-like objects returned by sock.makefile operate. Skip From tim.one at comcast.net Thu Mar 13 12:10:30 2003 From: tim.one at comcast.net (Tim Peters) Date: Thu, 13 Mar 2003 12:10:30 -0500 Subject: Threads with independant IO streams In-Reply-To: <3E70BAF7.EDAC3781@pobox.com> Message-ID: [Jason Harper] > Is it possible for multiple Python threads to have their own sys.stdout > (and other streams), such that plain `print' statements in each thread > send output to different places? Probably, but it wasn't designed to. > I have managed to create a separate sys module for each thread (using an > import hook much like rexec uses), and can have sys.stdout.write() > output go to different places, but print output still goes to the stdout > defined in the 'real' sys module. The print statement passes the object to be printed to sys.displayhook() for display. You could try supplying your own displayhook function. From rnd at onego.ru Wed Mar 5 16:22:28 2003 From: rnd at onego.ru (Roman Suzi) Date: Thu, 6 Mar 2003 00:22:28 +0300 (MSK) Subject: Speed *triples* by changing 'apply(f, args)' to 'f(*args)' In-Reply-To: Message-ID: On 5 Mar 2003, Aahz wrote: >In article , >Tim Peters wrote: >> >>There's more than meets the eye: because the apply() builtin is >>deprecated now, the implementation of __builtin__.apply() now calls >>warnings.warn() (a Python function) to see whether it should issue >>a deprecation warning. So the former also costs a new hidden call >>to a long Python function now, which in turn does many lookups and >>additional calls (both C and Python level) of its own. Luckily, >>Gerritt already figured out the best fix . > >Ouch. Should we consider postponing the official deprecation of apply() >for one more release? I'm concerned about the possible speed of the >logging module. Wow! apply() is going to be deprecated! Faster lane is under construction! ("there is only one obvious way") >>> def today1(*fff): print fff ... >>> today1(*[2]) (2,) >>> def today2(**fff): print fff ... >>> k = {'a':1,'b':2,'c':3} >>> today2(**k) {'a': 1, 'c': 3, 'b': 2} >>> def tomorrow(fff): print fff() ... >>> tomorrow(:len('123')) 3 i-need-to-read-c.l.p-more-frequently-yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by Linux RedHat 7.3 From tebeka at cs.bgu.ac.il Tue Mar 11 03:14:26 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 11 Mar 2003 00:14:26 -0800 Subject: Need some basics References: Message-ID: <33803989.0303110014.2009bd02@posting.google.com> Hello L.B, > I'm quite a newbie in programming and i'm soon getting tired of the VB > crap (and that's why i'm learning Python)... i'd like, someday, to > define myself a programmer, but i feel i'm missing some valuable > basics of computer science: algorithms, data-structures, software > engeenering... and when thinking about making even a simple game (like > tic-tac-toe) i found myself screaming just for thinking how it should > be done. > > So here is the question... assuming that i'm too old (26) for going > back to college and study something else that Politics and Economics > which doesn't seem to be anything computer-related ;-) which book > should i study, which books shouldn't miss from a serious programmer's > bookshelf? 1. http://mitpress.mit.edu/sicp/full-text/book/book.html 2. Read a lot of code. A good place to look is the standard library. HTH. Miki From maxm at mxm.dk Sun Mar 9 14:22:24 2003 From: maxm at mxm.dk (Max M) Date: Sun, 09 Mar 2003 20:22:24 +0100 Subject: tal template engine in python out of zope In-Reply-To: <20030309090638147-0500@braeburn.themorgue.org> References: <20030309090638147-0500@braeburn.themorgue.org> Message-ID: Kevin Smith wrote: > How convenient... I just released a package like this last week. > > http://zpt.sourceforge.net/ That looks great! -- hilsen/regards Max M Rasmussen, Denmark http://www.futureport.dk/ Fremtiden, videnskab, skeptiscisme og transhumanisme From gustav at morpheus.demon.co.uk Thu Mar 6 15:32:38 2003 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: Thu, 06 Mar 2003 20:32:38 +0000 Subject: Thread processing References: <8yvty3v0.fsf@morpheus.demon.co.uk> <87vfyw95sz.fsf@cassandra.evansnet> Message-ID: Tim Evans writes: > Paul Moore writes: > [snip] >> Look at this another way, then. Are there any examples of thread pool >> frameworks around which I could use as a starting point? I have >> searched round and found nothing much (Aahz has some specific examples >> on his site, but nothing generic, the cookbook doesn't have anything, >> where else could I look?) > > Well, I was bored, so here's one I just threw together. You can > subclass 'Task' the same as you would threading.Thread to store extra > state, or just pass a function and arguments as in the example. *sulk* I spent all day yesterday trying to get something like this right. You were "bored"??? Seriously, thanks for this - it makes it a lot clearer. I'd got so close to the problem I'd completely lost track of the overall picture. I should be able to sort out my problem a lot better based on the ideas from this. Paul. -- This signature intentionally left blank From abpillai at lycos.com Mon Mar 24 06:25:27 2003 From: abpillai at lycos.com (Anand B Pillai) Date: 24 Mar 2003 03:25:27 -0800 Subject: Iraqis Greeting Americans with Kisses & Handshakes? -----{[++]}-------- oxuvcaky References: Message-ID: Yeah... And I am proud to be a couch potato watching 'poor' iraqis being 'delivered' from the pythonic hug of 'evil' Saddam by an 'angelic' Bush with his 'instruments of peace' ... Huh! Sounds very ironic... bombs as instrument of 'peace'! Not a very inappropriate post I shud say! Anand Pillai Matthew wrote in message news:... > I agree absolutely. My post was not intended to minimise or belittle the > incredible serious situation of war in Iraq - rather it was intended to > poke fun at what was an obviously absurd and misguided troll. I > apologise if people have found my post offensive. matthew. > > Thomas Weholt wrote: > > I do believe it would be in the best interest of this group to post > > questions and things related to python only. The Iraq-US/UK War-discussion > > could very easily turn into a big mess, generate lots of traffic and take > > focus away from Python-development, where it should be. > > > > Thomas > > From achrist at easystreet.com Fri Mar 21 13:26:48 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Fri, 21 Mar 2003 10:26:48 -0800 Subject: Object oriented databae for Python References: <3E7A12BA.3A297B2F@easystreet.com> <3E7B38A5.B54F82BE@easystreet.com> Message-ID: <3E7B5968.6E421A5A@easystreet.com> Konstantin Knizhnik wrote: > > I have rebuild DyBASE with LIBC (instead of MSVCRT)? > Can you check if it fix the problem? > New version canbe uploaded from my site > www.garret.ru/~knizhnik/dybase.html > I can't check this, because your binary requires python23.lib and I've got python22.lib installed. I guess that I'll be caught up with you on that soon after a release comes out. Someone else maybe? Al From intentionally at blank.co.uk Thu Mar 13 18:44:34 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Thu, 13 Mar 2003 23:44:34 +0000 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <3E629E93.B94F7631@alcyone.com> <0bkv6v8akrd0db5i66eu685t5pmviuf0bk@4ax.com> <4fm07vg66gr4o4c74gb7ie5v85vlom1vhf@4ax.com> Message-ID: <0vv17v4vn4khffgr2io0otrnni8sc6rug7@4ax.com> I'm sorry for the way I responded this morning - I was in a bad mood for reasons that were not your fault. However... On Thu, 13 Mar 2003 11:54:55 GMT, Alex Martelli wrote: >Stephen Horne wrote: > ... >>>> I don't really see the relevance of the fact that "'lambda' never >>>> starts a line". Other frequently used words (such as built-in function >>>> names) also never start a line - 'reduce' is as long as 'lambda' for a >>> >>>Some built-in function names OFTEN "start a line" -- setattr, for >>>example (you're far more rarely going to use setattr EXCEPT at the >>>start of a line). >> >> So what? - some keywords not only OFTEN but ALWAYS start a line. > >So, the assertion that built-in function names never start a line >is incorrect. I never made that assertion, though on further examination I see why you thought I did. My words were "Other frequently used words (such as built-in function names) also never start a line". I did not say "_all_ built-in function names". Neither did I say "_some_ built-in function names". That part was not clarified because, in context, it was unnecessary - _all_ or _some_ makes no difference to the point I was making - and because the _some_ was, to me, implied by common sense anyway. Context pervades all natural language. That is why the (sadly highly subjective) thing called common sense is so important to natural language communication, and an important reason why natural language can never be a perfect medium of communication. One of the things I like about Steven Pinkers "The Language Instinct" and "Words and Rules" is the healthy disrespect that he, as a linguistics expert, has towards language pedantry and particularly towards "language mavens" as he calls them. "Words and Rules" is, in my opinion, actually quite a dull book relative to his others - mainly because I'm already familiar with the formal grammar concepts that he describes so painfuly slowly - but at a few points he certainly had me laughing out loud at his descriptions of how the pedants completely miss the point. Anyway, the fact that many built-in function names can start a line is common sense to me as Python has no equivalent to the Pascal distinction between functions and procedures. Hence I didn't feel any need to clarify "some" built-in functions. Hence, when you 'corrected' me, implying that I didn't know this common sense thing, I felt insulted and - in my already bad mood - I overreacted. Once again, I am sorry for that. Now I think about it, most built-in functions probably return a value (I can't be bothered checking, but most of the ones I can think of off the top of my head do anyway). While some of those may still be used (or abused) for their side effects, a person might reasonably consider that functions that can appear at the start of a line are exceptional. We then get into the subjective nature of common sense, and how I really wish I wasn't in such a foul mood this morning. From martin.vonloewis at hpi.uni-potsdam.de Wed Mar 26 06:17:10 2003 From: martin.vonloewis at hpi.uni-potsdam.de (Martin v. Löwis) Date: Wed, 26 Mar 2003 12:17:10 +0100 Subject: Extension Debugging References: <8ced17b6.0303260229.19195de8@posting.google.com> Message-ID: > I'm working with a set of DLL extension modules which mask the > Dialogic telephony API. They have been compiled using Visual Studio > (.NET), and they are being run on windows nt 4.0 with python 2.2. That won't work, in many cases. Python 2.2 was compiled with VC++ 6, and such code does not mix well with VC.NET. So I recommend you either recompile Python, or use VC++ 6 to compile your extension module. > occasionally it crashes with this, information: The instruction at > "0x00000008" referenced memory at "0x00000000". The memory could not > be "read". the addresses are always the same, looks to be a NULL > pointer thing, I've been lucky so far to discover as many of these > errors as I have - this one eludes me still. Can you run this in a debugger an obtain a stack trace of the point of crash? Regards, Martin From maxm at mxm.dk Wed Mar 12 02:57:02 2003 From: maxm at mxm.dk (Max M) Date: Wed, 12 Mar 2003 08:57:02 +0100 Subject: lambda question In-Reply-To: References: Message-ID: <3E6EE84E.5040307@mxm.dk> Andrew Koenig wrote: > I must confess that > > title = lambda s: " % " % s > > doesn't strike me as being any simpler than > > def title(s): return " % " % s > > which, in turn, I find slightly less readable than > > def title(s): > return " % " % s One could even argue that it is even more readable to skip the lambda alltogether: s = 'The Title' title_tag = ' %s ' print title_tag % s >>> The Title If it is simple enough to put into a lambda, it is probably simple enough to just use string substitution directly. -- hilsen/regards Max M Rasmussen, Denmark http://www.futureport.dk/ Fremtiden, videnskab, skeptiscisme og transhumanisme From mertz at gnosis.cx Mon Mar 3 18:17:43 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Mon, 03 Mar 2003 18:17:43 -0500 Subject: Can __iter__ be used as a classmethod? References: Message-ID: "Bjorn Pettersen" wrote previously: |I would like to be able to traverse the content of a class (not an |instance) using a regular for loop: "for item in MyClass:...". If you want to add methods to a *class*, you create the class using a custom metaclass: % cat classiter.py from __future__ import generators class ClassIter(object): vals = ['a', 'b', 'c'] class __metaclass__(type): def __iter__(cls): print 'iter' return cls.items() def items(cls): print 'items' for item in cls.vals: yield item items = classmethod(items) for x in ClassIter: print x % python classiter.py iter items a b c Yours, Lulu... -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! ------------------------------------------------------------------------- From thomas at xs4all.net Wed Mar 12 08:56:23 2003 From: thomas at xs4all.net (Thomas Wouters) Date: Wed, 12 Mar 2003 14:56:23 +0100 Subject: Tuples, what are they: read-only lists or heterogeneous data arrays? In-Reply-To: <20030312130239.GA2531@nl.linux.org> References: <15982.24855.181016.568236@montanaro.dyndns.org> <200303111449.42035.fincher.8@osu.edu> <200303120211.h2C2BCH28989@pcp02138704pcs.reston01.va.comcast.net> <20030312130239.GA2531@nl.linux.org> Message-ID: <20030312135623.GW2112@xs4all.nl> On Wed, Mar 12, 2003 at 02:02:39PM +0100, Gerrit Holl wrote: > Guido van Rossum wrote in Python-Dev: > > Tuples are for heterogeneous data, list are for homogeneous data. > > Tuples are *not* read-only lists. > This makes me wonder. Yes, taking Guido too seriously can have that effect on people <1.1 wink> The trick is in knowing when Guido is proscribing dogmatic law, and when he is describing his intent when he designed feature(tte)s of Python, or his point of view at this moment, or how he wished people would see it, or reacting to what he had for lunch. He's just human, you know, and no more infallible than the best of us. I think it may be safer for the general populace (and healthier for their faith in Python) if Guido would post under a pseudonym instead :) -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! From johnroth at ameritech.net Fri Mar 21 10:27:37 2003 From: johnroth at ameritech.net (John Roth) Date: Fri, 21 Mar 2003 10:27:37 -0500 Subject: What's up with rebinding assignment? References: Message-ID: "Beni Cherniavsky" wrote in message news:mailman.1048248875.10571.python-list at python.org... > Once upon a time, Just threw in a great (IMHO ;-) idea on pytohn-dev: > > http://mail.python.org/pipermail/python-dev/2003-February/032764.html > > The idea was to add am ``:=`` rebinding operator, one that changes a > visible binding without making it local to the current scope:: > > def bind(): > x = 1 > def rebind(): > x := 2 > rebind() > print x > > would print 2. > > Futhermore, augmented assignments can become always rebinding with > almost no breakage of code:: > > def bind(): > x = 1 > def rebind(): > x += 1 > rebind() > print x > > Currently this makes `x` local to `rebind` and raises an exception > because `x` is not initialized there; so no working code can change > its meaning (unless you do evil locals() manipulations perhaps). > > Using ``:=`` (but not augmented assignments) for names that are > already local to the current scope should probably be forbidden -- it > adds nothing and somebody would think it gives write-only access to > shadowed variables. > > This seems a very sound addition that will remove the need for the > ugly singleton-list hack:: > > def bind(): > x = [1] > def rebind(): > x[0] += 1 > rebind() > print x[0] > > My question is: is there a chance this will make it into Python? > Nobody seems to have noticed it... Will a PEP help? Two (or maybe three) thoughts. 1. I'd be very strongly against it, unless it was limited to static scoping. I can think of uses for this, but allowing any function to modify variables further up in the calling chain promiscuously is asking for trouble. Limiting it to static scope reduces the possibility of it causing trouble. That does, of course, mean that it could only be used in an embedded function, and that the embedded function couldn't be passed out to the caller. 2. I'm not certain I like the syntax. 3. I like the notion of an abbreviated notation for rebinding things at the instance or module level, however. By all means, submit a PEP. That's the formal way of getting things into the pipeline. John Roth > > -- > Beni Cherniavsky > From donn at drizzle.com Tue Mar 18 11:33:52 2003 From: donn at drizzle.com (Donn Cave) Date: Tue, 18 Mar 2003 16:33:52 -0000 Subject: Finding child pids References: Message-ID: <1048005232.53570@yasure> Quoth Ben Hutchings : | In article , Bernhard Herzog wrote: | | [re popen] |> Don't use a string. Use a list of strings with one string for each |> argument. E.g. instead of |> |> "mycommand arg1 arg2" use ["mycommand", "arg1", "arg2"] |> |> This has the additional benefit that you don't have to worry about |> quoting. | | Aha! Unfortunately this does not appear to be documented. (In fact I | don't see any documentation of the type of the command given to popen.) Well, note that it doesn't apply to popen - only to popen2 et al. But still, it does not seem to be as well documented as it should be, considering that this has important security consequences. Donn Cave, donn at drizzle.com From ruediger.maehl at web.de Thu Mar 13 05:18:28 2003 From: ruediger.maehl at web.de (Rüdiger Mähl) Date: 13 Mar 2003 10:18:28 GMT Subject: 2 UK Jobs References: Message-ID: Robin Becker wrote: > http://www.gojobsite.co.uk/showvac/3fGk0m/10429047/911177485 Hello Robin, is the mentioned 'client' perhaps a well known company that works in the field of reporting/PDF document generation? ;-) Ruediger From cartermark46 at ukmail.com Thu Mar 13 08:35:26 2003 From: cartermark46 at ukmail.com (Mark Carter) Date: 13 Mar 2003 05:35:26 -0800 Subject: ImportError: cannot import name Encoders Message-ID: I'm using: Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 I tried the email example in section 12.2.10, which begins: import smtplib # Here are the email pacakge modules we'll need from email import Encoders from email.MIMEText import MIMEText ... etc. but I get the error message: ImportError: cannot import name Encoders Is this a bug? If not, then what's going on? Thanks in advance. From abli at freemail.hu Tue Mar 25 17:11:44 2003 From: abli at freemail.hu (Abel Daniel) Date: Tue, 25 Mar 2003 23:11:44 +0100 Subject: Center new windows In-Reply-To: References: Message-ID: <20030325221144.GB1644@hooloovoo> richard.a.charts.1 wrote: > Hi, > I have a fairly quick question that I haven't been able find the answer > for. When opening a new window, how can I force it to open in the center > of the screen? > > I have searched through old messages but most are over 2 years old and I > am wondering if there has been changes for the better? If you mean the ones returned by google groups when searching for -tkinter center screen- then I guess there isn't anything easier. (at least i didn't hear of one, not that this means anything :) ) > On a small side note: > How does geometry work with a given widget? Whenever I try to use it, > Python says that some class has no instance of geometry or withdraw or > others for that matter. To me it looked like only instances of Toplevel have the methods you mention. Those methods deal with displaying windows, so they don't really make sense for a Listbox widget, for example. Abel Daniel From max at alcyone.com Sat Mar 29 11:33:43 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 29 Mar 2003 08:33:43 -0800 Subject: Function attributes: a bug? References: Message-ID: <3E85CAE7.AE18CFA6@alcyone.com> Tj wrote: > But there's a bug -- if I generate a function using this, use it for a > while to build up a list, then call make_list_accum() again, it will > want to init itself with the other list by default, sharing it! This > is surprising behavior, and doesn't happen if I don't use this > optional init form. This doesn't have anything to do with functio attributes; what you're discovering is that default arguments are only evaluated once: >>> def f(x, l=[]): ... l.append(x) ... print l ... >>> f(1) [1] >>> f(2) [1, 2] >>> f(3) [1, 2, 3] When the default argument is mutable, and you want to make sure you don't run into this issue, use an immutable sentinel in the argument and test for it in the body: >>> def g(x, l=None): ... if l is None: ... l = [] ... l.append(x) ... print l ... >>> g(1) [1] >>> g(2) [2] >>> g(3) [3] -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Divorces are made in Heaven. \__/ Oscar Wilde Bosskey.net: Counter-Strike / http://www.bosskey.net/cs/ A personal guide to Counter-Strike. From simon at uggs.demon.co.uk Fri Mar 7 20:46:45 2003 From: simon at uggs.demon.co.uk (Simon Foster) Date: Sat, 08 Mar 2003 01:46:45 GMT Subject: Socket connection References: Message-ID: <3e6a4b62.41009638@news.dsl.pipex.com> On Fri, 07 Mar 2003 08:59:39 -0600, sik0fewl wrote: >Hey, > >I fixed the problem, thanks for your input, guys. It problem ended up >having to do with assigning a list to another list. (That's what I get >for not posting all my code) > >I had no idea that x = y just references y to x (when x & y are lists). >ie, > >>> x = [] > >>> y = x > >>> id(x) >17763920 > >>> id(y) >17763920 > >Could somebody point me to the documentation on this? Here is the documentation: "In Python, everything is a reference" -- Simon Foster Somewhere in the West of England From andrew.henshaw at gtri.gatech.edu Sat Mar 1 22:48:35 2003 From: andrew.henshaw at gtri.gatech.edu (Andrew Henshaw) Date: Sat, 01 Mar 2003 22:48:35 -0500 Subject: Code speedup tips References: Message-ID: Carl Banks wrote: > Sean Richards wrote: >> Hi, > ...snip... > # Apply the rule > for step in xrange(Steps): > # In the workspace, add the shifted lattices > # This uses a bunch of += because it's faster > workspace[:] = left > workspace[:] += up > workspace[:] += right > workspace[:] += down > # Set the current lattice > current[1:-1,1:-1] = where(workspace,1,0) > You also might want to use bitwise or, so that you can elimnate the 'where' step # Apply the rule for step in xrange(Steps): workspace[:] = left workspace[:] |= up workspace[:] |= right workspace[:] |= down # Set the current lattice current[1:-1,1:-1] = workspace From a.schmolck at gmx.net Thu Mar 6 15:21:12 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 06 Mar 2003 20:21:12 +0000 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <58q36vgv1ga8ovde5ftub9t8ugaa2pnum5@4ax.com> <3E62778F.EED49083@alcyone.com> <3E629E93.B94F7631@alcyone.com> <3E63AFA0.A3CAC045@alcyone.com> Message-ID: Erik Max Francis writes: > But that has no bearing on whether Python should also have a compact form > _for the sole purpose of being compact_. No one suggests such a thing! I think there are maybe 4 different levels at which the mere conciseness of a construct FOO (with a hypothetical, more verbose alternative, FOO_VERBOSE) can affect a language: 1. FOO is used in the same places as FOO_VERBOSE would, but the code becomes more (or less) readable (e.g. ``Bignum(1).add(3)`` 'vs' ``1l + 3``) 2. FOO is used in places where FOO_VERBOSE wouldn't be used, because it is too cumbersome (e.g. I'd wager that people more readily use dicts in python than HashTables in java). 3. FOO's conciseness affects the design of interfaces of other functions (so that they become in some way better, or more general -- e.g. `ifAbsent` vs `.get`). 4. FOO's conciseness renders certain hypothetical language extensions unnecessary (e.g. control construct syntax, and to some extent even macros, in smalltalk). Now 3 and 4 are of course quite rare, (but all other things being equal), rather desirable. I think smalltalk's blocks satisfy all 4 (and smalltalk, although different, is not completely unlike python). Of course adding a (amongst other things, highly syntactically constrained and possibly rather restricted) lightweight anonymous function equivalent to python at this stage might not be worth while the trouble (and increase in complexity). Also, as you and others remarked, certain syntactic possiblities might be errorprone or unreadable. Nonetheless, I think the ability to easily pass chunks of code around (and no -- lambda does not qualify; or I'd like to see how you rewrite a smalltalk program by replacing blocks with something like lambda) that close over the current environment, even if added to python now, is unlikely to affect the only point 1 (as you seem to imply). alex From mwh at python.net Tue Mar 11 11:28:19 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 11 Mar 2003 16:28:19 GMT Subject: Flying With Python (Strong versus Weak Typing) References: <37a869bc.0303102102.4533973@posting.google.com> <1047398589.950487@yasure> Message-ID: <7h31y1door7.fsf@pc150.maths.bris.ac.uk> "Donn Cave" writes: > This seems to be a matter of one's faith in some set of techniques > that an engineering team can use to write correct software. The > Python world seems to place a great deal of faith in testing. > Statically typed languages can test, too, so the bottom line must > be whether testing is such a perfect solution that anything else - > like computer analysis of the program for structural correctness - > is irrelevant. Interesting question. I don't understand testing, > to me it seems highly vulnerable to human weaknesses like making > invalid assumptions, and it seems vulnerable to inaccuracies in > the simulation of the program's intended environment. I think the claim most safely attributed to the XP way is that test-heavy development makes it *easier* to write correct programs, not that it makes it *easy*. There's definitely an art to writing effective tests. > I have a vague impression that Ada is commonly specified for work > in this area, but I don't know that language, and perhaps not a > lot of others here do either since we regularly see C++ cited as > the example of a statically typed language. That's unfortunate, > since its type system is clumsy and ineffective. ML would probably > be a better example of a powerful static type system. Indeed. There's also an art to using a powerful type system such as MLs effectively. Dynamic typing folks often rubbish static typing folks' claim that the compiler catches many errors, but the dynamic typing folks probably aren't as good at using the type system, aren't so good at structuring their program so that the type system is in the best possible position to catch as many errors as it can. Conversely, static typing people who claim that without the backup of compile time checks you can't possibly write a reliable program probably aren't used to structuring their programs to allow easy unit testing. They also have to deal with ignoramuses who think that C++ has the most advanced static type system on the planet. I, of course, know the perfect way to develop software, but will only tell you after I've made my fourth billion. Cheers, M. -- We've had a lot of problems going from glibc 2.0 to glibc 2.1. People claim binary compatibility. Except for functions they don't like. -- Peter Van Eynde, comp.lang.lisp From rmunn at pobox.com Mon Mar 31 13:14:48 2003 From: rmunn at pobox.com (Robin Munn) Date: Mon, 31 Mar 2003 18:14:48 GMT Subject: Catching webbrowser error in RedHat References: Message-ID: Lance wrote: > Hi All, > > I'm running Python 2.2 under RedHat8. I use webbrowser to open an html file > in a browser window. This is my code: > > try: > webbrowser.open(fname) > except: > print "ERROR: "+fname+" not found." > > 1. A Redhat "splash" screen shows for a few seconds prior to my desired > screen when try block is successful. Can this splash screen be disabled? Reading the API documentation for the webbrowser module (http://www.python.org/doc/current/lib/module-webbrowser.html), I don't see any way within Python of setting options on the browser. You need to consult the Red Hat documentation for this one -- this is not a Python issue. By the way, you really shouldn't be using a bare "except:" -- you'll catch exceptions that you really didn't mean to catch. Use "except webbrowser.Error:" instead. > 2. If the try block is not successful, the Redhat splash screen shows, > followed by an ugly system message box saying that the file could not be > found. I want only the message in my except clause to display, not the > system message. Apparently your browser (which one is it? Netscape? Mozilla? Galeon?) doesn't return an error code to the calling application on "URL not found" conditions. Again, not something you can change within Python. Check your system documentation. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From marklists at mceahern.com Mon Mar 10 12:43:12 2003 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 10 Mar 2003 11:43:12 -0600 Subject: Testing for a list In-Reply-To: Message-ID: [Antun Karlovac] > Is there a way to test if a variable is a list? > > i.e. > > a = [] > > If I have 'a', I need to know whether it is a list or a string. Here's a unittest-demo of the code Alex posted here: http://groups.google.com/groups?selm=hi018.2207%24Qu1.90579%40news2.tin.it #!/usr/bin/env python import unittest def issequence(item): try: item + '' except TypeError: try: for x in item: break except TypeError: return False else: return True else: return False class test(unittest.TestCase): def test_unicode(self): u = u'test' self.failIf(issequence(u)) def test_string(self): s = 'string' self.failIf(issequence(s)) def test_list(self): l = [] self.failUnless(issequence(l)) def test_tuple(self): t = () self.failUnless(issequence(t)) if __name__ == '__main__': unittest.main() - From aleax at aleax.it Fri Mar 28 06:08:01 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 28 Mar 2003 11:08:01 GMT Subject: Beginner Question References: <8gSga.236197$L1.65045@sccrnsc02> Message-ID: Kevin Reeder wrote: > On Thu, 27 Mar 2003 20:45:04 -0800, Lee Harr wrote: > >> Well... it is not just the last line, but I think the best way would be: >> >> import random >> def shuffle(self): >> random.shuffle(self.cards) > > This one failed to work with the exception: Attribute error: shuffle. > Probably something I'm not seeing. Weird. Can you please try to reproduce the error "in the small" and just copy and paste it to a post rather than summarizing it? For me it works just fine, e.g.: >>> import random >>> def shuffle(self): ... random.shuffle(self.cards) ... >>> class X: ... cards = list('pacilokeruny') ... >>> shuffle(X) >>> X.cards ['u', 'k', 'r', 'y', 'a', 'e', 'c', 'o', 'l', 'p', 'i', 'n'] >>> What happens when YOU try this exact code? If this works and your script doesn't, what's the essential difference that breaks your script? >> def shuffle(self): >> import random >> nCards = len(self.cards) >> for i in range(nCards): >> j = random.randrange(i, nCards) >> self.cards.insert(i, self.cards.pop(j)) > > This solution worked great. Is insert a list method? Yes, it is. But in your shoes I'd invest more effort in trying to make random.shuffle work -- it's going to be faster (with Tim Peters having programmed it, that's almost guaranteed;-) AND you're going to feel more secure in its correctness (ditto) -- this one does seem OK, but inspection might miss some subtle issue... using solid modules from the standard library is just safer!-) Alex From gerrit at nl.linux.org Tue Mar 11 14:43:31 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 11 Mar 2003 20:43:31 +0100 Subject: Condorcet analysis of Official PEP308 Ballots In-Reply-To: <3E6DF10A.ADF57FD9@engcorp.com> References: <1047367657.1029.297.camel@chomsky> <3E6DF10A.ADF57FD9@engcorp.com> Message-ID: <20030311194331.GA3263@nl.linux.org> Peter Hansen schreef op dinsdag 11 maart om 15:26:52 +0000: > We wouldn't have Python without Guido's excellent judgment in the past, > and it's time for him to exercise it again, regardless of the specific > outcome of "the vote" (but taken it into account perhaps). And there's > yet another sense in which "obviously a vote isn't the most important > thing" (i.e. Guido's decision _is_). Interestingly, I think he's right regardless what he decides ;) yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From maxx at easynews.com Tue Mar 11 17:12:27 2003 From: maxx at easynews.com (Max) Date: Tue, 11 Mar 2003 22:12:27 GMT Subject: Flying With Python (Strong versus Weak Typing) References: <37a869bc.0303102102.4533973@posting.google.com> <95cs6vo5k8rm15cd1iv0389kqfa2d2k7ht@4ax.com> Message-ID: On Tue, 11 Mar 2003 21:46:04 +0100, "GerritM" wrote: >So maybe there exists a relation after all? Good programmers know Python, so >with Python the probability of having a good programmer is higher :-) ? You might be on to something there. I see a lot of programmers attempt languages because of the popularity/visibility of the language. Their discovery of languages is often driven by the number of times the language is mentioned in the press, or how frequent it is called for on job search sites. Python tends to be less visible, so perhaps there is some substance to a theory that states that for a programmer to become aware of Python, they often have have a certain amount of industry experience, and therefore exposure, to less known, but superior tool. In other words, more programmers shop at Wal-Mart. From mertz at gnosis.cx Fri Mar 28 22:51:26 2003 From: mertz at gnosis.cx (David Mertz) Date: Fri, 28 Mar 2003 22:51:26 -0500 Subject: Nice quote References: Message-ID: <+gRh+kKkX0ZD092yn@gnosis.cx> "Jeremy Bowers" wrote previously: |Personally, I've been noodling around with the idea of some sort of |declarative syntax where you tell the parser what you're expecting and it |presents you with an object model constructed using classes you give |it. You might want to look at Gnosis Utilities, both gnosis.xml.validity and gnosis.xml.objectify. For discussions, see: http://gnosis.cx/publish/programming/xml_matters_20.html http://gnosis.cx/publish/programming/charming_python_b11.html http://gnosis.cx/publish/programming/xml_matters_11.html http://gnosis.cx/publish/programming/xml_matters_2.html Maybe I discussed the issues elsewhere too. The actual download is: http://gnosis.cx/download/Gnosis_Utils-current.tar.gz Not that I think Tim Bray was talking about my stuff, even indirectly. But I'm still proud of these modules. Yours, David... -- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th. From dbrown2 at yahoo.com Thu Mar 27 19:27:15 2003 From: dbrown2 at yahoo.com (dbrown2 at yahoo.com) Date: 27 Mar 2003 16:27:15 -0800 Subject: Beginner: How to copy a string? Message-ID: I hate to ask this because the answer must be really obvious. So obvious in fact that I couldn't find it in the tutorial, FAQ search, and other docs, google searches, etc. I just want to make a copy of a string, say s='abc'. I understand that python is not like some other languages and '=' just assigns a name to an existing object and does not copy the object. But there is no s.copy() method apparently. The other intuitive way (to me) was to try str(s) which I think is similar to the way to copy some other types such as list(). That did not work. I did see a newsgroup post that said to use [:] and I tried it but this is what I get: s = 'abc' >>> id(s) 13356752 >>> t = s[:] >>> id(t) 13356752 >>> t 'abc' Just like with str() it looks like it's still the same object. Ok, so what's the trick. Please be kind. It's really not obvious to me. In fairness I did see in the FAQ you could convert it to a list and rejoin it which I assume would work, but I suspect there is a more direct way. -- David From eric.brunel at pragmadev.com Wed Mar 19 04:23:33 2003 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 19 Mar 2003 10:23:33 +0100 Subject: Tkinter and School Project References: <87050d3a.0303181139.68586c3b@posting.google.com> Message-ID: Melissa wrote: > I need serious help on my project. > > Here is what I am trying to make...An Address book. > > I want you to be able to search by last name and have all possible > people to show up in the top list box. Then you should be able to > click on the name and the information will appear in the bottom area. > > Here is what I have so far. > I am very new at this and dont really know what I am doing. I have it > "looking good", but is doesnt work. > > Could someone PLEASE help me with this. You were quite close: > # This file is named melissaproject.pyw > from Tkinter import * > import tkMessageBox > from tkSimpleDialog import * > from tkFileDialog import * > from ScrolledText import * > import newrecord > def openwindow (event): > newrecord.dialog() > def closeit(event): > root.destroy() > def findname(event): > thelist1.delete(0,END) > thename = findit.get() > x = open("C:\\python22\\addyfile.txt","r") > for y in x: > q = y.split(",") > if thename == q[1]: > thelist1.insert(END,y) > x.close() > def showit (event): > person = thelist.get(ANCHOR) > x = person.strip().split(',') > def readit(event): > thelist.delete(0,END) I think you want theList1 and not theList here. > x = open('c:\\python22\\addyfile.txt','r') > for y in x: > thelist.insert(END,y.strip()) Same here. > x.close() > root = Tk() > root.title("Easy Address Finder") > root.geometry('500x400') > b =Frame(root, bd = 3, bg='darkblue') > b.pack(side='top', fill = 'x') > findit = Entry(b, width=30) > find = Button(b, text = "SEARCH") > record = Button(b, text ="NEW RECORD") > record.bind('',openwindow) This should work, but it's not the way things are usually done. Use preferably the "command" option in buttons: record = Button(b, text ="NEW RECORD", command=openwindow) But note with this option, the "event" parameter in your functions above is not needed anymore. So you may remove it or give a default value (e.g. "def openwindow (event=None)"). > record.pack(side = "left", padx = 10, pady = 10) > find.bind('',findname) > find.pack(side = "right", padx = 10, pady = 10) > findit.pack(side='right') > a = Frame(root, bd = 3,bg='darkblue') > a.pack(side='left', fill = 'y') > openfile = Button(a, text = "OPEN") > openfile.pack(side = "top", padx =10, pady =10) > close = Button(a, text = "EXIT") > close.pack(side = 'bottom',pady = 10, padx = 20) > close.bind("",closeit) > openfile.bind("",findname) Don't you want "readit" instead of "findname" here? And same thing: you should use the "command" option on button "openfile". > c = Frame(root, bd = 3, relief = 'groove') > c.pack(side='top', fill = 'x') > i =Frame(root) > thelist1 = Listbox(i,bg = 'white') > thelist1.pack(fill = 'both') > i.pack(side = 'top',fill = 'both',expand = 1) > thetext = ScrolledText(i) > thetext.pack(side = 'top',fill = 'both',expand =1) > root.mainloop() [snip apparently working code for newrecord.py] Please note I work with Python 2.1, so I had to change things a bit to make things work, especially because I don't have nested scopes. So you may have to change a few more things. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From fuf at mageo.cz Thu Mar 13 05:07:40 2003 From: fuf at mageo.cz (Michal Vitecek) Date: Thu, 13 Mar 2003 11:07:40 +0100 Subject: NULL checks in Objects/abstract.c really needed? Message-ID: <20030313100740.GA21413@foof.i3.cz> hello, i had a quick look at Objects/abstract.c in 2.2.2's source. almost every function there checks whether the objects it's passed are not NULL. if they are, SystemError exception occurs. since i've never come across such exception i've commented out those checks. the resulting python binary did 6.5% more pystones on average (the numbers are below). my question is: are those checks really necessary in non-debug python build? the pystone results: BEFORE: $ for (( i = 0; i <= 5; i++ )); do ./pystone.py; done Pystone(1.1) time for 10000 passes = 0.6 This machine benchmarks at 16666.7 pystones/second Pystone(1.1) time for 10000 passes = 0.56 This machine benchmarks at 17857.1 pystones/second Pystone(1.1) time for 10000 passes = 0.58 This machine benchmarks at 17241.4 pystones/second Pystone(1.1) time for 10000 passes = 0.57 This machine benchmarks at 17543.9 pystones/second Pystone(1.1) time for 10000 passes = 0.57 This machine benchmarks at 17543.9 pystones/second Pystone(1.1) time for 10000 passes = 0.57 This machine benchmarks at 17543.9 pystones/second AFTER: $ for (( i = 0; i <= 5; i++ )); do ./pystone.py; done Pystone(1.1) time for 10000 passes = 0.54 This machine benchmarks at 18518.5 pystones/second Pystone(1.1) time for 10000 passes = 0.57 This machine benchmarks at 17543.9 pystones/second Pystone(1.1) time for 10000 passes = 0.55 This machine benchmarks at 18181.8 pystones/second Pystone(1.1) time for 10000 passes = 0.52 This machine benchmarks at 19230.8 pystones/second Pystone(1.1) time for 10000 passes = 0.52 This machine benchmarks at 19230.8 pystones/second Pystone(1.1) time for 10000 passes = 0.54 This machine benchmarks at 18518.5 pystones/second -- fuf (fuf at mageo.cz) From johnson at equadriga.com Thu Mar 6 23:40:19 2003 From: johnson at equadriga.com (Elester Johnson) Date: Fri, 7 Mar 2003 10:10:19 +0530 Subject: Python COM - Project 2000 (openPool attribute) Message-ID: Hi, I need to open a Project 2000 file without the Shared Resource Dialog poping-up using python. I tried to manipulate the openPool property in the FileOpen method by setting it to "pjDoNotOpenPool" - ie. 0x4 . But this doesnt work for me. Still I get the dialog poping-up. Kindly help me out. TIA. Kind Rgds, Elester Johnson -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Notebook.jpg Type: image/jpeg Size: 2950 bytes Desc: not available URL: From me at privacy.net Sun Mar 16 20:35:40 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Mon, 17 Mar 2003 13:35:40 +1200 Subject: Flying With Python (Strong versus Weak Typing) In-Reply-To: <_Xjca.126515$Hl6.11314509@news010.worldonline.dk> References: <37a869bc.0303102102.4533973@posting.google.com> <95cs6vo5k8rm15cd1iv0389kqfa2d2k7ht@4ax.com> <_Xjca.126515$Hl6.11314509@news010.worldonline.dk> Message-ID: Max M wrote: > There's some good names in there ... > > fel++, felc, felda, feleif, felfor, felja, felthon, felva, for++, ^^^^^^ If the language spec is to be released on April 1st, I'd pick this one. :-) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From aleax at aleax.it Thu Mar 6 04:31:12 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 06 Mar 2003 09:31:12 GMT Subject: range References: Message-ID: Hilbert wrote: > Hello, > > Why does range(1,4,1) return [1,2,3]? > It does not make sense at all. > It should return [1,2,3,4]. > > Am I crazy? No, just misguided. The best case I've ever seen made for always using half-open intervals, i.e., intervals including the lower bound but NOT including the upper bound, is in Koenig's book "C Traps and Pitfalls" -- almost worth learning C to be able to follow that exceppent book!-). Among the many regularities you gain by always using half-open intervals are, for example, the following two: len(range(X, Y)) == Y-X for any Y>=X range(A,B)+range(B,C) == range(A,C) for any A<=B<=C note the key issue -- the LACK of any need for +1 or -1 in these equalities. Not having to add or subtract one means you're far more likely to avoid the frequent bane of "off-by-one errors". > Hilbert > > (also 1/2 should return 0.5, but that's another thread) Sure, but for that you simply need to have a -Qnew on the python commandline, or a "from __future__ import" in your source -- it couldn't be done otherwise without breaking backwards compatibility. I hope it will be the default in Python 2.4, but in 2.2 and 2.3 Python chose to support backwards compatibility instead as the default -- quite sensibly too, if you think of how many millions of lines of Python code are in production programs being used all over the globe. *With* -Qnew: [alex at lancelot nubal]$ python -Qnew -c 'print 1/2' 0.5 So there's no particular need for any "other thread" on this, is there? Alex From mertz at gnosis.cx Wed Mar 19 19:04:29 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Wed, 19 Mar 2003 19:04:29 -0500 Subject: Incomparable abominations References: Message-ID: |> I want the ability to perform a total ordering on |> Python objects, at least within a sort. "Greg Ewing" wrote previously: |In a recent discussion on python-dev, Guido has expressed |favourable thoughts on introducing a before(x,y) operation |for arbitrary ordering. So there is hope that we may get |back the ability to sort arbitrary lists in some future |version. That would be great. Hopefully this operation also rolled into a .sort()-like method that avoids the function call overhead of using a custom comparison function. Or better still, the total ordering behavior can be the behavior of [].sort() itself... while the current behavior can be retained under the name: [].kinda_like_sort_but_crash_at_the_slightest_whiff_of_trouble() Yours, Lulu... -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! ------------------------------------------------------------------------- From zopestoller at thomas-guettler.de Tue Mar 4 11:11:34 2003 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Tue, 04 Mar 2003 17:11:34 +0100 Subject: Sorting lists of lists by columns References: <3E64BF02.9040901@motorola.com> Message-ID: Stephen Boulet schrieb: > Is there any list method available to sort lists of lists by columns? > I'm thinking of a spreadsheet-type function where you might sort rows by > the column x, y, and then z. Does this help you? def mycmp(a, b): return cmp(a[4], b[4]) mylist.sort(mycmp) thomas From eichin at metacarta.com Tue Mar 18 18:30:01 2003 From: eichin at metacarta.com (eichin at metacarta.com) Date: 18 Mar 2003 18:30:01 -0500 Subject: OT: Recommended Linux Laptops, suppliers? References: <01ab01c2ed82$b349e110$21795418@dell1700> <1048017989.1107.320.camel@software1.logiplex.internal> Message-ID: <7gptoop81y.fsf@pikespeak.metacarta.com> > Unless of course, the VNC project ever does an OSX port. That would at At risk of going even *more* offtopic, there has been one for months: http://www.redstonesoftware.com/osxvnc/ From dave at pythonapocrypha.com Tue Mar 4 13:40:57 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 4 Mar 2003 10:40:57 -0800 (PST) Subject: How to use threading and Queue modules In-Reply-To: <182bcf76.0303040901.23690dcc@posting.google.com> References: <182bcf76.0303040901.23690dcc@posting.google.com> Message-ID: On Tue, 4 Mar 2003, Paul Moore wrote: > I have a problem trying to use the threading and Queue modules. What > I'm trying to do is to fire off a host of background threads, and let > them do some work. In my main thread, I want to wait for the > background workers to complete, and then pick up their results. > > The best way to handle the results seems to be via a Queue.Queue, so > that I don't have to worry about locking issues. > > But now I hit a problem: How do I wait for the workers to all finish? > If I just join all the workers in turn, I risk the queue filling up, > resulting in deadlock. If I wait on the queue, I don't know when all > the workers have finished. > > Maybe a queue isn't the right data structure here. Is there another, > more suitable, data structure which can collect results from worker > threads? Maybe all I want is a locked list. After all, the queue would > be fine if it couldn't fill up. (There isn't enough data here for it > to be a problem to keep it all in memory). > > I'm new to multi-threading, so I don't want something too hard :-) > > Basically, the only reason I'm using threads at all is to multiplex a > lot of database conversations (50 or more) where IO and network times > are the bottleneck - with threading, I can run all 50 in the time it > takes the slowest to connect! If there are a fixed number of results, one per thread, then you can just get items off the queue until you have them all: def ThreadFunc(q): ret = None try: ret = # do some work here, assigning result to ret finally: q.put(ret) queue = Queue.Queue(0) # Infinitely large queue for i in range(NUM_THREADS): threading.Thread(target=ThreadFunc, args=(queue,)).start() for i in range(NUM_THREADS): result = queue.get() # do something with result You'll process the results in the order that they finish, and the wait-till-all-done condition happens automatically. Note that the thread func puts an item into the queue no matter what so that if an exception occurs your main thread doesn't hang forever. An alternate approach to wait on a large number of threads is to have the main thread acquire a semaphore (lock object) n times where n is the number of threads. Each worker would still do a try..finally but in the finally clause they'd release the semaphore to signal "I'm done". -Dave From edream at tds.net Mon Mar 10 08:20:25 2003 From: edream at tds.net (Edward K. Ream) Date: Mon, 10 Mar 2003 13:20:25 GMT Subject: pep 308: why doing (almost) nothing suffices References: <3E6BF37E.4FEBD4FF@alcyone.com> <3E6C024C.F06FFDBD@alcyone.com> Message-ID: > > Thanks for pointing this out. However, this does not change the fact > > that Python already provides more than enough tools for this job. > > Of course it does. No one has ever disputed that, as it's painfully > obvious. You can reformulate every conditional operator into a > statement or a more convoluted expression (the and/or tricks with > single-element lists or lambdas). > > The question is whether or not a conditional operator is warranted on > its own merits, not whether its presence is required to have a > Turing-complete language. We could continue this debate for a while, but Steven Taschuck's posting is the end of my not-quite-so-brilliant idea. In short, doing nothing isn't as good as I thought. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From stephen.boulet at motorola.com Mon Mar 31 17:31:52 2003 From: stephen.boulet at motorola.com (Stephen Boulet) Date: Mon, 31 Mar 2003 16:31:52 -0600 Subject: need help with game References: <3e88b3d3.30570106@news-server> Message-ID: <3E88C1D8.3070305@motorola.com> You could fire up a "cmd" console, and type in: C:\python22\python "C:\program files\pysol\pysol.py" Adjust the paths to fit your setup. Or you could associate ".py" files with the python executable. -- Stephen BBFoto wrote: > This question is so basic and I am so lacking in this area, that I > will completely understand if I am ignored. > > I received a cd from PC World with a game called PySol, among other > things. It says I need Python to play it. It gives a reference, so I > get Python and I load the game to my HD. (Win98 platform) Nowhere > in the game does it tell me how to get it to run. It refers to "drop > it on Python." I have no idea what that means. > > I run the Python executable and type in "PySol" at the prompt on the > black screen and get "name not defined." I can't find a .bat or .exe > file for PySol and I am totally unfamiliar with Python. > > If anyone could give me a clue, it would be greatly appreciated! > > BBfoto From cpl.19.ghum at spamgourmet.com Sun Mar 30 03:54:39 2003 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sun, 30 Mar 2003 10:54:39 +0200 Subject: Performance of Application / Is Python overhyped (just like Java)? References: Message-ID: The last years all the performance bottlenecks in my applications where connected to "waiting for the database" or "waiting for external programms to finish" So, if there would be a language running 200times faster than Python, it would just wait longer for the database - or the external application. From fperez528 at yahoo.com Thu Mar 20 12:22:28 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Thu, 20 Mar 2003 10:22:28 -0700 Subject: whos and clear (as in matlab) functionality References: <4e8c782d.0303200202.51b09ef7@posting.google.com> Message-ID: Thomas Knudsen wrote: > I'm a python newbie, currently in the process of moving > parts of my work from Matlab to python + Numeric. > > When using python interactively, I often need something > like the Matlab "whos" command. > > In Matlab "whos" returns a list of all variables: > %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% >>> a = 4; >>> b = [1 2 3; 4 5 6]; >>> whos > Name Size Bytes Class > > a 1x1 8 double array > b 2x3 48 double array > > Grand total is 7 elements using 56 bytes > %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% > > is there any way of doing something similar in python? Would this work for you? In [1]: a=4; In [2]: b=array([[1,2,3],[4,5,6]]); In [3]: whos Variable Type Data/Length ------------------------------ a int 4 b array [[1 2 3] [4 5 6]] Take a look at http://ipython.scipy.org/ Cheers, f From dave at pythonapocrypha.com Tue Mar 4 15:04:40 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 4 Mar 2003 12:04:40 -0800 (PST) Subject: Vote on PEP 308: Ternary Operator In-Reply-To: <_U59a.311281$SD6.15810@sccrnsc03> References: <882b0a41.0303020225.3caf0334@posting.google.com> <_U59a.311281$SD6.15810@sccrnsc03> Message-ID: On Tue, 4 Mar 2003, Jack D. Hammer wrote: > I will vote no ternary operator. > > I have not run in to a case where it is needed yet. I don't think that there > is any reason to make reading code more complicated. If the user really want > to do this, then they can always define their own function that takes three > paramters. No, as that does not support short-circuiting. The conditional operator is _not_ equivalent to a three-arg function. I know, I know, this has been discussed to death, but many of the 'no' votes have appeared to be from the 'you can simply do that with a function' camp, which is unfortunate because those are sort of false 'no' votes since it's based (at least in part) on a misunderstanding. Also, the 'you can do this another way' vote is unfortunate because IMO it misses the point. The language is Turing complete, so pretty much all features at this point can be done another way. We didn't strictly _need_ list comprehensions, lambdas, augmented assignments, generators, classes, etc., etc., but having them is very powerful, expressive, useful, whatever. Obviously many people feel that the conditional operator is not powerful, expressive, useful, whatever _enough_ to warrant adding it to the language - and that's fine, but please don't simply vote against it because it's not essential. Just my two cents, -Dave From exarkun at intarweb.us Tue Mar 18 19:39:43 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 18 Mar 2003 19:39:43 -0500 Subject: resource module Message-ID: <20030319003943.GA4544@meson.dyndns.org> I've looked at this module several times over the years. It seems to have been in a perpetual state of undocumented brokeness. Has anyone used it successfully? If so, how? In particular, I would like to reduce the number of allowed open files. Jp -- http://catandgirl.com/view.cgi?44 -- up 15 days, 16:00, 4 users, load average: 0.01, 0.03, 0.00 From max at alcyone.com Sun Mar 23 18:17:31 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 23 Mar 2003 15:17:31 -0800 Subject: Is Python the Esperanto of programming languages? References: <3oyea.61654$68.41484@nwrdny01.gnilink.net> <3E7ABD93.7DFBCFB@alcyone.com> <3E7BA475.2A0B41C6@alcyone.com> <3E7CDFA5.7FED4917@alcyone.com> <3E7D0A3B.58763752@alcyone.com> <3E7D65B8.B5A03AAB@alcyone.com> Message-ID: <3E7E408B.A69AAF27@alcyone.com> Carl Banks wrote: > You're a dispicable loser. Not only have you resorted to nitpicking > to deflect attention away from the real point of this discussion (for > reasons I suspect but will not state), ... Uh huh. I'm a loser. All I've done is pointed out your repeated semantic arguments and distinctions without a difference. It sounds like some cases are redundant but some are only _superfluous_ (and you really sit there and say you're not making a distinction without a difference) only so that what you said previously won't be wrong. Sounds like backpedalling, not reasonable discourse. > ... but your nitpick has also > strengthened my argument: No, it strengthened my argument. Which is that you keep going on without factual basis. My job isn't to counter your arguments, it's to demonstrate my own. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Wretches hang that jurymen may dine. \__/ Alexander Pope Official Omega page / http://www.alcyone.com/max/projects/omega/ The official distribution page for the popular Roguelike, Omega. From richie at entrian.com Fri Mar 14 08:42:05 2003 From: richie at entrian.com (Richie Hindle) Date: Fri, 14 Mar 2003 13:42:05 +0000 Subject: High performance IO on non-blocking sockets References: Message-ID: [Troels] > sent = self.socket.send(self.data) > self.data = self.data[sent:] > > This approach is bad [...] >From http://www.python.org/doc/current/lib/socket-objects.html : ------------------------------- snip snip ------------------------------- 7.2.1 Socket Objects [...] sendall( string[, flags]) Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Unlike send(), this method continues to send data from string until either all data has been sent or an error occurs. None is returned on success. On error, an exception is raised, and there is no way to determine how much data, if any, was successfully sent. ------------------------------- snip snip ------------------------------- Nothing springs to mind for the recv case (but the problems are lesser in that case). -- Richie Hindle richie at entrian.com From tjreedy at udel.edu Wed Mar 5 00:13:17 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 5 Mar 2003 00:13:17 -0500 Subject: A suggestion for a possible Python module References: <3E63FFE9.8A757617@alcyone.com> <2Gmdndr_z-5UJPmjXTWc3g@comcast.com> Message-ID: "Alex Martelli" wrote in message news:oK49a.5039$zo2.154480 at news2.tin.it... > Yes, and the boundaries play strangely...: > > >>> x = list('arrivederci') > >>> x[2:7] = x[7:2:-1] > >>> ''.join(x) > 'aredevierci' > >>> > > x[2:7] being 'rived', one would expect 'ardevirerci' -- but to > get that one needs an ample application of -1's, alas...: > > >>> x = list('arrivederci') > >>> x[2:7] = x[7-1:2-1:-1] > >>> ''.join(x) > 'ardevirerci' > >>> > > Goofy, slow, and error-prone, I think there's little to be said > for this idiom (x[start:stop] = x[stop-1:start-1:-1] in the > general case). As near as I can tell, the 19 February 2003 2.3a2 Ref Man, Section 5.3.3 Slicings, (on python.org) has not been updated to specify the long_slice behavior when *not* used as a dict key but used for seq access. If so, there is no way to tell if behavior above is intended or is a bug (except by analogy with Numeric behavior, which I am not familiar with). Terry J. Reedy From jsaul at gmx.de Mon Mar 10 10:03:48 2003 From: jsaul at gmx.de (jsaul) Date: Mon, 10 Mar 2003 16:03:48 +0100 Subject: time.strftime() In-Reply-To: References: <20030310092838.GB695@jsaul.de> Message-ID: <20030310150347.GD3278@jsaul.de> * Mikael Sch?nenberg [2003-03-10 12:51]: > On Mon, 10 Mar 2003, jsaul wrote: > > >>> time.strftime("%a, %d %b %Y %H:%M:%S %z", time.localtime()) > > 'Mon, 10 Mar 2003 10:26:51 +0000' > > It seems likely that what you've overlooked is this: > > "The use of %Z is now deprecated, but the %z escape that expands to the > preferred hour/minute offset is not supported by all ANSI C libraries." > > From: http://python.org/doc/current/lib/module-time.html#foot18650 OIC. In fact, "%z" appears to be an extension of the GNU-libc. But it is also specified by IEEE Std 1003.1-2001 aka POSIX.1-2001. Anyway, since I am on a GNU-libc system, I would expect either a proper conversion or no conversion at all. So it appears to be interpreted and it actually *is*, see below... > Not what you were hoping for, I'm sure, but probably the cause of your > problem. As to the solution... I can't think of any, apart from 'do it > yourself' :-( I did, but I found it frustrating that it appeared not to be possible to do it all in one call to strftime(). Somewhat "unpythonic". *But* I was too hasty and while I relied on the apparently somewhat incomplete information provided by help(time), I should have read the more exhaustime html-docs. It turns out that I can invoke time.strftime() without a second argument; the current local time is used then. And this results in the correct output: >>> time.strftime("%z") '+0100' Wow. On the other hand: >>> time.strftime("%z", time.localtime()) '+0000' Thus it actually could not have worked the way I tried it, because the tuple returned by time.localtime() contains no information about the time zone, therefore obviously no proper output from "%z" was possible. The way this is described in the html-docs is a bit misleading, IMHO: "If tuple is not provided, the current time as returned by localtime() is used." But both cases are *not* equivalent, as the tuple lacks time zone information. Cheers, jsaul -- Palo pa'que aprenda que aqu? s? hay honor! [Rub?n Blades] From bobnotbob at byu.edu Sun Mar 9 15:12:34 2003 From: bobnotbob at byu.edu (Bob Roberts) Date: 9 Mar 2003 12:12:34 -0800 Subject: tuples from lists Message-ID: I have a list of lists of lists. How can I turn that into a tuple of tuples of tuples? From cce at clarkevans.com Sun Mar 9 15:11:40 2003 From: cce at clarkevans.com (Clark C. Evans) Date: Sun, 9 Mar 2003 20:11:40 +0000 Subject: PEP308 Late Entry In-Reply-To: References: Message-ID: <20030309201140.GA81132@doublegemini.com> On Sat, Mar 08, 2003 at 10:35:00AM +0000, Stephen Horne wrote: | | select : (c1 : r1; c2 : r2; r3) | select s : (v1 : r1; v2 : r2; r3) | select sa, sb : (v1a, v1b : r1; v2a, v2b : r2; r3) | | 's' stands for 'switch expression'. | 'c' for condition. | 'r' for result. | 'v' for switch-value. Ok. But I think 'when' adds readability, and you don't need a separate case for your third example. a = select when c1 : r1; when c2 : r2; else r3 b = select s when v1 : r1; when v2 : r2; else r3 c = select (sa,sb) when (v1a, v1b): r1; when (v2a, v2b): r2; else r3 Or, written in multi-line form.. a = select when c1: r1 when c2: r2 else: r3 b = select s when v1: r1 when v2: r2 else: r3 c = select (sa,sb) when (v1a, v1b): r2 | Switch values could even support special syntaxes such as relative | operator prefixes ('<', '>' etc) or perhaps a '..' or 'to' notation | for ranges - though the non-switch first form might be clearer. I'd call it 'select' and not 'switch'; the 'switch' expression in "C" is a statement-level operation, while this proposal seems still to be an expression. And yes, I like the operator prefixes: select s when > 100: 'huge' when > 50 : 'big' when > 30 : 'medium' when > 20 : 'respectable' when > 10 : 'small' else: 'tiny' select x: when 'RHS': select y when 'UP': 'Upper Right' when 'DOWN': 'Lower Right' else: 'Center Right' when 'LHS': select y when 'UP': 'Upper Left' when 'DOWN': 'Lower Left' else: 'Center Left' else: select y when 'UP': 'Upper Middle' when 'DOWN': 'Lower Middle' else: 'Center Middle' | 1. It handles 'elif' simply and succinctly. | | 2. It supports the switch/case functionality as a simple extension, | but unlike the earlier proposal does not have to be split over | multiple lines unless clarity genuinely demands it. I don't mind being able to add a ';' to make it a one-line construct if it is necessary. | 3. The use of punctuation keeps it succinct while the initial keyword | makes it clear what is happening (easy to look up in documentation | etc). I think the parenthesis is ugly. | | 4. The initial ':' and the use of ':' and ';' in the parentheses | makes it clear that this is not a function, for those who see | function-call notation as implying no shortcircuiting. Yes, the ; is nice. Clark From mis6 at pitt.edu Fri Mar 14 14:46:50 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 14 Mar 2003 11:46:50 -0800 Subject: P.E.P. 3.0.8 ??? References: <3E71B03A.3A90C341@engcorp.com> <3E71B427.7BE071DE@alcyone.com> Message-ID: <2259b0e2.0303141146.64849580@posting.google.com> Gerrit Holl wrote in message news: > No problem, just add a 42nd dimension and all is fixed ;) > > going-to-study-physics-next-year-ly - y'rs - Gerrit. Already done. And studied all the dimensions from 3 to 11 ;) -- Michele Simionato - Dept. of Physics and Astronomy 210 Allen Hall Pittsburgh PA 15260 U.S.A. Phone: 001-412-624-9041 Fax: 001-412-624-9163 Home-page: http://www.phyast.pitt.edu/~micheles/ From gerhard.haering at opus-gmbh.net Tue Mar 11 08:11:02 2003 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 11 Mar 2003 13:11:02 GMT Subject: Stream Abstractions in python? References: <20030311123036.GA5514@daimi.au.dk> Message-ID: Daniel Nielsen wrote: > Hi. > > I'm toying around with python... The only reason I see right now to > continue using java for distributed stuff, is java's > Data{In,Out}putStream with sockets. Is there an equivalent abstraction > to TCP streams in Python? I have been looking around www.python.com, > but couldnt anything... > > Using google I've found http://www.0x01.com/~thanos/javadata.py , > which seems to do what I want, but I'd like to see what other > alternatives there are out there. You might want to take a look at Twisted [1]. It nicely decouples protocol implementations from the underlying transport, among others. If you're doing network programming and/or implementing custom protocols it's IMO a very good framework. > Note: I do not require it to be compatible with java's streams, I'd just > like the convenience of readUTF/writeUTF and friends. Hmm. What about using codecs.EncodedFile for this? [2] -- Gerhard [1] http://www.twistedmatrix.com/ -- Argh. Can't connect currently. [2] http://www.python.org/doc/current/lib/module-codecs.html From tebeka at cs.bgu.ac.il Wed Mar 5 02:07:24 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 4 Mar 2003 23:07:24 -0800 Subject: Help with wxPython BoxSizers References: <33803989.0303040753.1c47eefc@posting.google.com> <8b5e42a6.0303041235.6cad845d@posting.google.com> Message-ID: <33803989.0303042307.1e3b80ae@posting.google.com> Hallo All, > topsizer.Add(b) # <--- delete this line Thanks. I'm scheduled for a brain transplant tomorrow :-) Miki. From theller at python.net Fri Mar 21 16:18:04 2003 From: theller at python.net (Thomas Heller) Date: 21 Mar 2003 22:18:04 +0100 Subject: minimum python for distribution on Windows References: Message-ID: Dave Brueck writes: > On Fri, 21 Mar 2003, Bob Roberts wrote: > > > > > Is it possible to do this without py2exe? What if I have a > > > > large number of scripts that use pretty much the same modules? > > > > It would be nice to be able to distribute the python.exe, the > > > > libraries, and my scripts without having to have the python.exe > > > > bundled for each script. > > > > > > Yes, you can do this - the tradeoff is mostly that you are the one > > > responsible for finding and including all the dependencies. The > > > poor man's approach is to set your PATH environment variable to be > > > empty and rename the directory Python is installed in and put > > > Python.exe and your modules in an empty directory. Run it, see > > > what errors occur. Repeat until done. > > > > I tried almost the exact same thing in the beginning, but it kept > > requiring all sorts of modules like "site" that I never used. Would > > it just be that pygame was requiring them? > > site gets imported by Python on startup; do a "python -v" to see this. > > Better yet, though, see Thomas Heller's most recent post to this thread > for a not-so-poor-man's approach to locating modules. It should be added that for a minimum Python distribution, site should probably be *not* imported. Apart from setting up some additional, site specific sys.path entries, it adds stuff like pydoc (which includes HTTPServer, IIRC). See the -S flag to Python. (I always wondered why freezing 'print "hello"' script needed the HTTPServer stuff). Thomas From antonmuhin at sendmail.ru Thu Mar 20 06:53:26 2003 From: antonmuhin at sendmail.ru (Anton Muhin) Date: Thu, 20 Mar 2003 14:53:26 +0300 Subject: Does Python do try: except: finally: ? In-Reply-To: <3E78EBF8.5C59646F@alcyone.com> References: <20030319135147.A1830@ash.int.ca.pason.com> <3E78EBF8.5C59646F@alcyone.com> Message-ID: Erik Max Francis wrote: > Joseph Wilhelm wrote: > > >>>>>try: >> >>... print "Foo" >>... except: >>... print "Oof" >>... else: >>... print "Bar" >>... >>Foo >>Bar >> >>That what you need? > > > Probably not: > > >>>>try: > > .... print 'foo' > .... raise ValueError > .... except: > .... print 'oof' > .... else: > .... print 'bar' > .... > foo > oof > > The else clause is only executed in the case where there's no error, > quite contrary to what is usually intended by a try..except...finally > clause. > It can be easily improved: try: print "foo" raise ValueError except: print "oof" else: print "bar" print "zoo" # Anton. From dave at pythonapocrypha.com Tue Mar 4 14:13:10 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 4 Mar 2003 11:13:10 -0800 (PST) Subject: md5 for large files In-Reply-To: References: Message-ID: On Tue, 4 Mar 2003, Bob Ballard wrote: > Can someone provide me with a snippet or pointer to usinging Python to > verify the md5 value for a large file? All examples I've seen are for a > small string. I'm not yet using GPG for NT and I need to verify or generate > md5 values for file xfers. Hi Bob, How about: import md5 m = md5.new() f = open('somefile','rb') while 1: data = f.read(32768) # Read a block if not data: break m.update(data) print m.digest() -Dave From cce at clarkevans.com Tue Mar 4 06:01:03 2003 From: cce at clarkevans.com (Clark C. Evans) Date: Tue, 4 Mar 2003 11:01:03 +0000 Subject: Towards a more Pythonic "Ternary Operator" In-Reply-To: <882b0a41.0303020225.3caf0334@posting.google.com> References: <882b0a41.0303020225.3caf0334@posting.google.com> Message-ID: <20030304110103.GA54157@doublegemini.com> After looking over my code some, I found that where I thought I needed a terinary operator, I ended up taking one of two paths: exit = { 0: 'no exit', 1: 'a door' }.get(quantity, '%s doors' % quantity) Or, the more 'obvious' ... if 0 == quantity: exit = 'no exit' elif 1 == quantity: exit = 'a door' else: exit = '%s doors' % quantity The first construct has two advantages over the more 'obvious' solution: 1. It's clear that I'm making an assignment to exit 2. I don't have to duplicate the ugly '== quantity' each time. However, the first construct brings with it two problems: 1. The 'else' case is kinda ugly. 2. It doesn't short-circut cleanly, to have the short-circut behavior you need to use lambda's as the mapping values and then invoke the result... So, if you asked me, what I'd like is a hybrid of the two options above, a nicer-looking short-circuting in-line mapping: exit = select quantity case 0: 'no exit' case 1: 'a door' else: '%s doors' % quantity #NOTE: new lines/indentation is mandatory in this proposal IMHO, the other options in the survey are quite clean when you look at it this way: data = select hasattr(s,'open') case true: s.readlines() else: s.split() z = 1.0 + select abs(z) < .0001 case true: 0 else: z t = v[index] = select t <= 0 case true: (t-1.0) else: -sigma / (t + 1.0) return select len(s) < 10 case true: linsort(s) else: qsort(s) ... The other advantage of this mechanism is that the semantics could be made a bit more flexible by requiring the case item to be a predicate -- a boolean function with one argument, the item being selected upon. Thus, z = 1.0 + select abs(z) case lt(.0001): 0 case gt(.5): .5 else: -sigma / (t + 1.0) score = select die case 1: -2 case 2: -1 case between(3,4): 0 case 5: +1 case 6: +2 else: raise "invalid die roll %d " % roll Since the items 1,2,5,6 arn't predicates, then the "equal" predicate is assumed. Now... _this_ I would really find useful. Best, Clark From gh at ghaering.de Wed Mar 5 15:40:52 2003 From: gh at ghaering.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 5 Mar 2003 20:40:52 GMT Subject: Parsing a conf file References: Message-ID: Simon Faulkner wrote: > Hello All, > > Is there a simple / recommended way of parsing a setting from a conf > file? [...] If you can decide what the format of the config file will be, you could use the ConfigParser module, which can parse config files in the style of Windows .INI files. -- Gerhard From intentionally at blank.co.uk Tue Mar 11 10:12:45 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 11 Mar 2003 15:12:45 +0000 Subject: A possible lazy evaluation system? References: Message-ID: <2cur6v01645cnr688c0jfoccf6fbupnpfu@4ax.com> On Tue, 11 Mar 2003 08:08:44 -0600, Skip Montanaro wrote: >How does the compiler know (at compile-time) that bar.IF is going to be >bound at runtime to Foo.IF so it can check the laziness of the parameters >and generate the proper code? I had in mind an idea where the call notation would create a kind of call-context object. The functions bytecode would look at the call context to determine what the parameters should be. The call context would contain references to the callers scope and pointers to the parameters expression bytecode stuff. This should be enough to either create a lambda or evaluate immediately. The reference to scope (rather than immediate creation of a closure) should be possible, though I have a nasty feeling that each parameter would need to supply three items in the context... 1. Closure-aware bytecode compiled expression (for embedding in lambda) 2. Non-closure bytecode compiled expression expecting callers scope to be in effect, for non-lambda parameters. 3. Compiled bytecode to perform closure construction when lambda is needed. Of course, that is annoyingly complex and probably horribly inefficient :-( From dg96057 at teledomenet.gr Wed Mar 12 07:28:13 2003 From: dg96057 at teledomenet.gr (Dimitris Garanatsios) Date: Wed, 12 Mar 2003 14:28:13 +0200 Subject: Long integers: to L or not to L? References: <2632446.1047448854@dbforums.com> <3E6F18F1.5020208@teledomenet.gr> Message-ID: <3E6F27DD.6060901@teledomenet.gr> Dimitris Garanatsios wrote: > ...but if you ever call function h() you might get: > > Traceback (most recent call last): > File "script1.py", line 14, in ? > h() > File "script1.py", line 11, in h > i = h1() > File "script1.py", line 4, in h1 > i = i + 1 > UnboundLocalError: local variable 'i' referenced before assignment > > This is because nested scopes in python is a new addition which is not > supported in my version (2.2.1) unless a "from __future__ import ..." is > used. So in this case the "i = 0" statement is not seen inside h1(). > Again, you may consult python's documentation for more details about new > feature additions... A correction on my remark: I saw that nested scopes was part of python 2.2.1 (sorry about my mistake...). So the error gets raised when you try to assign a new value to variable i (an immutuable object: integer) in a scope that it does not exist (although it can be "seen" in that scope). So if you change h1 to def h1(): j = i + 1 print 1, j if j == 5: return j else: j = h1() return j You won't get the above UnboundLocalError (assuming nested scopes are supported in your version of python) but instead a RuntimeError: maximum recursion depth exceeded because j will never reach value 5 :-) If you want to use nested scopes to change the value of an object that is defined in an outter scope, use muttuable objects: def h(): i = [0] def h1(): i[0] = i[0] + 1 print 1, i[0] if i[0] == 5: return i[0] else: i[0] = h1() return i[0] # this will never get executed i[0] = h1() print 2, i[0] This might not be pretty, but it will happily run as expected :-) Again, sorry for my mistake Dimitris From intentionally at blank.co.uk Wed Mar 12 21:38:15 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Thu, 13 Mar 2003 02:38:15 +0000 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <58q36vgv1ga8ovde5ftub9t8ugaa2pnum5@4ax.com> <3E62778F.EED49083@alcyone.com> <3E629E93.B94F7631@alcyone.com> <3E63AFA0.A3CAC045@alcyone.com> Message-ID: On 06 Mar 2003 20:21:12 +0000, Alexander Schmolck wrote: >Erik Max Francis writes: > >> But that has no bearing on whether Python should also have a compact form >> _for the sole purpose of being compact_. > >No one suggests such a thing! I think there are maybe 4 different levels at >which the mere conciseness of a construct FOO (with a hypothetical, more >verbose alternative, FOO_VERBOSE) can affect a language: > >1. FOO is used in the same places as FOO_VERBOSE would, but the code becomes > more (or less) readable (e.g. ``Bignum(1).add(3)`` 'vs' ``1l + 3``) '+' is a common operation that everyone understands. 'lambda' is not. Completely removing the best clue to what's going on (ie a keyword to look up in the documentation) does not aid readability. >2. FOO is used in places where FOO_VERBOSE wouldn't be used, because it is too > cumbersome (e.g. I'd wager that people more readily use dicts in python > than HashTables in java). Having had to explain lists and dictionaries to a couple of programmers who'd only used statically typed languages before, I can say that some irritation would have been avoided if the respective syntaxes were... list {1, 2, 3, 4, ...} dict {1 : 2, 3 : 4, ...} It's not so much the "oh that - that's a list" that causes the problem. It's the explaining that list support is built in, doesn't require a library class, doesn't specify the implementation, etc etc. At the end of that, I've lost the thread of whatever I was doing before. All avoidable if the people involved could look up the keyword and find out for themselves. Well - probably 30 mins out of my life in total. Hardly a big issue. But let's get back to the point... I don't know how HashTables work in Java, but I do know that there is a happy medium for conciseness - like lossy compression, smaller representations are only better to a point. And the decision on where to stop is inherently a subjective one. For me, when a construct has no explicit indicator of what it's doing it usually means the compression has gone a step or two too far. Explicit does not always mean a keyword ('+' for instance is explicit enough), but quite often that is what is required. Every language has a few 'overcompressed' syntaxes. This isn't necessarily a bad thing. These syntaxes tend to define the style of a particular language, and they reflect the languages priorities. If there are too many highly compressed notations, though - and particular if some are rarely used except by code-obfuscators - it leads to unreadable code. In particular, if each symbol is put to too many different uses, the results can rapidly get very confusing. The C comma operator is probably the definitive example of conciseness gone mad. The comma is most often used as a separator punctuation, so the comma as an evaluate-and-discard operator is far from intuitive when its first seen. It works extremely well when used for in-step loops, but its wider generality leads to no end of confusion and errors. For example, what does the following code output... int x = 0; switch (x) { case 0, 1 : cout << "First case passed" << endl; break; default : cout << "Default case passed" << endl; break; } The correct answer is "Default case passed" - the first case evaluates the '0' but discards it, and only actually tests for the '1'. But can you honestly claim that result is intuitive? The fact is that the C comma should (at least in my opinion) never have been used as an evaluate-and-discard operator. Either a more explicit operator should have been used, or else the comma should have been recognised as a special separator in 'for' and 'while' clauses specifically designed for setting up in-step loops without the more general evaluate-and-discard meaning. If it did that, even the intended purpose would have been enhanced in C++ - you could write... for (int i = 0, float j = 1.0; i++, j *= 1.1; i < 100) { ... } As things stand, this is illegal - you can't combine the 'int' and 'double' declarations in one statement using the evaluate-and-discard operator, though if it was just a separator it could have been seen as separating two independent statements. By being too general, too concise, and by 'overloading' the comma symbol, the C evaluate-and-discard operator contributes significantly to the readability, maintainability and reliability problems in that language - and gets in the way of even the task it is designed to support. Python has a fair share of highly compressed syntaxes, but it also has a style which favours readability. Adding a new highly compressed syntax should be considered very carefully, and should really only be done if the syntax is likely to be put to everyday use by average programmers - ie if most people who would have a reason to read Python source code would recognise it immediately. As much as I like lambdas, they simply aren't used that much by most programmers - and I seriously doubt that dropping the 'lambda' keyword would make that much difference. And besides, the syntax should certainly be distinguished from plain expressions by more than a colon - a symbol which already has several uses in Python. >3. FOO's conciseness affects the design of interfaces of other functions (so > that they become in some way better, or more general -- e.g. `ifAbsent` vs > `.get`). The strength of the 'ifAbsent' notation, however, isn't just about having a single concise notation - it's tightly coupled to the overall design of SmallTalk, and I'm not convinced you can draw useful conclusions about conciseness in general from it. >4. FOO's conciseness renders certain hypothetical language extensions > unnecessary (e.g. control construct syntax, and to some extent even macros, > in smalltalk). I'm not convinced an abbreviated lambda could achieve this any more than the existing lambda - e.g. you could only render control constuct syntax less readable, and macros don't exist anyway in Python. >Now 3 and 4 are of course quite rare, (but all other things being equal), >rather desirable. I think smalltalk's blocks satisfy all 4 (and smalltalk, >although different, is not completely unlike python). Python has it's own style, and lambdas - while extremely useful for certain tasks - are not a fundamental part of that style. Smalltalks codeblocks seem much more fundamental to that languages style. This is a significant difference. >Of course adding a (amongst other things, highly syntactically constrained and >possibly rather restricted) lightweight anonymous function equivalent to >python at this stage might not be worth while the trouble (and increase in >complexity). Also, as you and others remarked, certain syntactic possiblities >might be errorprone or unreadable. Changing the subject a second, this can be linked to a the idea of using XML as a source language. The editor might display a marker in place of the lambda. Select the marker, and a drop-down editing pane (or separate window or whatever) could appear, containing the body of the lambda complete with indentation-based block structures. As the layout of the lambda body is independent of the layout of the code that it is embedded in, readability is improved and certain syntax related issues are avoided. >Nonetheless, I think the ability to easily pass chunks of code around (and no >-- lambda does not qualify; or I'd like to see how you rewrite a smalltalk >program by replacing blocks with something like lambda A naive translation of Python code to Smalltalk would also be pretty awkward. >) that close over the >current environment, even if added to python now, is unlikely to affect the >only point 1 (as you seem to imply). Everything you've said has some truth to it, but IMO the specifics of PEP312 raise serious issues that run counter to each of those points. The comparison with the C comma operator should give anyone good reason to fear the PEP312 syntax. From skip at pobox.com Fri Mar 28 06:46:33 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 28 Mar 2003 05:46:33 -0600 Subject: Python Admin Scripts In-Reply-To: References: Message-ID: <16004.13849.475251.542946@montanaro.dyndns.org> >>>>> "Norm" == Chris Tavares writes: Norm> Many of you must be Linux/NT admins. What I am looking for are Norm> projects to try out on Python. Norm> How have you found Python to be useful in making the job easier? Here's a simple one. We recently began using Firewall-1 to protect servers in the group I work in at Northwestern. While it provides a nice GUI to create rules and can dump voluminous log files in CSV format, it provides essentially no logfile analysis tools. I wrote a simple summarizer in Python which identifies the most frequent source and target machines, the most frequently targetted services, and the most frequently used rules in the database. Sort of a a (very) poor man's Internet Storm Center (http://isc.incidents.org/). Skip From intentionally at blank.co.uk Wed Mar 5 21:49:14 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Thu, 06 Mar 2003 02:49:14 +0000 Subject: PEP 308: an additional "select/case" survey option References: <882b0a41.0303020225.3caf0334@posting.google.com> <20030305005906.GA56890@doublegemini.com> Message-ID: <8pad6v8k527ihnm11b9n6pfratcg1ok9up@4ax.com> On Wed, 5 Mar 2003 18:12:39 +0000, "Clark C. Evans" wrote: > a = ((when b != 0: a/b > else: 1000) > + (when d != 0: c/d > else: 1000) > + (when h != 0: g/h > else: 1000)) > >Which I admit isn't very pretty. I wouldn't really complain that much about this example - my point is mainly about the validity of the preference. After all, a conditional doesn't need to get all that complex and you need multiple lines anyway. > However, if you assume that >in the select/when proposal a missing else clause causes >non-matches to evaluate to None, you get... > > a = ( ((when b != 0: a/b) or 1000)) > + ((when d != 0: c/d) or 1000)) > + ((when h != 0: g/h) or 1000))) > >I guess this is one extra level of parenthesis... but then >again the if/then proposal could be limited to such a scope >(not having an else). The reason I dislike this has nothing to do with parentheses - it's keeping a part of the old and/or paradigm, and in particular it keeps the main 'bug' in the and/or paradigm - i.e. (when true : None) or 1000 evaluates to 1000 - not None. It's an improvement in that it 'reads better' than the and/or paradigm but, IMO, it's not enough of an improvement. But getting back to the point, just because you've used the 'or' operator to express the 'else' part does not change the fact that you've put each conditional on a single line. You've spelled it differently, but you've structured and formatted it exactly the same way that I did ;-) > def sum(lst): > res = 0 > for itm in lst: > res += itm > return res > > def div(numerator, denominator, ifzero = None): > if denominator != 0: return numerator/denominator > return ifzero > > a = sum([div(x,y) for x,y in ((a,b),(c,d),(g,h))]) I'd personally keep your div, but replace the rest with... temp = ((a,b), (c,d), (g,h)) reduce (operator.add, [div(x,y) for x,y in temp]) But not always. Creating lists of tuples purely to exploit list comprehensions etc. can easily distract from the real intention of the code. It could depend on how those variables are related, for instance, or where they came from. And of course, I wouldn't necessarily want to apply the same operator on the LHS of each line - it could just easily have been... a = (if (b != 0) then a/b else 1000) * ( (if (d != 0) then c/d else 1000) + (if (h != 0) then g/h else 1000))) -- steve at ninereeds dot fsnet dot co dot uk From intentionally at blank.co.uk Wed Mar 12 19:39:15 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Thu, 13 Mar 2003 00:39:15 +0000 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <58q36vgv1ga8ovde5ftub9t8ugaa2pnum5@4ax.com> <3E62778F.EED49083@alcyone.com> <3E629E93.B94F7631@alcyone.com> Message-ID: <0bkv6v8akrd0db5i66eu685t5pmviuf0bk@4ax.com> On Wed, 12 Mar 2003 17:54:37 -0500, Jack Diederich wrote: >A groups.google link to a post where (in the footnotes) I mention that 'lambda' >is both A: a long keyword, and B: one of the few keywords that never starts >a line (hence it jars the eye). I don't really see the relevance of the fact that "'lambda' never starts a line". Other frequently used words (such as built-in function names) also never start a line - 'reduce' is as long as 'lambda' for a start. What is the relevance of the distinction between keywords and standard identifiers in this issue? From tebeka at cs.bgu.ac.il Mon Mar 3 07:01:46 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 3 Mar 2003 04:01:46 -0800 Subject: Best way to hash a dictionary References: <33803989.0302260008.23833001@posting.google.com> Message-ID: <33803989.0303030401.70861718@posting.google.com> Hello Steve, > You will, I hope, pardon me saying that it sounds like rather important > design decisions have already been made. Perhaps if you were to explain > *why* you need to use dictionary equivalents as dictionary keys someone > might be able to spot a solution that doesn't require such contortions. Yap. It design decision. I'm doing a NLP M.Sc. thesis where I tag words with part of speech. I Hebrew words have complex part of speech with many attributes. An example might be: {'POS':'Verb', 'Gender':'Male', 'Tense':'Past'} My algorithm is a learning one and I need to store some statistics per tag, the most efficient way is hash tables. > Please note, I'm not saying you definitely don't need to use dictionaries as > dictionary keys. Simply that it sounds like there may be a better way. If you find one, please tell me. Basically I need immutable hash. > Finally: the reason you can't just use the dictionaries as keys, of course, > is that dictionaries are mutable. Does you design preclude any change to the > dicionaries after they become keys in the other dictionary? If so then you > may just be able to subclass the standard dict type. This has performance penalties, and since an average run of my thesis is 5 days I can't do that. Plus if you try: >>> class D(dict): pass >>> d = D() >>> h = {} >>> h[d] = 1 Traceback (most recent call last): File "", line 1, in ? h[d] = 1 TypeError: dict objects are unhashable >>> Miki From sholden at holdenweb.com Tue Mar 11 18:50:23 2003 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 11 Mar 2003 23:50:23 GMT Subject: Suggestion for yet another (O'Reilly) Python book References: Message-ID: <3Duba.3468$374.533@news2.central.cox.net> "Steven Cummings" wrote ... > claird at lairds.com (Cameron Laird) wrote: > > >In article , > >Steven Cummings wrote: > >>Cool idea. I've thought it would be nice to have an O'Reilly "Python > >>Web Services" written by someone who has done all of those articles > >>for developerWorks and XML.com, like Uche. To have it all and much > >>more from the expert-author's knowledge in one coherent book would be > >>very marketable right now I think. > > . > > . > > . > >... and also a lot of work, more than is generally ap- > >parent to those who haven't been through sausage-mak--I > >mean, book publication, themselves. > > Too right. It's a lot of work for a pretty small return, even if the book turns out to be sucessful. Then some Dutch smartarse goes and brings out a new version of Python and your text is out if date. Sheesh... > >Incidentally, "Python Web Services" is ambiguous in at > >least a couple of dimensions. Are you aware of Steve > >Holden's book ? > >-- > > That's true I suppose. I was presuming the typical SOAP/UDDI/WSDL family of basic deployment, with maybe some XML database/repository type material. I did know about that book, but I didn't realize that it contained material on web services. I'll definitely check it out if that's the case. Although that link doesn't seem to be working this moment... > Well it's working for me, but I'd appreciate any feedback on its continued non-responsiveness. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Register for PyCon now! http://www.python.org/pycon/reg.html From t.evans at paradise.net.nz Mon Mar 3 04:44:56 2003 From: t.evans at paradise.net.nz (Tim Evans) Date: Mon, 3 Mar 2003 09:44:56 GMT Subject: critical section References: Message-ID: <87d6l8wzqf.fsf@cassandra.evansnet> "John Burton" writes: > Are there any python facilities for synchronising access to a resource from > two seperate processes running python programs? Semaphores etc? Or do I have > to drop down to calling OS facilities. I didn't see anything but sometimes > it's hard to know what to look for,.. I'm assuming that you're using win32... Look at the win32event.CreateMutex function, part of the win32all extensions. http://aspn.activestate.com/ASPN/Python/Reference/Products/ActivePython/PythonWin32Extensions/win32event__CreateMutex_meth.html -- Tim Evans From Gareth.McCaughan at pobox.com Sat Mar 15 03:46:31 2003 From: Gareth.McCaughan at pobox.com (Gareth McCaughan) Date: Sat, 15 Mar 2003 08:46:31 +0000 Subject: Using SHA1 as RNG References: Message-ID: Paul Foley wrote: > On Fri, 14 Mar 2003 18:14:12 +0000 (UTC), Klaus Alexander Seistrup wrote: > > > It is probably quite expensive to use the sha module for shuffling > > the bits, but the resulting period is huge. > > How do you know what the period is? What makes you think it doesn't > depend on the seed? [I.e., for some seed, it may only produce a > single value continuously]. Suppose f is the SHA-1 hash function and you calculate f(x), f(f(x)), f(f(f(x))), etc. And suppose this sequence repeats after N iterations. Then, after N trials, you have found either something that maps to x under SHA-1 or else two things that map to the same place. If N is much less than the square root of the number of possible SHA-1 values -- i.e., if N is much less than 2**80 -- then SHA-1 is broken with high probability :-). Another way to use a cryptographic hash function to generate random numbers is to calculate f(0), f(1), f(2) and so on. This has some advantages: you can revisit any set of old values you like without having to start at the beginning and recalculate them all, and you can start several sequences off in different places and know how long it will be until any sequence starts reproducing any other. Using the Mersenne Twister that will be in Python 2.3 is, as others have said, probably a better approach in practice. :-) -- Gareth McCaughan Gareth.McCaughan at pobox.com .sig under construc From vivek-killspam at cs.unc.edu Tue Mar 18 15:38:27 2003 From: vivek-killspam at cs.unc.edu (Vivek Sawant) Date: Tue, 18 Mar 2003 15:38:27 -0500 Subject: Help: re.match puzzle Message-ID: <3E7783C3.4050701@cs.unc.edu> I am not able to figure out why re.match is not matching the following simple regex. Python 2.2.2 (#1, Nov 27 2002, 11:14:26) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import string >>> import re >>> line = '24 bytes from 128.59.67.201: icmp_seq=1 ttl=56 time=15.2 ms' >>> pat = '(?P
1 abc 2 def 3 > ghi 4 jkl Using RE's to parse HTML, when Python already offers wonderful tools such as HTMLParser to do that, is rather absurd, of course. > With a regular expression like below (where the variable 'text' is the > sample above), re1 saves the numbers, but not the text. Why is that? ... >>>> re1 = re.compile("([0-9]+?)(.*?)") I don't understand the question. You're matching one or more digits quite explicitly with [0-9]+? -- why would you expect that to match any non-digits? BTW, you may as well use + rather than +? here -- no difference in doing the repetition as non-greedy, since you're then explicitly going for a non-digit. After the you match "zero or more of any character, non-greedy" and there ends -- so of course the last group will always match zero characters. If I divine correctly what you're trying to do, then: "]*>([0-9]+)([^<]*)" may come closer to your purposes. [^>]* means, zero or more characters that aren't right-angle-brackets; and similarly [^<]* means, zero or more that aren't left-angle-brackets. But you're still better off using HTMLParser or the like. Alex From andy at reportlab.com Thu Mar 20 16:42:54 2003 From: andy at reportlab.com (Andy Robinson) Date: Thu, 20 Mar 2003 21:42:54 +0000 Subject: Website using Python--what's best architecture? CGI? References: Message-ID: > >So, don't CGI ! Programming a CGI highly dynamic site is a hassle, even with >the help of a templating or HTML generator package (like HTMLGen and >others). I disagree. Several years of making reporting 'add-ons' to other people's app servers, which are usually CGI scripts, has taught me something very interesting. Our apps consistently respond several times faster than the big Websphere or ASP systems that talk to them. The other systems have usually been written by large numbers of smart programmers over time and tend to get big and slow as they add more features, or maybe just because they have a heck of a lot of code to execute in their main loops.. I also think that how the process is initiated (which is what CGI is about) has absolutely nothing to do with the framework you use or don't use. You can make a simple, clean dispatch mechanism and a few utilities to preserve state with tokens in very few lines of code. And if your web frame work is <1000 lines of Python code, which is plenty, there won't be a big startup overhead. Please measure for yourself the actual time taken to execute a 'hello world' type page which does one query and formats the output on the different frameworks you are considering. I usually find the startup overhead is < 0.1 seconds. Then consider the benefits of never having to worry about a memory leak, contend with bugs in large frameworks, restart an app server or whatever. Web architectures are like all other optimisation issues in programming: don't guess what the results will be without measuring, and don't optimize if the simple solution is already fast enough. >In addition, playing with CGI means creating a new DB connector for each >request when (most) Web application servers handle open DB connections pools >for you. True, but...please measure the connection overhead. I constantly hear this old thing about database connections taking time and resources, but on the environments I have worked with most (Sybase and MySQL, with the database in the same server rack as the app server), the connect-query-disconnect time is almost identical to the straight query time. OTOH I was told once that Oracle could take seconds and allocate megabytes of RAM for each connection. This would be a really fun topic for a Python conference: set a simple task and actually test and benchmark all those web frameworks. ;-) Andy Robinson ReportLab inc. From mwh at python.net Mon Mar 31 08:19:58 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 31 Mar 2003 13:19:58 GMT Subject: Is Jython development still undergoing? References: <40Hha.18261$VM3.6268848@news4.srv.hcvlny.cv.net> Message-ID: <7h365pzn05d.fsf@pc150.maths.bris.ac.uk> "John Smith" writes: > I apologize if this is a wrong plact to ask. I think there is a jython-dev list somewhere... > First, I'm so thankful to the Jython project. It's so wonderful tha > I just can't have enough of it. But I can't help but wondering if > Jython development is still alive. The latest version (2.1) is about > 2 release behind CPython (2.3alpha now) and is 15 months old. Is > Jython 2.2 on the horizon? No idea myself, sorry, but: > I really like to port my code full with "class mylist(list): " to > jython. Can't you do this already? I though this was one limitation jython didn't have... Cheers, M. -- I have gathered a posie of other men's flowers, and nothing but the thread that binds them is my own. -- Montaigne From hilbert at microsoft.com Fri Mar 7 04:19:35 2003 From: hilbert at microsoft.com (Hilbert) Date: Fri, 7 Mar 2003 01:19:35 -0800 Subject: c = {x: '' for x in a} Message-ID: Ok. This works: a = [1,2,3] b = [x for x in a] What's wrong with this one though? It would totally make sense to me... a = [1,2,3] c = {x: '' for x in a} Where can I find documentation about "[x for x in a]"? What is it called? Thanks, Hilbert From skender at webman.com Tue Mar 25 04:26:13 2003 From: skender at webman.com (Skender) Date: Tue, 25 Mar 2003 20:26:13 +1100 Subject: I/O Serial and Parallel References: Message-ID: Les Smithson wrote: >>>>>> "Skender" == Skender writes: > > Skender> Hi, Is there any modules out there which will allow you > Skender> to address hardware I/O ports from Python. I foud a site > Skender> "http://www.hare.demon.co.uk/ioport/ioport.html", but > Skender> this does not seem to compile/work. > > Skender> Skender. > > Works for me. What didn't compile/work for you? I got the following message: skender at webman ioport0.2]$ python ./setup.py build running build running build_ext Traceback (most recent call last): File "./setup.py", line 11, in ? ext_modules=[module_ioport]) File "/usr/lib/python2.2/distutils/core.py", line 138, in setup dist.run_commands() File "/usr/lib/python2.2/distutils/dist.py", line 893, in run_commands self.run_command(cmd) File "/usr/lib/python2.2/distutils/dist.py", line 913, in run_command cmd_obj.run() File "/usr/lib/python2.2/distutils/command/build.py", line 107, in run self.run_command(cmd_name) File "/usr/lib/python2.2/distutils/cmd.py", line 330, in run_command self.distribution.run_command(command) File "/usr/lib/python2.2/distutils/dist.py", line 913, in run_command cmd_obj.run() File "/usr/lib/python2.2/distutils/command/build_ext.py", line 231, in run customize_compiler(self.compiler) File "/usr/lib/python2.2/distutils/sysconfig.py", line 145, in customize_compiler (cc, opt, ccshared, ldshared, so_ext) = \ File "/usr/lib/python2.2/distutils/sysconfig.py", line 427, in get_config_vars func() File "/usr/lib/python2.2/distutils/sysconfig.py", line 332, in _init_posix raise DistutilsPlatformError(my_msg) distutils.errors.DistutilsPlatformError: invalid Python installation: unable to open /usr/lib/python2.2/config/Makefile (No such file or directory) From bbondi at pacbell.net Sat Mar 1 18:52:43 2003 From: bbondi at pacbell.net (Bob) Date: 1 Mar 2003 15:52:43 -0800 Subject: Help: except clause ordering Message-ID: C:\Python22\Doc\tut\node11.html#SECTION0011100000000000000000 is the location on my PC with the 9.7.1 Exceptions Can Be Classes section displayed you can see this example which will display B C D class B: pass class C(B): pass class D(C): pass for c in [B, C, D]: try: raise c() except D: print "D" except C: print "C" except B: print "B" yet if moving the except clauses to reverse the order what is displayed is B B B this is all just as the tutorial says. I do not 'get it'. Why B, B, B rather than D, C, B? From thomas at xs4all.net Wed Mar 5 11:11:57 2003 From: thomas at xs4all.net (Thomas Wouters) Date: Wed, 5 Mar 2003 17:11:57 +0100 Subject: Waffling (was Re: single-line terinary operators considered harmful) In-Reply-To: References: <882b0a41.0303020225.3caf0334@posting.google.com> Message-ID: <20030305161157.GA29060@xs4all.nl> On Wed, Mar 05, 2003 at 02:45:53PM +0000, Stephen Horne wrote: > On Wed, 5 Mar 2003 12:43:05 +0100, Thomas Wouters > wrote: > >On Wed, Mar 05, 2003 at 11:06:46AM +0000, Stephen Horne wrote: > >> just as Guido kept ';' as an optional statement terminator. > >';' is more of a statement separator than a terminator. From the Grammar > >file: > >simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE > Hmmm - that final [';'] looks like an optional terminator, even for > the final statement in the line, to me ;-) Of course, I really > wouldn't expect to see it used. Well, you can add whitespace between the statement and the newline... does that make whitespace an 'optional terminator' too ? :-) It might seem as a silly semantic issue, but there is definately a difference between a ';' in C and Perl et al, and in Python. I see the final ';' above more as a consistency feature (which is important in Python, at least to me.) And having an "optional terminator" is just silly, it either terminates or it doesn't, and if it's optional it doesn't really terminate :) > Once it's optional, the separator-or-terminator distinction really > doesn't make much difference though. IIRC the semicolon is a separator > rather than a terminator even in C. For instance... > if (condition) > { > statement; > /* there is an implicit null statement here */ > } No, sorry. In C, the semicolon is a terminator, not a separator. For instance: i++ +j; is something completely different than i++; +j; (And to make things even more fun, i+ ++j; is not what it seems to be; this will post-inc i, not pre-inc j, because of C's syntax rules.) If the semicolon was really just a separator, C would be able to tell when a statement (that consists of just an expression) ended without them. In Python, statements are terminated by a newline. > Proper indentation is good coding style in any block structured > language, whether it's enforced or not. Even where the compiler > doesn't use or enforce it, anyone who has to read or maintain your > source code is likely to bite your head off if the indentation is > confusing or misleading. I've seen cases where this almost literally > came true. Once or twice it was only the zits and greasy hair that > stopped me doing it myself ;-) I've seen worse. One project I'm involved in had a function to open a directory and read the entries looking for all files fulfilling a requirement. As usual, it skipped files with leading dots. However, something must have gone wrong, because the entire function was #if 0'd out, and replaced by a function that popen()'d a perl process to do exactly the same thing. Now this wasn't a terribly frequent operation, but still frequent enough for me to be scared about executing perl each time :) So I tried to figure out what was wrong with the disabled, pure C code, and found it after a single pass of indent. This was the code before the indent: if (line[0] == '.'); continue; Isn't C luverly ? :) For those who don't know C, what the above statement does should be obvious, as it's nearly the same as the Python. Except that in C, an 'if' suite isn't marked by a colon and an indented block, but either by curly braces, or by being exactly one line. so if (condition) { code(); } and if (condition) code(); do the same thing. The problem with the above example was the semicolon after the if(), which basically turned the block into: if line[0] == '.': pass continue > Some people really seem to miss the explicit '{' and '}' (or 'begin' > and 'end' or whatever). I've never quite understood why, but having > seen the debate run a couple of times I have accepted that to be a > failing of my imagination. There are also lots of people who can't seem to like Python, or really prefer Perl. I really can't imagine that (I write Perl for a living, nowadays, and I really wish I wasn't) but I can accept that they don't like Python. Python apparently can't cater to everyone (but yes, I do wonder why :) I've heard maybe one compelling reason not to use indentation, embedding code into other markup, but having written Perl that uses HTML templates to generate JavaScript that generate HTML tables for inside overlays (and in particular, debugging those) I now consider that a feature. Other uses for blocks can be solved using '# {' and '# }', in my eyes. > >If I ever were to design my own language, I certainly would not use block > >delimiters unless I really really had to, and even then I'd try to find an > >alternative. > I'm not sure I understand what you mean by finding an alternative. An > alternative to '{' and '}'? Or a wider alternative avoiding any > explicit delimiting tokens, yet different to indentation? No, an alternative to solve the problem that would otherwise be solved by not making indentation mark blocks. E.g. issues with embedding the code into other markup. I would rather solve that in the embedding than in the language. > If you'd look for a non-delimiter solution, the only real alternative > I can think of is a continuation-based system - like using '\' to > continue statements over multiple lines. Which leads me to say - > "yuck!!!". I find multiline statements generally get that way by > containing big expressions, so I use extra brackets to avoid the '\' - > which brings us back, in principle, to delimiters! On the other end of the spectrum, I find that whenever I think I need a \, I go back and look at the code, and decide another way with a shorter 'if' or one that continues naturally (like braces) is clearer, and I end up with (to me) nicer code. This often involves more objects and more features, without too much extra effort. (I find I do that a lot nowadays, incremental software development by running several cycles (including tests, of course) before releasing the product to user-testing. :) > Delimiters aren't really bad in principle, or else they wouldn't have > lasted this long in so many different languages. It's just that > indentation is usually even better - or else it wouldn't be considered > good style in languages that already require delimiters. Don't forget that programming languages are still in development. They are quite new, and also have to struggle to keep in pace with hardware development. Considerations that were true for such languages as FORTRAN or C, such as ease and efficacy of parsing, compiler-writing and resulting code, are no longer an issue for a language as, say, Python or Perl or even language that share part of the domain, such as Java and C++. And also don't forget that languages are designed by humans, and many designers build on the features that they are familiar and comfortable with -- even if they aren't terribly efficient. Even Python! Python really isn't that innovative as a language, it's just very well put together, both in design and in implementation. Just look at how strained the ternary operator proposals all look; the idea comes from C and Perl (for many people, at least) and so the tendency is to make the syntax look like C -- and all other syntactic suggestions look odd. (Or is that just me ? :) -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! From m.faassen at vet.uu.nl Fri Mar 21 06:11:29 2003 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 21 Mar 2003 11:11:29 GMT Subject: Python and Nuclear Safety (Re: PEP 312 (and thus 308) implemented with a black magic trick) References: Message-ID: "Greg Ewing (using news.cis.dfn.de)" wrote: > Tim Churches wrote: >> Are you the Greg Ewing of Pyrex fame, from Canterbury University in New >> Zealand? If so, I didn't think New Zealand had a nuclear arsenal. > > I am, but on that occasion the PSU was using me to channel > their thoughts (they frequently pick random people from around > the world for that, to better obfuscate their identity, or > lack thereof). It seems that "our country" in their > announcement is meant to refer to the USA. Can't have been the real PSU then, as the real PSU is a cross-time organization and "our country" would mean From mwh at python.net Thu Mar 6 08:16:26 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 6 Mar 2003 13:16:26 GMT Subject: Concerns about performance w/Python, Pysco on Pentiums References: <3E660EB3.4065D81F@engcorp.com> <3E66B6AE.2AAAAEC5@engcorp.com> Message-ID: <7h38yvsiqpe.fsf@pc150.maths.bris.ac.uk> Peter Hansen writes: > > Still this sounds like memory is the bottleneck ... You could try to look > > at the cache misses for your process, if that is at all possible. > > Not knowing that much about Linux I'd be at a loss to do this on my > own. Any suggestions for where to look? Googling for cachegrind might lead to enlightenment. It comes with valgrind. Interpreting its output is probably something of a black art. 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 intentionally at blank.co.uk Wed Mar 5 11:44:09 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Wed, 05 Mar 2003 16:44:09 +0000 Subject: Waffling (was Re: single-line terinary operators considered harmful) References: <3e6618c4$0$248$edfadb0f@dread11.news.tele.dk> Message-ID: On Wed, 05 Mar 2003 16:11:40 +0000, Stephen Horne wrote: >On Wed, 5 Mar 2003 16:34:21 +0100, "Anders J. Munch" > wrote: > >>You are wrong on this point. > >OK - I'm surprised, but can't be bothered looking up the standard, >especially as I'm probably just getting confused with the comma >operator (which is *effectively* a separator, being an infix >operator). Oops - I think I just figured it out... There was definitely a language I used where you'd get a null statement by having a semicolon after the last statement of a block (not that anyone cared), and now - I think it was Pascal. I can't believe I confused Pascal and C !!! Or am I still wrong? -- steve at ninereeds dot fsnet dot co dot uk From aleax at aleax.it Tue Mar 25 10:39:59 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 25 Mar 2003 15:39:59 GMT Subject: Const in python? References: Message-ID: David Brown wrote: > > "Alex Martelli" wrote in message > news:bAXfa.6199$Jg1.139809 at news1.tin.it... >> David Brown wrote: >> ... >> > might use. For example, some programs might want to change some >> > built-ins, or some common library functions - perhaps as part of > debugging >> > or profiling (maybe you want to find out how many times "len" is > called - >> >> And what if you want to find out how many times operator + is used (on >> any objects whatsoever, just as here you want to count uses of built-in >> 'len' on any object whatsoever)? What makes counting the uses of 'len' >> more important than counting the uses of '+', enough to warrant slowing >> all programs down (or making everything more complicated) to enable the >> former by simpler means than the latter? >> > > Is it not possible to override the "+" operator as well? As you point Not for ALL types of objects -- no way to get at the + used when you code 2+2. You can override __plus__ in your OWN type -- just as you can override __len__ in your own type. That you can REBIND the built-in name 'len' is a completely different issue, and you cannot do anything comparable with '+' (you need to work on bytecode, etc, etc). > out, the vast majority of users have no need of doing that sort of thing - > that > includes me, so I've never looked at how it might be done. My preference > is, of course, to have the best of both worlds - in general I too would > prefer increased speed for common operations, but I think the flexibility > to > override things when needed is important. In the case of something like "When needed" is the key here. > "len", or "+", the overwhelming majority of uses do not require > overriding, > and could benifit from speed-ups. But what about, for example, methods in > a > user defined class? The majority of these are static, but sometimes you > want to change them - the ability to do this, even while running the > program, is one of the big benifits of Python. If it were practical, then > flexible locking would allow you to choose - perhaps builtins and standard > libraries would be locked by default, but unlockable if desired, and other > modules would be unlocked until explicitly locked. Yes, that would make sense. But to enable compiler optimizations, unlockable builtins would not be an option. > Failing that, a compiler (command-line) switch that selects locked or > unlocked builtins (with locked being the default) would be likely to make > a big difference, with perhaps less work. It may be necessary to allow disabling of the locked-builtins optimization, perhaps. But I suspect the amount of work to allow both ways would not necessarily be trivial. > Perhaps it would also be possible to make use of a pysco-like system, > except > that optomised Python bytecode is produced rather than machine code? As > far as I understand it, pysco "locks" common functions such as built-ins. It does? Didn't last I checked it, but that WAS quite a while ago. Alex From mwh at python.net Tue Mar 4 07:58:02 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 4 Mar 2003 12:58:02 GMT Subject: code coverage tool References: <7h3n0kbjpnk.fsf@pc150.maths.bris.ac.uk> Message-ID: <7h3el5njnqv.fsf@pc150.maths.bris.ac.uk> Alex Martelli writes: > Michael Hudson wrote: > > > Alex Martelli writes: > > > >> Haven't tried pyCover, but I _have_ noticed the hotshot "profiler" has > >> all the hooks one needs to use it in a simple statement-coverage mode, > >> and it seems to have very low overhead when used that way; > > > > I've probably done for that in 2.3, alas. > > meaning that hotshot doesn't work any more in 2.3, or that > it's become high-overhead, or...? The overhead is probably somewhat higher because of the way line trace events are generated in 2.3 is what I meant. Fallout from the removal of SET_LINENO. I haven't actually tried it, so I might be hopelessly wrong... Cheers, M. -- : exploding like a turd Never had that happen to me, I have to admit. They do that often in your world? -- Eric The Read & Dave Brown, asr From eddie at holyrood.ed.ac.uk Wed Mar 26 07:24:14 2003 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Wed, 26 Mar 2003 12:24:14 +0000 (UTC) Subject: Remote MAC Address In Python References: Message-ID: g.papamarkos at dcs.bbk.ac.uk (George Papamarkos) writes: >Hi guys, > Does anyone know if there is a way in Python to grab the MAC >Address of a computer in a network knowing only its IP Address from a >Linux machine ? Solutions using "arp" command etc. do not work >properly. I'd like something more generic pls. If the machine is up and running and on your LAN then ARP is the proper way to get the MAC address. I notice you say arp "command" rather than "protocol" so you may be relying on the existing ARP table which will time out after a while. If you ping the address first then it will make sure that an entry is in the ARP table when you come to check it. If the remote machine is not on your LAN you need to probe routers using SNMP or such like. Eddie From missive at frontiernet.net Mon Mar 10 19:09:07 2003 From: missive at frontiernet.net (Lee Harr) Date: Tue, 11 Mar 2003 00:09:07 -0000 Subject: A fun tool for demonstrating or teaching python? References: <9s7ba.2698$4q6.305236@news20.bellglobal.com> Message-ID: In article <9s7ba.2698$4q6.305236 at news20.bellglobal.com>, WP wrote: > There was a discussion (I found it using groups.google.com) a while ago with > some people interested in building a very easy-to-use IDE for teaching Python, > possibly even with Kids. > > I am thinking of whipping up something, perhaps with the ability to walk > through the code ('animated' debugger) and to do something visual or > graphical, turtle graphics, or a game, or something like that. > I am working on a project with a similar idea: http://www.nongnu.org/pygsear/ http://savannah.nongnu.org/projects/pygsear/ I have a turtle module... though it just uses the terminal for input right now. From mcherm at mcherm.com Thu Mar 20 08:43:42 2003 From: mcherm at mcherm.com (mcherm at mcherm.com) Date: Thu, 20 Mar 2003 05:43:42 -0800 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 17) Message-ID: <1048167822.3e79c58e27b54@mcherm.com> Michael Chermside: > [1] A really interesting argument can be made that it's got just as > many 9's as 0's, since "x.00000..." = "(x-1).99999..." by most useful > definitions. Does this mean that integers are normal in base 2? Steven Taschuk: > Imho, the argument is not so interesting. The equiprobable > distribution property is a property of the symbol sequence, not > strictly speaking of the number. Thus the notion of normality of > a number requires some function from numbers to symbol sequences, > or a set of such functions. That is, unique representations are > required. Indeed... that's part of what I find interesting about it. Normality seems a sensible thing to define on numbers (and every definition I've seen so far has proported to define it as a property of numbers) -- until you encounter this and realize it's REALLY a property of symbol sequences, which do NOT have a simple, obvious, one-to-one mapping to (all) real numbers. Perhaps Python 4000 will run on a quantum computer[1]: import sys assert sys.version_info[0] >= 4 # class IrrationalNumber: """Actual irrational numbers should subclass this and implement the iterDigits() method.""" def iterDigits(base): """Returns an iterator of the digits of the sequence. subclasses should implement.""" raise NotImplementedError def __iter__(self): return self.iterDigits(base=10) def isNormal(self, base=None): if base is None: for b in range(2, Infinity): if not isNormal(self,b): return False return True else: digitCounts = dict( [(d,0) for d in range(base)] ) for digit in iter(self): digitCounts[ digit ] += 1 for count in digitCounts[1:]: if count != digitCount[0]///Infinity: return False return True I-started-testing-this-code-but-it-hasn't-finished-running-yet -- Michael Chermside [1] From http://www.newsfactor.com/perl/story/19601.html: "Our quantum algorithm could, in fact, be regarded as an infinite search through the integers in a finite amount of time". I don't know enough to evaluate this independently. But I can dream! From aleax at aleax.it Thu Mar 6 17:30:29 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 06 Mar 2003 22:30:29 GMT Subject: Pure Embedding References: <20030306212940.3a2ca6e5.khornie@poczta.onet.pl> Message-ID: <9_P9a.22020$zo2.642946@news2.tin.it> Khorne wrote: > Hello! > > Can anyone tell me why *untouched* "pure embedding" example from > python.org just does not work? The code can be found at > http://www.python.org/doc/2.2.2/ext/pure-embedding.html > > I wote the following script: > > -script.py- > > def func(a,b): > return a+b > > -end- > > And I get: > > [root at khorne python]# ./call ./script.py func 1 2 > ValueError: Empty module name > Failed to load "./script.py" > > WTF? The example usage give in the URL you quote is: $ call multiply 3 2 Hint: does the example usage give a path and extension? Does your failing use attempt give them? I think the example will probably also fail when used as documented, because the current directory is not, by default, in sys.path for embedded Python -- I just posted about this and the solution[s] in another thread, just a few hours ago, so please look my other post up for details. Alex From b.maryniuk at forbis.lt Tue Mar 11 02:32:11 2003 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 11 Mar 2003 09:32:11 +0200 Subject: Fixes to zipfile.py [PATCH] In-Reply-To: References: <87heae244i.fsf@christoph.complete.org> <3E6A4322.9010908@rsballard.com> Message-ID: <200303110932.11812.b.maryniuk@forbis.lt> On Saturday 08 March 2003 21:32, Steve Holden wrote: > A good idea for Windows, but sadly not portable to Unix. And thanks to God. We have dozen of small and free zip/unzip utilities in our accessories. -- Regards, Bogdan Linux -- the OS for the Renaissance Man From BPettersen at NAREX.com Thu Mar 6 14:44:23 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 6 Mar 2003 12:44:23 -0700 Subject: embedding python - PyImport_ImportModule returns null Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192022DD94C@admin56.narex.com> > From: Alex Martelli [mailto:aleax at aleax.it] > > JW wrote: > > > I am trying to embed python within a c program, but I can't get > > PyImport_ImportModule() command to load my module. > > Please let me know what I'm doing wrong. > ... > > Both main.c and func.py are in the same directory. > > I run main and get the error > > Failed to load "func", meaning that PyImport_ImportModule > returns NULL. > > The current directory is not necessarily on sys.path. Notice: Hi Alex, Perhaps you would know how to import a module so that it can be used in PyRun_String()? I've tried PyImpor_Import, PyImport_ImportModule, and PyImport_ImportModuleEx which all imported the module but didn't make it visible. void main() { Py_Initialize(); PySys_SetPath(Py_GetPath()); PyObject* mainmod = PyImport_AddModule("__main__"); Py_INCREF(mainmod); PyObject* ns = PyModule_GetDict(mainmod); Py_INCREF(ns); PyObject* timeModule = PyImport_ImportModuleEx("time", ns, ns, NULL); if (!timeModule) std::cout << getTraceback() << std::endl; std::cout << "time module imported successfully" << std::endl; PyObject* timeFn = PyRun_String("time.time", Py_eval_input, ns, ns); if (!timeFn) std::cout << getTraceback() << std::endl; Py_XDECREF(timeModule); Py_XDECREF(timeFn); Py_DECREF(ns); Py_DECREF(mainmod); Py_Finalize(); } and the output: Adding parser accelerators ... Done. time module imported successfully Traceback (most recent call last): File "", line 0, in ? NameError: name 'time' is not defined [4099 refs] -- bjorn From dg96057 at teledomenet.gr Mon Mar 10 20:03:51 2003 From: dg96057 at teledomenet.gr (Dimitris Garanatsios) Date: Tue, 11 Mar 2003 03:03:51 +0200 Subject: referring from within containers objects In-Reply-To: References: <3e6c8de7$0$6145$4d4eb98e@read.news.gr.uu.net> Message-ID: <3e6d34fe$0$6152$4d4eb98e@read.news.gr.uu.net> Terry Reedy wrote: > "Dimitris Garanatsios" wrote in message >>For your example i would use a class definition instead of a > > dictionary like > >>class Baptize: >> def __init__(self, fname, mname, lname): >> self.fname = fname >> self.mname = mname >> self.lname = lname >> self.fullname = fname +' '+ mname +' '+ lname >> >>and instantiate it like >> >>baby = Baptize('Pretty', 'Python', 'Syntax') > > > A class is a good idea, but the above still has the same problem of > consistency management. One can use use __getattr__ and __setattr__ > to get and set virtual attributes as needed. Even better: make > Baptize a new class (subclass from object) and you can use a fullname > property that will do the catenation on demand. This is one of the > sorts of things that properties were meant for ;-). > > Terry J. Reedy > I admit that new-style classes is a powerfull tool indeed but they seem to be under heavy development for the last few months... So far i have come into several problems using them because of the lurking bugs among their innocent implementation :-) that made my code unportable between the various 2.x.x python versions due to bugfixes that were released... So until the whole situation is somewhat stabilized (and i imagine this should be soon) the godfather can better Baptize babies the old way like this: class Baptize: def __init__(self, fname, mname, lname): self.fname = fname self.mname = mname self.lname = lname def fullName(self): return self.fname +' '+ self.mname +' '+ self.lname while keeping data consistent at the same time and with no need to complicate things using __getattr__ and __setattr__. Of course this is just an example to demonstrate an alternative to the original idea, afterall we all know that it whould be best to godfather.baptize(baby) using simple and more appropriate data structures ;-) From blakeg at metalink.net Wed Mar 12 22:01:54 2003 From: blakeg at metalink.net (Blake Garretson) Date: Wed, 12 Mar 2003 22:01:54 -0500 Subject: GCD in standard library? References: <3E6FE2A7.DCDE0C96@alcyone.com> Message-ID: > So I'm thinking the recursive version is faster? Is that right? Forget everything I said. I screwed up the whole timing thing. I REALLY shouldn't be doing this so late at night! Sorry. From mchermside at ingdirect.com Tue Mar 18 11:07:11 2003 From: mchermside at ingdirect.com (Chermside, Michael) Date: Tue, 18 Mar 2003 11:07:11 -0500 Subject: PEP 312 (and thus 308) implemented with a black magic trick Message-ID: <7F171EB5E155544CAC4035F0182093F03CF7AE@INGDEXCHSANC1.ingdirect.com> I just wanted to say that I'm really impressed. It's pure evil, of course, but nonetheless very beautiful and astoundingly simple. For some reason I'm more disturbed by the mis-use of operator overloading than by the metaclass which modifies code... perhaps because I've been burned by the former before (in C++). -- Michael Chermside From zhitenev at cs.vsu.ru Fri Mar 28 08:37:34 2003 From: zhitenev at cs.vsu.ru (Lexy Zhitenev) Date: Fri, 28 Mar 2003 16:37:34 +0300 Subject: Pickling objects into database References: Message-ID: "Kresimir Kumericki" wrote in message: news:b61431$ms1$1 at bagan.srce.hr... > dict = { ... some items ...} > > qry = 'UPDATE table SET blobcolumn="%s" WHERE id=someid' %\ > (MySQLdb.escape_string(cPickle.dumps(dict)), someid) > > cursor.execute(qry) > > > This seems to be working properly but, being a newbie to all this, I am > somewhat concerned about forwarding cPickle.dumps() *ugly* strings to > database like this. Is MySQLdb.escape_string up to the job of escaping > everything that should be escaped? Is there a better way of doing this? According to PHP documentation, 'escape_string', which is an alias for 'mysqli_real_escape_string' escapes all special characters taking into account the current charset of the connection. Escaping is done for all characters with codes under 32 (space ' ') and over 127 for ASCII. I think Python version does the same. Generally, you don't need to worry. escape_string will escape all symbols which it will think unusable, at least '. Also remember that cPickle has two formats of data: binary and text. Text format saves all data using ASCII symbols (32..127), while binary format uses all 256 symbols, thus requiring less bytes. Regards, Lexy. From rudy.schockaert at pandora.be Tue Mar 25 14:21:27 2003 From: rudy.schockaert at pandora.be (Rudy Schockaert) Date: Tue, 25 Mar 2003 19:21:27 GMT Subject: Searching in Active Directory (also using LDAP in Windows) References: <2d0ga.6354$t_2.924@afrodite.telenet-ops.be> Message-ID: "Michael Str?der" wrote in message news:m7m6l-g83.ln1 at nb2.stroeder.com... > Rudy Schockaert wrote: > > > > I also tried Python-LDAP, but no avail either. > > > > > > Which version, which platform? > > > > All I'm doing for the moment is on Windows 2000 platform. I used > > Python-LDAP-1.10a3.win32-py2.2.exe which was the latest version I could find > > for Windows > > This is build against ancient Umich 3.3 LDAP libs => LDAPv2. This could be > the problem (see also item 7. on http://python-ldap.sourceforge.net/faq.shtml). > > Ciao, Michael. > Indeed, that will probably be the reason. Maybe I'll try to get the OpenLDAP 2.0 libs running under Cygwin. I know what to try next; Thanks, Rudy From durdn at yahoo.it.oops!.invalid Sat Mar 22 07:11:27 2003 From: durdn at yahoo.it.oops!.invalid (Nicola Paolucci) Date: Sat, 22 Mar 2003 12:11:27 GMT Subject: a regular expression question In-Reply-To: <577e43a1.0303212331.5eaf93e5@posting.google.com> References: <577e43a1.0303212331.5eaf93e5@posting.google.com> Message-ID: Hi Luke, Luke wrote: > 1 abc 2 def 3 > ghi 4 jkl > > If I use re2, it works, but obviously only gets the odds since there > is no overlapping. Is there a way to modify re1 to get the text, or > is there a way to overlap with python's re engine somehow? >>>>re1 = re.compile("([0-9]+?)(.*?)") >>>>matches = re.findall(re1,text) >>>>matches > > [('1', ''), ('2', ''), ('3', ''), ('4', '')] This worked for me: >>> re1 = re.compile("]+>([0-9]+?)([^<]*)") >>> print re.findall(re1,text) [('1', ' abc '), ('2', ' def '), ('3', ' ghi '), ('4', ' jkl')] Best regards, Nicola Paolucci -- #Remove .oops!.invalid to email or feed to Python: 'Tmljb2xhIFBhb2x1Y2NpIDxuaWNrQG5vdGp1c3RjYy5jb20+'.decode('base64') From andres at mamey.com Sun Mar 2 11:31:18 2003 From: andres at mamey.com (Andres Corrada) Date: Sun, 02 Mar 2003 16:31:18 GMT Subject: How to turn tkinter module install off Message-ID: <20030302163118.19085.qmail@mail.sitepassport.net> Hello, I'm getting an error on install related to not finding the tkinter libraries. I don't care to have tkinter in my Python installation. But when I look at Modules/Setup I see that the tkinter paths are not enabled yet it still tries to compile them. I'm obviously not understanding Python's 2.2.2 way of doing module installs. How do I turn off the tkinter installation? Andres Corrada-Emmanuel From thomas at xs4all.net Thu Mar 13 04:40:22 2003 From: thomas at xs4all.net (Thomas Wouters) Date: Thu, 13 Mar 2003 10:40:22 +0100 Subject: "is" and "==" In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE2E78E9@au3010avexu1.global.avaya.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DE2E78E9@au3010avexu1.global.avaya.com> Message-ID: <20030313094022.GD2112@xs4all.nl> On Thu, Mar 13, 2003 at 07:05:13PM +1100, Delaney, Timothy C (Timothy) wrote: > > From: Thomas Wouters [mailto:thomas at xs4all.net] > > One can, but it would still be better to use '==', as this works even > > when intern (possible, in the future) would fail to do its job, and the > > identity test is the first test == does. > There is a guarantee that intern() will always[1] return the same string > instance for strings that compare equal. So you can rely on this > behaviour. It is *not* possible for intern to fail to do its job except > via a bug. Not at this time, no, hence my remark 'possible, in the future'. We started deprecating 'apply', so there is no reason to assume 'intern' will never go away. However, my post was wrong for a different reason: the identity check is no longer done in the fast path of ==, starting at Python 2.1 (from the looks of it.) It's still in the fast path of string comparison though. So, while 'is' being true no longer means '==' is true, I still believe, in general, it's better coding style to use '==' rather than 'is', even if you know you have intern'ed strings. It isn't *that* much slower than string-comparing interned strings, and it could save you from embarassing bugs where you forgot to intern a string ;) -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! From godoy at metalab.unc.edu Tue Mar 25 19:06:27 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Tue, 25 Mar 2003 21:06:27 -0300 Subject: Finding out the weekday References: <86adfjz286.fsf@ieee.org> <1ZKcnQPKB9e4Kh2jXTWcpQ@comcast.com> Message-ID: <86vfy7c7p8.fsf@ieee.org> "Terry Reedy" writes: > don't know if new datetime module has that. But formula is easy to > program. This has been asked various times on various newgroups. I know how to get that in Perl. I didn't want to convert the thing :-) I was trying not to reinvent the wheel. > Google 'day week formula', first hit says Oh my! Thanks I haven't included 'formula' in my search :-) Thank you very much for your help. -- Godoy. From eg at rootshell.be Wed Mar 5 07:22:35 2003 From: eg at rootshell.be (Eliran Gonen) Date: Wed, 5 Mar 2003 14:22:35 +0200 Subject: Books Database In-Reply-To: References: Message-ID: <20030305122235.GA930@rulix> Alex Martelli : > That depends on your purposes and on the size the database > is likely to grow to. A list of books, ability to locate books, remove/add entries. No more than 200-300 books (perhaps even less). > Example|Somedood|1969 > Wuffy|Puffy|2010 This seems to be nice, as I don't need any complexity. > and "parse" this with [ rec[:-1].split('|') for rec in afile ]. Thanks you all From andrew-pythonlist at puzzling.org Mon Mar 17 07:13:10 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Mon, 17 Mar 2003 23:13:10 +1100 Subject: generators and exceptions In-Reply-To: <20030317072755.GA9877@doublegemini.com> References: <20030315212905.GA3656@doublegemini.com> <20030317072755.GA9877@doublegemini.com> Message-ID: <20030317121310.GB22628@frobozz.local> On Mon, Mar 17, 2003 at 07:27:55AM +0000, Clark C. Evans wrote: > Thank you for responding Tim, as you expected my question is less > about what generator behavior is, as it is about what generator > behavior with regard to exceptions could be. > > On Sat, Mar 15, 2003 at 11:20:46PM -0500, Tim Peters wrote: > | > from __future__ import generators > | > class MyExc(Exception): pass > | > def mygen(val): > | > while val > 0: > | > if val % 2: raise MyExc > | > yield val > > val -= 1 > > | Read the PEP and your expectations will change . The code exactly as > | you gave should obviously produce only 4 (val is set to -1 and so the loop > | exits). With the suggested guess at what was intended, it should still > | produce only 4, but due to raising an exception within the generator when > | val is 3 (instead of falling off the end because val is -1). > > Right. I did, but this still didn't stop my expectations. I was wishing > that I could resume the generator after the exception was thrown. But from which would you expect it to resume? Just before the exception was raised? Just after? What about try/except blocks? What if the exception was raised inside a function called by a generator? What about an exception thrown by a generator that your generator calls? I can't see any useful answers to these that make sense, unless exceptions behave exactly as they do now. -Andrew. From enrique.palomo at xgs-spain.com Mon Mar 17 08:07:35 2003 From: enrique.palomo at xgs-spain.com (Enrique Palomo) Date: Mon, 17 Mar 2003 14:07:35 +0100 Subject: ftp Message-ID: Hello all There's any python module to transfer files (ftp) only with ftp commands (put, get, mput, ...) different of ftplib in which i must open the file to transfer, read it, ... Thanks. Enrique -------------- next part -------------- An HTML attachment was scrubbed... URL: From student00 at angelfire.com Thu Mar 20 14:02:42 2003 From: student00 at angelfire.com (student) Date: 20 Mar 2003 11:02:42 -0800 Subject: how to resize mega widgets Message-ID: sorry if this is somewhere in the docs .. .but i just can't find it i'm creating a Pmw.TextDialog and i can figure out how to change the default size of the text window inside, i create it as follows: self.dialog = Pmw.TextDialog(parent, scrolledtext_labelpos = 'n', title = title, defaultbutton = 0, label_text = label, hull_width = 100, hull_height = 150) these options don't seem to do anything (hull_width and hull_height), any ideas? thanks From me at privacy.net Tue Mar 11 18:10:28 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Wed, 12 Mar 2003 12:10:28 +1300 Subject: Vote on PEP 308: Ternary Operator In-Reply-To: <882b0a41.0303020225.3caf0334@posting.google.com> References: <882b0a41.0303020225.3caf0334@posting.google.com> Message-ID: Raymond Hettinger wrote: > Vote by email no later than Noon (EST) on Sunday, March 9, 2003. > > Vote Early. Vote Once. I would like to have done so, but, due to circumstances beyond my control, I was without news access during the week following the announcement of this vote, and I only found out about it after the deadline had passed. I feel somewhat disenfranchised. :-( Also, I see that this is being referred to as the "official" vote. Does that mean Guido has officially blessed this particular vote and given Raymond the authority to administer it? I don't remember seeing any announcement about that, although I may have missed it amongst all the other PEP 308 noise... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From exarkun at intarweb.us Mon Mar 17 01:13:23 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 17 Mar 2003 01:13:23 -0500 Subject: cPickling and variable scope problem In-Reply-To: References: Message-ID: <20030317061323.GC21859@meson.dyndns.org> On Sun, Mar 16, 2003 at 09:07:56PM -0800, Cere Davis wrote: > > Using Python2.2 > > I've got a piece of code that goes something like this: > > import sys,os,cPickle > > def getData(): > data["x"]="y" > > def stash(): > ouf=open("stuff",'wb') > cPickle.dump(data,ouf) > ouf.close() > > def unstash(): > inf=open("stuff",'rb') > data=cPickle.load(inf) > inf.close() "data" is a local in the above function. > > def main(): > global data > data={} > if os.path.exists("stuff"): > unstash() > print data.keys() > print data.values() > sys.exit(0) > getData() > stash() > > > if __name__ == '__main__': > main() > > > But I don't get any output for the data.keys() or data.values() from > "main". Can someone tell me what's wrong here? > Perhaps obvious, but I am not seeing the problem..... Jp -- "Pascal is Pascal is Pascal is dog meat." -- M. Devine and P. Larson, Computer Science 340 -- up 13 days, 21:59, 8 users, load average: 0.00, 0.00, 0.00 From cben at techunix.technion.ac.il Fri Mar 21 04:46:03 2003 From: cben at techunix.technion.ac.il (Beni Cherniavsky) Date: Fri, 21 Mar 2003 11:46:03 +0200 (IST) Subject: Idea for reduce (Re: Question regarding a recent article on informit.com) In-Reply-To: References: Message-ID: On 2003-03-21, Greg Ewing (using news.cis.dfn.de) wrote: > Ben S wrote: > > Are there any good tutorials of examples of list comprehension use? In > > particular, I'm interested in how to replicate the functionality of > > reduce? Map and filter seem easy to do, though. > There is an evil way: >>> from operator import add >>> numbers = [1, 2, 3, 4, 5] >>> reduce(add, numbers) 15 >>> [sum for sum in [0] for n in numbers for sum in [sum + n]] [1, 3, 6, 10, 15] >>> [sum for sum in [0] for n in numbers for sum in [sum + n]][-1] 15 The trick is using single-value lists for avriable assignment. This is not entirely ugly but not readable enough; better don't use it in your code ;-) > As has been pointed out, list comprehensions don't (and > aren't meant to) substitute for reduce, only for map > and filter. > > Something else again would be needed if we wanted a > reduce-substitute. While I'm far from certain that it > would be worth it, it's interesting to speculate on what > a Pythonic reduce-syntax might look like. > > We want something that says things like "add up this > list of numbers". Let's see... if we were to make > "up" a new (possibly pseudo) keyword... > > from operator import add > numbers = [1, 17, 42] > total = add up numbers > > Howzat look? :-] > ``sub up`` wouldn't look good :-). You also need syntax for initial value. Most importantly, your syntax still expects a callable - avoiding that is the main benefit of list comprehensions over `map`. How about:: total = (accumulate sum = 0 then sum + n for n in numbers) Not brilliant either... I'd vote this YAGNI since the equivallent loop is more readable anyway:: total = 0 for n in numbers: total += n For inspiration on baroque loop design, look at Common Lisp's `loop` macro. It has all this and more, for all cases you want, if you want them, else it still has it :-]. -- Beni Cherniavsky [Sorry for some recent duplicate posts... My news gateway is bogus] From BrenBarn at aol.com Fri Mar 7 14:22:54 2003 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 7 Mar 2003 19:22:54 GMT Subject: Perl Vs Python References: <3E68DC7B.3020706@indy.rr.com> Message-ID: Tim Ottinger wrote: > If one has web access, the python wiki and web sites are quite > good. > > But you don't see as many python books as perl books at the local > shop. Maybe we don't need as many. Indeed, I tend to prefer online docs to bound printed volumes. Even if you don't have regular web access, you can do a one-time download of the docs at an e-cafe or whatever to get them. It's much easier to update computerized docs and much easier to obtain the updated versions, so you get much more current information. Plus, you get it for free instead of having to pay for a book. -- --OKB (not okblacke) "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From exarkun at intarweb.us Thu Mar 20 12:41:19 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 20 Mar 2003 12:41:19 -0500 Subject: calling a program without waiting for it to finish In-Reply-To: References: Message-ID: <20030320174119.GA2880@meson.dyndns.org> On Thu, Mar 20, 2003 at 09:07:42AM -0800, Brian Munroe wrote: > > the shell interactively, only, of course!-) as soon as it's done > > setting things up, so the pipeline runs in separate processes. > > > > os.system delegates the whole operation to the system shell (normally > > sh) so the above information should be directly applicable... > > > > So if you enter os.system('ping blah.com &') it will basically shell out > to the os and run the ping command in the background? If you use ping > without a -n option (atleast on the machine I am on) it will continue > to ping forever (or until ^C) > > So, do you know if this process terminates when the python script > finishes, or will it continue to run in the background? If it continues > to run, this could cause problems. > > I would try it, but I don't have access to a python interpeter at the > moment. > Python is the parent of the shell os.system() creates, and so is the parent of the ping process that shell execvs itself into. Like any other parent/sibling relationship, the parent disappearing has negligible effect on the child. The ping will continue to run after Python disappears. Check out the commands and popen2 module, these might provide a workable alternative to os.system(). Jp -- Examinations are formidable even to the best prepared, for even the greatest fool may ask more the the wisest man can answer. -- C.C. Colton -- up 13:58, 4 users, load average: 0.55, 0.57, 0.47 From wsonna at attglobal.net Fri Mar 14 11:29:44 2003 From: wsonna at attglobal.net (William Sonna) Date: Fri, 14 Mar 2003 10:29:44 -0600 Subject: No Do while/repeat until looping construct in python? References: Message-ID: On Thu, 13 Mar 2003 09:27:07 -0600, sismex0 wrote: > Troll? Flamebait? Or just uninformed? None of the above. Legitmate criticism of questionable design decisions made. Either respond to the issues raised or look foolish- your choice. >> ...so file it right next to "self" as the second of the two most-hated >> "features" of the language. The problem is that as a relatively small >> language, you can't escape them. >> >> > "Hated"? Yeesh... > > > > > > > Yes. Hated. Go to the Ruby web site - one of the quoted "features" of Ruby is not having to type "self". >> The workaround for (no) repeat is to brake after the test placed at the >> end of the loop. >> >> > repeat ... until (condition) > > is exactly the same thing; only that the language places the > responsability of choosing the condition's location and exit point on > the programmer, not the other way around. > > For bonus points, can you point out the advantage of Python's approach > and the disadvantage of language X's? > > > > > > > > > Item 1 - one-or-more is *not* the same as zero-or-more. It is mathematically incorrect to make that claim. Item 2 - There can be no "advantage" to Python's way since there is no way. There is only a workaround. The question is whether the addition results in a correspnding disadvantage that outweighs the advantage. The argument is NOT whether its already there (it isn't), or whether it would be nice to have (it would), but whether it is sufficiently important to justify its existence. The general concensus is that it is not. A substantial number disagree. >> The workaround for "self" is to assign a local variable and use it >> instead. >> >> > Really... > > "self", in an instance method, *IS* a local variable. You can call it > whatever you want: "me", "self", "this", "_", "obj", "instance", "here", > "etc", ... > > And, having it explicit and not implicit keeps the instance's namespace > apart from the local namespace. > > > > > > You've just contradicted yourself, (which is OK; it illustrates the problem). Why would a local variable need to be qualified to keep it separate from the local namespace? That's the *conceptual* problem with "self". The *practical* problem is that because common sense says the instance variables are local, and typing "self" is a pain, the user has a double disincentive to include it, resulting in gratuitous bugs. It MAY be consistent with Python's general tendency to favor least-type (both as in class, and as in typewriter), it DOESN'T help get the job done. Now, as for your personal attacks ("troll", "flaimbait", etc.), I have taken the time to post legitimate criticism substatiated with facts. If you feel the need to respond with trash-talk, you are welcome to do so, but you really should look in the mirror before you call me anything. On the other hand, if you have a valid reason why "self" is advantageous FROM THE USER's POINT OF VIEW I would like to hear it. I already know that: a. "its already been talked to death! see html://blahblahblah" b. "real Python programmers KNOW why" c. "use (c++|Java|Perl|$your_pick) instead" d. Python RULEZZZ e. Please don't question the language or post critiques - somebody might agree with you!! So you can skip those (or cut and paste, if you prefer). [snip] From sandskyfly at hotmail.com Mon Mar 10 14:41:28 2003 From: sandskyfly at hotmail.com (Sandy Norton) Date: 10 Mar 2003 11:41:28 -0800 Subject: referring from within containers objects References: <3e6c8de7$0$6145$4d4eb98e@read.news.gr.uu.net> Message-ID: Dimitris Garanatsios wrote: > I think that the need of refering to the elements of a container at the > time it is created is quite rare and usually means bad design of the > data structures it represents. Your proposal would propably require a > two step process for the creation of a container (especially for > dictionaries) at python's C implementation, unless more strict rules > would apply, such as to only refer to elements already specified. > > In case my english confuse anyone (sorry about that...), this means that > code like > > lst = [ _[1] + ' ' + _[2], 'Nit', 'Wit' ] > > whould raise some kind of an error. > > In my opinion this whould result in an uglier syntax (for the C level > ofcourse) that slows down an object's creation without a good reason... I see your point, and agree that the added complexity (at the c level) required to make this happen makes this proposal impractical. > Regards, > Dimitris cheers, Sandy. From stojek at part-gmbh.de Mon Mar 10 14:53:50 2003 From: stojek at part-gmbh.de (Marcus Stojek) Date: Mon, 10 Mar 2003 20:53:50 +0100 Subject: uniquely identifying a machine... References: <97hp6vsg1daclecotuevtm3n581uhupkuk@4ax.com> Message-ID: <20rp6vgo82ot8lt30eknthcsimoqc3mdfq@4ax.com> Hi, I found this somewhere in the net. Don't remember the author, but it is someone well known in this group. With this you can check the unique hardware ID of the Ethernet-card installed. from netbios import * ncb = NCB() ncb.Command = NCBENUM la_enum = LANA_ENUM() ncb.Buffer = la_enum rc = Netbios(ncb) adresslist=[] if rc != 0: raise RuntimeError, "Unexpected result %d" %(rc,) for i in range(la_enum.length): ncb.Reset() ncb.Command = NCBRESET ncb.Lana_num = ord(la_enum.lana[i]) rc = Netbios(ncb) if rc != 0: raise RuntimeError, "Unexpected result %d" %(rc,) ncb.Reset() ncb.Command = NCBASTAT ncb.Lana_num = ord(la_enum.lana[i]) ncb.Callname = "* " adapter = ADAPTER_STATUS() ncb.Buffer = adapter Netbios(ncb) adress='' for ch in adapter.adapter_address: adress+=( "%02x" % (ord(ch),)) adresslist.append(adress.upper()) print adresslist Chris Spencer schrieb: >This might not be a direct Python question, but I thought I'd pose it anyways. > >I have a need, for licensing purposes, to be able to uniquely identify a >machine. For various policy reasons, we can not rely on the TCP/IP stack being >active. So uniquely identifying a machine by IP address, machine name, or NIC >address is not possible. > >Cross-platform is a plus, but definately not necessary. > >Anyone out there have any ideas? > >Chris. From exarkun at intarweb.us Thu Mar 20 18:46:38 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 20 Mar 2003 18:46:38 -0500 Subject: Raising an exception in the caller's frame In-Reply-To: References: Message-ID: <20030320234638.GA4795@meson.dyndns.org> On Thu, Mar 20, 2003 at 09:14:22PM +0100, Thomas Heller wrote: > Is there any way to raise an exception in the callers (parent) frame? > I don't believe so (at least not without performing unspeakable evil). > See the following code, I want the exception to be raised in the > do_some_work function, without changing this function itself: > > def check_result(value): > if somecondition(value): > raise ValueError > return value > > def do_some_work(): > value = dosomething() > return check_result(value) > Consider this alternate definition of do_some_work... def do_some_work(): value = dosomething() try: return check_result(value) except Exception, e: raise e I'm not sure I'd use this, though - it masks useful information about the real source of the exception. If I might ask, why do you want to do this? Jp -- "One World, one Web, one Program." - Microsoft(R) promotional ad "Ein Volk, ein Reich, ein Fuhrer." - Adolf Hitler -- up 19:58, 4 users, load average: 0.06, 0.04, 0.00 From kkrueger at example.edu Wed Mar 12 13:18:42 2003 From: kkrueger at example.edu (Karl A. Krueger) Date: Wed, 12 Mar 2003 18:18:42 +0000 (UTC) Subject: Tuples, what are they: read-only lists or heterogeneous data arrays? References: <15982.24855.181016.568236@montanaro.dyndns.org> <200303111449.42035.fincher.8@osu.edu> <200303120211.h2C2BCH28989@pcp02138704pcs.reston01.va.comcast.net> Message-ID: Gerrit Holl wrote: > Guido van Rossum wrote in Python-Dev: >> Tuples are for heterogeneous data, list are for homogeneous data. >> Tuples are *not* read-only lists. > > This makes me wonder. > > FAQ entry 6.15 states: > >> 6.15. Why are there separate tuple and list data types? >> This is done so that tuples can be immutable while lists are mutable. > > I don't understand. Doesn't this FAQ entry mean that tuples are read-only > lists? Why are tuples not read-only lists? Lists are for homogeneous data? > Well, [0, None, "twelve"] is perfectly legal, of course, so what does this > mean? I'm curious! Delurking to speculate on this one ... Tuples are more "struct-ish" than lists are, and represent a single "structured" value, even though they have multiple data elements. The Python library seems to use tuples in places where C would use structs -- to represent records which encompass multiple pieces of data but are still being used as a single value. The example of the 9-tuple returned by time.localtime has been mentioned elsewhere -- even though there are nine pieces of data there, in some sense it represents only one value, namely a time. Similarly, a Cartesian coordinate pair (x, y) is a single value even though it has two data elements. This is a natural tuple. Since a tuple represents a single value, it often makes sense to use it as a dictionary key. You can only use an object as a dictionary key if you know it is not going to get changed in-place, because that would invalidate the hashing of the key. For instance, suppose we could do this: pt = (1, 2) point_names = { pt: "The Park" } pt[1] = 3 # pt is now (1, 3) What should locations[pt] yield? Since pt and the first key of the point_names dictionary both refer to the same place in memory (that is, "pt is point_names.keys()[0]" is true), altering the value of pt[1] would alter the value of the key in the dictionary! That would break the dictionary's hashing, which would be bogus. In short, since everything is a reference, if tuples are going to be usefully hashable they have to be immutable. Lists do not conceptually represent a single value; they represent a sequence of values. As such, it makes sense to do things like add and remove values in-place, which would not make much sense on a tuple. (To add a value to a tuple would be to change its structure.) What is meant by "tuples are for heterogeneous data, lists are for homogeneous data", I suspect, is not that you can't put different data types in a list. It is that the usual thing to do with a list is iterate over it, executing the same operations on each element. This is not the usual thing to do with a tuple -- you would not usually iterate over the elements of the time 9-tuple, doing the same operation to all of them, since they mean different things. So, in short, lists are sequences of values whereas tuples are complex values. -- Karl A. Krueger Woods Hole Oceanographic Institution Email address is spamtrapped. s/example/whoi/ "Outlook not so good." -- Magic 8-Ball Software Reviews From chris.lyon at spritenote.co.uk Sun Mar 9 12:42:32 2003 From: chris.lyon at spritenote.co.uk (Chris Lyon) Date: 9 Mar 2003 09:42:32 -0800 Subject: The ultimate irony Trouble installing Installer. Message-ID: I'm trying to construct a mechanism to install a small set of scripts to either windows or Linux to machines that might not have python( obviously mostly Windows). Having trawled around it seems the generally considered approach is the McMillan Installer suite. So I start to follow the instructions in Getting Started. quoting :-On non-Windows platforms, the first thing to do is build the runtime executables. Windows users can skip this step, because all of Python is contained in pythonXX.dll, and Installer will use your pythonXX.dll. It appears the first instruction for those running on Windows is II) so I download extract to a directory cd to that directory run c:\python22\python Configure.py and get:- Traceback (most recent call last): File "Configure.py", line 13, in ? import mf, bindepend File "mf.py", line 234, in ? import hooks ImportError: No module named hooks Now it is EXCEPTIONALLY depressing when you can't even install an Installer... Is this another conceptual error that the 'average' python user does 15 times before breakfast, or am I mis-reading things and this is a Linux only step. Secondly Has anyone got a step by step guide somewhere to how exactly to distribure little_app.py this way? I'm sure Installer is an excelent tool but the manuals contain no obvious example? Do I construct a spec file? does makeCOMServer do everything for me? Is the COMServer the entire windows component that I need or is this just a specific subset of operations? I sort of hope that at the end of this I can end up with an exe I can load up up on Windows machine, ( and some equivalent in the Linux world I assume an rpm or similar) and click the exe sit back and watch it build icon's and menu items? Is this laughingly optimistic and I should go away and learn to use the windows interface properly before even claimimng any degree of python proficientcy or is this actually a perfectly exceptable thing to do? Sorry that this all sounds so damn misserable but I've been kicking this all around for a year now and I'm staggered by how difficult python installation on machines all seems. For instance I would point at the level of conprehension requied to add flat files into a Distutils Setup.py script just to get idle to install a few icons. Is the python way do not use a tool unless you've read understood and personalized the source completely? Sulk, sulk, moan, moan, blooming computers, I'm going off to grow mushrooms... From bokr at oz.net Fri Mar 14 14:46:02 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Mar 2003 19:46:02 GMT Subject: referring from within containers objects References: Message-ID: On 10 Mar 2003 02:11:48 -0800, sandskyfly at hotmail.com (Sandy Norton) wrote: >Hi, > >This is just an idea that occurred to me while working with >dictionaries in which the values of certain keys were composed of the >values of other keys and I found that the syntax for solving that >problem wasn't as pretty as I would have liked. > >Here's an example: > >d = { > 'fname' : 'Nit', > 'lname' : 'Wit' >} > >Now I have to do this: > >d['fullname'] = d['fname'] + ' ' + d['lname'] > >if I want to reuse the keys/values within the dict. This forces me to >break out of the dictionary definition, which I don't like doing for >some reason. > >Now what if I could do something like this: > >d2 = { > 'fname' : 'Nit', > 'lname' : 'Wit', > 'fullname' : _['fname'] + ' ' + _['lname'] >} > >where '_' refers to the containing dict. > >This can be extended to lists: > >lst = [ 'Nit', 'Wit', _[0] + ' ' + _[1] ] > > >Sandy You could subclass dict to retrieve compositions of key values in specialized ways, e.g., (not tested beyond what you see below): ====< compose.py >========================================= class Compose(object): def __init__(self, fmt, *keys): self.fmt = fmt self.keys = keys def __call__(self, dct): return self.fmt % tuple(map(dct.__getitem__, self.keys)) class Cdict(dict): def __getitem__(self, key): v = dict.__getitem__(self, key) if isinstance(v, Compose): return v(self) return v cd = Cdict() cd['fname']='Nit' cd['lname']='Wit' cd['fullname'] = Compose('%s-%s', 'fname', 'lname') print cd['fname'] print cd['lname'] print cd['fullname'] cd['lname'] = 'Twit' print cd['fullname'] d2 = Cdict({ 'fname' : 'Nit', 'lname' : 'Wit', 'fullname' : Compose('%s %s', 'fname', 'lname') }) print d2['fullname'] =========================================================== The output is: [11:52] C:\pywk\clp>compose.py Nit Wit Nit-Wit Nit-Twit Nit Wit Note that just changing the lname key value caused a change in the sythesized 'fullname' value. d2 is initialized with a literal more or less like your format. Of course you can use other ways to make synthetic key values. Regards, Bengt Richter From peter at engcorp.com Fri Mar 21 11:17:01 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Mar 2003 11:17:01 -0500 Subject: struct module... References: Message-ID: <3E7B3AFD.BE091B6@engcorp.com> Franck Bui-Huu wrote: > > I'm trying to read from a binary file data. > These data have been written by a C soft using structure like > struct xxx { > u1 length; > u1 array[length]; > } What's a "u1"? Is it an unsigned value of length one? In that case, why not just pull off the length byte first by indexing the binary string "arrayLength = ord(arrayData[0])" and then build the template to pass to struct() dynamically using that value? From paul at boddie.net Mon Mar 10 07:14:40 2003 From: paul at boddie.net (Paul Boddie) Date: 10 Mar 2003 04:14:40 -0800 Subject: The ternary operator: more than one way to do it? Message-ID: <23891c90.0303100414.64c2a054@posting.google.com> The whole PEP 308 debate seems to reveal a secret desire in the community to have more than one way of doing the ternary operator thing - after all, there wouldn't have been so many creative suggestions if this were not so. So my question is: after the voting procedure and following decision on PEP 308, will all the different syntaxes be donated to the Perl community? :-) Paul From eichin at metacarta.com Tue Mar 18 18:08:14 2003 From: eichin at metacarta.com (eichin at metacarta.com) Date: 18 Mar 2003 18:08:14 -0500 Subject: changes to shelf items fail silently? References: <7gy93dmzzu.fsf@pikespeak.metacarta.com> <7gptop2ryj.fsf@pikespeak.metacarta.com> Message-ID: <7gy93cp929.fsf@pikespeak.metacarta.com> > Am I skipping over some important assumption without realizing it? I think the distinction is that in any other context, and any other use of that *syntax*, you don't especially care that it is a reference, because if you mutate the object, the dict still contains a reference to the mutated object. With shelf, you're *not* mutating the object, you're mutating a temporary copy. Also: > of a key-value database on disk (dbm) and a generic object > serialization protocol (pickle). While the __doc__ does say that, it isn't clear why that should cause this effect; serialization is just "how it is stored", and doesn't inherently imply "so you only get temporaries out". > *chuckle* Good point. (I assume you also don't need multiple > users reading and writing simultaneously.) Right - another way of describing my use case is "single daemon that does stuff, keeps information about it in-memory in a dict - great prototype, now it needs to be restartable." One could just pickle the whole dict and write it out at every commit point, but (1) shelve looks more efficient (2) using shelve is far easier to write [literally, import it, and then use shelve.open() instead of {} as an initializer.] > I don't know Perl, as it happens. What's a tied hash? A perl hash is basically a python dict; the main difference is that it can hold only "scalars" (numbers, strings, references; not other hashes, or lists.) A "tied" hash is one that has an associated Class with a standard set of methods (FETCH, DELETE, STORE, etc.) that get called when the relevant thing is done. Defining __getitem__/__setitem__ has pretty much the same effect in python. Hmm. I suspect it's actually harder to do this in perl (you pretty much have to take the wrapper approach) since the only way to put higher level objects in *is* to put in references - so that would have led me to what the problem was much more quickly... (On a side note, it occurs to me that the dict structure *isn't* arbitrarily deep, it's only a dict-of-dicts, so I could instead shelve.open each subdict. Then at startup, scan the values and open all of the subshelves explicitly. A little tricky but may end up more efficient once the subdicts start getting large (ie. that's the way to handle it if the overhead of repickling on inserts gets too big.)) > Now, what about shelved foobar.wombat objects? Which of their > methods should cause commits? Mmm, throw an exception if they don't "conform" to some interface. The reason I went down this path isn't that it silently discarded the changes, after all; I'd have been happy if it had non-silently told me (perhaps by having the references be non-mutable and cause exceptions to be thrown on changes, for example.) From mwh at python.net Thu Mar 13 07:37:30 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 13 Mar 2003 12:37:30 GMT Subject: Help: /bin/ping problem with Red Hat References: <3E6F51A9.3030706@cs.unc.edu> <3E6F8CF9.8050402@cs.unc.edu> Message-ID: <7h365qnmohk.fsf@pc150.maths.bris.ac.uk> Vivek Sawant writes: > That worked! Thanks a zillion for replying with that code > fragment. That was a *huge* help. Thanks again. > > Wish the same think can be achieved from within Python. I tried; it worked on Linux and broke spectacularly on just about any platform anyone else tried it on (FreeBSD, Darwin, Solaris, ...). Cheers, M. -- You owe the Oracle a star-spangled dunce cap. -- Internet Oracularity Internet Oracularity #1299-08 From nomad*** at ***absamail.co.za Sun Mar 2 15:47:44 2003 From: nomad*** at ***absamail.co.za (Nomad) Date: Sun, 02 Mar 2003 22:47:44 +0200 Subject: pygtk2 vs. pyqt. pros and cons References: <3e60b3c9$0$49107$e4fe514c@news.xs4all.nl> Message-ID: On 01 Mar 2003 13:21:13 GMT, ivo at NOSPAMamaze.nl wrote: >Except for Glade, there aren't any good interface builders, and portability >to windows is a strict requirement for my project, so I'm currently looking >into wxPython. Too bad the wxPython / wxWindows documents aren't downloadable >(as far as I could see) What about QT Designer? It's great for GUI painting, and has the pro that you can use the same form design for any language supported by the Q framework -- via a UI compiler tool (such as the pyuic that comes with PyQt). -- Nomad Wondering of the vast emptyness of the 'net in search of something cool. From piet at cs.uu.nl Fri Mar 14 18:35:03 2003 From: piet at cs.uu.nl (Piet van Oostrum) Date: 15 Mar 2003 00:35:03 +0100 Subject: self (was Re: No Do while/repeat until looping construct in python?) References: Message-ID: >>>>> "William Sonna" (WS) wrote: WS> You've just contradicted yourself, (which is OK; it illustrates the WS> problem). Why would a local variable need to be qualified to keep it WS> separate from the local namespace? That's the *conceptual* problem with WS> "self". WS> The *practical* problem is that because common sense says the instance WS> variables are local, and typing "self" is a pain, the user has a double WS> disincentive to include it, resulting in gratuitous bugs. The common sense is wrong. Instance variables are not local variables. You have in general three kinds of variables in a method: module level variables (global), local variables, and instance variables. There must be some way to distinguish them. If instance variables are not prefixed by self, then they must be declared as such or the local variables must be declared to be local. Smalltalk chose to do the latter; I have no idea what Ruby does, but I guess it will do something similar. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From zhitenev at cs.vsu.ru Thu Mar 6 05:22:40 2003 From: zhitenev at cs.vsu.ru (Lexy Zhitenev) Date: Thu, 6 Mar 2003 13:22:40 +0300 Subject: embedding python - PyImport_ImportModule returns null References: <3607e8e4.0303051802.7ddf1dfd@posting.google.com> Message-ID: "JW" wrote in message: news:3607e8e4.0303051802.7ddf1dfd at posting.google.com... > I am trying to embed python within a c program, but I can't get > PyImport_ImportModule() command to load my module. > Please let me know what I'm doing wrong. > > -- > #file func.py > def func1(): > print "inside func1()" > > -- > //main.c > int main() > { > PyObject *pFunc, *pModule; > Py_Initialize(); > > pModule=PyImport_ImportModule("func"); //fileread.py > if(pModule==NULL) > { > > PyErr_Print(); > fprintf(stderr,"Failed to load \"%s\"\n","func"); > } > //etc.... > } > > --- > Both main.c and func.py are in the same directory. > I run main and get the error > Failed to load "func", meaning that PyImport_ImportModule returns NULL. > You aren't doing anything wrong. I've tried to compile your code and it didn't give me any errors. I use MinGW GCC 2.95 under Windows 2000. You only forgot to #include , but I don't think that's the problem. Possibly, this is your compiler's fault. What compiler are you using, what arguments are for it? Lexy. From Franck.BUI-HUU at gemplus.com Thu Mar 20 09:56:20 2003 From: Franck.BUI-HUU at gemplus.com (Franck Bui-Huu) Date: Thu, 20 Mar 2003 15:56:20 +0100 Subject: zipfile exception. Message-ID: <3E79D694.4000503@gemplus.com> Hey ! I'm trying to unzip a file with ZipFile class but got this exception instead : zipfile.BadZipfile: Bad magic number for central directory. Winzip works fine on this file! Anyone can help me ? Thanks From mathias-usenet at valpo.de Wed Mar 12 04:56:51 2003 From: mathias-usenet at valpo.de (Mathias Waack) Date: 12 Mar 2003 09:56:51 GMT Subject: overloading __mul__ References: <7d728336.0303120103.3348148a@posting.google.com> Message-ID: zunlatex at hotmail.com (zunbeltz) wrote: > I want to be able to write things like that > 2*matrix > matrix * 2 > 2*vector > vector *2 > but also > matrix*vector > vector*matrix > > How can i overload __mul__ for matrix in two ways depending if the > other elemetn is a number or a vecotr? This doesn't work. But you can test the type of the argument of the __mul__ method and call different operations. > and in wich class have i to > overload __mul__ to get vector * matrix and matrix * vector; in the > vector class? in the matrix class? in both? In both. Mathias From thomas at xs4all.net Mon Mar 17 11:30:45 2003 From: thomas at xs4all.net (Thomas Wouters) Date: Mon, 17 Mar 2003 17:30:45 +0100 Subject: No Do while/repeat until looping construct in python? In-Reply-To: References: Message-ID: <20030317163045.GR2112@xs4all.nl> On Mon, Mar 17, 2003 at 03:30:34PM +0000, Steve Holden wrote: > "William Sonna" wrote to comp.lang.python, in various > posts and at various times, but invariably in the same strident tone ... > [...] > > Now be a good boy, eat some more shit and get back to your regularly > > scheduled trolling NOW or I'll tell your mother what you've been up to!! > I surely can't be the only c.l.py who finds this approach to technical > debate both unnecessary and offensive. You definately were not. However, rather than try to correct William Sonna, I went the easy way out and made him make that wonderful *plonk*[1] sound. It was a sad occasion too; the killfile was otherwise empty. But I could not make myself reply in such an eloquent, clear-headed, mentally stable manner as you have, Steven, so I'm glad I didn't try. My attempt likely would have failed, and fueled the flames even more, so I decided to skip it and let other people handle it better. I'm very happy to find my trust was not misplaced! Yours was not the only good response, either, but it was well worth reading all the way and I found myself agreeing on all accounts. I'm glad you did actually send it. Conciliatori'ly y'rs, [1] http://www.dict.org/bin/Dict?Query=plonk&Form=Dict1&Database=*&Strategy=* -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! From michael at stroeder.com Tue Mar 25 12:29:15 2003 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 25 Mar 2003 18:29:15 +0100 Subject: Searching in Active Directory (also using LDAP in Windows) In-Reply-To: <2d0ga.6354$t_2.924@afrodite.telenet-ops.be> References: <2d0ga.6354$t_2.924@afrodite.telenet-ops.be> Message-ID: Rudy Schockaert wrote: > > I also tried Python-LDAP, but no avail either. Which version, which platform? > Has anyone been able to access or search Active Directory succesfully? Yes, with python-ldap running on Linux. Make sure you have proper access rights. There are a bunch of security config options in M$ AD. > Does anyone know of another LDAP module for Python on Windows? In theory one should be able to build OpenLDAP and python-ldap on Win32. Contributed binaries welcome! > I can always send some example scripts if someone's interested. Yepp. Ciao, Michael. From pedronis at bluewin.ch Tue Mar 4 13:56:51 2003 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Tue, 4 Mar 2003 19:56:51 +0100 Subject: Can __iter__ be used as a classmethod? References: <3e649aa3_4@news.bluewin.ch> <2259b0e2.0303041023.43e8b81f@posting.google.com> Message-ID: <3e64f743_4@news.bluewin.ch> > However, I noticed that > > >>> isinstance(object.__new__,staticmethod) > False > > Therefore if I try to retrieve all the staticmethods from a class I will > miss __new__. That's unfortunate, even if I understand this is done in order > to avoid to write > > __new__=staticmethod(__new__) > > each time I redefine __new__. In a sense, __new__ is an "implicit" static > method. no, object.__new__ is a special case: >>> class C(object): ... def __new__(cls): ... print "C__new__" ... return object.__new__(cls) ... >>> c=C() C__new__ >>> C.__new__ >>> C.__dict__['__new__'] >>> isinstance(_,staticmethod) 1 >>> isinstance(object.__dict__['__new__'],staticmethod) 0 for normal new style classes, __new__ lives as staticmethod in the class __dict__ but notice it is unwrapped to a function on lookup. That's true for general staticmethods: >>> class C(object): ... def f(): ... return 'f' ... f=staticmethod(f) ... >>> C.f >>> C.__dict__['f'] regards. From staschuk at telusplanet.net Fri Mar 21 10:30:32 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Fri, 21 Mar 2003 08:30:32 -0700 Subject: Is Python the Esperanto of programming languages? In-Reply-To: <3oyea.61654$68.41484@nwrdny01.gnilink.net>; from imbosol-1048226545@aerojockey.com on Fri, Mar 21, 2003 at 06:34:39AM +0000 References: <7i65qe953z.fsf@enark.csis.hku.hk> <3oyea.61654$68.41484@nwrdny01.gnilink.net> Message-ID: <20030321083032.C4363@tibia.amotlpaa.bogus> Quoth Carl Banks: > Steven Taschuk wrote: > > Quoth Greg Ewing (using news.cis.dfn.de): > > [...] > >> So is redundancy (at the grammatical level, at least) so > >> necessary in a natural language after all? > > > > Clearly *some* redundancy is necessary, for error detection and > > correction purposes. > > C'mon. Nobody who utters a subject really needs a redundant verbal > ending in case the subject was uttered wrongly. Indeed, the speaker hardly ever needs redundancy; to the extent that it is useful, it is for the listener's benefit. (ObPython: Like block-starting colons.) Note also that "error" in "error detection and correction" includes errors in transmission and interpretation, not merely errors in utterance. > I say redundancy is not required at all for a language, and most > languages have very little of it. Sometimes what looks like > redundancy isn't really redundancy, but rather superfluousness. For > example, in English, if I say, "The man go to the store," no native > listener is going to wonder what I meant. Leaving the final sibilant > off the word "go" sounds bad, but it doesn't affect the meaning of the > sentence. It's completely superfluous. ... because the information it carries is redundantly available elsewhere in the sentence. Suppose you do not make that error, but you speak with an unfamiliar accent that leaves me uncertain about the vowel in "man"; what I hear is: The m?n goes to the store. I can guess "man" instead of "men" because it's "goes" and not "go". In this scenario the maligned sibilant carries useful information, and isn't superfluous at all. > However, even though redundant and superfluous lexemes are not > required, all natural languages have them, simply as a side effect of > language change. Even if this explanation of redundancy's origin is correct, it does not speak to its utility; in particular, I am not convinced that a natural language can function with no redundancy at all. -- Steven Taschuk staschuk at telusplanet.net Receive them ignorant; dispatch them confused. (Weschler's Teaching Motto) From h.stegmann at arcor.de Fri Mar 7 10:08:03 2003 From: h.stegmann at arcor.de (Heiko) Date: 7 Mar 2003 07:08:03 -0800 Subject: Shifting numpy array contents References: Message-ID: John, I have to admit that my post was really quite imprecise. You'll see what I mean below - meanwhile, I have found a solution that does what I want, and it's beautifully simple: Consider, e.g., a = array([[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12]]) I want to, for example, shift the 2nd row one cell to the right (with wrapping around at the ends): a[1]=concatenate((a[1,-1:],a[1,:-1])) [[ 1 2 3] [ 6 4 5] [ 7 8 9] [10 11 12]] now last the row two to the left: a[3]=concatenate((a[3,2:],a[3,:2])) [[ 1 2 3] [ 6 4 5] [ 7 8 9] [12 10 11]] In general, to shift row i by j cells (left for j>0 and right for j<0): a[i]=concatenate((a[i,j:],a[i,:j])) From adalke at mindspring.com Wed Mar 26 17:27:49 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 26 Mar 2003 15:27:49 -0700 Subject: writing to file very slow References: <41538.164.15.134.155.1048690460.squirrel@http://moritz.homelinux.or g> Message-ID: John Machin > No, it's not what [the OP] wanted, and it's not a correct translation but > the original is so god-awfully-obscure that you are forgiven :-) > > Here's his original, with two substitutions, and removing the str() -- > this makes it much clearer what is going down ... > > for row in gotten_result: > var = "" > for y in range(numfields-1): > var += row[y] + '|' > var += row[numfields-1] > f.write(var) > f.write('\n') Being lazy and not reading the other threads in detail... This can be simplified and made faster with for row in gotten_result: f.write("|".join(row)) f.write("\n") (assuming numfields == len(row), else use join(row[:numfields]) ) Andrew dalke at dalkescientific.com From roy at panix.com Mon Mar 17 21:27:24 2003 From: roy at panix.com (Roy Smith) Date: Mon, 17 Mar 2003 21:27:24 -0500 Subject: It feels so good, so quick and not C! References: Message-ID: In article , "BB" wrote: > Hi ya'all > I've been lurking and learning as much as I can. I then decided to do a > simple project to write a "reverse string" routine. This helped a lot! It > showed me that I really think in C terms. I am beginning to see the value of > lists and the simplicity they bring to manipulation of data. > Anyway, I throwing this piece of code into the arena to be kicked about - > I hope to learn even more this way. > > print "This is a prompt. Enter a string to be reversed: ", > sOrig = raw_input()#get a string to work on > sRev=""#init > char_count=len(sOrig)#now I have the string length > while ((char_count - 1) >= 0):#loop thru string backwards, zero based > char_count = char_count - 1 > sRev = sRev+sOrig[char_count]#create the reverse string > print sRev > > While what you've written will probably work (I'll confess, I havn't run it myself to make sure), it is a very C-like way of doing things. In general, anytime in Python you find yourself walking through a sequence by incrementing an index, you should suspect you're doing something in an "un-pythonic" way. I've fallen into that trap more than once, and each time, after I've recognized the problem and rewritten it pythonicly, I've ended up with more readable (and often, faster executing) code. Ignoring for the moment convenient built-ins like reverse(), I'd be thinking more along the lines of: reverseList = [] # create an empty list for c in sOrig: # walk the string, one char at a time reverseList.insert (0, c) # pushes c onto front of reverseList sRev = ''.join(reverseList) # squashes list of characters into string print sRev From aleax at aleax.it Wed Mar 26 07:38:25 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 26 Mar 2003 12:38:25 GMT Subject: Integer arithmetic References: Message-ID: <5bhga.17993$i26.423807@news2.tin.it> Daniel Timothy Bentley wrote: > It seems like so long as there's a distinction in the language between > ints and longs, there should be a way to create ints reliably. > > If > > int(foo % sys.maxint) > > is such a call, great. Is this guaranteed to work? I don't know. It's guaranteed to do funny things indeed! >>> int(-23 % sys.maxint) 2147483624 >>> a % b, for b>0, always return an x such that 0 <= x < b. That is most definitely NOT what you want in this case for a<0... and I suspect that this would also not be what you want: >>> int(sys.maxint % sys.maxint) 0 >>> yet it IS totally guaranteed by the semantics of %. > Basically, if you're going to say ints and longs are separate types, I > think there should be a way to makes ints from longs fairly reliably. I > don't think that's a niche, I think it's something a consistent language > should provice. Well, your proposed expression DOES "make ints from longs fairly reliably", it's just that I think the ints it makes are probably not the ones you'd like to get (except for 0<=foo=0: return int(foo&sys.maxint) else: return -int(-foo&sys.maxint) and I'd further factor out the "int(X&sys.maxint)" part because I loathe duplicated code. But that brings us right back to the same suggestion I already gave you, with a tiny perhaps-improvement: def mask(x, themask=sys.maxint): return int(x & themask) def toint(x): if x>=0: return mask(x) else: return -mask(-x) I originally proposed using a literal 2**32-1 as the default value of themask (because I think that is likely to be more useful for the purpose of simulating an abstract machine's arithmetic), now we're using sys.maxint instead (thus putting ourselves at the mercy of the specific machine we're running on), big deal. > Maybe python is moving towards a day where ints and longs are completely > indistinguishable. This probably wouldn't be a bad thing, from many That's what PEP 237 states, yes. > standpoints. But until that day comes, I think that there should be a way > to construct an object without getting an exception. I guess it's more a There are many, depending on what object you want...;-). You seem adamantly convinced that "mask off however many least-significant bits the current machine allows into an int" is the one and obvious way of constructing an int from a long, when the long has more significant bits that will fit into an int, but I think this is unproven. Why shouldn't some other application prefer, e.g.: def toint(x): try: return int(x) except OverflowError: return [sys.maxint,-sys.maxint][x<0] i.e. a "saturating" conversion (warning: doesn't work in 2.3 since int(alongthatstoobig) just returns the long rather than an int, NOT raising any exception whatsoever...). > matter of taste whether the implentation or the interface-user should do > it, but since one still allows the other, I'd say the implementation > probably should. "In the face of ambiguity, refuse the temptation to guess", and I think it's NOT obvious how N>32 bits should be squeezed into 32 (the idea of choosing the LEAST significant ones may look obvious to you, but I'd suggest thinking again about it, in terms of application needs rather than traditional behavior of hardware components...:-). > I like the flexibility python provides, but it seems that there might be > cracks where orthogonality or consistency of interface have cracks; which > makes sense in an evovling language. If I managed to arrive at python at > a point where this "problem" was just begotten and there's a good chance > it will go away soon, perfect. But I stil think there's an elegant > solution to be had, that works across implementations. Is it sys.maxint? > Maybe. Silent exceptions, like Java will do for math stuff? Maybe. I'm > getting the impression the solution is maxint, so great. Thanks. If taking just as many LSB's as sys.maxint happens to have is what your application needs, then yes, sys.maxint (plus some care about sign!) is indeed "the solution". As to what needs your application actually happens to have, well, that's something that only you, as the designer thereof, can determine -- the language sure can't do it for you! Alex From do-not-spam-ben.hutchings at businesswebsoftware.com Wed Mar 26 07:24:04 2003 From: do-not-spam-ben.hutchings at businesswebsoftware.com (Ben Hutchings) Date: 26 Mar 2003 12:24:04 GMT Subject: urllib.urlretrieve and PASV mode References: <3e7b3eba.90530195@news.zianet.com> Message-ID: In article <3e7b3eba.90530195 at news.zianet.com>, Mats Wichmann wrote: > > Is there a way when using urllib.urlretrieve() to > use passive mode for ftp transfers? It looks like > this is supported in ftplib (set_pasv method), > but not used by urllib. Unless I'm missing something. In Python 2.2, the initial setting of passive mode in new FTP objects is controlled by the class attribute ftplib.FTP.passiveserver, which is initially set to 1. Python 2.1's ftplib also defaults to passive mode. Unless you're using an earlier version, you shouldn't need to do anything special. From claird at lairds.com Mon Mar 3 08:20:42 2003 From: claird at lairds.com (Cameron Laird) Date: Mon, 03 Mar 2003 13:20:42 -0000 Subject: Using an operator as an object References: <8d3e714e.0303021819.24f1aa38@posting.google.com> Message-ID: In article , Alex Martelli wrote: . . . >Python library. However, if you DO have a string representing >an operator, an if/elif tree is still not the best way to find >out which one of the functions in module operator you have to >call -- rather, you're probably better off building a dictionary >once only: > >import operator >string_to_op = { > '+': operator.add, > '-': operator.sub, > '*': operator.mul, > '/': operator.div, > '%': operator.mod, > # and possibly others if you need them, of course >} . . . Is such a mapping not already exposed somewhere? 'Near as I can tell, the answer is, "No". Would this not be one of the benefits of the (several) project(s) to script more of Python's core in Python? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From usenet at pobice.com Mon Mar 24 21:50:16 2003 From: usenet at pobice.com (Robert Naylor) Date: 25 Mar 2003 02:50:16 GMT Subject: Tkinter, swig and threads Message-ID: I've not been using python that long and I'm trying to make a gui using tkinter. The problem I have is that that some of the functions take quite a long a time to complete (although they spend most of their time asleep) - rendering the gui unusable for the period. Usually this would be no problem but its the swig functions that take up this time - so most of the tricks I've seen in the threading examples don't work/apply. One method I am curretnly thinking about is that I could re-write the c functions so that they recurse using python. However the time period involved means that the total time its asleep could be over 15 min - and in it current form thats only over 255 (usually less) steps. However for the gui to be responsive extra steps would have to be added - say at least once a second making 900 instead. Does anyone know what the time cost of doing this is likekly to be? Has anyone got any better soloutions to this? Ideally I'd like to also be able to stop the functions mid-way through if need be as well (easy to do in the above method). Thanks for any replies. -- Robert Naylor aka Pobice (The Goblin) - http://www.pobice.com ukmrr Chat Room - http://www.pobice.com/radcliffe/ Gearstones Lodge - http://www.gearstones.com/ Need A Website? - http://www.pobice.com/website/ From noway at sorry.com Tue Mar 4 07:16:33 2003 From: noway at sorry.com (Giovanni Bajo) Date: Tue, 04 Mar 2003 12:16:33 GMT Subject: Can __iter__ be used as a classmethod? References: Message-ID: "Lulu of the Lotus-Eaters" ha scritto nel messaggio news:mailman.1046733846.16852.python-list at python.org... > "Bjorn Pettersen" wrote previously: > |I would like to be able to traverse the content of a class (not an > |instance) using a regular for loop: "for item in MyClass:...". > If you want to add methods to a *class*, you create the class using a > custom metaclass: So, what is classmethod exactly doing? Looking at the example snippet, it seems like it added a new method "items()" to the class. Giovanni From jdhunter at ace.bsd.uchicago.edu Tue Mar 11 18:08:26 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 11 Mar 2003 17:08:26 -0600 Subject: clear derived list Message-ID: I have a class derived from a list. I want to be able to set the list from another list, first clearing the existing members. I don't see an analog to the clear method of dictionaries. Here is what I am doing now class mylist(list): def set(self, seq): # flush the old list [self.pop() for i in range(len(self))] self.extend(seq) l = mylist() l.append(1) l.append(2) x = [3,4,5] l.set(x) print l This prints [3,4,5], which I want. But my gut tells me there is a better way. John Hunter From intentionally at blank.co.uk Mon Mar 10 06:23:08 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Mon, 10 Mar 2003 11:23:08 +0000 Subject: OT: Programmers whos first language is not English References: <74ij6vcebl67dto60dun42hd625qrkmcv7@4ax.com> Message-ID: On Mon, 10 Mar 2003 12:06:22 +0100, Max M wrote: >I believe that is a fault, as a programming language is usually defined >by having: > > - Sequential statements > - Logical operations > >xml only has sequential statements and no logical operations, so it >fails in this regard. This isn't as clear cut as you may think. Your "sequential statements" condition, for instance, is really limited to imperative programming languages - programming languages with a functional or declaritive style normally don't have sequential statements. And it could be claimed that a DTD defines a logical operation which determines the validity of the document. For me, what makes XML different to programming languages is quite simple - an XML document has no concept of input nor of output. It may itself be input or output, but it cannot accept input or output itself unless the XML application adds these facilities. XSLT defines a mapping from input to output, and thus has some claim to being a programming language. Even though it has no sequential statements. From tomchance at gmx.net Sat Mar 15 19:40:24 2003 From: tomchance at gmx.net (Tom Chance) Date: Sun, 16 Mar 2003 00:40:24 +0000 Subject: Closing pipes Message-ID: Hullo, I've got a bit of code that opens a new pipe with os.popen, to start mencoder. When I call the close() function on it, it takes an unacceptably long time to close the pipe and return to the main thread. I've tried using popen2.popen2 to open and close the thread, and this will close the thread instantly, but rather than killing the process, it simply seems to detach itself from the thread and return python to its main thread. Is it simply an unavoidable feature of python and its pipe support that it will take quite a while to kill a process? Is there any way I can kill the process more quickly? Tom From maxm at mxm.dk Thu Mar 6 03:35:15 2003 From: maxm at mxm.dk (Max M) Date: Thu, 06 Mar 2003 09:35:15 +0100 Subject: Squirrelmail or Phpmyadmin in Python? In-Reply-To: References: Message-ID: <_ID9a.112475$Hl6.10279607@news010.worldonline.dk> Kyoskyu wrote: > P.S. If I just wanted a package to run, I'd download all the necessary > components and just run it but these days, I actually want to look at the > code and understand what it's doing. With Python, I'm hoping to learn a > single scripting language and use it for both web programming as well as > system maintenance. Then I think you would be better of writing your own package in Python. You should probably use mod_python, and then start from there. This will probably make you understand the problems better than reading someone elses code. In other peoples code is a lot of steps down the wrong path that you simply don't see. But these wrong paths often contains a valuable lesson for a programmer. Others might disagree, but I find this to be the most effective way of learning for me. When I do a learning project like this, I am agressively using "proper" methodologies like patterns, XP etc. This way it is possible to learn a lot in a short amount of time. -- hilsen/regards Max M Rasmussen, Denmark http://www.futureport.dk/ Fremtiden, videnskab, skeptiscisme og transhumanisme From aleax at aleax.it Tue Mar 25 11:24:18 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 25 Mar 2003 16:24:18 GMT Subject: Subclassing types and __init__ problems References: Message-ID: Lucio Torre wrote: > Hello all, > > I have subclassed int and i am having some problems. > > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> class myclass(int): > ... def __init__(self, param): > ... print param > ... > >>> i = myclass(1) > 1 > >>> i = myclass([1,2,3]) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: int() argument must be a string or a number > >>> > > I imagine this is an issue with the types/class unification and stuff. Well, "and stuff", yes. It's __new__ that's giving you the problem, though. You aren't overriding it, so int.__new__ runs, and it doesn't know what to do with a list argument! > My questions are: > is the previous code supposed to call int.__init__? > how can i make a class so that isinstance(myclass, int) is 1, but im not I assume you mean issubclass -- using int as a metaclass is not viable. > forced to call int.__init__? Override __new__ and do whatever you wish. E.g.: >>> class myc(int): ... def __new__(cls, param): ... print param ... return int.__new__(cls) ... >>> i = myc(1) 1 >>> i 0 >>> Note that "seen as an int", i has been generated without parameters, so it's 0 -- and that's the value used by __repr__, as we haven't overridden THAT. Alex From andy at wild-flower.co.uk Fri Mar 21 15:08:54 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Fri, 21 Mar 2003 20:08:54 +0000 Subject: How to find subsidiary files? Message-ID: <200303212008.54910.andy@wild-flower.co.uk> On Friday 21 Mar 2003 7:19 am, Michael Saavedra wrote: > I am working on a gui app, and I'm having trouble figuring out how to find > and load subsidiary files such as toolbar images and the like. The app is > written to run on both windows and linux. It will be distributed as source > code and in binary form using py2exe. I will not have any control over > where in the directory tree the app will be installed. > > Here's the problem: on linux, executables are usually put in /usr/bin, > /usr/local/bin, or somewhere in the /opt directory, with the other files in > another dir such as /usr/share. On windows, the app and the other files are > usually all stored in their own directory under C:\Program Files, though > sometimes people use other locations, such as on the D:\ drive. How can I > get the app to find the files at run-time in a cross-platform way? > > Are the distutils sufficient for doing this sort of thing? I've been > looking at the documentation, and they seem to be more oriented toward > distributing modules rather than apps. For the source code, I suppose I > could modify it on installation to have a variable point to the proper > directory, but this wouldn't work for the .exe distribution. Also, I > considered using sys.argv[0] on linux to attempt to divine the base > installation dir, but using symlinks to the executable would break this. > Anyone have any other ideas? > > Thanks in advance, > Mike The *windows* way of doing this would be to store the locations in the registry: module winreg The *unix* way would be to have a .conf file somewhere, usually in the directory where the main application lives. I had a similar problem, and chose to use the *old* windows way: .ini files. I store this in the same directory as the main file, and open it without a path, ie from the 'current' directory. I augmented the .ini syntax with python expressions for more power. Ini files have the structure: [section] key=value You can have many sections, each with many keys. Section names and key names are arbitrary - of your choice. My Ini module opens a .ini file and returns a dictionary in the form: {"section":{"key":value}} Programs may then use: conf["section"]["key"] to query values. I relaxed the rules about comments. Errors are simply ignored, and are not reported. You may want to change this. Here's the whole module (I'm not saying it's perfect, but it does the job for me): -andyj # Ini file handling # By Andy Jewell - use freely, but keep this comment, please def load(file): " ini file -> dictionary " f=open(file,"r") lines=f.readlines() f.close() section="" dictionary={} for line in lines: # Trim off comments if line.find("#")>-1: line=line[:line.find("#")] line=line.strip() if not line: pass elif section and (line.find("=")>-1): key,value=line.split("=") try: dictionary[section][key]=eval(value) except: dictionary[section][key]=None elif line.startswith("[") and line.endswith("]"): section=line[1:-1] if section: dictionary[section]={} return dictionary def save(dictionary,file): """ Saves dictionary to file in ini format. Destroys comments and section/key order. """ f=open(file,"w") for section in dictionary.keys(): f.write("["+section+"]\n") for key in dictionary[section].keys(): f.write("\t%s=%s\n" % (key,dictionary[section][key])) f.write("\n") From gerhard.haering at opus-gmbh.net Mon Mar 3 08:58:03 2003 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 3 Mar 2003 13:58:03 GMT Subject: Looking for Free Visual Programming Library as User Interface References: <4y3cm4egej.fsf@faepsv01.tu-graz.ac.at> Message-ID: Nikolaus Wagner wrote: > On Mon, 03 Mar 2003 14:19:48 +0100, Pierre Schnizer wrote: >> I am looking for a free visual programming library [...] > www.wxpython.org Visual Programming != GUI programming. Unfortunately, I don't know any Visual Programming-oriented library for Python, either. -- Gerhard From cce at clarkevans.com Sat Mar 15 16:29:05 2003 From: cce at clarkevans.com (Clark C. Evans) Date: Sat, 15 Mar 2003 21:29:05 +0000 Subject: generators and exceptions Message-ID: <20030315212905.GA3656@doublegemini.com> Hello, I'm playing with 2.2 generators, and it seems that they don't like exceptions... from __future__ import generators class MyExc(Exception): pass def mygen(val): while val > 0: if val % 2: raise MyExc yield val val =- 1 iterator = iter(mygen(4)) while 1: try: val = iterator.next() print val except MyExc: pass except StopIteration: break Anyway, this _only_ prints out 4, instead of 4, 2 as I expected. I expect 4, 2 beacuse an equivalent iterator would produce 4, 2. It seems that generators die on the first exception... is there a way around this? I'm asking beacuse I'm using generators in a non-blocking database system, where I want to raise WouldBlock in my generator, but still be able to call the generator at a later time when it may not block... Clark From tweedgeezer at hotmail.com Tue Mar 18 00:02:33 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 17 Mar 2003 21:02:33 -0800 Subject: [Q] Databases -- Gadfly vs Metakit vs SQLite References: Message-ID: <698f09f8.0303172102.751bc668@posting.google.com> "David LeBlanc" wrote in message news:... > There has been discussion on python-dev about merging the python only > version (no C coded kjbuckets) of Gadfly into the next distro of Python > (2.3), but I don't recall what was decided. I believe they decide it was better off left as an external package, since most people don't expect that "Batteries included" means "SQL database included." Jeremy From marshall at spamhole.com Mon Mar 3 22:32:41 2003 From: marshall at spamhole.com (marshall) Date: 3 Mar 2003 19:32:41 -0800 Subject: Looking for Free Visual Programming Library as User Interface References: <4y3cm4egej.fsf@faepsv01.tu-graz.ac.at> Message-ID: <4017400e.0303031932.3d2e6546@posting.google.com> Pierre Schnizer wrote in message news:<4y3cm4egej.fsf at faepsv01.tu-graz.ac.at>... > Dear all, > > I am looking for a free visual programming library as an interface to > my simulation similar to the Simulink interface of Labview's G Language. It > should allow to drag a few objects (~ 10) around on a sheet and connect them > accordingly. > I have lots of experience with such languages (Helix on mac, Extend, Prograph, and lots of specialized controller interfaces) but none in writing them. There is this: http://www-2.cs.cmu.edu/~amulet/ It is C++ though and I was wondering how SWIGable it is. I guess you could also embed Python into it so that the blocks could be programmed in Python. (of course _I_ can't do either of those things yet ;-) If you find something, post it. From matthew at newsgroups.com Sat Mar 22 20:00:19 2003 From: matthew at newsgroups.com (Matthew) Date: Sun, 23 Mar 2003 13:00:19 +1200 Subject: Module/namespace question Message-ID: Hi, I'm working on a small aplication which allows various lexicons (stored in their own modules) to be snapped into a parser to extract varying information from files. As different users will be writing their own lexicons, I'm wondering about namespace conflicts when the same vaiable may be defined in differing ways. From my newbie experiments, this doen't seem to be an issue as the variable changes references as the different modules are imported. Are there any dangers in this approach? Any help/hints/examples would be greatly appreciated. Thanks, matthew. BTW, thanks to Greg Ewing for his very cool Plex. From shendley at email.unc.edu Wed Mar 26 19:13:14 2003 From: shendley at email.unc.edu (Sam) Date: 26 Mar 2003 16:13:14 -0800 Subject: Passing params to single instance of wxApp References: <3088fc9a.0303241702.11bdbe2e@posting.google.com> <33803989.0303250410.35e12368@posting.google.com> <3088fc9a.0303251556.740ccce7@posting.google.com> Message-ID: <3088fc9a.0303261613.52b3bf59@posting.google.com> > Actually, I don't think there is a better way (at least not if > portability matters at all). But frankly, it's neither *that* ugly nor > difficult. Take a look at the example in the Python docs for sockets to > get started. Thanks Cliff, I took that example and threw it straight in to my app works great, had to cut and paste myself an Invoke Later handelr but it works spectacuarly. Im posting the code I used here cause I think it might be useful for other people looking for a solution to this problem. ######################################################### # These all need to go in your main app class ######################################################### def startPortListener(self): self.serverflag=Event() athread = (Thread(target = startportlistener, args = [self.CheckFile, self.serverflag])) athread.setDaemon(false) athread.start() def onInvoke(self, event): # print 'invoking envent' apply(event.func, event.args, event.kwargs) def invokeLater(self, func, args = [], kwargs = {}): # print 'posting event' wxPostEvent(self, InvokeEvent(func, args, kwargs)) def checkParamsLater(self, params): # print 'laoding event' self.invokeLater(self.CheckFile, [params]) ######################################################### # these are at root level in the file ######################################################### wxEVT_INVOKE = wxNewEventType() def EVT_INVOKE(win, func): win.Connect(-1, -1, wxEVT_INVOKE, func) class InvokeEvent(wxPyEvent): def __init__(self, func, args, kwargs): wxPyEvent.__init__(self) self.SetEventType(wxEVT_INVOKE) self.func = func self.args = args self.kwargs = kwargs def main(params): print 'params are ' + str(params) checker = btChecker('PTC- ' + str(wxGetUserId())) if checker.IsAnotherRunning(): if params != []: print 'Starting Client Server' # Echo client program import socket import sys import pickle import StringIO HOST = socket.gethostbyname(socket.gethostname()) # The remote host PORT = 50007 # The same port as used by the server s = None for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: s = socket.socket(af, socktype, proto) except socket.error, msg: s = None continue try: s.connect(sa) except socket.error, msg: s.close() s = None continue break if s is None: print 'could not open socket' sys.exit(1) print 'about to send' + str(params) pickledstring = StringIO.StringIO() pickle.dump(params,pickledstring) s.send(pickledstring.getvalue()) pickledstring2 = StringIO.StringIO() data = s.recv(1024) s.close() print 'Received', `data` else: app = MyApp(params) app.MainLoop() def startportlistener(paramshandlerlater, doneflag): # paramshandlerlater is a function in your main app takes the params stores # them and then calls your normal paramshandler from main thread # Doneflag is an Threading.Event() in your main App, use self.doneflag.set() # to kill the thread the only # problem is this thing will stay open till it gets a packet # Echo server program import socket import sys import pickle import StringIO HOST = '' # Symbolic name meaning the local host PORT = 50007 # Arbitrary non-privileged port print 'Starting Port Listener' while not doneflag.isSet(): s = None for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE): af, socktype, proto, canonname, sa = res try: s = socket.socket(af, socktype, proto) except socket.error, msg: s = None continue try: s.bind(sa) s.listen(1) except socket.error, msg: s.close() s = None continue break if s is None: print 'could not open socket' sys.exit(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break pickledstring = StringIO.StringIO(data) unpickled = pickle.load(pickledstring) print 'unpickled is '+str(unpickled) paramshandler(unpickled[0]) conn.send(unpickled[0])#sends back first param for debugging conn.close() From nav at adams.patriot.net Mon Mar 3 11:07:03 2003 From: nav at adams.patriot.net (Nick Vargish) Date: 03 Mar 2003 11:07:03 -0500 Subject: Vote on PEP 308: Ternary Operator References: <882b0a41.0303020225.3caf0334@posting.google.com> Message-ID: First, thanks for taking on this difficult task -- you've just put a huge target on your forehead... I've read ahead before replying, and I think there are some serious problems with the ballot as proposed. I believe the ballot should have a couple of places to vote before we have to select or reject specific "styles". Like: 0. Proposed: the addition of a short-circuiting ternary operator to Python [ ] In favor [ ] In favor with reservations [ ] Neutral [ ] Opposed with reservations [ ] Opposed 0.b. Should the ternary operator be nestable? [ ] Yes [ ] Neutral [ ] No 0.c. Must the conditional precede both consequents? [ ] Yes [ ] Neutral [ ] No For myself, I'm neutral as to whether a ternary operator is introduced, but I'm opposed unless the condition precedes the two consequents. In other words, I oppose the form 'x if C else y' and all variants. I am okay with 'C then x else y' and variants. I oppose all 'C ? x : y' variants, in that I don't believe complex punctuation syntax is "pythonic". It's confusing that I can list three syntax options, and either accept or reject each. So, should I be a positivist, and vote in favor of all the 'C then x else y' variants? Should I be negativist, and vote against the forms I dislike? Finally, I'm not sure that one week is enough time for everyone who might have a valid opinion to chime in. For example, I was taking a course last week, and fully participating in the decision process would have been quite a bit more difficult if this call for votes had come a week earlier. Nick -- # sigmask.py || version 0.2 || 2003-01-07 || Feed this to your Python. print reduce(lambda x,y:x+chr(ord(y)-1),'Ojdl!Wbshjti!=obwAqbusjpu/ofu?','') From spahievi at vega.bg Tue Mar 25 14:35:59 2003 From: spahievi at vega.bg (Niki Spahiev) Date: Tue, 25 Mar 2003 21:35:59 +0200 Subject: Incomparable abominations In-Reply-To: References: Message-ID: <1876151745.20030325213559@vega.bg> 3/25/2003, 6:05:17, Tim Peters wrote: TP> [Niki Spahiev] >> I do. It's easiest way to get point on the convex hull of point set. >> (point === complex). TP> Except that isn't true. If Python compared complex numbers TP> lexicographically (as it used to do), then the easiest way to get a point on TP> the convex hull would be to do min(list_of_complex) or max(list_of_complex). TP> Sorting isn't necessary for this, and would be far less efficient than the TP> min/max ways. Actually i used min (but point is min and sort crash the same way). Now i use: def minll(a,b): if a.real < b.real: return a elif a.real > b.real: return b elif a.imag < b.imag: return a else: return b pi = reduce(minll, complex_list) ugly, but works on any python version. Niki Spahiev From just at xs4all.nl Fri Mar 7 11:17:51 2003 From: just at xs4all.nl (Just) Date: Fri, 07 Mar 2003 17:17:51 +0100 Subject: [newbie] PIL ImageFont References: Message-ID: In article , "Mauro" wrote: > Dear All, > is there any way to use ImageFont under Windows? > I need either a PILFONT file under windows or to have the -truetype method > working. At the moment it asks me for _imagingft module that seems to be > missing. > Any hint more than welcome and apreciate. I think that's part of the commercial PIL package. You might want to look into reportlab, which has a nice 2d graphics API (reportlab.graphics) with Type 1 font support. Just From hilbert at microsoft.com Thu Mar 6 11:12:24 2003 From: hilbert at microsoft.com (Hilbert) Date: Thu, 6 Mar 2003 08:12:24 -0800 Subject: python vs. perl readability Message-ID: Hello, A friend of mine uses perl at work, I'm converting to python. I've showed him a couple of times how much easier it is to read python code than perl, but last night he sent me this: (I know it's ajoke, just wanted to share...) ------- import sys z,x,y= "}{|}A|k{|kA|}=BE1)|BF}))|$}:~pI~/;@Go{H%{&A?|if }:~pJ"\ "IJ-1~#>=0:GoAG at HG;o{G;%-I&{?|m,kJ,j=C?;/@~o{~D:Gl[c]("\ ")?","G$p:%~;%~;el!]':p%break~;![':p%#':c,'<':d,'-': b,'+':a,',':e,'.':f,'[':g,']':h} i() ------------------------------ Hilbert From LogiplexSoftware at earthlink.net Wed Mar 19 13:53:48 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 19 Mar 2003 10:53:48 -0800 Subject: OT: Recommended Linux Laptops, suppliers? In-Reply-To: References: <3e787f66$1_1@spamkiller.newsgroups.com> Message-ID: <1048100028.1301.98.camel@software1.logiplex.internal> On Wed, 2003-03-19 at 07:10, Aahz wrote: > In article <3e787f66$1_1 at spamkiller.newsgroups.com>, > Brad Clements wrote: > > > >Dell says my Laptop is expected to ship april 24th. > >Do you think this thread will still be going then? ;-) > > Only if we start arguing about whether it should be Linux or GNU/Linux. Emacs works best on x86 hardware. vi is best on Apple, but vi sucks. Plus, Apples automatically indent Python code with tabs and there's no way to change it. 20000 elstones on an Athlon 1.4GHz'ly yrs, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From peter at engcorp.com Tue Mar 4 13:21:51 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 04 Mar 2003 13:21:51 -0500 Subject: md5 for large files References: <3E64E467.B64551E2@engcorp.com> Message-ID: <3E64EEBF.BAA4462A@engcorp.com> Bob Ballard wrote: > "Peter Hansen" wrote: > > Bob Ballard wrote: > > > > > > Can someone provide me with a snippet or pointer to usinging Python to > > > verify the md5 value for a large file? > > > Define "large"... > > Large is any file that I want to transfer around. For example the gpg > library for windows that I just downloaded is a little over 1 mb and has a > defined md5 value that I'd like to compare. Well, if you're really talking about such small "large" files, then don't worry about memory usage and just use Dave's solution without the reading- a-block-at-a-time thing: import md5 m = md5.new() m.update(open('somefile','rb').read()) print m.digest() -Peter From thomas.g.willis at pobox.com Sat Mar 8 15:07:38 2003 From: thomas.g.willis at pobox.com (Thomas G. Willis) Date: Sat, 08 Mar 2003 15:07:38 -0500 Subject: GUI Toolkits In-Reply-To: <001301c2e5ad$a17f90b0$8800a8c0@Sirius> References: <3E6A254C.4000205@pobox.com> <001301c2e5ad$a17f90b0$8800a8c0@Sirius> Message-ID: <3E6A4D8A.4010906@pobox.com> YES! thank you. this is what I was looking for. And it seems that most of the the other gui projects out there right now, pretty much leverage this library. This must be the right choice. Thanks Again, -- Tom Willis ERROR 406: file corrupt: config.earth --- reboot universe (Y/N) ERROR 404: Universe not found. http://daspuchen.dyndns.org/paperback/bio.html L?tez? wrote: > Consider using wxPython: http://wxpython.org/ > > ----- Original Message ----- > From: "Thomas G. Willis" > To: "comp.lang.python" > Sent: Saturday, March 08, 2003 6:15 PM > Subject: GUI Toolkits > > > >>Hello all, >>I'm a newbie to python. And I'm really excited about exploring python >>and putting it to work. >> >>I wanted to know if there are any reccomended GUI toolkits for python. >>I've played around with Tkinter a little bit and I haven't noticed >>anything like treeviews and listviews, so it seems a little incomplete. >>What would the python experts consider to be the most complete GUI >>toolkit? I'm primarily developing on Windoze, cuz that's what I get paid >>to do. But cross platform capability would be a bonus, but lacking such >>would not be a show stopper necessarily. >> >>I'd really like to use Mozilla with all the cool XUL stuff, but I've >>only seen theory about the ability for XUL to call python scripts >>instead of Javascript. >> >>So what are my options? >> >>-- >>Tom Willis >> >>ERROR 406: file corrupt: config.earth --- reboot universe (Y/N) >>ERROR 404: Universe not found. >> >>http://daspuchen.dyndns.org/paperback/bio.html >> >> >> >> >>-- >>http://mail.python.org/mailman/listinfo/python-list >> >> > > > > From jwhan at dreamwiz.com Thu Mar 27 19:48:16 2003 From: jwhan at dreamwiz.com (Jongwoo Han) Date: Fri, 28 Mar 2003 09:48:16 +0900 Subject: Beginner: How to copy a string? References: Message-ID: That's because python assigns pointer dynamically. However you don't have to strictly keep the pointer. Modifying the value of t does not affect content of s. t points the destination of s as long as it's value is same as s. >>> s='abc' >>> id(s) 9761824 >>> t=s[:] >>> id(t) 9761824 >>> t=s+s >>> id(t) 9958680 >>> t 'abcabc' >>> s 'abc' >>> wrote in message news:d524bdb3.0303271627.739fa868 at posting.google.com... > I hate to ask this because the answer must be really obvious. So > obvious in fact that I couldn't find it in the tutorial, FAQ search, > and other docs, google searches, etc. > > I just want to make a copy of a string, say s='abc'. I understand > that python is not like some other languages and '=' just assigns a > name to an existing object and does not copy the object. But there is > no s.copy() method apparently. The other intuitive way (to me) was to > try str(s) which I think is similar to the way to copy some other > types such as list(). That did not work. I did see a newsgroup post > that said to use [:] and I tried it but this is what I get: > > s = 'abc' > >>> id(s) > 13356752 > >>> t = s[:] > >>> id(t) > 13356752 > >>> t > 'abc' > > Just like with str() it looks like it's still the same object. > > Ok, so what's the trick. Please be kind. It's really not obvious to > me. In fairness I did see in the FAQ you could convert it to a list > and rejoin it which I assume would work, but I suspect there is a more > direct way. > > -- David From aleax at aleax.it Sat Mar 1 03:20:27 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 01 Mar 2003 08:20:27 GMT Subject: Borg - is that a singleton? References: Message-ID: Giovanni Bajo wrote: ... > Since Borg (as in > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531) rebinds the Expanded and clarified in the printed Cookbook (O'Reilly) and in my IPC11 essay, online at www.aleax.it/Python/5ep.html -- qv. > class Borg: > def __init__(self): > cls = self.__class__ > try: cls.__shared_state > except: > cls.__shared_state = {} > self.__dict__ = cls.__shared_state > > Which leads to what seems to me the expected behaviour from a singleton, I suggest, as explained in the paper: class Borg: _shared_state = {} # only ONE leading _ def __init__(self): self.__dict__ = self._shared_state class Monitor(Borg): _shared_state = {} # all Monitors share state among themselves class SpeclalMonitor(Monitor): pass # including SpecialMonitor instances class Printer(Borg): _shared_state = {} # all Printers share state among themselves class SpeclalPrinter(Printer): pass # including SpecialPrinter instances If you want to FORCE each direct subclass of Borg to define its own _shared_state, just omit the assignment to _shared_state in the body of the Borg class itself. But subclasses of such direct classes should still be _allowed_ to keep sharing state with their base, in order to customize its behavior but not the state, if desired. I find your suggested approach a bit fragile, because it conflates issues of class initialization with ones of instance initialization. Consider, with your implementation of Borg: class Super(Borg): pass class Sub(Super): pass now if the code continues with: a = Sub() b = Super() then a and b do NOT share state. But if it instead continues with: b = Super() a = Sub() then a and b DO share state. This is far from obvious to the reader of the code, and it's what I would call a typical "black magic effect". If you DO want to avoid the clear, simple, explicit solution of having classes that don't want their instances to share state with instances of superclasses just bind their own _shared_state dict in class scope, you're probably better off generating the magic _shared_state in a custom metaclass, e.g.: class metaBorg(type): def __new__(cls, name, bases, clasdict): clasdict.setdefault('_shared_state', {}) return type.__new__(cls, name, bases, clasdict) def __call__(cls, *args, **kwds): self = cls.__new__(cls, *args, **kwds) self.__dict__ = self._shared_state cls.__init__(self, *args, **kwds) return self class Borg: __metaclass__ = metaBorg This version _forces_ a _shared_state class attribute on each subclass (though it also lets such a subclass explicitly define a _shared_state for nefarious purposes and doesn't override it in that case -- that's why the setdefault call). You might chose to soften this a bit, e.g. by making metaBorg.__new__ into: def __new__(cls, name, bases, clasdict): for base in bases: if hasattr(base, '_shared_state'): break else: clasdict.setdefault('_shared_state', {}) return type.__new__(cls, name, bases, clasdict) this LETS each subclass define a _shared_state, but only defaults to setting it to a new empty dict if no base has a _shared_state attribute already. I thought this metaclass might be of some interest because it also overrides type.__call__ (a bit roughly perhaps -- it does not allow classes to set a weird __new__, but rather assumes __new__ returns a cls instance and unconditionally calls __init__ on that instance) in order to automate the setting of each instance's __dict__, without any need for borgs to explicitly call Borg.__init__(self) any more. Whether this level of "implicitness" qualifies as black magic best avoided, or as an elegant solution, I'll leave to readers to decide. Anyway, the point is you can now: class Foo(Borg): pass class Bar(Borg): pass and get _separately-borgized_ Foo and Bar classes without doing anything more than inheriting from Borg. Alex From gustav at morpheus.demon.co.uk Wed Mar 12 17:19:07 2003 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: Wed, 12 Mar 2003 22:19:07 +0000 Subject: Strange discrepancy between Excel VBA and Python References: Message-ID: "Moore, Paul" writes: > When I try to resize a range in Python, I get a different answer from VBA. > > Simple example, get a block of 10 cells at the top left of sheet 1 (I know > I can do this other ways, but it illustrates the point) > > From the Excel VBA immediate window: > > ? Sheets(1).Cells(1,1).Resize(10,10).Address > $A$1:$J$10 > > From PythonWin: > >>>> xl = Dispatch("Excel.Application") >>>> xl > >>>> xl.Sheets(1).Cells(1,1).Resize(10,10).Address > u'$J$10' > > (You note that I have run Makepy). > > Why is Python showing this as a single cell??? I discovered that there is a GetResize method which does work. But I'm not sure what Resize() is meant for, in that case. Can anyone explain? Thanks, Paul -- This signature intentionally left blank From max at alcyone.com Sun Mar 2 16:57:53 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 02 Mar 2003 13:57:53 -0800 Subject: Ordinal not in range(128) References: <3e614c68$0$227$626a54ce@news.free.fr> <3E615273.E4E3CE93@alcyone.com> <3E628A82.2050501@caramail.com> Message-ID: <3E627E61.6CBF738@alcyone.com> Fabien HENON wrote: > In my case, my editor is multilanguage and users can choose between > many > fonts. I am not a Unix guru, but latin-1 is for Western Europe (?). > Is > it going to work for polish or Spaniards,... Well the example "extended characters" you gave looked like Latin-1. As I indicated, if you want the encoding to be Latin-1, use 'latin-1' as the encoding name. If you want it to be something else, use the appropriate name for that encoding. I don't know which encoding you really want, only you do. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Mona Lisa / Come to discover / I am your daughter \__/ Lamya Fauxident / http://www.alcyone.com/pyos/fauxident/ A "faux" ident daemon in Python. From mchermside at ingdirect.com Wed Mar 19 12:41:54 2003 From: mchermside at ingdirect.com (Chermside, Michael) Date: Wed, 19 Mar 2003 12:41:54 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 17) Message-ID: <7F171EB5E155544CAC4035F0182093F03CF7B8@INGDEXCHSANC1.ingdirect.com> Peter Hansen writes: > But it's irrational, right? So irrationality is now defined as > normal? Erik Max Francis replies: > No. Irrational does not necessarily imply normal. Take for instance > the irrational number (decimal expansion): > > 0.1010010001000010000010000001... > > This number does not terminate and does not repeat, so therefore it is > irrational. However, it clearly does not have a normal distribution for > all digits (or indeed even for the only two decimal digits which > appear). Thus it is irrational, but not normal. But we CAN conclude that being rational implies you're not normal. I-better-not-forget-the--on-this-one -- Michael Chermside From wsonna at attglobal.net Fri Mar 21 21:26:25 2003 From: wsonna at attglobal.net (William Sonna) Date: Fri, 21 Mar 2003 20:26:25 -0600 Subject: No Do while/repeat until looping construct in python? References: Message-ID: On Mon, 17 Mar 2003 15:30:34 +0000, Steve Holden composed the following delusional long-winded post: > "William Sonna" wrote to comp.lang.python, in > various posts and at various times, but invariably in the same strident > tone ... > > Sorry, but policy is not to respond to stalkers. And no, you can't have my garbage. [snip] From exarkun at intarweb.us Mon Mar 17 01:11:48 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 17 Mar 2003 01:11:48 -0500 Subject: Flying With Python (Strong versus Weak Typing) In-Reply-To: <3E755C7C.8040102@email-server.info> References: <37a869bc.0303102102.4533973@posting.google.com> <20030312175754.GB30375@meson.dyndns.org> <3E755C7C.8040102@email-server.info> Message-ID: <20030317061147.GB21859@meson.dyndns.org> On Mon, Mar 17, 2003 at 06:26:20AM +0100, Alexander Skwar wrote: > Jp Calderone wrote: > > > Can you "cast" a square peg to a round one, though? ;) I think a better > > Sure, as was demonstrated by the Apollo 13 "problems", were they fitted a > square peg to a round hole - sort of (atleast that's how they showed it > in the film, IIRC). I liked the hammer analogy someone else used. What the Apollo 13 ground crew and mission crew did strikes me as more akin to using a proxy type to make one thing fit the interface of another. Jp -- "Pascal is Pascal is Pascal is dog meat." -- M. Devine and P. Larson, Computer Science 340 -- up 13 days, 21:59, 8 users, load average: 0.00, 0.00, 0.00 From intentionally at blank.co.uk Wed Mar 5 22:20:32 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Thu, 06 Mar 2003 03:20:32 +0000 Subject: Waffling (was Re: single-line terinary operators considered harmful) References: Message-ID: On Wed, 5 Mar 2003 12:31:34 -0700, Steven Taschuk wrote: >Quoth Stephen Horne: > [...] >> When I was saying that optionalness of the semicolon makes the >> difference between separation and termination, [...] > >So, in Python: > [1, 2, 3,] > [1, 2, 3] >Is the comma a terminator or a separator? Same thing. With either semicolons for (at least Pascal) statements and commas in the above lists, the most pragmatic answer is 'who cares'. Of course I tend to see commas as separators and find your top example strange, and of course I might well see semicolons the same way if I hadn't used them as terminators in several other languages. > while ((*p_Dest++ = *p_Src++) != 0) > ; I'm not sure. With modern compilers, using side effects like this is IMO inherently bad - without the side-effects the loop has no purpose. So while your right about the 'this line intentionally left blank' effect, I still wouldn't use it myself. This style of code had value when C was created (before decent optimisers had been developed), but IMO it's had its day. >It's not redundant at all: 0*1 and 0*[] yield objects of different >types; if x is an instance of a user-defined vector class, the >multiplication should return the zero vector, not 0; and so forth. >The second operand must be evaluated to achieve this polymorphism. Of the mistakes I've made recently, this is certainly the most annoying. Damn. -- steve at ninereeds dot fsnet dot co dot uk From jdhunter at ace.bsd.uchicago.edu Thu Mar 6 22:33:56 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 06 Mar 2003 21:33:56 -0600 Subject: Problem finding modules In-Reply-To: ("Janos Blazi"'s message of "Thu, 06 Mar 2003 22:53:26 +0100") References: <3E67BC35.F54C9C17@engcorp.com> Message-ID: >>>>> "Janos" == Janos Blazi writes: Janos> The values point to drive d: but they point to drive c:. You lose me here: is this what you meant to say? This appears contradictory to me. You can set the PATH variables several ways. In Win NT like systems, go to your My Computer icon, right-click it, and select the Properties tab. Under the Advanced tab, choose Environment Variables. Double click on the system variable you are interested in and add the path, separating the path entries with a semicolon. You can also edit c:\\autoexec.bat. Which module is not being imported? Doe the file __init__.py exist in D:\\Python22\\Lib\\site-packages\somemodule ? John Hunter From cct at tavaresstudios.com Mon Mar 17 02:30:18 2003 From: cct at tavaresstudios.com (Chris Tavares) Date: Mon, 17 Mar 2003 07:30:18 GMT Subject: [Q] Databases -- Gadfly vs Metakit vs SQLite References: Message-ID: "David LeBlanc" wrote in message news:mailman.1047802347.7044.python-list at python.org... > > Aside from it's dubious parentage, Jet has a reputation for being > excruciatingly slow. I believe, but am not positive, that Outlook uses Jet > and there are times when Outlook is incredibly slow. With a lot of saved > mail message, and after a normal shutdown, Outlook can take several minutes > to startup. It can take a noticable time to switch from viewing one email to > another in the same folder! > Outlook does not use Jet for its storage. It'd actually be an improvement if it did, I think. :-) > Sqlite is my db of choice for it's rubustness, performance, licensing > (totally unencumbered!) and the fact that it comes from a developer with a > sterling reputation across no less than 3 language groups. > I also like Sqlite; I haven't had a need for it YET, but I really appreciate the effort that the author has put into development AND packaging. Sqlite is powerful, and incredibly easy to link into your app. It's definately good stuff. -Chris From staschuk at telusplanet.net Sun Mar 23 21:17:56 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Sun, 23 Mar 2003 19:17:56 -0700 Subject: Question on dynamically loaded modules. In-Reply-To: <62sfa.3236$WQ5.710@tornadotest1.news.pas.earthlink.net>; from adonisv@earthlink.net on Mon, Mar 24, 2003 at 12:10:42AM +0000 References: <62sfa.3236$WQ5.710@tornadotest1.news.pas.earthlink.net> Message-ID: <20030323191756.A993@tibia.amotlpaa.bogus> Quoth Adonis: > What is the best way to instantiate a module's class and it's members given > that the module(s) can be loaded at any given time? It's difficult to answer this question without more detail about what you're trying to do. If you're thinking of having your application load a bunch of plug-ins, where each plug-in is in its own module, then perhaps will be of some use. -- Steven Taschuk staschuk at telusplanet.net "Its force is immeasurable. Even Computer cannot determine it." -- _Space: 1999_ episode "Black Sun" From yoda at dagobah.org Thu Mar 20 05:28:22 2003 From: yoda at dagobah.org (Jedi Master Yoda) Date: 20 Mar 2003 10:28:22 GMT Subject: Is Python the Esperanto of programming languages? References: <200303192233.30383.andy@wild-flower.co.uk> <3E7908A7.CCEF27E8@alcyone.com> <3E791678.182F8916@alcyone.com> <7i1y1294g5.fsf@enark.csis.hku.hk> Message-ID: On 20 Mar 2003 10:06:50 +0800, Isaac To spouted: > This contrasts sharply with any programming language. For many people, as > long as the things they need are there, the choice of programming language > is more or less based on personal preference. Then even a language that is > not "as easily learnt as it should be" can be successful. So the success of > Python, but the failure of Esperanto. Ooh, OK, I'll bite. :) By what criteria has Python 'succeeded'? By what criteria has Esperanto 'failed'? I'd love to know. Sincerely, Kia Stulteco From exarkun at intarweb.us Sat Mar 22 15:28:29 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sat, 22 Mar 2003 15:28:29 -0500 Subject: tracing routes (traceroute) In-Reply-To: <3E7CC4F4.9090707@overdrivepc.com> References: <3E7CC4F4.9090707@overdrivepc.com> Message-ID: <20030322202829.GA10393@meson.dyndns.org> On Sat, Mar 22, 2003 at 03:17:56PM -0500, Joe Brown wrote: > I've written a rudimentary traceroute that works well on win32 (python 2.2) > > For the little hair left on my head, I can't figure out how to get this > thing to work on Linux (python 2.3). My every attempt to open an ICMP > socket on Linux has been ill-fated. I'm drawing the conclusion that > sockets are somewhat broken in this version of python on Linux. > > Anyway, this traceroute works pretty good on windows, where it's useful, > since window's tracert is rather slow (unless you have two nic's > installed into your winbox --go figure ;) On linux, you need root permissions to open these kinds of sockets. I tried your program as root, and it works :) Jp -- C/C++/Java/Perl/Python/Smalltalk/PHP/ASP/XML/Linux (User+Admin) Genetic Algorithms/Genetic Programming/Neural Networks Networking/Multithreading/Legacy Code Maintenance/OpenGL See my complete resume at http://intarweb.us:8080/ -- up 2 days, 15:59, 6 users, load average: 0.02, 0.02, 0.00 From intentionally at blank.co.uk Mon Mar 3 03:17:55 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Mon, 03 Mar 2003 08:17:55 +0000 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <58q36vgv1ga8ovde5ftub9t8ugaa2pnum5@4ax.com> Message-ID: <7k366vonlu82mq7ve83bmq7ijfhrv03hpf@4ax.com> On 02 Mar 2003 23:16:53 +0000, Alexander Schmolck wrote: >Stephen Horne writes: > >> Actually, I've always thought that having separate 'def' and 'lambda' >> syntaxes is a bit redundant. In lisp (and a few others) you'd use the >> 'lambda' form to do both jobs, rather like (in current Python) >> writing... >> >> sum = lambda a, b : a + b > >Not true, I think. Apart from scheme (which's lispness is often disputed in >both lisp and scheme circles). Wierd - I've hardly used scheme, but I have looked at it much more recently than lisp (not used properly in more than a decade). Still, I appologise for the confusion. -- steve at ninereeds dot fsnet dot co dot uk From f98dawa at dd.chalmers.se Thu Mar 13 12:45:21 2003 From: f98dawa at dd.chalmers.se (Dag) Date: 13 Mar 2003 17:45:21 GMT Subject: reading remote files Message-ID: I'm trying to find a way to read (and possibly write) files on remote machines over ssh. All that should be required on the remote machine is a standard ssh server (I don't want to write some kind of special server for this) and all the local machine should need is path and username/password combo with read access to the relevant file. Ideally I'd like to be able to created some kind of remote file object which can be read by readlines(), failing that I'll settle for slurping the whole file into a list and then read through it that way. I've been playing with the pyssh module a bit, but it's not very well documented and I'm wondering if anyone has solved a similar problem or if anyone has a good idea on how to tacle this. Dag From dave at pythonapocrypha.com Fri Mar 14 12:01:41 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 14 Mar 2003 09:01:41 -0800 (PST) Subject: High performance IO on non-blocking sockets In-Reply-To: References: Message-ID: On Fri, 14 Mar 2003, Richie Hindle wrote: > > [Troels] > > sent = self.socket.send(self.data) > > self.data = self.data[sent:] > > > > This approach is bad [...] > > >From http://www.python.org/doc/current/lib/socket-objects.html : > > ------------------------------- snip snip ------------------------------- > > 7.2.1 Socket Objects > > [...] > > sendall( string[, flags]) > > Send data to the socket. The socket must be connected to a remote socket. > The optional flags argument has the same meaning as for recv() above. > Unlike send(), this method continues to send data from string until either > all data has been sent or an error occurs. None is returned on success. On > error, an exception is raised, and there is no way to determine how much > data, if any, was successfully sent. > > ------------------------------- snip snip ------------------------------- Nope - the OP needs something for non-blocking sockets. -Dave From uwe.schmitt at procoders.net Thu Mar 13 17:34:44 2003 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 13 Mar 2003 22:34:44 GMT Subject: SandBox.py new version References: Message-ID: Uwe Schmitt wrote: > Hi, > I updated SandBox.py to version 0.5. SandBox.py allows > executing python code in a restricted environment. I just updated the sandbox module, there were some minor bugs and wrong identations. There is still a problem concerning poor memory management, some objects will not be deleted correctly by the garbage collector. I know the source of the problem and fix it as soon as possible. Be aware that the code is still v0.5 and should not be used in sensitive applications. Greetings, Uwe -- Dr. rer. nat. Uwe Schmitt Computer science is no more about Computers, uwe.schmitt at num.uni-sb.de than astronomy is about telescopes. (Dijkstra) http://www.procoders.net From opengeometry at yahoo.ca Wed Mar 5 13:25:20 2003 From: opengeometry at yahoo.ca (William Park) Date: 5 Mar 2003 18:25:20 GMT Subject: pointer in Python References: <20030306025005.349cd43a.rm@no-mail.com> Message-ID: Roy Marteen wrote: > Hi, > > Can I parse a variable using a pointer in Python? And how can I > declare pointer to function in Python? Thank you very much. Actually, everything in Python is "pointer to something real". This is called "object reference" in Python. So, you can assign function to a variable, and that variable will be a pointer to that function, ie. def func(a): return a + 1 print func(5) f = func print f(5) -- William Park, Open Geometry Consulting, Linux solution for data management and processing. From tim.one at comcast.net Sun Mar 2 11:46:19 2003 From: tim.one at comcast.net (Tim Peters) Date: Sun, 02 Mar 2003 11:46:19 -0500 Subject: Is the OS win9x or winnt? How to detect it? In-Reply-To: Message-ID: [Chen] > Is it possible to detect whether the OS is win9x or winnt? > > I used os.name but it returns "winnt" even on win98se. While sys.platform > returns "win32". sys.getwindowsversion() is new in Python 2.3, and returns a 5-tuple of values built from from calling the Win32 GetVersionEx() function. Before 2.3, you have to do something trickier. For example, version_string = os.popen("ver").read() and then parse version_string, assuming the box's COMPSPEC points to a shell that supports the VER command. From andersjm at dancontrol.dk Wed Mar 5 06:13:40 2003 From: andersjm at dancontrol.dk (Anders J. Munch) Date: Wed, 5 Mar 2003 12:13:40 +0100 Subject: Why no RE match of A AND B? References: Message-ID: <3e65dbab$0$203$edfadb0f@dread11.news.tele.dk> "Tim Peters" wrote: > [Anders J. Munch] > > It's [regexp intersection] useful in combination with complement ("it's > > a .*day but not a Sunday"). > > If that's the use case, it's more an argument for adding a difference > operator (like R-S = the strings matched by R less the strings matched by > S). That might be so. Not that I'm proposing to add anything of either kind. It's easier though to express difference through intersection and complement R-S = R & ~S than the other way around R & S = (R|S) - (R-S) - (S-R) - Anders From bkc at murkworks.com Sat Mar 8 20:23:42 2003 From: bkc at murkworks.com (Brad Clements) Date: Sat, 08 Mar 2003 20:23:42 -0500 Subject: Recommended Linux Laptops, suppliers? In-Reply-To: References: <3e6a571b$1_1@spamkiller.newsgroups.com> Message-ID: <3E6A4E1D.12593.A58549E0@localhost> On 8 Mar 2003 at 15:38, David LeBlanc wrote: > If you don't object to Lindows (I do), they're selling an inexpensive Linux > laptop - $800! www.lindows.com Sorry, I forgot to mention .. I want a real machine ;-) > Why not put Linux on the Tecra? It's a P1-133 with 80 mb ram and 1GB disk, a slow disk. I have run Linux on it, but Mozilla is incredibly slow.. I bet phoenix is slow too. > There is also the theory that if you never run the MS OS product on the > machine you buy, you can get a refund of the license fee. Don't recall all > the details, but you must have never run it or accepted the EULA or some > such nonsense. I've heard that too, but I think that's too much hassle. I think it's time big-name vendor sell Linux laptops! -- Brad Clements, bkc at murkworks.com (315)268-1000 http://www.murkworks.com (315)268-9812 Fax http://www.wecanstopspam.org/ AOL-IM: BKClements From tzot at sil-tec.gr Thu Mar 13 07:35:31 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 13 Mar 2003 14:35:31 +0200 Subject: Pausing until threads are done References: Message-ID: On Thu, 13 Mar 2003 07:50:52 GMT, rumours say that Alex Martelli might have written: >Don't use the thread module in your application code: it's a very low >level module, meant basically as an engine for module threading, which >is the one you _should_ be using, Why _should_ he? The question mark actually refers to "should", so I am asking about the reasoning. Actually, this is not a question directed only to Alex; I have also read others posting "don't use thread, you should use threading" or similar remarks, but the reasoning seems to be "dogmatic" (in quotes because I don't mean it in an offensive way) a la snickers-ads: "Just do it." I would offer the following reasoning: "you _should_ use the threading module since it offers a much better abstraction of threading, but if you feel comfortable using directly the thread module, locks and queues, do so." -- TZOTZIOY, I speak England very best, bofh at sil-tec.gr (I'm a postmaster luring spammers; please spam me! ...and my users won't ever see your messages again...) From mwm at mired.org Sun Mar 23 11:04:33 2003 From: mwm at mired.org (Mike Meyer) Date: Sun, 23 Mar 2003 16:04:33 GMT Subject: Incomparable abominations References: Message-ID: mertz at gnosis.cx (David Mertz, Ph.D.) writes: > You seemed to be answering Mike Meyer's stronger statement that the same > *version* should always sort the same, which I agree is too strong. I never made any claims about sorting. What I did claim was that Python would be better off if comparisons made sense or raised exceptions. This does mean that sorting a list will give the same results - but that's not the point. I don't think I've ever had a reason to sort a heterogenous list. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From martin at v.loewis.de Mon Mar 3 04:25:34 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 03 Mar 2003 10:25:34 +0100 Subject: IME withTix on multilanguagesupported system ? References: <34e4328e.0303020911.7c7ed0c9@posting.google.com> Message-ID: "vincent wehren" writes: > I doubt that any IME will provide the right results in Tix as long as the > default setting on his W2K machine is Russian (CP866/ACP1251). Doesn't Tk > use the current encoding to internalize into unicode? I missed that point, and it has its merits. However, in Tk 8.4, win/tkWinKey.c, I find } else if (eventPtr->xkey.send_event == -2) { /* * Special case for win2000 multi-lingal IME input. * xkey.trans_chars[] already contains a UNICODE char. */ int unichar; char buf[TCL_UTF_MAX]; int len; unichar = (eventPtr->xkey.trans_chars[1] & 0xff); unichar <<= 8; unichar |= (eventPtr->xkey.trans_chars[0] & 0xff); len = Tcl_UniCharToUtf((Tcl_UniChar) unichar, buf); Tcl_DStringAppend(dsPtr, buf, len); } else { So it *looks* like it could work "correctly" in some cases. It appears that this processing occurs when WM_IME_COMPOSITION has been received before (*). I don't know under what circumstances that would happen, though. W2k seems to be a prerequisite, but there are probably more prerequisites (like using an IME with composition, whatever that is). Regards, Martin (*) On W2k, Tk will invoke ImmGetCompositionStringW in this case; on W98, it will invoke ImmGetCompositionStringA. From philip at tildesoftware.com Wed Mar 19 18:38:08 2003 From: philip at tildesoftware.com (Philip Greer) Date: Wed, 19 Mar 2003 23:38:08 +0000 Subject: RFD: comp.databases.berkeley-db Message-ID: <1048117088.326@isc.org> REQUEST FOR DISCUSSION (RFD) unmoderated group comp.databases.berkeley-db This is a formal Request For Discussion (RFD) for the creation of a world-wide unmoderated Usenet newsgroup comp.databases.berkeley-db. This is not a Call for Votes (CFV); you cannot vote at this time. Procedural details are below. Newsgroup line: comp.databases.berkeley-db Berkeley database and related topics. RATIONALE: comp.databases.berkeley-db Today there is not a specific usenet location for discussions on berkeley database management software (from this point forward I'll refer to as just 'berkeley-db'). I've seen discussion occur on comp.databases, comp.lang.python, comp.lang.perl.misc and other usenet forums pertaining to sendmail and other solutions that utilize berkeley-db for storage purposes. Sure, those discussions can be specific to the software that is utilizing berkeley-db in the back end, but a majority of those discussions are specific to the database software itself and/or issues thereof. A central forum specific to berkeley-db itself will greatly benefit the programming community that utilizes the tool. As well, with today's increased usage of embedded systems, and of the use of berkeley database libraries within embedded solutions, a need for a common area to discuss this software tool will continue to increase. CHARTER: comp.databases.berkeley-db The newsgroup comp.databases.berkeley-db shall be a forum devoted to the discussion of the berkeley database management software, it's usage and it's support in a free atmosphere. All postings must be in ordinary text format only; no special format files (BinHex, MIME, UUEncode, etc.) are to be posted. Crossposting of articles irrelevant to the berkeley database solution is strongly discouraged. Also discouraged are personals and personal messages, and any postings of a purely commercial nature. END CHARTER. PROCEDURE: This is a request for discussion, not a call for votes. In this phase of the process, any potential problems with the proposed newsgroups should be raised and resolved. The discussion period will continue for a minimum of 21 days (starting from when the first RFD for this proposal is posted to news.announce.newgroups), after which a Call For Votes (CFV) may be posted by a neutral vote taker if the discussion warrants it. Please do not attempt to vote until this happens. All discussion of this proposal should be posted to news.groups. This RFD attempts to comply fully with the Usenet newsgroup creation guidelines outlined in "How to Create a New Usenet Newsgroup" and "How to Format and Submit a New Group Proposal". Please refer to these documents (available in news.announce.newgroups) if you have any questions about the process. DISTRIBUTION: This RFD has been posted to the following newsgroups: news.groups, news.announce.newgroups, comp.databases, comp.lang.python, comp.lang.perl.misc Proponent: Philip Greer Proponent: Dave Segleau From maxm at mxm.dk Wed Mar 12 03:22:20 2003 From: maxm at mxm.dk (Max M) Date: Wed, 12 Mar 2003 09:22:20 +0100 Subject: string.replace() produces TypeError: an integer is required In-Reply-To: References: Message-ID: <3E6EEE3C.20105@mxm.dk> theKid wrote: > As far as I can tell, I'm using the function correctly: > > import string > import types > > print type(data) > print data > data = string.replace(data, '\t', '\\t') # line 58 > data = string.replace(data, '\n', '\\n') > print data > > > Am I using string.replace() correctly? Yes. Most likely the problem is that you have deleted your "data" variable by mistake. It works when I define data. data = "Hi\tThere" import string import types print type(data) print data data = string.replace(data, '\t', '\\t') # line 58 data = string.replace(data, '\n', '\\n') print data >>> >>> Hi There >>> Hi\tThere -- hilsen/regards Max M Rasmussen, Denmark http://www.futureport.dk/ Fremtiden, videnskab, skeptiscisme og transhumanisme From zopestoller at thomas-guettler.de Tue Mar 25 10:04:52 2003 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Tue, 25 Mar 2003 16:04:52 +0100 Subject: py2exe: LookupError: no codec search function registered References: Message-ID: Thomas Guettler schrieb: > Hi! > > My script works fine, but if I use the exe created > by py2exe, I get: > > LookupError: no codec search functions registered: can't find encoding > > The code: > unicode(bulg, "windows-1251").encode("utf-8") found the answer myself: """ Recent Python versions contain support for unicode, which requires the encodings package to be included in the exe-file. This is not included by default, and it would be very difficult for py2exe to find that this is needed. So if your exe-file reports errors like LookupError: no codec search functions registered: can't find encoding or LookupError: unknown encoding, you should advise py2exe to include this package with the '--packages encodings' command line option. """ http://starship.python.net/crew/theller/py2exe/ thomas From james.kew at btinternet.com Sun Mar 2 09:44:10 2003 From: james.kew at btinternet.com (James Kew) Date: Sun, 2 Mar 2003 14:44:10 -0000 Subject: Vote on PEP 308: Ternary Operator References: <882b0a41.0303020225.3caf0334@posting.google.com> Message-ID: Gerrit Holl wrote: > James Kew schreef op zondag 2 maart om 13:46:11 +0000: >> [re: the examples section] >> If they're not used, and can be wrong, what on *earth* are they for? > > Raymond's original mail states: >> The purpose of the examples section is voter education. This >> provides some assurance that each voter has at least tried >> their own preferred syntax. Ah -- yes, so it does. My apologies. -- James Kew james.kew at btinternet.com From staschuk at telusplanet.net Fri Mar 21 14:24:16 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Fri, 21 Mar 2003 12:24:16 -0700 Subject: Is Python the Esperanto of programming languages? In-Reply-To: ; from imbosol-1048259891@aerojockey.com on Fri, Mar 21, 2003 at 03:45:51PM +0000 References: <7i65qe953z.fsf@enark.csis.hku.hk> <3oyea.61654$68.41484@nwrdny01.gnilink.net> Message-ID: <20030321122416.A5100@tibia.amotlpaa.bogus> Quoth Carl Banks: [... -s agreement marker on English verbs ...] > Sure, there's a marginal benefit to it. The morpheme has a tad of > meaning left, when the number of the subject can't be determined. > (E.g. "The sheep go to the barn.") The ending is a little redundant, > but mostly superfluous. I think we agree that the information "the subject of this verb is third person and singular" is usually but not always available elsewhere. (I ignore the tense-marking aspect of the morpheme.) I see in your other recent post the claim that, in real language processing (as opposed to after-the-fact thought), the information from the subject takes precedence over that of the inflection of the verb if they contradict one another (which they do if the morpheme is omitted when agreement calls for it). This seems plausible, so I'll so stipulate. I don't, however, think that these add up to the morpheme "saying nothing". In my personal theory of meaning (idiosemantics?), it always means "third person singular", and its absence always means "not third person singular"; this explains why 1. The man goes to the store. is good, 2. *The man go to the store. is bad, and 3. The sheep goes to the barn. is not ambiguous as to the number of sheep. It does not, on its own, explain why (2) is merely bad instead of ambiguous to the point of incomprehensibility; for that we can use your idea that the information from the subject dominates. I don't see what is explained by calling the morpheme meaningless in (1). [...] > If a language could be invented that completely lacked redundancy, and > was simple enough to be internalizable, then I don't think humans > would have any problems communicating with it. Ah. I understand better now your point. There are scenarios of language use in which noise is a major concern; military speech over radio comes to mind. (Both the so-called phonetic alphabets, which are by design highly redundant, and the use of formulaic utterances such as "say again, all after X".) Admittedly such speech is not representative of typical language use, and has little if any influence on language development in the broader community. However, there's always *some* noise. I think it plausible that there's enough noise normally (not so much in transmission as in utterance and interpretation) to require some degree of redundancy for error detection and correction. How much, I don't know; it might well be less than any existing natural language actually has. -- Steven Taschuk staschuk at telusplanet.net "Telekinesis would be worth patenting." -- James Gleick From btate at objectmastery.com Sun Mar 16 19:41:35 2003 From: btate at objectmastery.com (Bradley Tate) Date: Mon, 17 Mar 2003 00:41:35 GMT Subject: usenet newsgroups Message-ID: <3R8da.5$aW4.248@news.optus.net.au> news0.optus.net.au From news at snakefarm.org Mon Mar 10 07:24:46 2003 From: news at snakefarm.org (Carsten Gaebler) Date: Mon, 10 Mar 2003 13:24:46 +0100 Subject: time.strftime() References: <20030310092838.GB695@jsaul.de> Message-ID: jsaul wrote: >>>>time.strftime("%a, %d %b %Y %H:%M:%S %z", time.localtime()) >>> > 'Mon, 10 Mar 2003 10:26:51 +0000' > > It should be '+0100' because this is CET time zone: > >>>>time.strftime("%Z",time.localtime()) >>> > 'CET' Same on my system. But 'date +%z' works fine, so it doesn't seem to be a library issue but a python bug. cg. From reply.in at the.newsgroup Thu Mar 6 03:07:06 2003 From: reply.in at the.newsgroup (Rene Pijlman) Date: Thu, 06 Mar 2003 09:07:06 +0100 Subject: range References: Message-ID: Hilbert: >Why does range(1,4,1) return [1,2,3]? >It should return [1,2,3,4]. "If step is positive, the last element is the largest start + i * step less than stop" ^^^^^^^^^^^^^^ http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-47 -- Ren? Pijlman From member16943 at dbforums.com Sat Mar 8 12:18:50 2003 From: member16943 at dbforums.com (Tetsuo) Date: Sat, 08 Mar 2003 17:18:50 +0000 Subject: Really, Amazingly Silly Question References: <%Qhaa.505$LR7.340479160@newssvr30.news.prodigy.com> Message-ID: <2620692.1047143930@dbforums.com> Py2exe? -- Posted via http://dbforums.com From pan-newsreader at thomas-guettler.de Sat Mar 22 08:06:57 2003 From: pan-newsreader at thomas-guettler.de (Thomas Guettler) Date: Sat, 22 Mar 2003 14:06:57 +0100 Subject: Creating XML using Python References: Message-ID: On Sat, 22 Mar 2003 05:30:23 +0100, David Mitchell wrote: > Hello group, > > I'm trying to find options for creating XML documents using Python. > There's any amount of options and documentation for *consuming* XML, but > I'm having trouble finding options for *producing* XML. Well, I suppose > "print" is an option... Maybe this article helps you: http://www.xml.com/pub/a/2003/03/12/py-xml.html Nevertheless, I always use "print" for creating xml. > The DTD I'm using is still a work-in-progress, and I'd like > to be able to perform relatively minor surgery to my code as the DTD > changes in order to bring the XML files I'm producing in sync with the > revised DTD. I don't like DTD, XSchema, XSL, XSLT, XPointer, XPath. I only need a syntax (XML) and a programming language (python). If you need a common xml schema, because you want to exchange data, I would write a small validate script in python which parses the xml with sax and tests if it is correct. thomas -- Thomas Guettler http://www.thomas-guettler.de From sjmachin at lexicon.net Tue Mar 4 02:46:17 2003 From: sjmachin at lexicon.net (John Machin) Date: 3 Mar 2003 23:46:17 -0800 Subject: Why no RE match of A AND B? References: Message-ID: Joshua Marshall wrote in message news:... > I think the difference is that in Python, the RE "abc" matches any > string containing 'abc', not just the exact string itself. I am using "match" in the ordinary sense which coincides with the Python definition of re.match(), whereas you seem to be using "match" to mean what re.search() does. If I had have meant the RE ".*abc.*", I would have said that. From follower at iname.com Sat Mar 1 19:46:50 2003 From: follower at iname.com (Follower) Date: 1 Mar 2003 16:46:50 -0800 Subject: Advice for wxPython error: "'NoneType' object is not callable" in ignored Message-ID: This post is about an issue relating to wxPython, module importing and global variables referring to (native?) wxWindows objects. (It is mostly intended as Google-bait for anyone else having the problem in the future, but any further information is welcome.) The following Python error message may indicate you have this problem: Exception exceptions.TypeError: "'NoneType' object is not callable" in ignored Simplest Problem Form ===================== You have these files: myapp.py mypackage/__init__.py mypackage/mymodule.py With the following content: # ---- myapp.py ---- import mypackage.mymodule # ---- mypackage/__init__.py ---- # # ---- mypackage/mymodule.py ---- import wxPython.wx import mypackage # <1> myglobal = wxPython.wx.wxSize(780, 580) # -- -- When you execute the command: python myapp.py The following is the output: Exception exceptions.TypeError: "'NoneType' object is not callable" in ignored Solutions ========= * Don't have global variables ('myglobal' in this example) referring to wxWindows objects. (Best solution.) * Don't explictly import the parent package from a module within it. (i.e. delete the line marked with "<1>"--it's not necessary in real life anyway.) While this solves the problem in certain circumstances you may run into the problem again if you have sub-packages which import the parent package. Explanation (as far as I understand things) =========== Error messages of the form " in ignored" are generated when an exception occurs in an object's __del__() method. (In this case it would seem Python can't identify where the exception occurred which is why "" is blank, leaving the message " in ignored".) The actual message indicates there are issues with the order of object deletion with wxPython and global variables referring to wxPython/wxWindows objects. Other Resources =============== See also particularly these messages on the 'wxPython-users' mailing list: * "[wxPython-users] Errors when app is closed by logging out", * "[wxPython-users] weird bug with imports", Hope this saves someone some time. :-) From max at alcyone.com Thu Mar 27 19:52:17 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 27 Mar 2003 16:52:17 -0800 Subject: Beginner: How to copy a string? References: Message-ID: <3E839CC1.C84AF0BA@alcyone.com> dbrown2 at yahoo.com wrote: > Ok, so what's the trick. Please be kind. It's really not obvious to > me. In fairness I did see in the FAQ you could convert it to a list > and rejoin it which I assume would work, but I suspect there is a more > direct way. I think the real question here (in all seriousness) is: Why you think you need this? It's really an implementation detail whether an immutable object (a particular one, that is) can be copied to make a unique object with the same value. Since immutable objects cannot in any way be changed, it makes no difference whether or not two references have reference to the same immutable object, or have references to two unique immutable objects with the same value. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Who, my friend, can scale Heaven? \__/ _The Epic of Gilgamesh_ Alcyone Systems / http://www.alcyone.com/ Alcyone Systems, San Jose, California. From sludin at ludin.org Fri Mar 14 13:10:47 2003 From: sludin at ludin.org (Stephen Ludin) Date: 14 Mar 2003 10:10:47 -0800 Subject: Thread safety of the python API References: Message-ID: <412a1fa3.0303141010.588088e3@posting.google.com> Here's maybe a better example. Let's say I wanted to use the python dictobject directly in my code (vesus some other c hash table or an STL map) since implementation is robust and efficient, not to mention actively maintained. This would require the use of PyObjects, such as PyInt and PyString. To create the intobject, I call PyInt_FromLong. Let's also assume that I am not sharing objects between threads, just calling the API from multiple threads (e.g. creating intobject in multiple threads). Note that I am not embedding the interpreter, just using the API. >From what I am hearing, this is 'bad' and is not a valid use scenario for the API. It is not safe to have two threads simultaneously using the Python API. In order to make it safe, I need to get the GIL (or some other global mutex) before I call PyInt_FromLong, and then release it. Is this correct? Thanks for your responses, this is the information I needed. Stephen Tim Peters wrote in message news:... > [Stephen Ludin] > > I am developing an application that I may want to make scriptable with > > python. If I do so I'd like to use the convenience of the Python API > > in the rest of my application for containers and user defined method > > dispatch. I am concerned though about using the API in a > > multit-hreaded program. > > As you should be. As a not-too-close reading of the Python/C API manual > will reveal, almost all Python API functions require that the caller hold > the global interpreter lock: > > http://www.python.org/doc/current/api/threads.html > > The only exceptions are a handful of initialization and finalization > functions, explicitly identified on that page. Even the simplest API > operations can cause disaster if the lock isn't held -- you don't have to > search for subtleties, one unprotected Py_INCREF or Py_DECREF is enough to > hose you. > > Other than that, it's very robust . From user at domain.invalid Mon Mar 3 10:03:02 2003 From: user at domain.invalid (user at domain.invalid) Date: Mon, 03 Mar 2003 17:03:02 +0200 Subject: Looking for Free Visual Programming Library as User Interface References: <4y3cm4egej.fsf@faepsv01.tu-graz.ac.at> Message-ID: Try "Tkinter" From staschuk at telusplanet.net Sat Mar 22 15:54:23 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Sat, 22 Mar 2003 13:54:23 -0700 Subject: Is Python the Esperanto of programming languages? In-Reply-To: ; from aleax@aleax.it on Sat, Mar 22, 2003 at 09:37:36AM +0000 References: <7i65qe953z.fsf@enark.csis.hku.hk> <3oyea.61654$68.41484@nwrdny01.gnilink.net> Message-ID: <20030322135423.G421@tibia.amotlpaa.bogus> Quoth Alex Martelli: [... redundancy in natural language ...] > The key result: P(W) is far less affected by grammar than one > might think. Most of the redundancies we were able to detect > and exploit are in semantics, pragmatics, and the usage of > formulaic language, idioms, and the like. [...] Interesting! (And nice to see (reference to) some evidence on this point.) I may have to change my mind about grammatical redundancy. -- Steven Taschuk staschuk at telusplanet.net "What I find most baffling about that song is that it was not a hit." -- Tony Dylan Davis (CKUA) From bens at replytothegroupplease.com Thu Mar 20 08:33:22 2003 From: bens at replytothegroupplease.com (Ben S) Date: Thu, 20 Mar 2003 13:33:22 -0000 Subject: Question regarding a recent article on informit.com References: Message-ID: Cameron Laird wrote: > In article , > Alex Martelli wrote: >> From >> my POV the list comprehension is more elegant, more practical, >> simpler, more powerful, AND overall far more Pythonic than the >> jumble of map, lambda and filter you'd have to write in its place -- >> yet I was very strongly attracted to Python even before list >> comprehensions were >> added to it, so I can't claim this is the key of the attraction!-) > > ... and, let's repeat, list comprehension isn't anti-functional, > it's just a style of functional expression (or can be seen as > such) which happens to be more Pythonic. Ok, fair points; I probably just misunderstood what Boudewijn had meant in the first place - the 'functional programming style constructs' may be discouraged but the functional style will still be possible. Right? Are there any good tutorials of examples of list comprehension use? In particular, I'm interested in how to replicate the functionality of reduce? Map and filter seem easy to do, though. -- Ben Sizer http://pages.eidosnet.co.uk/kylotan From aleax at aleax.it Tue Mar 4 10:05:12 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 04 Mar 2003 16:05:12 +0100 Subject: Towards a more Pythonic "Ternary Operator" References: <882b0a41.0303020225.3caf0334@posting.google.com> Message-ID: Clark C. Evans wrote: > I was thinking, perhaps if people first agreed on the problem > finding a solution could become more of a detail. Here is a > stab at the 'terinary operator' problem. > > Consider the following two constructs, ignoring the syntax > details for a moment: > > if : > = # first assignment > else: > = # second assignment > > In this example, the first and second assignment have > a parallel structure; but the ' =' part happens > to be duplicated. This is somewhat inefficient for > two reasons: > > (a) someone reading the code has to scan the whole > structure and determine that there is a parallel > structure, where the variable is assigned a value > in either case of the condition; and > > (b) someone writing/editing the code has to make sure > that the variable is the same in both places or > else the parallel structure is broken. Good points -- basically similar to arguments for having such augmented-assignment operators as += in the language (avoiding = redundancy both in reading and writing the code). > Besides the left hand side of the assignment, there happens > to be another parallel structure which occurs often... > > if a == X: > b = Q > elif a == Y: > b = R > else: > b = S > > In this case, not only is 'b = ' duplicated three times, > but 'a ==' is duplicated twice. These two can be combined Hmmm, well, yes, but this is somewhat less convincing to me. > into the select/case pattern: > > b = select a: > case X: Q > case Y: R > else: S > > So, really, we have two categories of duplication: > > (a) the left hand side of the assignment > (b) the left hand side of the conditional Yes, but they're orthogonal -- i.e. the second case might just as well be: if a == X: c = Q elif a == Y: d = R else: e = S which only shows redundancy kind [b], not kind [a]. Why are we assuming the two redundancies go together? > Perhaps we can scratch two itches at the same time? The syntax > really doesn't matter now; what matters is that we agree on the > problem. Then we can throw up our best syntaxes and let Guido > choose and work his magic... I like this analysis, but I do not understand the reason to assume the two redundancy problems should occur together. Alex From staschuk at telusplanet.net Fri Mar 21 10:30:19 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Fri, 21 Mar 2003 08:30:19 -0700 Subject: How to create a CDATA XML node In-Reply-To: ; from martin@v.loewis.de on Fri, Mar 21, 2003 at 08:05:34AM +0100 References: Message-ID: <20030321083019.A4363@tibia.amotlpaa.bogus> Quoth Martin v. L?wis: > Steven Taschuk writes: > > > As far as I know, DOM has no notion of CDATA nodes; they are > > considered a low-level detail which does not properly belong in > > the model. > > That is not true. The DOM has (atleast in level 2) an interface > CDATASection, and an operation Document::createCDATASection. They are > extension interfaces, supported only if an implementation supports the > "xml" feature. Erk! Yes, even Level 1 has them. Disregard my previous, utterly false, post. I think I must have been thinking of SAX. -- Steven Taschuk staschuk at telusplanet.net "What I find most baffling about that song is that it was not a hit." -- Tony Dylan Davis (CKUA) From tjreedy at udel.edu Sat Mar 22 17:07:32 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 Mar 2003 17:07:32 -0500 Subject: Newbie question about reference References: Message-ID: "Tim Smith" wrote in message news:a5jp7v4n254bu0j4nnu16sevll3qeiaglp at 4ax.com... > Something that this beginner does not understand about Python. correct ;-) > Why does the following-- > > > python > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more > information. > >>> x = 1 > >>> y = 2 > >>> z = 3 > >>> list = [x, y, z] You here bind 'list' to the object [1,2,3]. (Note: DON'T use builtin names as vars unless you have a positive reason for so doing.) > >>> list > [1, 2, 3] > >>> y = 0 You here rebind the name 'y' to the value 0. Neither has nothing to do with 'list' > >>> list > [1, 2, 3[ > > do what it does? I expected the last "list" to return [1, 0, 3]. This is almost funny. More ofter, newbies do something like the following a = b= [0,1] a[0]=2 and then wonder why b[0] is 2 rather than 0. Terry J. Reedy From staschuk at telusplanet.net Wed Mar 19 22:40:49 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 19 Mar 2003 20:40:49 -0700 Subject: Combinations and recursion, from an ASPN snippet In-Reply-To: <180320032212546765%camel@oasis.com>; from camel@oasis.com on Tue, Mar 18, 2003 at 10:12:54PM -0500 References: <180320032212546765%camel@oasis.com> Message-ID: <20030319204049.C358@tibia.amotlpaa.bogus> Quoth dromedary: [...] > I'm still rather green with recursion. I understand it in principle, > but I'm not quite following what happens, say, here: > > printUniqueCombinations(alist[i+1:], numb-1, blist) > blist.pop() > > For example, when numb gets to 1, the > > if not numb: > > kicks in. But the recursive loop is still running (on its second > iteration?), so to me it looks as it the next printCombinations() call > gets fed a 0 for numb, making the numb -1 a negative 1. Is that what > finally breaks that loop and allows the next line, the blist.pop(), to > run? Wouldn't the function just accept a negative number? In fact there is no call to printUniqueCombinations with -1; numb never gets updated. To see this, first use these line numbers: 0 def printUniqueCombinations(alist, numb, blist=[]): 1 if not numb: 2 return printList(blist) 3 for i in range(len(alist)): 4 blist.append(alist[i]) 5 printUniqueCombinations(alist[i+1:], numb-1, blist) 6 blist.pop() Now, the call printUniqueCombinations(list('love'), 2) causes this sequence of events: (0) # called with alist = 'love', numb = 2, blist = [] (1) if not numb: # false; numb == 2 (3) for i in range(4): # iteration with i = 0 (4) blist.append('l') # blist is now ['l'] (5) printUniqueCombinations('ove', 1, blist) # recursion! (0) # called with alist = 'ove', numb = 1, blist = ['l'] (1) if not numb: # false; numb == 1 (3) for i in range(3): # iteration with i = 0 (4) blist.append('o') # blist is now ['l', 'o'] (5) printUniqueCombinations('ve', 0, blist) # recursion! (0) # called with alist = 've', numb = 0, blist = ['l','o'] (1) if not numb: # true! numb == 0 (2) return printList(blist) # prints 'lo' and returns (6) blist.pop() # blist is now ['l'] # iteration with i = 1 (4) blist.append('v') # blist is now ['l', 'v'] (5) printUniqueCombinations('e', 0, blist) # recursion! (0) # called with alist = 'e', numb = 0, blist = ['l','v'] (1) if not numb: # true! numb == 0 (2) return printList(blist) # prints 'lv' and returns (6) blist.pop() # blist is now ['l'] # iteration with i = 2 (4) blist.append('e') # blist is now ['l', 'e'] (5) printUniqueCombinations('', 0, blist) # recursion! (0) # called with alist = '', numb = 0, blist = ['l','e'] (1) if not numb: # true! numb == 0 (2) return printList(blist) # prints 'le' and returns ... and so forth. Not especially that the value of numb one level down in the recursion does not affect the value of numb in the current level. > (BTW, is the printCombinations() function above for combinations or > permutations? I'd have thought it was the latter.) Combinations. (But it does give each permutation of a combination unique status.) -- Steven Taschuk staschuk at telusplanet.net "Telekinesis would be worth patenting." -- James Gleick From woodsplitter at rocketmail.com Mon Mar 31 14:27:13 2003 From: woodsplitter at rocketmail.com (David Rushby) Date: 31 Mar 2003 11:27:13 -0800 Subject: [ANN] Python-Hosting.com: new Hosting Provider specialized in Python References: <3e885514$0$2719$626a54ce@news.free.fr> Message-ID: <7876a8ea.0303311127.56d89096@posting.google.com> "Remi Delon" wrote in message news:<3e885514$0$2719$626a54ce at news.free.fr>... > We are pleased to announce http://python-hosting.com, a new hosting provider > specialized in Python. > > Supported softwares include Zope, Plone, WebWare, CherryPy, SkunkWeb, > Twisted, Spyce, mod_python and others (in fact, pretty much everything you > want that runs on Python :-) Cool! By the way, when you refer to Firebird as an "embedded" database, do you really mean you're using it in embedded mode, or is it running as a persistent server? If the latter, is it SuperServer or Classic? From whisper at oz.net Fri Mar 21 18:45:17 2003 From: whisper at oz.net (David LeBlanc) Date: Fri, 21 Mar 2003 15:45:17 -0800 Subject: pylibpcap for Win32? In-Reply-To: <3E7B96FC.6040609@ghaering.de> Message-ID: link has "forbidden" access. David LeBlanc Seattle, WA USA > If you want pylibpcap on Windows a try, I've done a quick port: > > http://www.ghaering.de/python/unsupported/pylibpcap/ > > pylibpcap-0.4.win32-py2.2.exe 21-Mar-2003 23:41 41k > pylibpcap_win32.dif 21-Mar-2003 23:42 4k > > -- Gerhard From bachhx at mail.ru Tue Mar 4 08:04:13 2003 From: bachhx at mail.ru (Bach) Date: 4 Mar 2003 05:04:13 -0800 Subject: IME withTix on multilanguagesupported system ? References: <34e4328e.0303020911.7c7ed0c9@posting.google.com> Message-ID: <34e4328e.0303040504.59cec0bd@posting.google.com> "vincent wehren" wrote in message > Exactly my point. I don't know about 8.4, with in 8.3 there's no way I can > *input* German and Russian in the same widget by switching the keyboard > layout and have them both rendered correctly with the same underlying > codepage (pasting cyrillic alongside German is no problem). It sure seems > like Tk doesn't do anything with the WM_INPUTLANGCHANGE notification (yet). > > Regards > Vincent My problem like it.If you find exact answer,please post to me ! Regards Hoang X B From tjreedy at udel.edu Sat Mar 29 13:03:22 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 29 Mar 2003 13:03:22 -0500 Subject: List of given type References: Message-ID: "Zaur Shibzoukhov" wrote in message news:mailman.1048955145.6567.python-list at python.org... > I am thinking on solution of the following problem: > "Create and support a list so that all objects in list has a given type". You *might* find either the array module or (3rd party) numerical Python lib of interest also (if you have not checked them out already). TJR From hleblanc at bitstream.net Wed Mar 19 22:07:24 2003 From: hleblanc at bitstream.net (Harry LeBlanc) Date: Wed, 19 Mar 2003 21:07:24 -0600 Subject: ogg, UML, twisted vs. zope References: <3E6BE300.4090908@bitstream.net> Message-ID: <3E79306C.60400@bitstream.net> Didn't know Dia2code supported Python! I've got Dia already, too. Thanks! Alessio Pace wrote: > You can also usi DIA e and the plug in DIA2CODE which does some useful > (although not perfect) translation from UML to code (python, java, C++, > ...) > From andersjm at dancontrol.dk Tue Mar 4 12:15:59 2003 From: andersjm at dancontrol.dk (Anders J. Munch) Date: Tue, 4 Mar 2003 18:15:59 +0100 Subject: Vote on PEP 308: Ternary Operator References: <882b0a41.0303020225.3caf0334@posting.google.com> <2259b0e2.0303040823.f8c8974@posting.google.com> Message-ID: <3e64df15$0$16160$edfadb0f@dread11.news.tele.dk> "Michele Simionato" wrote: > This voting procedure forces me to write what I like the best > (even in the 'reject' case, I must check the last hated expression). > I have no way to express what I dislike the most. THE JUDEAN PEOPLE'S FRONT?! Seriously, it is much better to conduct a debate or vote in terms of what you like than in terms of what you dislike. The things you hate the most tend to be the things where you are the most in conflict with yourself; things that you might have almost liked, but for some reason chose not to. Decidedly bad things do not evoke such strong emotion. - Anders From hilbert at microsoft.com Tue Mar 11 01:11:57 2003 From: hilbert at microsoft.com (Hilbert) Date: Mon, 10 Mar 2003 22:11:57 -0800 Subject: sql binding Message-ID: Hello, How come python doesn't come with an sql library module? Is there a library module available for python2.2? Is there a supported secure way of storing databases that's not sql? Thanks, Hilbert From mgerrans at mindspring.com Fri Mar 14 12:57:22 2003 From: mgerrans at mindspring.com (Matt Gerrans) Date: Fri, 14 Mar 2003 09:57:22 -0800 Subject: dictionary with order? References: Message-ID: Do you just want shorthand for something like this: keys = dictionary.keys() keys.sort() zip( keys, [d[key] for key in keys] ) From maxm at mxm.dk Thu Mar 13 05:14:38 2003 From: maxm at mxm.dk (Max M) Date: Thu, 13 Mar 2003 11:14:38 +0100 Subject: IDLE, windows and non-us characters In-Reply-To: References: Message-ID: <4QYba.125563$Hl6.11184907@news010.worldonline.dk> Svenne Krap wrote: > Hi. > > I cannot enter non-us (i.e. the danish '?') characters in IDLE. Is > something set up wrongly ? I can strongly recomend pythonWin. The editor is somewhat better than idle, and does not have as many issues. Even though I have found that I get the least trouble at all using Ultraedit under windows. Which I have set up to execute the current pythn file when I press CTRL+SHIFT+0. The output then pops up in another editor window. -- hilsen/regards Max M Rasmussen, Denmark http://www.futureport.dk/ Fremtiden, videnskab, skeptiscisme og transhumanisme From nada at nowhere.xxx Wed Mar 26 14:35:37 2003 From: nada at nowhere.xxx (Lenard Lindstrom) Date: Wed, 26 Mar 2003 19:35:37 GMT Subject: type function does not subtype References: <3E7E81EF.1992BFD4@alcyone.com> Message-ID: "Lenard Lindstrom" wrote >... > Actually I was happy with your first suggestion. However in a previous > posting someone proposed having C like static variable declarations within a > function body. Beni Cherniavsky said this would complicate things since all > function bodies would then have to be checked for the special code ( > messages 11 and 12 of 'PEP 309 - Built-in closure type (with tentative > syntax proposal)' ). It seems to me __functionclass__ in the function body > would be the same way. Having __functionclass__ in the argumet list is fine > with me as well. And it doesn't require a syntax change. >... I forgot about doc strings. I guess I finally got used to them. :-) They get stripped from the function body. So putting '__functionclass__ =' right after a doc string should not cause too much difficulty. And why not permit a module level __functionclass__, like with __metaclass__, to keep everything consistant? Lenard Lindstrom "<%s@%s.%s>" % ("len-l.", "telus", "net") From maxm at mxm.dk Fri Mar 14 07:18:14 2003 From: maxm at mxm.dk (Max M) Date: Fri, 14 Mar 2003 13:18:14 +0100 Subject: Has anyone created a simple POP3 and SMTP server using TWISTED? In-Reply-To: <1047621015.523173@yasure> References: <0001HW.BA9660EB0012EC36F0407600@netnews.attbi.com> <1047595161mnewscandiazoo@attbi.com> <1047621015.523173@yasure> Message-ID: Donn Cave wrote: > Oh, right. Sendmail wouldn't work for sure, and it's a terrible > choice for a 3 person site anyway. Don't know about the other two, > but I'd guess very strong odds of some platform incompatibility that > would be the end for someone who only knows Python. A simplistic > SMTP and POP3 implementation isn't a huge undertaking, might be a > fun project. That was my sentiments exactly ... it sounds like a fun an educational process. -- hilsen/regards Max M Rasmussen, Denmark http://www.futureport.dk/ Fremtiden, videnskab, skeptiscisme og transhumanisme From vze4rx4y at verizon.net Sun Mar 2 00:01:03 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 02 Mar 2003 05:01:03 GMT Subject: Code speedup tips References: Message-ID: "Carl Banks" > Here is how I rewrote CA_Function. There are some details in it I've > left unexplained; feel free to ask for a clarification: > > > def CA_Function(Length,Steps): > # Create the two lattices > current = zeros((Length,Length),Int) > workspace = zeros((Length-2,Length-2),Int) > > # Create slices of the current lattice > # We don't have to do this every step because slicing shares memory > left = current[0:-2,1:-1] > up = current[1:-1,0:-2] > right = current[2:,1:-1] > down = current[1:-1,2:] > > # Set the start cell to black > current[Length/2,Length/2] = 1 > > # Apply the rule > for step in xrange(Steps): > # In the workspace, add the shifted lattices > # This uses a bunch of += because it's faster > workspace[:] = left > workspace[:] += up > workspace[:] += right > workspace[:] += down > # Set the current lattice > current[1:-1,1:-1] = where(workspace,1,0) Nice job. From aahz at pythoncraft.com Thu Mar 6 10:16:14 2003 From: aahz at pythoncraft.com (Aahz) Date: 6 Mar 2003 10:16:14 -0500 Subject: OT: polyamory (was Re: [OT] Re: Python training time) References: Message-ID: In article , Tim Peters wrote: >[Aahz] >> >> Yup. For some reason, overall alt.poly is even better than c.l.py at >> resisting trolls and flamefests. Besides, at this point I wouldn't be >> surprised if there were more poly people than Pythonistas, although I'm >> working to change that. ;-) > >Editorial note: Guido does not officially support the attempted >extermination of any group just to increase the number of Pythonistas >relative to that group. Or perhaps it's just the death of humans he objects >to? Whichever, I get in trouble whenever I try it, so don't. Naw, I'm just trying to convert the poly Perl/Java lovers to Python. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Register for PyCon now! http://www.python.org/pycon/reg.html From martin at v.loewis.de Mon Mar 3 03:25:37 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 03 Mar 2003 09:25:37 +0100 Subject: Doe the language have an standard? In-Reply-To: <271b0abf.0303030019.d57d466@posting.google.com> References: <271b0abf.0303030019.d57d466@posting.google.com> Message-ID: <3E631181.6010708@v.loewis.de> Nishant wrote: > Doe the Python have an standard? No, there is no international standard specifying the Python language. The closest to a formal standard is the language reference, which is updated every release. Regards, Martin From abli at freemail.hu Wed Mar 12 14:00:44 2003 From: abli at freemail.hu (Abel Daniel) Date: Wed, 12 Mar 2003 20:00:44 +0100 Subject: passing **kwargs to a function In-Reply-To: References: Message-ID: <20030312190044.GA1496@hooloovoo> Bob Roberts (bobnotbob at byu.edu) wrote: > Observe the folling code: > def a(*args, **kwargs): > print args,kwargs > b(kwargs) b(**kwargs) is what you want here > > def b(*args, **kwargs): > print args,kwargs > > a(a=1,b=2 > > And it's output: > > () {'a': 1, 'b': 2} > ({'a': 1, 'b': 2},) {} > > I am trying to pass int b() the exact same keyword arguments that were > passed into it. As you can see, it does't arrive in ths same way. I > want the kwargs variable inside a() and b() to be exactly the same. > How do I do that? -- Abel Daniel From syver-en+usenet at online.no Thu Mar 20 13:50:51 2003 From: syver-en+usenet at online.no (Syver Enstad) Date: 20 Mar 2003 19:50:51 +0100 Subject: open() in binary vs. text mode References: Message-ID: bobnotbob at byu.edu (Bob Roberts) writes: > I just finished tracking down a cross-platorm bug. The problem was > that I didn't open() a file in binary ("rb") mode. What exactly does > the binary flag do on windows? What is it's purpose? On windows text files are written with \r\n (carriage return and linefeed) as the end of line marker. On Macintosh \r is the end of line marker, and on *nix systems just \n is the end of line marker. When opening a file in 'r' mode under windows the library translates all the \r\n in your file into \n. When you write to a file with 'w' under windows, library translates all \n your data to \r\n in the file. To avoid this auto translation, you can specify b ('rb' or 'wb') to indicate that the file library should not translate (useful for binary files, therefore called binary or mode). Hope this clears up things. -- Vennlig hilsen Syver Enstad From bh at intevation.de Tue Mar 4 09:01:01 2003 From: bh at intevation.de (Bernhard Herzog) Date: 04 Mar 2003 15:01:01 +0100 Subject: Memory leak References: <2830c89c.0303040407.ed8457e@posting.google.com> Message-ID: <6qheajgrj6.fsf@salmakis.intevation.de> andrew.gregory at npl.co.uk (Andrew Gregory) writes: > I keep being troubled by memory leaks when using C/C++ extensions (I > have Python 2.2.2 on Windows). The problem is most acute in > mathematical code, in which a C routine in an extension is called > repeatedly in a loop. So I wrote a simple test program: > > // test.h > typedef PyObject* RESULTOBJ; > > // Hand-coded wrapper for returning string > RESULTOBJ wrap_string(char *s) > { > RESULTOBJ result; > result = PyString_FromString(s); > return Py_BuildValue("O",result); > }; Here's your memory leak. The "O" code will incref the argument. Use either "N" or simply return result. In the latter case you might as well get rid of wrap_string and use PyString_FromString directly. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From benoit.besse at club-internet.fr Tue Mar 11 16:38:18 2003 From: benoit.besse at club-internet.fr (Benoit BESSE) Date: Tue, 11 Mar 2003 22:38:18 +0100 Subject: Convert a C pgm Message-ID: <3e6e5746$0$14733$7a628cd7@news.club-internet.fr> Hello, who is able to convert this C program into a Python script or mudule Thanks -------------------------------------------------------------------------------- file sdplex.h -------------------------------------------------------------------------------- #ifndef _SDPLEX__H #define _SDPLEX__H #include #include #include /* pour inet_addr inet_ntoa gethostbyaddr */ #include /* pour inet_addr inet_ntoa gethostbyaddr */ #include /* pour inet_addr inet_ntoa gethostbyaddr */ #include /* pour inet_addr inet_ntoa gethostbyaddr */ #include /* pour gethostbyaddr */ #include #include /* pour la date */ #include /* pour min, max */ #include /* pour chdir */ #include /* for mutex library */ #include "config.h" #include "record-session.h" #include "update-sessions.h" #define ANNOUNCE 0 #define DELETION 1 void analyseSAP (char *buf, int length, struct in_addr from); void analyseSDP (char *buf, int length, struct in_addr from); void deleteSDP (char *buf, int length, struct in_addr from); int checkSignature (char*authHeader, int length); // int verifyGrammar (char buf[2048], int length); int verifyField(int *i, int *j, int globalRepeat, char *CurrentField, char fields[10], char optional[10], char repeat[10]); int verifyFieldIgnoreOrder(int *i, int *j, int GlobalRepeat, char *CurrentLine, char fields[10], char compulsory[10], char repeat[10]); char *extractLine (char *buf, int maxlength, char *field); char *nextField (char *buf, int maxlength, char *field, char NameOfField); void fnextField (FILE *file, int maxlength, char *field, char NameOfField); void saveSession (Session *session); void addSessionToList(char *buf, int length, char *ID); void addSessionToCache(char *buf, int length, char *ID); /* fin des declarations */ #endif /* _SDPLEX__H */ -------------------------------------------------------------------------------- file sdplex.c -------------------------------------------------------------------------------- #include "sdplex.h" void analyseSAP(char *buf, int length, struct in_addr from) { unsigned long addr_src; int header_length, datagram_type; printf("Analyse du paquet recu :\n\n"); printf("Version de SAP : %d\n", ((buf[0] >> 5) & 0x7)); /* bits 5 a 7 */ printf("Type de message : "); switch ((buf[0] >> 2) & 0x7) /* bits 2 a 4 */ { case 0 : printf("annonce de session\n"); datagram_type = ANNOUNCE; break; case 1 : printf("annulation de session\n"); datagram_type = DELETION; break; default : perror("type de paquet SAP inconnu"); exit (0); } if (buf[0] & 0x2) printf("annonce chiffree\n"); /* bit 1 */ else printf ("annonce en clair\n"); if (buf[0] & 0x1) printf("annonce gzipee\n"); /* bit 0 */ else printf("annonce non gzipee\n"); printf("version de l'annonce: "); if (buf[3]) printf("%d\n", buf[3]); else printf ("ignoree\n"); addr_src = *((unsigned long*) &buf[4]); printf("annonce envoyee depuis l'hote %s d'apres le paquet SAP\n", inet_ntoa(*((struct in_addr*) &addr_src))); printf("annonce envoyee depuis l'hote %s en realite\n", inet_ntoa(from)); printf ("taille des donnees d'authentification %hu x 32 bits\n", buf[2]); printf("\n"); if (buf[2]) if (checkSignature(&buf[4], buf[2])==0) { perror("authentification failure"); return; } header_length = ((int) buf[2])*4+8; if (datagram_type == ANNOUNCE) analyseSDP(&buf[header_length], length-header_length, from); else if (datagram_type == DELETION) deleteSDP(&buf[header_length], length-header_length, from); } int checkSignature(char*authHeader, int length) { /* je ne sais pas encore faire */ return 0; } void analyseSDP(char *buf, int length, struct in_addr from) { // FILE *f; // char FileName[256], SessionOwner[256], CurrentField[256]; char bufCopy[2049]; Session *session; SessionInfo *info; /* trouver un nom au fichier du cache */ /* ce nom doit etre de preference une clef d'identification de la session */ /* donc se baser sur le champ SDP o= */ strncpy(bufCopy, buf, 2048); bufCopy[length]=0; session = verifyGrammar(bufCopy, length); printf("Session address in memory : %d\n", (int) session); if (session) { if ( (info = whereIs(session))!=NULL) delSessionInfo(info); mutex_lock(&lock); info = addSessionInfo(session); mutex_unlock(&lock); if (info) { saveSession(session); createMediaFile(session); } else printf("Session obsolete\n"); dealloc(session); } } void saveSession(Session *session) { FILE *f; int i; chdir(BASE_DIRECTORY); chdir(CACHE_DIRECTORY); printf ("Creating cache file %s.\n", session->cachename); if ((f=fopen(session->cachename, "w")) == NULL) { perror ("fopen (write)"); return; } for(i=0; ibuflen; i++) if (session->buf[i]=='\0') fputc('\n', f); else fputc(session->buf[i], f); fclose(f); printf ("Cache file %s created.\n", session->cachename); } char *extractLine(char *buf, int maxlength, char *field) { /* extrait une ligne (field) d'une chaine de caractere (buf) * qui en contient plusieurs. Une ligne se termine avec un \n * field contient la chaine extraite et la fonction retourne * le pointeur sur le \n final. Pour eviter le debordement * de la chaine field, on ne depasse pas la taille maxlength */ char* index; int sizeOfLine; index=strstr(buf,"\n"); sizeOfLine = min ( (int)(index - buf), maxlength - 1 ); strncpy(field, buf, sizeOfLine); field[sizeOfLine]='\0'; return index; } char *nextField (char *buf, int maxlength, char *field, char NameOfField) { char tag[4]="\n ="; if (NameOfField=='\0') return extractLine(buf, maxlength, field); else { tag[1]=NameOfField; return extractLine(strstr(buf, tag)+3, 256, field); } } void fnextField (FILE *file, int maxlength, char *field, char NameOfField) { char CurrentField[256]; char *state; while ( ((state=fgets(CurrentField, maxlength, file))!=NULL) && (CurrentField[0]!=NameOfField)); if (state) strncpy(field, CurrentField+3, 256); else field[0]='\0'; } void deleteSDP (char *buf, int length, struct in_addr from) { printf("Explicit session deletion requested\n"); return; } int verifyField(int *i, int *j, int GlobalRepeat, char *CurrentLine, char fields[10], char compulsory[10], char repeat[10]) { if (CurrentLine[1]!='=') return 0; if (CurrentLine[0]==fields[*i]) { /* note: only optional fields may be multiple defined */ if(repeat[*i]=='0') { (*i)++; if (fields[*i]=='\0') { *i=0; /* if several descriptions of that group may exist and * a new description of that type is detected, then do not * increment j */ if ((GlobalRepeat==1) && (CurrentLine[0]==fields[0])); else (*j)++; } } return 1; } while (CurrentLine[0]!=fields[*i]) { if (compulsory[*i]=='1') return 0; else { (*i)++; if (fields[*i]=='\0') { *i=0; /* if the group of fields may not be repeated, then go * to next group of fields */ if (GlobalRepeat==0) { (*j)++; return -1; } } } } return 1; } int verifyFieldIgnoreOrder(int *i, int *j, int GlobalRepeat, char *CurrentLine, char fields[10], char compulsory[10], char repeat[10]) { char *matchingChar; if ((matchingChar=strchr(fields, CurrentLine[0]))!=NULL) { /* character marked as already matched, though cannot be defined several times */ if (*matchingChar=='.') return 0; if(repeat[*i]=='0') /* mark that an unrepeatable field matched */ fields[*i]='.'; return 1; } else { (*j)++; return -1; } } void addSessionToCache(char *buf, int length, char *ID) { FILE *cacheFile; chdir(BASE_DIRECTORY); chdir(CACHE_DIRECTORY); printf("Writing cache file %s in %s/%s\n", ID, BASE_DIRECTORY, CACHE_DIRECTORY); if ((cacheFile = fopen(ID, "w"))==NULL) { perror("fopen"); return; } fwrite(buf, 1, length, cacheFile); fclose(cacheFile); } -------------- next part -------------- An HTML attachment was scrubbed... URL: From jack at performancedrivers.com Fri Mar 14 13:10:06 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 14 Mar 2003 13:10:06 -0500 Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... In-Reply-To: ; from intentionally@blank.co.uk on Fri, Mar 14, 2003 at 04:30:31PM +0000 References: <0bkv6v8akrd0db5i66eu685t5pmviuf0bk@4ax.com> <4fm07vg66gr4o4c74gb7ie5v85vlom1vhf@4ax.com> <0vv17v4vn4khffgr2io0otrnni8sc6rug7@4ax.com> <%dica.80722$zo2.2065641@news2.tin.it> Message-ID: <20030314131006.S996@localhost.localdomain> As the butterfly that flapped its wings a week ago causing an ensuing shift storm, I hereby declare the thread over. I use this .emacs bit which was posted about a year ago in this thread. I still type 'lambda' but it is displayed in context as newlist = map(L x: x.a + x.b, oldlist) # vs the standard newlist = map(lambda x: x.a + x.b, oldlist) The L snuggles up to the opening paren. Plus it isn't a real word so you can see it without having to 'read' it. All in all, a much quicker and more low maintenance solution than a custom Grammar [pun very much intended]. -jackdied ;;Stefan Monnier's hack to make "lambda" display as (a greek lambda symbol) ;; EDIT - I use it to display 'L' instead (defun pretty-lambdas () (font-lock-add-keywords nil `(("\\" (0 (progn (compose-region (match-beginning 0) (match-end 0) ,'"L") nil)))))) (add-hook 'emacs-lisp-mode-hook 'pretty-lambdas) (add-hook 'python-mode-hook 'pretty-lambdas) (add-hook 'ilisp-mode-hook 'pretty-lambdas) From johnfabel at btinternet.com Sun Mar 23 12:37:10 2003 From: johnfabel at btinternet.com (John Abel) Date: Sun, 23 Mar 2003 17:37:10 +0000 Subject: How to install a size-package? In-Reply-To: <3E7DA110.9050101@web.de> References: <3E7DA110.9050101@web.de> Message-ID: <3E7DF0C6.9060407@btinternet.com> Have a look at Distutils. It will do everything that you're looking for. The python documentation has a complete section dedicated for it. HTH John Ingo Linkweiler wrote: > Hello, > > I want to install my software as python site-package. > I have tested it this way: > - created a directory "mymod" in the "site-packages" > - copied my software (submod1.py ... submodn.py) in this directory > - renamed the main module to "__init__.py" > > This is working, but now I want to write a "setup.py", which will do > this for the user. > > I have looked at "site.py", but still do not know what to do. > > Ingo > From aleax at aleax.it Mon Mar 24 07:34:09 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 24 Mar 2003 12:34:09 GMT Subject: a regular expression question References: <577e43a1.0303212331.5eaf93e5@posting.google.com> <577e43a1.0303221649.40498141@posting.google.com> Message-ID: <5XCfa.1218$i26.23245@news2.tin.it> Roy Smith wrote: > Alex Martelli wrote: >> Oh yes -- I find myself using RE's about 100 times less than I was >> using them back when I programmed in Perl, thanks on one side to the >> useful built-in methods of string objects, on the other to higher >> level library modules and extensions. > > I suspect there's one other reason, and that's because RE's are easier > to use in Perl than they are in Python. The toolset drives how you use Having extensively used both Perl (in the past) and Python (in the last few years), I strongly disagree. In particular, one of my relatively early experiences with Python was a "mass porting" of tons of Perl scripts that I had authored and accumulated over the years -- I was sick and tired of maintaining them, and porting everything to the "new toy" Python seemed a good learning experience as well as a way of "getting closure" with Perl once and for all so I could then, at long last, start forgetting it. I did a somewhat literal transliteration, at first, because my grasp of Python was not yet perfect AND because my main focus was to make sure everything worked in the new version so I could cashier the old one. Transliterating RE usage, in particular, was never a problem (as soon as I understood that what i needed was almost invariably the "search" method rather than the "match" one, that is;-). One thing that WAS occasionally problematic was assign-and-test (and http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66061 is how I worked around THAT one -- you'll see some other "traces" of my migration in other Cookbook recipes, too;-), btw. > Perl is a disaster as a general purpose programming language, but the > one place it shines is the job it was designed for, and that's doing > pattern matching on text. It shines at this, yes, but not any brighter than Python does, IMNSHO. Alex From abelikov72 at hotmail.com Thu Mar 13 11:25:45 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Thu, 13 Mar 2003 16:25:45 GMT Subject: os.path.walk arg Message-ID: What is the purpose of arg in os.path.walk(path, visit, arg) ? The documentation states : Calls the function visit with arguments (arg, dirname, names) for each directory in the directory tree rooted at path (including path itself, if it is a directory). The argument dirname specifies the visited directory, the argument names lists the files in the directory (gotten from os.listdir(dirname)). The visit function may modify names to influence the set of directories visited below dirname, e.g., to avoid visiting certain parts of the tree. (The object referred to by names must be modified in place, using del or slice assignment.) I assume I can pass arguments to my visitor function, so I specify None. Upon doing so I wonder why that would not be a default and am reminded of the magic of specifying so many NULL's in Win32 API calls from C. From rballard_99 at yahoo.com Tue Mar 4 12:24:09 2003 From: rballard_99 at yahoo.com (Bob Ballard) Date: Tue, 4 Mar 2003 11:24:09 -0600 Subject: Curses, PC and Python Message-ID: I've googled until I'm googled out. Is there a curses lib for NT that I can drive with Python? Bob From mwh at python.net Mon Mar 31 08:22:57 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 31 Mar 2003 13:22:57 GMT Subject: weird float() behavior References: Message-ID: <7h3wuifllfy.fsf@pc150.maths.bris.ac.uk> pball at umich.edu (pball) writes: [snip screwiness] > ok, it seems pretty likely that it's the gentoo python 2.2.2 with the > bleeding-edge gcc 3.2.2. I found that float was triggering it, but > actually, int() is just very sick: > > > [pball at wylbur]% python > ~ > Python 2.2.2 (#1, Mar 29 2003, 23:20:21) > [GCC 3.2.2 20030322 (Gentoo Linux 1.4 3.2.2-r2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> s = '3.1415' > >>> int( float(s) ) -610 > >>> int( 3.1416 ) 0 > >>> int( 3.1415 ) -610 > >>> int( 3.1417 ) 0 > >>> int( 3.1419 ) > Traceback (most recent call last): > File "", line 1, in ? > OverflowError: float too large to convert > >>> > > Ok, that's enough. Has anyone else seen this? Any ideas how I broke > it so completely? Is there more info I can post to better identify it? > Is there a regression test we could add to the post-compile process to > flag this? There is an extensive test suite already; I'd be amazed if a Python so obviously broken passed it. Cheers, M. -- In that case I suggest that to get the correct image you look at the screen from inside the monitor whilst standing on your head. -- James Bonfield, http://www.ioccc.org/2000/rince.hint From aleax at aleax.it Fri Mar 14 05:33:31 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Mar 2003 10:33:31 GMT Subject: PEP 312 - Making lambdas implicit worries me, surely it's just the name 'lambda' that is bad... References: <3E629E93.B94F7631@alcyone.com> <0bkv6v8akrd0db5i66eu685t5pmviuf0bk@4ax.com> <4fm07vg66gr4o4c74gb7ie5v85vlom1vhf@4ax.com> <0vv17v4vn4khffgr2io0otrnni8sc6rug7@4ax.com> Message-ID: <%dica.80722$zo2.2065641@news2.tin.it> Stephen Horne wrote: ... >>>>> starts a line". Other frequently used words (such as built-in function >>>>> names) also never start a line - 'reduce' is as long as 'lambda' for a ... >>So, the assertion that built-in function names never start a line >>is incorrect. > > I never made that assertion, though on further examination I see why > you thought I did. Ah, yes -- I do see a parenthesis of "Other s (such as s)" as meaning "all s are s" without needing a redundant "all" after the word "as" (just as "all s are s" does not need the pleonasm of the reinforcing "all" -- it means the same thing without it). So, I believe you simply mis-spoke, and are now trying to hedge by claiming some ambiguity (needing to be resolved by context) for a phrasal form that I believe has no such ambiguity. Feel free to keep tilting at this particular windmill -- I'll no doubt remain convinced of my thesis, and you, of yours. As for the meta-thesis -- if I make an unambiguous assertion, I can get quite angry when people try to distort it into something else by claiming that "context" justifies their attempt to make me say something different than what I _DID_ say. When my assertion is ambiguous the responsibility for possibly mis-interpreting it is often shared, but not ALL assertions are inevitably ambiguous -- and when an assertion IS non-ambiguous, it stands or falls on its own; trying to weasel it into meaning something quite different by invoking "context" is a game that's no doubt of huge interest to lawyers and literary critics, but of no interest to me as an engineer. In particular, when I say something unambiguously wrong (by badly chosen wording, OR because I did not know the true state of things, makes no difference) I prefer to admit it and apologize for it, rather than attacking those who correct me and/or climbing over mirrors of "context" to avoid admitting I was wrong. Personal tastes, I guess. > need to clarify "some" built-in functions. Hence, when you 'corrected' > me, implying that I didn't know this common sense thing, I felt > insulted and - in my already bad mood - I overreacted. > > Once again, I am sorry for that. No problem, except that the implication you're reading is also quite unwarranted -- somebody may know something perfectly well but still err in expressing it. Thus, correcting a wrong expression carries no necessary implication that the utterer of said expression did not know the true state of affairs, any more than it carries any necessary implication that the utterer was deliberately lying -- in the general case, both are possible, but mis-expression is also quite possible. > Now I think about it, most built-in functions probably return a value They all do, but that value can of course be None. > (I can't be bothered checking, but most of the ones I can think of off > the top of my head do anyway). While some of those may still be used > (or abused) for their side effects, a person might reasonably consider > that functions that can appear at the start of a line are exceptional. There are 43 built-in names of type builtin_function_or_method (in Python 2.3 just built from CVS). Of those, I'd say apply, delattr, execfile, intern, raw_input, reload and setattr are typically or at least quite frequently called without caring about their return values (one could quibble both ways, e.g. adding map or removing intern, but, roughly) -- whether 7 out of 43 qualifies as "exceptional" is quite dependent on what meaning one attaches to that adjective, of course, but to me it seems to qualify as a substantial minority, even without considering the common try/except idioms (e.g., hash(x) in a try clause to check if x is hashable without caring about its hash value). Once again, the _relevance_ of this to anything whatsoever appears to be totally mysterious to me. If MOST built-in functions very rarely make sense at the start of a logical line, then the "context" you were earlier claiming as the justification for (what I do still consider) your mis-statement is very weak indeed -- and so much more important was it then for me to correct that mis-statement, according to your own interpretations as previously presented. Alex From hust_zxq524 at 263.net Mon Mar 17 02:07:52 2003 From: hust_zxq524 at 263.net (Frank Zheng) Date: Mon, 17 Mar 2003 15:07:52 +0800 Subject: a question about map object Message-ID: Hi, all i have a map object: DataMap = {'Index': (14,1,ord), 'name': (16,22,stripnulls), 'group': (39,1,ord), 'email1': (41,48,stripnulls), 'email2': (90,48,stripnulls), 'email3': (139,48,stripnulls), 'URL:' : (187,48,stripnulls), 'ringtone': (237,1,ord), 'msgtone': (238,1,ord), 'memo': (240,32,stripnulls), 'phonetypes' : (274,5,stripnulls), 'phone1:': (279,48,stripnulls), 'phone2:': (328,48,stripnulls), 'phone3:': (377,48,stripnulls), 'phone4:': (426,48,stripnulls), 'phone5:': (475,48,stripnulls) } then,i want to list all the keys: >>> for k, v in DataMap.items(): ... print k ... Index group name phone5: msgtone memo phone4: phonetypes ringtone phone3: phone2: phone1: email1 email2 email3 URL: >>> u will find the orders of keys have been changed i think the map is a ordered-sequences, but what should i do can keep its order be same with input order thanks Frank From achrist at easystreet.com Sat Mar 15 20:01:56 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Sat, 15 Mar 2003 17:01:56 -0800 Subject: [Q] Databases -- Gadfly vs Metakit vs SQLite References: <3E737FA3.51AB478E@easystreet.com> <6e07b825.0303151612.4d377690@posting.google.com> Message-ID: <3E73CD04.9AFA6F94@easystreet.com> "yaipa h." wrote: > > If you are not worried about cross platform, then why not > use the Jet (access) DB. Yes, that's part of Windows, so it's almost safe to assume that it's there, and you can get to it through com. However, I don't want to worry one bit about what version is there or if MS will put in changes in subsequent releases that will break my application. And I'd rather embed the database so that I don't have to worry about the user changing it with an MS desktop app to violate my rules of relational integrity and crash my app. Al From shagshag13 at yahoo.fr Fri Mar 14 05:26:36 2003 From: shagshag13 at yahoo.fr (Shagshag) Date: 14 Mar 2003 02:26:36 -0800 Subject: is there a nmore pythonic way ? References: <3e6dbc5e$0$2688$626a54ce@news.free.fr> <3ac67cce.0303111100.7c5a8755@posting.google.com> Message-ID: <409a56e2.0303140226.620f4c5c@posting.google.com> really thanks to all, i didn't get that my first statements were broken... but my question was more about : exec("from %s import %s" % (im, func)) and i wondered if there were better ways to do it and which was best (using __import__ maybe ?) thanks, s13. From i.linkweiler at web.de Sun Mar 23 06:57:04 2003 From: i.linkweiler at web.de (Ingo Linkweiler) Date: Sun, 23 Mar 2003 12:57:04 +0100 Subject: How to install a size-package? Message-ID: <3E7DA110.9050101@web.de> Hello, I want to install my software as python site-package. I have tested it this way: - created a directory "mymod" in the "site-packages" - copied my software (submod1.py ... submodn.py) in this directory - renamed the main module to "__init__.py" This is working, but now I want to write a "setup.py", which will do this for the user. I have looked at "site.py", but still do not know what to do. Ingo From donn at drizzle.com Sat Mar 22 19:38:54 2003 From: donn at drizzle.com (Donn Cave) Date: Sun, 23 Mar 2003 00:38:54 -0000 Subject: Incomparable abominations (was: python-dev Summary) References: None Message-ID: <1048379933.586672@yasure> Quoth "Tim Peters" : | I think it's approximately impossible to explain why | | 1 + "2" | | raises an exception now, but | | 1 < "2" | | doesn't. In the earliest Pythons, for obscure technical reasons it wasn't | *possible* for a comparison operation to raise an exception, and I expect | the current inconsistency was driven at least as much by that technical | glitch as by deliberate choice. What about 1 == "2" , should it also be cause for an exception? Sorry if I missed the earlier posts in this thread that would explain how == differs from < in this application. Donn Cave, donn at drizzle.com From warrenpstma at _______.com.hotmail Tue Mar 4 12:01:33 2003 From: warrenpstma at _______.com.hotmail (WP) Date: Tue, 04 Mar 2003 12:01:33 -0500 Subject: Code to recognize MS-Word document files? In-Reply-To: <3e64d3c3$0$52915$a1866201@newsreader.visi.com> References: <3e64d3c3$0$52915$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: > I'm looking for a snippet of python that I can use to determine > if a file is a MS-Word document. People around here seem to > have gotten into the habit of attaching MS-Word files without a > ".doc" on the name. > > Even with the .doc, the mimetypes module doesn't seem to get it > right. :( > Extremely Bogus Hack: (probably no help, sorry!) f=open(wordfilename,'rb') str1=f.read(10) # arbitrary # of bytes for i in str1: hex = hex + ( '%02x ' % Ord(i) ) if hex='d0 cf 11 e0 a1 b1 1a e1 00 00 ': print 'match' // My word files all seem to start like this // (MS Office 2000 WORD iles) // d0 cf 11 e0 a1 b1 1a e1 00 00 00 00 00 00 // 00 00 00 00 00 00 00 00 00 00 // Your mileage may vary. Warren -- -------------------------------------- warren.postma at adaptivenetworks.on.ca Toronto Ontario Canada From anamax at earthlink.net Fri Mar 14 15:43:42 2003 From: anamax at earthlink.net (Andy Freeman) Date: 14 Mar 2003 12:43:42 -0800 Subject: OT: Programmers whos first language is not English References: <74ij6vcebl67dto60dun42hd625qrkmcv7@4ax.com> <7noo6v030lm362rlajodpkvgfhm5ksogd8@4ax.com> Message-ID: <8bbd9ac3.0303141243.657650ac@posting.google.com> Stephen Horne wrote in message news:... > As for the parsing being trivial - it's not exactly rocket science in > either case, though I admit that LISP-style expressions barely need > more than tokenising and parenthesis matching. But even trivial > scanners and parsers are, well, sufficiently non-trivial that writing > one when theres one already written and available to use seems a bit > masochistic. You're looking at the wrong problem. I've found that the time/energy/etc saved by folks who omit "unnecessary" grouping elements (parentheses, curly brackets, etc.) is dwarfed by the time spent fixing problems due to omitting said "unnecessary" elements. If there were only binary operators and there were only three of them and there was a very tight limit on the expression complexity, then, and only then, would precedence make sense for code written/read by humans. It took me a while to figure that out, but it sure would be nice if language designers learned that parsers capabilities far exceed programmer abilities, and that the latter is a more important constraint. It would be okay to omit "unnecessary" parens in a hidden representation, but the display and authored representation should have them. > Parenthesis matching (especially with all parenthesised expressions > using the same pair of symbols) is a much weaker check. Umm, who said that a lisp-aware editor can only do paren matching? Even in the 70s, they knew the structure of special forms. (Paren matching IS sufficient for lisp expressions.) This shouldn't be a surprise - other language-aware editors knew about keywords by the 80s. (They'd auto-insert "then", "do", "end", etc as appropriate.) -andy From glc at well.com Thu Mar 6 09:52:00 2003 From: glc at well.com (Greg Chapman) Date: Thu, 06 Mar 2003 14:52:00 GMT Subject: Can __iter__ be used as a classmethod? References: <3e649aa3_4@news.bluewin.ch> <2259b0e2.0303041023.43e8b81f@posting.google.com> <4B89a.6715$zo2.218162@news2.tin.it> <3e65273f$1_3@news.bluewin.ch> Message-ID: <90oe6vccthidi7h443od1ndrls8h5oakr5@4ax.com> On Tue, 4 Mar 2003 23:21:16 +0100, "Samuele Pedroni" wrote: >It is worth to notice that once you override one of them (like g in D >overriding g in C) it is impossible to call in a clean way the parent >version (C g) passing the derived class (D), which is what would happen in >case of no overriding (if D would not define g, then D.g() would call g in C >passing D), (so above C.g() obviously is calling g in C passing C). "Let's >call this their price". > This works for me with 2.22 and 2.3a2: class C(object): def g(cls): print 'C', cls g = classmethod(g) class D(C): def g(cls): print 'D', cls super(D, cls).g() g = classmethod(g) Both D.g() and D().g() print: D C Am I missing some subtlety here? --- Greg Chapman From b.maryniuk at forbis.lt Tue Mar 4 13:11:37 2003 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 4 Mar 2003 20:11:37 +0200 Subject: what exactly is "None" ? In-Reply-To: References: Message-ID: <200303042011.37675.b.maryniuk@forbis.lt> On Tuesday 04 March 2003 17:37, Andrei Doicin wrote: > I know that "None" is the Boolean false value Not exactly. Think it like undef in Perl. -- Regards, Bogdan Experience varies directly with equipment ruined. From mf at mrinfo.de Thu Mar 27 10:05:42 2003 From: mf at mrinfo.de (Marko Faldix) Date: Thu, 27 Mar 2003 16:05:42 +0100 Subject: alternative manuals Message-ID: Hi there, I would like to ask if someone uses other functions and library references then these at www.python.org. Maybe web references, maybe real books. thx Marko Faldix From antifod at yahoo.com Tue Mar 4 15:59:38 2003 From: antifod at yahoo.com (antifod at yahoo.com) Date: 4 Mar 2003 12:59:38 -0800 Subject: can not run a TCL demo python script. Message-ID: <242ac56c.0303041259.7ac29db5@posting.google.com> Hello, I am working on a Win NT machine. I have installed Python in C:/Python and TCL in C:/Program Files/Tcl. The problem is that I can't run the demo python script C:\Program Files\Tcl\demos\Tktable\tktable.py from Python. The script exits with an error message in the following sequence of statements :---------- try: master.tk.call('package', 'require', 'Tktable') except Tkinter.TclError: master.tk.call('load', '', 'Tktable') The error that it throws is :---------- File "C:\Program Files\Tcl\demos\Tktable\tktable.py", line 68, in __init__ master.tk.call('load', '', 'Tktable') TclError: package "Tktable" isn't loaded statically :---------- I tried the following variant of the above code\ :--------------- master.tk.call('package', 'require', 'Tktable') ## except Tkinter.TclError: ## master.tk.call('load', '', 'Tktable') Tkinter.Widget.__init__(self, master, 'table', cnf, kw) :---------------- .. and it threw the following error :-------- File "C:\Program Files\Tcl\demos\Tktable\tktable.py", line 66, in __init__ master.tk.call('package', 'require', 'Tktable') TclError: can't find package Tktable :-------- So, the problem looks like a path configuration problem. The *.tcl scripts in the directory as the *.py script run just fine under TCL. I have edited the PYTHONPATH environment to include the TCL\demos, TCL\bin, TCL\lib, and TCL\include directories. Does anybody know where TCL/TK gets its path to search packages from? In this case for example, I don't know which file TK is trying to "require". Is it one of the files in the tcl/include, tcl/lib or another directory altogether? -Ajo. From usenet at voygr.com Mon Mar 31 10:17:47 2003 From: usenet at voygr.com (Dave Bates) Date: Mon, 31 Mar 2003 09:17:47 -0600 Subject: MySQLdb Message-ID: <3e886259$1@nntp01.splitrock.net> Hello all, I'm having some issues with MySQLdb, and the docs on it seem pretty sparse.. So here goes, does anyone know if the password that is transmitted is cleartext or using the PASSWD encryption that mysql has. All of my passwords in MySQL are encrypted, as they well should be, but I can't seem to get access to mysql using the MySQLdb module as it's telling me the password is wrong. Thanks in advance Dave From tjreedy at udel.edu Wed Mar 19 12:12:09 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Mar 2003 12:12:09 -0500 Subject: Tutorial on programming devices? References: Message-ID: "Wouter van Marle" wrote in message news:b59ams$6jp3 at imsp212.netvigator.com... > www.pyhton.org is a very valuable source on these things. > > And besides that, isn't reading/writing from some port (almost) the same as > read/write to a file? Just use /dev/ttySxx (with xx your port number) as > filename. Supposed to work like that (never tried myself). Just a thought. > > Oh if you are not in Linux/Unix/etc it will probably be different. In DOS I In WIN/DOS, I believe, one can open "com1:', 'lpt1:', etc. But using pyserial or higher-level package is probably better way to go. TJR From peter at engcorp.com Sun Mar 16 22:57:30 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 16 Mar 2003 22:57:30 -0500 Subject: twisted.conch example References: Message-ID: <3E7547AA.DB9D3B29@engcorp.com> Dag wrote: > > I'm trying to write a program that uses twisted.conch ssh client > connection. However I cannot really get twitsed.conch working and > the documnetation for it is lacking. > > Does anyone have any sample code which shows twisted logging onto an > ssh server (using a supplied password), executing a command and getting > the output of the command? I'm sure if I could just see that basics > working I can figure out the rest. This may be of little help, but it's the best I can offer: Twisted apparently comes with a "full" suite of unit tests, as it was developed with an Extreme Programming type of process (or so I read on the twistedmatrix.com web pages). If that's true, the unit tests themselves might be an excellent place to look for examples of the intended use. -Peter From kife00 at yahoo.com Thu Mar 13 20:34:00 2003 From: kife00 at yahoo.com (Ian Terrell) Date: 13 Mar 2003 17:34:00 -0800 Subject: Tkinter callback problem References: <5b6217b0.0303130918.5409b763@posting.google.com> <20030313175826.GC3471@unpythonic.net> Message-ID: <5b6217b0.0303131734.7421b619@posting.google.com> > So, Ian, in the meantime, can you install Tk 8.4.1 instead (assuming you > are using 8.4.2)? That's correct, it is 8.4.2. I should have included that in the original post. =) So, knowing now that it's a problem with the new version of Tk, instead of downgrading, I'm just going to edit Tkinter.py to wrap the getint() calls in try/except, like: try: getint(h) except: pass This should fix the problem without loss of functionality. Ian From mis6 at pitt.edu Wed Mar 19 13:57:10 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 19 Mar 2003 10:57:10 -0800 Subject: Can __iter__ be used as a classmethod? References: <60FB8BB7F0EFC7409B75EEEC13E20192022DD8D3@admin56.narex.com> <2259b0e2.0303050740.52a92487@posting.google.com> <89G9a.12708$pG1.332485@news1.tin.it> <2259b0e2.0303061331.2b0b2028@posting.google.com> <25b5433d.0303131213.1c7b38dd@posting.google.com> <2259b0e2.0303181434.721838c@posting.google.com> <6hZda.81274$pG1.1839790@news1.tin.it> Message-ID: <2259b0e2.0303191057.4ad11dc4@posting.google.com> Alex Martelli wrote in message news:<6hZda.81274$pG1.1839790 at news1.tin.it>... > Michele Simionato wrote: > ... > >> > doesn't give any functionality. I also think staticmethod is poorly > >> > named, since it does not produce a method, and it definitely doesn't > >> > do what a 'static method' does in Java or any other language I know > ... > >> regarding your objection to the name. Where's the "definitely doesn't > >> do" -- isn't a Python staticmethod just like e.g. a C++ static method? > ... > >> What "definite" difference is totally escaping my notice...? > ... > > A staticmethod is not a method, is a function, when called as in the > > Nor did I say otherwise. But I'm still totally puzzled by the > "definitely doesn't do what a 'static method' does in Java" and I > don't see how your answer addresses this. What am I missing? > > > this context) from regular methods(which now are functions). No difference > > at all in the normal usage, but big difference in metaprogramming > > In Java there are no "functions" distinct from static method, so that > can't have anything to do with whatever the OP meant by "definitely > doesn't do". In C++ there is no introspection / reflection, and a > static method IS also "a function" (you can take its address as a > pointer to function, NOT as a pointer to method). So, I'm still > totally in the dark about what the "definitely doesn't do" refers > to -- *how* does a Python staticmethod differ from Java's or C++'s??? > > > Alex I don't claim expertise nor in Java nor in C++, therefore let the OP to clarify this issue :) From Kyler at lairds.com Thu Mar 6 13:54:53 2003 From: Kyler at lairds.com (Kyler Laird) Date: Thu, 6 Mar 2003 13:54:53 -0500 Subject: help! advocacy resources needed fast In-Reply-To: <20030306180016.GB14377@isis.gerrietts.net> References: <6igij-8sl.ln1@news.lairds.org> <20030306180016.GB14377@isis.gerrietts.net> Message-ID: <20030306185453.GF7024@remote.lairds.org> On Thu, Mar 06, 2003 at 10:00:16AM -0800, Geoff Gerrietts wrote: > A tenfold increase in traffic with linear scalability would mean 220 > Zope boxes. That does not seem like a reasonable solution to our > problem. Oh?! 200 new machines at what - around $500 each? (It's been awhile since I spec'd rackmounted Zope servers. I imagine they've gotten cheaper than that.) That's only $100,000. Sounds like a bargain for being able to stick with the tools you've developed and are comfortable using. We could yank a Googlemaster aside for some insight on throwing lots of commodity machines at a problem, but you you could also buy some superserver from IBM and just segment it into a bunch of virtual machines. My gut feeling is that you'd probably find that your perceived performance shoots up to "reasonable" after adding far fewer than 200 new machines. > But there's a point at which that stops being true, and stops being > reasonable. If it takes you twice or three times as long to create the > equivalent solution in Java, but it takes 22 boxes to run it instead > of 220, the long-term amortized cost of developing in Java is > significantly lower: at some point you save yourself some development > time, but at the expense of hiring more sysadmins and paying for more > real estate in your co-lo. Yes, of course there's a personal analysis to be done, but I always assume that programming/maintenance is a major expense and hardware costs are somewhere just above the noise level. And hardware just keeps getting cheaper. --kyler From drew.smathers at earthlink.net Wed Mar 12 21:20:55 2003 From: drew.smathers at earthlink.net (Drew Smathers) Date: Wed, 12 Mar 2003 21:20:55 -0500 (GMT) Subject: How to better control print and stdout? Message-ID: <7368139.1047682671392.JavaMail.nobody@ernie.psp.pas.earthlink.net> Hello, I'm new to python and have been having a hell of a time using stdout. Obviously Python has a unique way of printing strings. Basically, all I want to do is be able to make nice countdowns, or the classic spinner (|,/,-,\), using the escape code '\b'. This following function is an example: def spinner(rotations, interval): phase = 0 for i in range(rotations): if phase == 0: print '|', phase = phase + 1 elif phase == 1: print '/', phase = phase + 1 elif phase == 2: print '-', phase = phase + 1 else: print '\\', phase = 0 time.sleep(interval) print '\b\b', print '' The program waits for the loop to end before printing anything. (If I omit the comma, this results in the program printing in sync with the loop but throws in the unwanted newline of course.) Is there anyway to get around this without using any fancy libs like ncurses? I would appreciate any help... From jbperez808 at yahoo.com Wed Mar 5 02:00:27 2003 From: jbperez808 at yahoo.com (Jon Perez) Date: Wed, 5 Mar 2003 15:00:27 +0800 Subject: PEP 308 original proposal "used" already in Python Documentation References: Message-ID: "Christoph Becker-Freyseng" wrote: > Hello, > > I just found something funny in Python's Documentation. > In 2.1.6 Mapping Types you can find the following: > > a.get(k[, x]) a[k] if k in a, else x (4) > a.setdefault(k[, x]) a[k] if k in a, else x (also setting it) (5) > > It looks very similar to the original proposalof PEP 308, but it's the > explanation of {}.get and {}.setdefault . The ternary operator would definitely be a more intuitive way to get the same behaviour as get() (albeit longer - but we're not Perlistas are we?). [a[k] if k in a else x] Now how would we express setdefault() using the ternary operator though?I don't think it is legal to have multiple statements in a single line if/else contruct in Python: [a[k] if k in a else a[k]=x: x] or [a[k] if k in a else a[k]=x: return x] wouldn't work. From vivek-nospam at cs.unc.edu Wed Mar 12 11:11:16 2003 From: vivek-nospam at cs.unc.edu (Vivek Sawant) Date: Wed, 12 Mar 2003 11:11:16 -0500 Subject: Help: /bin/ping problem with Red Hat References: <3E6F51A9.3030706@cs.unc.edu> Message-ID: <3E6F5C24.7090006@cs.unc.edu> Looks like this has something to do with Linux threading in general or perhaps python threading in particular. I scripted a simple python program to invoke the following command line and ping terminated as expected. If I create a thread and get it to invoke the following command line, it blocks forever and does not terminate as directed using the -w option. Does this have something to with alarm/signal. Perhaps the ping running within this thread does not get its signals delivered to it properly? What do you guys think? Thanks. \vivek Vivek Sawant wrote: > I am having a peculiar problem with the /bin/ping program. I am running > Red Hat with Kernel 2.4.18-19.7.xsmp. Ping to a non-responsive (down) > host does not terminate when invoked from my python application even > though I use the timeout (-w) flag. Details: > > My Python application has two threads: a main thread and another created > by the main thread. The second thread invokes the following ping command > using os.system () of Python. > > /bin/ping -c 3 -s 548 -p "0003a8e4" -w 3 -l 3 > > The stdout and stderr of this command has been redirected to a file. > For a destination that is down (does not respond to pings), the above > command never terminates while it is supposed to after 3 seconds (-w 3). > If I cut and paste the above command at the command line, it terminates > after 3 seconds as expected even though the destination does not > echo back any of the packets. > > If I kill the above ping command using 'kill -9', the rest of my app > logic behaves like the ping has terminated. Also, for the destinations > that respond to ping, the app is behaving normally. So, I don't think > there is any problem with my prorgam logic. > > While the ping thread is pinging, the main thread periodically reads a > file to see if the user has signalled termination of application. This > thread gets periodically scheduled even when the ping thread is stuck as > described above. > > Does anyone have any insight about what's going on here. I am hopelessly > stuck :-( > > Thanks. > > \vivek > From dmetzler.nospam at partner.auchan.fr Thu Mar 27 04:52:28 2003 From: dmetzler.nospam at partner.auchan.fr (Damien Metzler) Date: Thu, 27 Mar 2003 10:52:28 +0100 Subject: [BOA] pb while loading Message-ID: When i start boa-constructor, the splash screen freezes near the end... at "importing Explorers" Can anyone help me ? My configuration : Windows 2000 Python 2.2 wxPython 2.4.0.1 Boa 0.2.0.0 (i tried also a fresh CVS snapshot but i have the same pb) From tdelaney at avaya.com Mon Mar 31 16:53:56 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 1 Apr 2003 07:53:56 +1000 Subject: Is Python overhyped (just like Java)? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE3DCF5F@au3010avexu1.global.avaya.com> > From: David Abrahams [mailto:dave at boost-consulting.com] > > Alex Martelli writes: > > > Thanks to the excellent support given for these tasks by > the standard > > library, the C++ source is ONLY twice as big as the Python > source for > > the same job (a more usual ratio is around 5:1). This > holds for both > > the simplest versions, and the slightly more complicated ones with > > somewhat better optimization. The runtimes on my box > (Linux Mandrake > > 9.0, gcc 3.1, Python 2.3) are, when the programs are run on > the 4.4 MB > > of the "King James Bible" in plain ASCII text: 17.4 seconds for the > > simplest C++, going down to 15 with optimizations; 11.2 seconds for > > the simplest Python, going down to 8.1 with optimizations (CPU times > > are in very similar ratios). Of course, this basically reflects the > > excellence of Python's intrinsics (dictionaries, lists, strings) > > versus the lesser quality of C++'s library implementation (maps, > > vectors, strings) -- with different implementations, you may see > > different ratios. > > Really? Are you sure that time wasn't sunk into I/O? "Read all the > lines from a file" is a primitive in Python, but not in C++. > > Also, it's only fair to point out that C++ doesn't have one library > implementation -- each compiler comes with its own. Which > implementation(s) were you testing? Oh, I see it was probably > libstdc++ that comes with gcc 3.1. Well, IIRC GCC-3.1 was well known > to optimize poorly (it took them some time to figure out how to > integrate all the new optimizations that came in with GCC-3, and they > actually made things slower for a while), and I wouldn't exactly say > that libstdc++ is the fastest implementation. I think if you'll read the above, you will notice that Alex says exactly the same thing "...with different implementations, you may see different ratios." Also, "read all the lines from a file" is not a primitive in Python - it's a method call ... *and* it is written in C. Obviously there could be as good an implementation in C++ on the same platform - whether there could be a *better* implementation is another question. Tim Delaney From gcangiani at yahoo.it Mon Mar 3 02:19:52 2003 From: gcangiani at yahoo.it (Multiscan) Date: Mon, 03 Mar 2003 08:19:52 +0100 Subject: beginner oo programming References: Message-ID: On Tue, 25 Feb 2003 10:47:57 +0000, Steven Taschuk wrote: > > If you use Cartesian coordinates internally, the Cartesian > coordinate system object can access them directly. Other > coordinate system objects ask for the Cartesian representation and > convert. (This assumes that > v.components(polar) > delegates to, say, > polar.components(v) > And the reverse: vector(tuple, coordsystem) delegates to > coordsystem.makevector(tuple) or some such. The nice thing about > this scheme is that the knowledge of how to convert to/from a > given coordinate system is stored in the object which represents > that coordinate system. Good abstraction.) > > (Note, incidentally, that oblique (and rotated) coordinate systems > can be implemented with a matrix and a bit of linear algebra.) > > How does that sound? I couldn't imagine a better answer. Thanks very mutch ! giovanni From eichin at metacarta.com Mon Mar 17 16:42:29 2003 From: eichin at metacarta.com (eichin at metacarta.com) Date: 17 Mar 2003 16:42:29 -0500 Subject: changes to shelf items fail silently? Message-ID: <7gy93dmzzu.fsf@pikespeak.metacarta.com> shelftest.py: #!/usr/bin/python import shelve complex_example = shelve.open("/tmp/complex_example_shelf") complex_example["a"] = [] print complex_example["a"] complex_example["a"].append("b") print complex_example["a"] complex_example["a"].extend(["b"]) print complex_example["a"] complex_example["a"] = complex_example["a"] + ["b"] print complex_example["a"] $ python shelftest.py [] [] [] ['b'] So, I see why the last case works (it can't help *but* work) but I don't get why the append/extend mutators don't. Or rather, why if they can't work, I don't get an error thrown so I notice it... (this occurs in 2.1 and 2.2. Is there a "better" shelf-like thing that I should use instead, for more completely persistent data?) From gh at ghaering.de Fri Mar 21 13:47:16 2003 From: gh at ghaering.de (Gerhard Haering) Date: Fri, 21 Mar 2003 19:47:16 +0100 Subject: Object oriented databae for Python In-Reply-To: <147119607.20030321213132@garret.ru> References: <3E7A12BA.3A297B2F@easystreet.com> <3E7B38A5.B54F82BE@easystreet.com> <3E7B494D.2E745631@easystreet.com> <147119607.20030321213132@garret.ru> Message-ID: <20030321184715.GA1036@mephisto.ghaering.test> * Konstantin Knizhnik [2003-03-21 21:31 +0300]: > Hello achrist, > > This is problem with definition DL_EXPORT macro in Python 2.2.2 [...] There is no problem. The problem might be in the Makefiles you use. So don't use Makefiles. Use distutils through the setup.py I created :-) The only thing you'll likely have to change is the library to link against, cos MSVC doesn't have any libstdc++. It's called otherwise, but I don't recall how. The proper solution for setup.py on win32 is to distinguish the compiler used and then set the appropriate libraries. As that's probably not easily done, make it configurable in that the user has to edit setup.py manually, with clear instructions. > With 2.3 it works ok, but not with 2.2.2. > May be I just do not define some environment variable. But neither > USE_DL_EXPORT, USE_DL_IMPORT properly works: There is no need to set any defines. > So looks like USE_DL_EXPORT should be used for building Python core, > and USE_DL_IMPORT is not enough for building proper client extension > - it doesn't define DL_EXPORT, so module init function is not > imported. If you want to use Makefiles, get a working extension module (like PySQLite ;-), then invoke "python setup.py build" and look which compiler options are used with MSVC. > That is why in original version I did it it such way: > > #ifdef _WIN32 > __declspec(dllexport) > #endif > void > initpythonapi(void) > { > Py_InitModule("pythonapi", dybase_methods); > } > > But Gerhard send me patch where this my hack was removed (by using > DL_EXPORT macro). > At this moment I already forgot the reason of such hack, so I check > that this code works (with Python 2.3) and apply the fix. > I forgot about the problem with Python 2.2. > So no I am going to return back to my original code which should work > with both versions of Python. Or may be there is some better solution? Please leave it as it is, as there is no problem with DL_EXPORT. The problem is in your Makefiles, so just use distutils. Well, I'm getting redundant. Once I get to a machine with MSVC6 installed (or I dig for the CD at home) I'll check the combination DyBASE/MSVC6/distutils. Anyways, in Pyhton 2.3, DL_EXPORT is deprecated in favour of a better solution, but DL_EXPORT still works under 2.3. Here's what a contributor to PySQLite sent me: #v+ /* Compatibility macros * * From Python 2.2 to 2.3, the way to export the module init function * has changed. These macros keep the code compatible to both ways. */ #if PY_VERSION_HEX >= 0x02030000 # define PySQLite_DECLARE_MODINIT_FUNC(name) PyMODINIT_FUNC name(void) # define PySQLite_MODINIT_FUNC(name) PyMODINIT_FUNC name(void) #else # define PySQLite_DECLARE_MODINIT_FUNC(name) void name(void) # define PySQLite_MODINIT_FUNC(name) DL_EXPORT(void) name(void) #endif [...] PySQLite_DECLARE_MODINIT_FUNC(init_sqlite); [...] PySQLite_MODINIT_FUNC(init_sqlite) { [...] } #v- HTH, Gerhard -- mail: gh at ghaering.de web: http://ghaering.de/ From pan-newsreader at thomas-guettler.de Thu Mar 27 00:29:39 2003 From: pan-newsreader at thomas-guettler.de (Thomas Guettler) Date: Thu, 27 Mar 2003 06:29:39 +0100 Subject: mit Python Verzeichnisse rekursiv durchsuchen? References: <94e97915.0303260811.661189bb@posting.google.com> Message-ID: On Wed, 26 Mar 2003 17:11:15 +0100, Jan van Helsing wrote: > Hallo allerseits! > > Ich habe ein Problem - ich will mit einem Python-Skript Verzeichnisse > rekursiv nach einem bestimmtbaren Dateityp durchsuchen und die > Ergebnisse nach Verzeichnissen sortiert in eine HTML oder LaTeX Datei > ausgeben. There is a german speaking mailing list at: http://starship.python.net/mailman/listinfo/python-de thomas -- Thomas Guettler http://www.thomas-guettler.de From aleax at aleax.it Thu Mar 20 02:37:14 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 20 Mar 2003 07:37:14 GMT Subject: Is Python the Esperanto of programming languages? References: <200303192233.30383.andy@wild-flower.co.uk> <8b5e42a6.0303192123.2f7b5187@posting.google.com> Message-ID: Levente Sandor wrote: ... >> I would wager there are more people using python than know Esperanto! > > Google says: > Searched the web for python language. Results 1 - 10 of about > 663,000 And perhaps more significantly, python -monty gives 1.4 M hits (not sure how to square this with the fact that python monty gives 453K hits and just python 4.9 M hits...). > Searched the web for esperanto. Results 1 - 10 of about 1,260,000 Something strange here -- I'm seeing only 151 K hits... (?!) Alex From aleax at aleax.it Tue Mar 4 16:08:16 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 04 Mar 2003 21:08:16 GMT Subject: Can __iter__ be used as a classmethod? References: <3e649aa3_4@news.bluewin.ch> <2259b0e2.0303041023.43e8b81f@posting.google.com> Message-ID: <4B89a.6715$zo2.218162@news2.tin.it> Giovanni Bajo wrote: > > "Michele Simionato" ha scritto nel messaggio > news:2259b0e2.0303041023.43e8b81f at posting.google.com... > >> It seems to me I could always use a regular method instead of >> a classmethod, by accessing the class trough self.__class__ or >> type(self), therefore classmethods only provide a very small amount >> of syntactical sugar. > > Actually, they let you also call the method without any instance of the > class (they do not need to be bound to any instance). Yes, that's difference #1. >> Actually they seems to me an unessential complication to the language, >> expecially because they are easily confused with the methods in the >> metaclass. ... > The only difference I can see is: > >>>> a = A() >>>> a.g() > Hello from , value is 10 >>>> a.f() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'A' object has no attribute 'f' > > This is because of the lack of transitivity in the 'inheritance' from > types, as explained by Alex in another post in this thread. And that's difference #2. > So, what are the other differences (if any)? Why do classmethods exist? Aren't these reasons enough? How else would you code a method that you can indifferently call either on any instance or on the class object itself? And _having_ to write a custom metaclass as the only way to get classmethods would be somewhat of an overkill. Whether static methods (which to many are familiar from C++ or Java) and class methods (which have some pluses and some minuses, and to some are familiar from Smalltalk) need to exist at all is moot -- C++'ers and Javaites have been clamoring for them for a long time, not wanting to use free-standing (module top-level) functions instead (and in effect, a free-standing function could not be written to receive the classobject automatically -- and custom metaclasses where a nightmare before Python 2.2). Overall I'm slightly happier to have them in Python than not, but I do realize they contribute to "featuritis" -- Python does keep getting richer with every release, as it's always easier to give in to the pressure of those who DO want the feature (and can muster good direct arguments and use-cases for it), when the only negative is "the more feechurs we keep piling up, the less simple our beloved language". Sigh. Alex From staschuk at telusplanet.net Thu Mar 6 15:04:40 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 6 Mar 2003 13:04:40 -0700 Subject: why self instead obj ? In-Reply-To: <698f09f8.0303061027.698b4e7e@posting.google.com>; from tweedgeezer@hotmail.com on Thu, Mar 06, 2003 at 10:27:09AM -0800 References: <698f09f8.0303061027.698b4e7e@posting.google.com> Message-ID: <20030306130440.B4617@tibia.amotlpaa.bogus> Quoth Jeremy Fincher: > "Gerard Breiner" wrote in message news:... [...] > > Moreover, "obj" is easier to type on the keyboard and shorter than "self". > > I don't really think this is the case. On a QWERTY keyboard, self is > a quick four taps of the keyboard, each using a different finger, > three belonging to the home row and one belonging to the > slightly-slower top row. obj, on the other hand, is three taps of the > keyboard, the first two of which are the same finger, one of those two > is even a ghastly bottom-row-stretch key. [...] I can't imagine a sensible method of touch-typing which would have o and b on the same finger on a qwerty keyboard. I assume you meant "last two" instead of "first two", and are typing b with the right-hand index finger, whose home is j. If this is so, I'd suggest typing b with the left-hand index finger (home at f); this is the usual method afaik. (Note the symmetry: r t g b v on the left, u y h n m on the right.) It also happens to make 'obj' a finger-per-letter word. -- Steven Taschuk "The world will end if you get this wrong." staschuk at telusplanet.net (Brian Kernighan and Lorrinda Cherry, "Typesetting Mathematics -- User's Guide") From tzot at sil-tec.gr Tue Mar 4 19:28:10 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 05 Mar 2003 02:28:10 +0200 Subject: Sorry ... References: Message-ID: On Tue, 04 Mar 2003 21:10:33 GMT, rumours say that "Lance LaDamage" might have written: >If I shocked you by my various errors, it's because one thing ... and >prepare for the shock ... : > >I am an 11 year old child who enjoys to program in Visual Basic and have >recently learned Python Hey, Lance, that's great! Welcome to the wonderful world of computer programming... Just a friendly advice: in case you often find yourself losing your sleep over programming, don't; especially at your age. You will thank me for this years later. And a quote that came up through the mists of memory: "good advice is what one gives when they are too old to set a bad example". Cheers :) -- TZOTZIOY, I speak England very best, bofh at sil-tec.gr (I'm a postmaster luring spammers; please spam me! ...and my users won't ever see your messages again...) From usenet-posting.zu.askwar at spamgourmet.com Mon Mar 17 09:28:44 2003 From: usenet-posting.zu.askwar at spamgourmet.com (Alexander Skwar) Date: Mon, 17 Mar 2003 15:28:44 +0100 Subject: ftp In-Reply-To: References: Message-ID: Enrique Palomo wrote: > There's any python module to transfer files (ftp) only with ftp commands > (put, get, mput, ...) different of ftplib in which i must open the file > to transfer, read it, ... What's your problem with ftplib? Alexander Skwar -- Herzlichen Gl?ckwunsch zum Namenstag, heute ist Volltrottel! [Andreas Hirschberg in t-o.s] From thomas_hatesspam at wana.at Tue Mar 4 13:07:52 2003 From: thomas_hatesspam at wana.at (Thomas Wana) Date: Tue, 04 Mar 2003 19:07:52 +0100 Subject: Code to recognize MS-Word document files? References: <3e64d3c3$0$52915$a1866201@newsreader.visi.com> Message-ID: <1046799459.947699@newsmaster-03.atnet.at> WP wrote: > // My word files all seem to start like this > // (MS Office 2000 WORD iles) > // d0 cf 11 e0 a1 b1 1a e1 00 00 00 00 00 00 > // 00 00 00 00 00 00 00 00 00 00 > // Your mileage may vary. MS Excel files have the same signature; it seems that all office documents have it. (I know that because I had to manually recover some lost excel files from a vfat partition) Thomas > > Warren From tim.one at comcast.net Tue Mar 11 22:02:15 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 11 Mar 2003 22:02:15 -0500 Subject: Flying With Python (Strong versus Weak Typing) In-Reply-To: <20619edc.0303111308.62d6a8e2@posting.google.com> Message-ID: [Mike Silva] > Is a factor of 100 difference in error rates of certified, fielded > aviation software relevant? If it concludes Python is the winner, yes; else it's riddled with methodological flaws, if not outright deception . Provable correctness doesn't have much of a following in Dynamic Language Land, perhaps because such languages are so effective at tackling problems where "the solution" isn't known-- perhaps not even recognizable --in advance. Dijkstra was famous for saying that testing can't demonstrate the absence of bugs, only their presence, and he was right. That's what XP *does* in this part of the world, but it's not ashamed of it. Provable correctness is far too expensive for most of the world's software to even contemplate as a design goal. That doesn't mean a Python program can't be proved correct, although exploiting the full power of the language would make that very difficult for a program of any appreciable size. then-again-i-started-my-career-flying-on-planes-designed-by- legacy-fortran-programs-and-lived-to-type-about-it-ly y'rs - tim From nada at nowhere.xxx Sat Mar 22 18:22:32 2003 From: nada at nowhere.xxx (Lenard Lindstrom) Date: Sat, 22 Mar 2003 23:22:32 GMT Subject: A library approach to the ternary operator References: Message-ID: "Lenard Lindstrom" wrote in message news:KqLea.42008$Ty5.2786625 at news0.telusplanet.net... >... > # ternary module > def select(test, fn_iftrue, fn_iffalse): > if test: > return fn_iftrue() > return fn_iffalse() > > then: > > from ternary import * > x = select(condition, lambda:true_result, lambda:false_result) >... I see that PEP 312 mentions this form of a conditional operation as an example of use. Lenard Lindstrom "%s@%s.%s" % ("len-l.", "telus", "net") From aleax at aleax.it Mon Mar 24 07:46:05 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 24 Mar 2003 12:46:05 GMT Subject: Prime number algo... what's wrong? References: <1MudnTyOEK1mauGjXTWcqg@speakeasy.net> Message-ID: A.M. Kuchling wrote: ... > (Has anyone implemented the polynomial-time primality test discovered a > few months back? Wonder how complicated it is...) You might want to check: http://fatphil.org/maths/AKS/#Implementations Since you're from Canada, you should be able to get through (as should people from France, Germany, Belgium); the guy is blocking off access from the US and all countries supporting the attack on Iraq, which includes Italy, so I can't check myself. Alex From johnp at reportlab.com Tue Mar 18 06:29:20 2003 From: johnp at reportlab.com (John Precedo) Date: Tue, 18 Mar 2003 11:29:20 -0000 Subject: Python UK conference Wikki up Message-ID: A basic Wikki Wikki is up for the UK Python Conference at http://server.reportlab.com/accu-2003/moin.cgi/FrontPage. Could anyone who will be attending the conference please add their name to the Attendees page? This will be the place to discuss travel arrangements, sort out lifts and ride shares etc. We also plan to have organisation of the various short talks here. And of course since it is a Wikki, if you think of something else that should be included you can add it yourself. -- John Precedo (johnp at reportlab.com) Developer Reportlab Europe Ltd (http://www.reportlab.com) From zf_acs at DELETETHIShotmail.com Fri Mar 14 07:18:21 2003 From: zf_acs at DELETETHIShotmail.com (zif) Date: Fri, 14 Mar 2003 07:18:21 -0500 Subject: strings in Python (newbie) References: <9397bfd5.0303120610.6d7b2f20@posting.google.com> <7Xica.56121$pG1.1289243@news1.tin.it> Message-ID: Thanks. zif Alex Martelli wrote in message news:7Xica.56121$pG1.1289243 at news1.tin.it... > zif wrote: > > > Thanks, I'll try that as well. Another question: how > > can I break long text/array elements across multiple > > lines? > > If I'm reading your question correctly, the answer is > easy -- Python concatenates multiple adjacent "physical" > lines into a single "logical" line as long as an open > parens (or bracket) hasn't yet been closed. So for ex: > > longstuff = [ 0, 1, 45, 67, 223, 23, > 15, 43, 88, 99, 1, 0, > 23, 24, 42, 15, 0, 2 ] > > just works. Note that indentation is arbitrary for all > the physical lines except the first one (also known as > "continuation lines") -- the one I'm showing here is just > one reasonably popular convention (there are others, too). > > > Alex > From ulope at gmx.de Sun Mar 9 18:18:41 2003 From: ulope at gmx.de (Ulrich Petri) Date: Mon, 10 Mar 2003 00:18:41 +0100 Subject: How to Pickle a C-Extension-Class Instance? Message-ID: Hi, i try to pickle an instance of an c-extension class. (The class is part of Zope (lib/python/DocumentTemplate/cDocumentTemplate.c)) Unfortunately the pickled result is all but a correct representation of the instances contents. What can i do about this? Thanks Cu Ulrich From opengeometry at yahoo.ca Thu Mar 13 16:30:00 2003 From: opengeometry at yahoo.ca (William Park) Date: 13 Mar 2003 21:30:00 GMT Subject: Has anyone created a simple POP3 and SMTP server using TWISTED? References: <0001HW.BA9660EB0012EC36F0407600@netnews.attbi.com> Message-ID: Zoo Keeper wrote: > I thought I'd be looking more along the lines of pop3d and smtpd in > that case. BeOS is not rich with server code that is free. There is > a version of Enamel that works, but is flaky. I could also wait for > Zeta to be released, which might solve some of my problems, especially > if they implement a full network api as the various unix's have. Curious that you'd be holding onto BeOS, when they've gone out of business. Wouldn't it make more sense to run Linux as server, and BeOS for whatever desktop stuffs that you are running? -- William Park, Open Geometry Consulting, Linux solution for data management and processing. From clifford.wells at attbi.com Sun Mar 30 04:37:45 2003 From: clifford.wells at attbi.com (Cliff Wells) Date: 30 Mar 2003 01:37:45 -0800 Subject: Easibox 0.1.5 released In-Reply-To: References: Message-ID: <1049017065.2397.1.camel@cliff> On Sun, 2003-03-30 at 01:11, Simon Burton wrote: > On Sun, 30 Mar 2003 07:01:57 +0100, phil hunt wrote: > > > > > Easibox is a utility for making tar files, zip files and other > > archive files, designed to be particularly useful when making > > releases of open source projects. > > > > Easibox was written to solve a problem I had when releasing > > open source software packages, such as my Leafwa program. The > > technique I was using was manually creating a directory with > > the required filename (such as "leafwa-0.6.1"), copying those > > files to be archived into the directory, and then cd'ing to > > that directory's parent and running tar to create the tarball. > > I found this process time-consuming and error-prone. So I > > decided there must be a better way... > > > > I use make for this; the files are listed in a makefile. Some people program in Perl. Doesn't mean there isn't a better way Regards, Cliff From stuart at bmsi.com Tue Mar 11 21:07:37 2003 From: stuart at bmsi.com (Stuart D. Gathman) Date: Wed, 12 Mar 2003 02:07:37 GMT Subject: Working example of extension class in C/C++ ? References: <3e6e5329@news.mt.net.mk> Message-ID: On Tue, 11 Mar 2003 16:20:41 -0500, ???????????? ??. wrote: > There already is a shared memory support in Pytohn, look at the mmap > module. What would be nice, though, is a shared-mem dictionary that also > can store its values in the sahred memory, thus creating a super-fast > and simple mmaped Python IPC. mmap is a different API than shm. The OP wants to wrap the SysV shared memory API - which does not involve files (except as a kludgey convention for constructing 'keys' to identify shm segments). -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From thomas at xs4all.net Sat Mar 15 12:03:28 2003 From: thomas at xs4all.net (Thomas Wouters) Date: Sat, 15 Mar 2003 18:03:28 +0100 Subject: use of "self", was "No Do while/repeat until looping construct in python?" In-Reply-To: References: Message-ID: <20030315170328.GN2112@xs4all.nl> On Sat, Mar 15, 2003 at 08:44:38AM -0500, John Roth wrote: > Ruby, for example, requires a "funny character" to distinguish > instance variables and module/global variables from local variables. > It borrowed the concept from Perl, although for a very different use. Well, that depends on how you look at it. In Perl, '@', '%' and '$' (and subs and FILEHANDLES and such, which have no prefix character) all live in separate namespaces (and sometimes with subtly different rules governing them, too.) @spam, %spam and $spam (can, and usually do) all point to different objects, in different namespaces. So if you forget that the namespaces are also type-specific, you can think of '@spam' as saying "get me 'spam' from the 'array' namespace". If you do think of it like that, the 'glob' identifier ('*spam') also makes more sense; the * matches any namespace ;) -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! From staschuk at telusplanet.net Tue Mar 11 03:35:00 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 11 Mar 2003 01:35:00 -0700 Subject: libglade-2.0-0.dll In-Reply-To: ; from m.schubert@sh.cvut.cz on Tue, Mar 11, 2003 at 06:15:19AM +0100 References: Message-ID: <20030311013500.B1626@tibia.amotlpaa.bogus> Quoth Marian Schubert: > have someone this file? Have you looked at ? -- Steven Taschuk o- @ staschuk at telusplanet.net 7O ) " ( From intentionally at blank.co.uk Sat Mar 8 05:35:00 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Sat, 08 Mar 2003 10:35:00 +0000 Subject: PEP308 Late Entry Message-ID: I've been putting off making my vote because I wasn't fully happy with any option. I finally came up with a new choice - it's late, I know, but here is my late attempt to drum up support. The syntax would have variants such as... select : (c1 : r1; c2 : r2; r3) select s : (v1 : r1; v2 : r2; r3) select sa, sb : (v1a, v1b : r1; v2a, v2b : r2; r3) 's' stands for 'switch expression'. 'c' for condition. 'r' for result. 'v' for switch-value. Switch values could even support special syntaxes such as relative operator prefixes ('<', '>' etc) or perhaps a '..' or 'to' notation for ranges - though the non-switch first form might be clearer. Advantages are... 1. It handles 'elif' simply and succinctly. 2. It supports the switch/case functionality as a simple extension, but unlike the earlier proposal does not have to be split over multiple lines unless clarity genuinely demands it. 3. The use of punctuation keeps it succinct while the initial keyword makes it clear what is happening (easy to look up in documentation etc). 4. The initial ':' and the use of ':' and ';' in the parentheses makes it clear that this is not a function, for those who see function-call notation as implying no shortcircuiting. -- steve at ninereeds dot fsnet dot co dot uk From none at of.your.business Thu Mar 6 20:15:54 2003 From: none at of.your.business (lynx) Date: Thu, 06 Mar 2003 20:15:54 -0500 Subject: python vs. perl readability References: <3e678486@newsflash.abo.fi> Message-ID: On Thu, 06 Mar 2003 19:23:58 +0200, Simon Dahlbacka wrote: > what was that supposed to do? I got a IndexError (possibly for > sys.argv[1]) i got a syntax error on the z.split('|') statement. possibly i need a newer python interpreter. -- PGP/GnuPG key (ID 1024D/3AC87BD1) available from keyservers everywhere Key fingerprint = FA8D 5EA4 E7DC 84B3 64BC 410C 7AEE 54CD 3AC8 7BD1 "...if you can fill the unforgiving minute with sixty seconds' worth of distance run..." From lrl at cox.net Sat Mar 22 02:31:38 2003 From: lrl at cox.net (Luke) Date: 21 Mar 2003 23:31:38 -0800 Subject: a regular expression question Message-ID: <577e43a1.0303212331.5eaf93e5@posting.google.com> I suppose this isn't really a python question as much a R.E. question, but I'm using python to do it, so... I'm trying to parse link data from a webpage that looks like this: 1 abc 2 def 3 ghi 4 jkl With a regular expression like below (where the variable 'text' is the sample above), re1 saves the numbers, but not the text. Why is that? If I use re2, it works, but obviously only gets the odds since there is no overlapping. Is there a way to modify re1 to get the text, or is there a way to overlap with python's re engine somehow? >>> re1 = re.compile("([0-9]+?)(.*?)") >>> matches = re.findall(re1,text) >>> matches [('1', ''), ('2', ''), ('3', ''), ('4', '')] >>> re2 = re.compile("([0-9]+?)(.*?)>> matches = re.findall(re2,text) >>> matches [('1', ' abc '), ('3', ' ghi ')] Thanks From tebeka at cs.bgu.ac.il Sun Mar 23 08:55:20 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 23 Mar 2003 05:55:20 -0800 Subject: Reading from an External Buffer References: <4ecaae91.0303222204.52aa4299@posting.google.com> Message-ID: <33803989.0303230555.2c4afc01@posting.google.com> Hello Bill, > I working on a Macintosh C program that embeds some python code. I'm > using "PyMac_SetConsoleHandler" to suppress the SIOUX console, and > I've created my own write handler that captures Python's stdout & > stderr and redirects them into my C code. So far no problem. > > Now I'd like to do the same for stdin, reading lines from a buffer in > my C code and passing them to sys.stdin in my Python code. > Unfortunately, the only thing I've found that works so far is to write > the data to temp file in C and then read it out from Python. But > that's a not much of solution, is it? > > Any advice/pointers/tips/suggestions would be greatly appreciated. Use a StringIO object? HTH. Miki From spam at magnetic-ink.dk Fri Mar 14 14:25:00 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Fri, 14 Mar 2003 19:25:00 +0000 (UTC) Subject: Using SHA1 as RNG References: <3e7228e0$0$49110$e4fe514c@news.xs4all.nl> Message-ID: <4d0ec854-54f9-46a0-99ea-86534e100ba1@news.szn.dk> Irmen de Jong wrote: > I think your idea is flawed, sorry. It only depends on a few > random values at seeding time, and after that - see my previous > comment. No need to be sorry. I posted the example here to get some feedback, and I have clearly overlooked something, because I never thought about the possibility that the process might end up repeating itself. Thanks. > Even if the hash doesn't repeat itself, you still get a 100% > predictible sequence of numbers because the SHA algorithm is > repeatable. But the same goes for the original Wichmann-Hill generator, doesn't it? But to predict the sequence of the SHARandom generator you would need to know the three initial seeds plus all of the intermediate values, and the number of steps taken, wouldn't you? // Klaus -- ><> unselfish actions pay back better From robin at jessikat.fsnet.co.uk Wed Mar 19 20:05:15 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 20 Mar 2003 01:05:15 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 17) References: <3E790E71.9351E229@alcyone.com> Message-ID: In article <3E790E71.9351E229 at alcyone.com>, Erik Max Francis writes >Robin Becker wrote: > >> well in base pi, pi has a a value which isn't exactly random. > >Hence why he said "positive integer bases (>= 2)" :-). Non-integral >bases have meaning, but aren't usually used. > well I choose to be slightly more general. Is that forbidden? -- Robin Becker From alloydflanagan at attbi.com Tue Mar 11 12:08:49 2003 From: alloydflanagan at attbi.com (A. Lloyd Flanagan) Date: 11 Mar 2003 09:08:49 -0800 Subject: Reference count problem (Python -> C) References: Message-ID: Carl Bevil wrote in message news:... > Basically, I want to use Python to build a data structure up for use in C++. > So I have Python code that looks like this: > > > import myStuff > > root = myStuff.Tree("Root") > root.AddChild(myStuff.myObject("Child 1")) > root.AddChild(myStuff.myObject("Child 2")) > root.AddChild(myStuff.myObject("Child 3")) > > > Under the hood, this creates a new "Tree" object, which gets attached to a > pointer internally. Three "myObject" objects are also created, and each one > gets attached to the tree object. > > The problem is that Python doesn't know that under the hood the objects are > getting assigned to internal pointers, so as soon as they are no longer > referenced by Python objects, the are deleted. So the "Child 1" object is I would think you'd have to use Py_INCREF() in C++ to increment the reference counts for for the objects. So when you add an object to the tree, the tree will have to increment the reference count. Python won't do it since it doesn't have a python variable referring to the object. When the tree is done with object, it will have to do a Py_DECREF() so python can free up the memory. From riccardo at Togli_Quest0sideralis.net Tue Mar 11 10:02:48 2003 From: riccardo at Togli_Quest0sideralis.net (Riccardo Galli) Date: Tue, 11 Mar 2003 16:02:48 +0100 Subject: is there a nmore pythonic way ? References: <3e6dbc5e$0$2688$626a54ce@news.free.fr> Message-ID: On Tue, 11 Mar 2003 11:40:18 +0100, shagshag13 wrote: > hello, > > i need to use module.function passed from command line, by now i use : > [...] > [...] > is there a more correct way to do it ? > > thanks, > > s13. Probably you'd like to import getopt Ciao, Riccardo -- -=Riccardo Galli=- _,e. s~ `` ~@. ideralis Programs . ol `**~ http://www.sideralis.net From llchen223 at hotmail.com Tue Mar 25 18:25:41 2003 From: llchen223 at hotmail.com (Lei Chen) Date: 25 Mar 2003 15:25:41 -0800 Subject: Python NT service SERVICE_INTERACTIVE_PROCESS Message-ID: Hi, I'd like to create a GUI process (through CreateProcess) under a Python service. Is this possible? If so, how? (snippets of code would be nice.) I would like to use the win32serviceutil.ServiceFramework class if this is doable. Thanks From johnfabel at btinternet.com Mon Mar 17 15:29:48 2003 From: johnfabel at btinternet.com (John Abel) Date: Mon, 17 Mar 2003 20:29:48 +0000 Subject: Problem Using win32security In-Reply-To: <3E7625E3.5000703@btinternet.com> References: <3E7625E3.5000703@btinternet.com> Message-ID: <3E76303C.30802@btinternet.com> Just to add to this. I have searched the archives, and have added the AdjustPrivilege code by Mark Hammond, and it still isn't working. I've added : AdjustPrivilege(SE_TCB_NAME) AdjustPrivilege(SE_CHANGE_NOTIFY_NAME) AdjustPrivilege(SE_ASSIGNPRIMARYTOKEN_NAME) before the LogonUser call, without success. After reading another post, I've also added Administrators to "act as part of the os". I presume I need to reboot after this? Has anyone got this working? Thanks John John Abel wrote: > Hi, > > I am trying to use win32security.LogonUser(). However, I always get > this: > > api_error: (1314, 'LogonUser', 'A required privilege is not held by > the client.') > > The code isn't spectaculer: > > import win32security, win32con > > logonHandle = win32security.LogonUser( 'johnab', > None, > 'test', > > win32con.LOGON32_LOGON_INTERACTIVE, > > win32con.LOGON32_PROVIDER_DEFAULT ) > > I'm running the code, whilst logged on as Administrator. Has anyone > any pointers? > > Thanks > > John > > From theller at python.net Tue Mar 11 09:22:31 2003 From: theller at python.net (Thomas Heller) Date: 11 Mar 2003 15:22:31 +0100 Subject: Can __iter__ be used as a classmethod? References: <3e649aa3_4@news.bluewin.ch> <2259b0e2.0303041023.43e8b81f@posting.google.com> <4B89a.6715$zo2.218162@news2.tin.it> Message-ID: "Greg Ewing (using news.cis.dfn.de)" writes: > Alex Martelli wrote: > > Aren't these reasons enough? How else would you code a method that > > you can indifferently call either on any instance or on the class > > object itself? > > How often do people actually *need* that functionality, > though? Smalltalkers don't seem to be bothered by the > need to know whether to call a method on a class or an > instance. Can someone provide a compelling use case > for this in Python? Although I use metaclasses and class-methods extensively in the ctypes module, I haven't yet needed to call a class-method from an instance. Maybe 'classmethod' is as weird as what some people aks for in this forum (and they are overly happy if I point out that it is indeed possible, while the 'right' answer would probably be 'you don't want to desing your program in this way'): Have a method that binds to the class if called from the class, and binds to the instance if called from an instance. > > > And _having_ to write a custom metaclass as the > > only way to get classmethods would be somewhat of an overkill. While Guido doesn't like this notation, I actually find it nice: class MyClass(object): class __metaclass__(type): def my_class_methods(cls): ..... def my_normal_method(self): .... (Donald Beaudry had a similar notation in his objectmodule.c, which also provided class methods). Thomas From lorenzo at mysurname.net Sat Mar 22 09:02:41 2003 From: lorenzo at mysurname.net (L. B.) Date: Sat, 22 Mar 2003 14:02:41 GMT Subject: Prime number algo... what's wrong? References: Message-ID: <52_ea.38106$Lr4.1172380@twister2.libero.it> "Rene Pijlman" ha scritto nel messaggio news:viqo7v85ijk78p4pf5c27iatq2t367v8vg at 4ax.com... > L. B.: > > if test != 0: > > x += 1 #still may be prime so go on trying > > elif test == 0: > > mayP += 1 #is not prime, test the second prime candidate > > else: > > Hmmm... so if test is not not 0 and it's not 0, what else can it > be? :-) I'll work with the neurons i have left on it! ;-) Thank You, Lorenzo From okumee at compuserve.de Tue Mar 18 04:26:04 2003 From: okumee at compuserve.de (mnietz) Date: 18 Mar 2003 01:26:04 -0800 Subject: calling a program without waiting for it to finish References: <6b9f8eda.0303170520.534f53f4@posting.google.com> <7tkda.69218$JE5.22506@news2.central.cox.net> Message-ID: <6b9f8eda.0303180126.7210eefc@posting.google.com> > You need to look at os.fork and os.spawn* and choose the method that suits > you best. > > regards I've tested this now, but in some cases I get an OSError Errno 11 Resource temporarily unavailable. I've been looking around, but none of the given advises (to many processes running, lack of swap) fits. Actually it works in one programm continuously, but not in another programm (with nearly the same code) Any proposals? From mats at laplaza.org Fri Mar 21 11:39:58 2003 From: mats at laplaza.org (Mats Wichmann) Date: Fri, 21 Mar 2003 16:39:58 GMT Subject: urllib.urlretrieve and PASV mode Message-ID: <3e7b3eba.90530195@news.zianet.com> Is there a way when using urllib.urlretrieve() to use passive mode for ftp transfers? It looks like this is supported in ftplib (set_pasv method), but not used by urllib. Unless I'm missing something. Mats Mats Wichmann From ark at gmx.net Wed Mar 12 12:44:42 2003 From: ark at gmx.net (Arne Koewing) Date: Wed, 12 Mar 2003 18:44:42 +0100 Subject: ReportLab and barcodes References: Message-ID: Svenne Krap writes: > > import reportlab.extensions.barcode.code128 > > > barks the following error : > > > Traceback (most recent call last): > File "", line 1, in ? > import reportlab.extensions.barcode.code128 > ImportError: No module named extensions.barcode.code128 > > > What is wrong ? did you install the reportlab extensions? the barcode stuff is not part of the reportlab-package get the extensions here: http://www.reportlab.com/extensions.html Arne From stephen.boulet at motorola.com Tue Mar 25 10:44:08 2003 From: stephen.boulet at motorola.com (Stephen Boulet) Date: Tue, 25 Mar 2003 09:44:08 -0600 Subject: Wishlist: string attributes Message-ID: <3E807948.5040401@motorola.com> Being a big fan of string methods, here's what I'd like to see for python strings: I can access string methods like (str.lower) but I would like to be able to access all string module attributes without importing the string module (like str.ascii_lowercase, str.whitespace, etc.). Not being a guru, are there any good reasons against? -- Stephen From syver-en+usenet at online.no Thu Mar 6 07:16:35 2003 From: syver-en+usenet at online.no (Syver Enstad) Date: 06 Mar 2003 13:16:35 +0100 Subject: Servicing events from a COM server References: Message-ID: jbrydon at precisiondesign.com.au (John Brydon) writes: > Sorry - I don't seem to have made myself clear. The COM object is > happily working as an out-of process server but I need a way of > passing to it the location of a function written in Python script so > that the script can service an event originating in the COM. Were I > doing this all in C++, for example, I would be passing to the COM > object a pointer to my external (client) function. Writing this in > Python, however, I can't see how to do this. Here is an example that services InternetExplorer events import win32gui import win32com import win32com.client import pythoncom import time class EventHandler: def OnVisible(self, visible): global bVisibleEventFired bVisibleEventFired = 1 def OnDownloadBegin(self): print "DownloadBegin" def OnDownloadComplete(self): print "DownloadComplete" def OnDocumentComplete(self, pDisp = pythoncom.Missing , URL = pythoncom.Missing): print "documentComplete of %s" % URL ie = win32com.client.DispatchWithEvents("InternetExplorer.Application", EventHandler) ie.Visible = 1 ie.Navigate("www.hegnar.no") # Important you have to pump messages in some way, because the # COM event mechanism depends on using window messages to dispatch # incoming calls print pythoncom.PumpMessages() #~ while ie.Visible: #~ time.sleep(2) #~ print 'looping' ie.Quit() -- Vennlig hilsen Syver Enstad From gerard.breiner at ias.u-psud.fr Mon Mar 17 05:05:31 2003 From: gerard.breiner at ias.u-psud.fr (Gerard Breiner) Date: Mon, 17 Mar 2003 11:05:31 +0100 Subject: how to send a form html by email ? Message-ID: Hello, Is someone has already made a script python so that to send a form by email from the web server ? thanks in advance. G?rard From http Wed Mar 26 12:19:43 2003 From: http (Paul Rubin) Date: 26 Mar 2003 09:19:43 -0800 Subject: critical sections protecting multiple processes (not threads) References: <12257ec4.0303260737.c42faf3@posting.google.com> Message-ID: <7xel4ujb9s.fsf@ruckus.brouhaha.com> davidccarson at hotmail.com (David Carson) writes: > Specifically, I want to test for the existence of a file and open if > non-existent in an atomic fashion. Obviously, if I cannot do this > atomically, it is possible for the file to not exist when the test is > done but to exist before the creation is done. In Un*x, the traditional way is to have a permanent file (call it "permfile") and link to it to create the lock file: success = link("permfile", "lockfile"); If the lockfile already exists, the link attempt will fail. If the lockfile doesn't exist, the link attempt will create it. This is atomic. From yaipa at yahoo.com Fri Mar 21 16:43:53 2003 From: yaipa at yahoo.com (yaipa h.) Date: 21 Mar 2003 13:43:53 -0800 Subject: Working with binary data, S-records (long) References: Message-ID: <6e07b825.0303211343.15889577@posting.google.com> Hans-Joachim, I amd looking at the PyTables modules for handing HDD binary sector data. http://groups.google.com/groups?dq=&hl=en&lr=&ie=UTF-8&group=comp.lang.python.announce&selm=mailman.1048090984.682.clpa-moderators%40python.org Cheers, -Alan "Hans-Joachim Widmaier" wrote in message news:... > We have a program to download (Flash-)Eprom images to an embedded device. > It reads the image data from a file in Motorola S-record format, augments > the image with some device specific data and sends the thing via a serial > port to the device, usually after downloading a small piece of software, > a second-stage bootloader, first, in the same manner. This program is > currently written in C and runs under Linux and in a DOS shell under older > Windows versions. Over the years said program accumulated a lot of cruft > and grew command line options like weed. Now my boss asked me to make a > new version which offers a GUI and runs under Windows 2000, XP as well. > Which is perfectly fine with me, 'cause after finding pyserial that'll be > more like a fun job (I've already written a similar thing in Python that > reads an ELF program file and downloads the needed section to another > device - it worked in a few hours; a C version would have taken weeks to > write and debug). > > Time to get to the topic. Reading S-records in Python is not all that much > fun (ok, it's neither in C). I've thought about doing it in C and > returning a string, but that would lose the address information. And > creating more complex python data types in C is something I've never done. > And I don't want to compile under Windows. Thus I wrote a pure Python > reader, which looks like (this is the whole class so far): > -------------------------- > import operator > > class SRecord: > def __init__(self, init=0xff, checkcs=True): > self.udata = [] > self.data = [] > self.tail = {} > self.offset = 0 > self.size = 0 > self.start = None > self.comm = [] > self.init = init > self.check = checkcs > > def readrecord(self, line): > """Lese eine Zeile als S-Record und gebe Adresse, Daten und Pr?fsumme zur?ck.""" > type = line[:2] > data = [int(line[i:i + 2], 16) for i in range(2, len(line), 2)] > cs = (reduce(operator.add, data) + 1) & 0xff # Mu? 0 ergeben > if type in ('S1', 'S9'): > adr = (data[1] << 8) + data[2] > fd = 3 > elif type in ('S2', 'S8'): > adr = (data[1] << 16) + (data[2] << 8) + data[3] > fd = 4 > elif type in ('S3', 'S7'): > adr = (long(data[0]) << 24) + (data[2] << 16) + (data[3] << 8) + data[4] > fd = 5 > elif type == 'S0': # Kommentar > return 'C', 0, data[3:-1], cs > else: > raise ValueError, "Kein g?ltiger S-Record" > if type > 'S6': # Startadresse > type = 'S' > else: # Daten > type = 'D' > return type, adr, data[fd:-1], cs > > def readrecords(self, records): > """Eine Liste (Zeilen) von S-Records lesen.""" > recno = -1 > for line in records: > recno += 1 > line = line.rstrip() > type, adr, data, cs = self.readrecord(line) > if cs and self.checkcs: > raise ValueError, "Pr?fsummenfehler in Record %d" % recno > if type == 'D': > self.udata.append((adr, data)) > elif type == 'S': > self.start = adr > else: > self.comm.append("".join(map(chr, data))) > if not self.udata: > return > self.udata.sort() > loadr = self.udata[0][0] > hiadr = self.udata[-1][0] + len(self.udata[-1][1]) > size = hiadr - loadr > self.data = [self.init] * size > for adr, data in self.udata: > dlen = len(data) > adr -= loadr > self.data[adr:adr + dlen] = data > self.offset = loadr > self.size = size > > ----------------------- > On my development machine (1.7 GHz) it's reasonably fast with a file worth > 100 KB. But I'm afraid it'll suck on our production machines, which run at > 166 MHz (give or take some). I thought about using array, but it's lacking > a method to create a big array without creating a list or string first. > > Anyway, does anyone see a way to speed this up? I'm not going to inline > readrecord(), as I don't care about 10 %. I'm asking if you see a real > flaw in my algorithm. > > > Whenever I play with binary data in Python, a dream of a mutable string > data type crops up. Doing byte fiddling with strings is quite ok as long > as the data is comparably small. But when the thing gets largish, the > slicing, copying and reassembling are getting increasingly inelegant, not > to say "un-pythonic." Even if that hypothetical mutable string type > wouldn't be returned by read() and wouldn't be accepted by write(), > conversion from and to normal immutable strings should be cheap. > > > Hope you're not distracted by the german comments, and just presuming you > know what S-records are, > > Hans-Joachim From martin at v.loewis.de Fri Mar 7 03:00:40 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 07 Mar 2003 09:00:40 +0100 Subject: How to remove files from a zip? References: Message-ID: Nev at Delap.com (Nev) writes: > Ok. I stuffed up. Truncate works perfectly. Now my tests are passing. > I'll write more tests, then I'll send you the code. Please submit patch to sf.net/projects/python; context or unified diffs are preferred. Regards, Martin From Gareth.McCaughan at pobox.com Wed Mar 26 16:24:34 2003 From: Gareth.McCaughan at pobox.com (Gareth McCaughan) Date: Wed, 26 Mar 2003 21:24:34 +0000 Subject: Conjugate gradients minimizer References: <3K9ga.7304$kU.2710@nwrdny01.gnilink.net> Message-ID: Carl Banks wrote: > But let me recommend something else. You have only a thousand > variables, which is really not a lot. Conjugate gradient is best > suited for systems of millions of variables, because it doesn't have > to store a matrix. It doesn't scale down well. > > So, unless you have reason to believe conjugate-gradient is specially > suited to this problem (indeed, I have heard of an atomic structure > problem that was like that), or if you plan to scale up to DNA > crystals someday, use the BFGS method instead. I concur. If it turns out that the overhead from BFGS *is* too much for some reason, you might also consider something intermediate between conjugate gradient and BFGS, such as L-BFGS. But it's not true that BFGS requires inverting a matrix at each step. The matrix you maintain is an approximation to the *inverse* of the Hessian, and no inversion is necessary. -- Gareth McCaughan Gareth.McCaughan at pobox.com .sig under construc From blakeg at metalink.net Thu Mar 13 09:01:35 2003 From: blakeg at metalink.net (Blake Garretson) Date: 13 Mar 2003 06:01:35 -0800 Subject: GCD in standard library? References: Message-ID: Tim Peters wrote in message: > What advantage would that be? The speed of gcd on large integers is > dominated by the speed of large-integer arithmetic, and that's coded in C no > matter how it's *driven*. I learn something new every day. :) > > I guess I'm wondering why it isn't there. > Because it's trivial to code in (literally) a few lines of Python. Yeah, I guess, but I figured it is in the same category as abs(). > ... BTW, I've never seen another user community > so keen to lobby for inclusion of every 1-, 2- and 3-line function they can > dream up. I hope I didn't sound like I was lobbying. Like I said, I certainly don't want to bog down the standard library with everyone's pet function. I was just wondering what *why* GCD isn't there. I actually have quite a bit of faith in you and the other Python developers, so I always assume there's a good reason for stuff in (or not in) Python. :) Python's design is why I use it over other languages 98.2% of the time. Blake G. From Vector180W at netscape.net Fri Mar 21 00:29:32 2003 From: Vector180W at netscape.net (vector) Date: Fri, 21 Mar 2003 16:29:32 +1100 Subject: setting colour and font for scrolledText widget label Message-ID: <3E7AA33C.5000706@netscape.net> Hi is it possible to set the colour,font and size of the label_text in a scrolledText widget? From gh at ghaering.de Sun Mar 23 19:45:59 2003 From: gh at ghaering.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Mon, 24 Mar 2003 01:45:59 +0100 Subject: handling boolean values from a c api In-Reply-To: References: Message-ID: <20030324004559.GA12713@mephisto.ghaering.test> * Bryan [2003-03-23 16:37 -0800]: > i have a function in python that returns a boolean. i'm currently > using PyInt_Check to verify the return value, but this limits me to > integers and True/False (in 2.2). is there an easy way to tell the > boolean value of any aritrary object in 2.2? [...] PyObject_IsTrue Gerhard -- mail: gh at ghaering.de web: http://ghaering.de/ From revanna at mn.rr.com Tue Mar 4 14:23:10 2003 From: revanna at mn.rr.com (Anna) Date: Tue, 04 Mar 2003 13:23:10 -0600 Subject: c enum - how to do this in python? References: Message-ID: On Sat, 22 Feb 2003 07:50:16 +0000, Alex Martelli wrote: > Anna wrote: > >> On Fri, 21 Feb 2003 23:50:12 +0100, Rene Pijlman wrote: >> >>> "yelims tluafed .p.l.c eht rof detanimoN"[::-1] >> >> Seconded! >> >> 'annA'[::-1] >> >> -- >> (Gee - I hope that's right... I can't run it in IDLE cuz I get an error >> that it's not integers... and I'd try from future import but I don't >> know what it's called...) > > It's only in Python 2.3 (latest release, 2.3a2, the second alpha), not in > any version of 2.2 (not even with "from __future__ import"). Oh. Never mind... > Python 2.3 is not yet recommended for production use, being an alpha > release. It does have a few neat things such as this one (and sets and > enumerate and itertools) and is faster than 2.2, so for play/study > purposes downloading it and installing it might be fun, but be sure to > keep a 2.2.2 around for "production use"!-) Sets? So I can write "dogs is dogs and cats is dogs but them turtles is insects" in Python? Kewl! Hmmm - now I gotta figure out how to put two different versions of Python on my box without one overwriting the other... and figure out how to tell it which one to call. Ohboy - new challenges... > "from __future__ import" is meant to introduce features gradually when > they BREAK the compatibility of some old code. When that is the case, > then for at least one release cycle the old behavior remains the default > and you have to ask for the new one in this explicit way. But for > additions that do not break existing code, there is no need for the > mechanism, so it's not used. Oh. Thank you. > Reversing strings with [::-1] is more or less a divertissement, Actually, the more I play with it, the better I like it. It still looks wierd though... and I still want it to have a NAME. I like names. Names are a Good Thing. So - what's this mutant smilie called? > generalized slicing also has serious uses. Say for example you want to > return the LAST item in a list that meets some condition. With > generalized slicing in Python 2.3 it's easy: > > def lastone(somelist, condition): > for item in somelist[::-1]: > if condition(item): return item > raise ValueError, "No item matches the condition" Can't you do: def lastone(somelist, condition): for item in somelist.reverse(): if condition(item): return item raise ValueError, "No item matches the condition" Wouldn't that do the same thing? Confused, Anna From aleax at aleax.it Tue Mar 18 11:39:12 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 18 Mar 2003 16:39:12 GMT Subject: Witch globalizacion (was: RE: Recommended Linux Laptops, supp liers?) References: Message-ID: sismex01 at hebmex.com wrote: >> From: Alex Martelli [mailto:aleax at aleax.it] >> Sent: Tuesday, March 18, 2003 8:33 AM >> >> ...And to think there are people busy >> protesting against "globalization"... *WICH* globalization?!... >> >> Alex > > "Witch" globalization. Hmmm, I _am_ in favour of globalizing witches, too, but as it happens it was an H I dropped here, not a T... Alex From LogiplexSoftware at earthlink.net Thu Mar 20 11:43:51 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 20 Mar 2003 08:43:51 -0800 Subject: Is Python the Esperanto of programming languages? In-Reply-To: <3E79A948.E6C688A3@engcorp.com> References: <200303192233.30383.andy@wild-flower.co.uk> <8b5e42a6.0303192123.2f7b5187@posting.google.com> <3E79728C.AED36CCD@alcyone.com> <3E79A948.E6C688A3@engcorp.com> Message-ID: <1048178631.1283.15.camel@software1.logiplex.internal> On Thu, 2003-03-20 at 03:43, Peter Hansen wrote: > Erik Max Francis wrote: > > > > Alex Martelli wrote: > > > > > Levente Sandor wrote: > > > > > > > Searched the web for esperanto. Results 1 - 10 of about 1,260,000 > > > > > > Something strange here -- I'm seeing only 151 K hits... (?!) > > > > I'm getting 1.26 million as well. > > Google is screwed... I'm getting "about 188,000" right now... thought > it might make a difference whether Google redirects you to a national > version (www.google.ca for me, probably www.google.it for Alex) but > it doesn't, and by using the numeric address for the .com version I > was able to override this behaviour and it's the same: 188,000... Language preferences? -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From dave at pythonapocrypha.com Mon Mar 24 16:15:13 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Mon, 24 Mar 2003 13:15:13 -0800 (PST) Subject: Const in python? In-Reply-To: References: Message-ID: On Mon, 24 Mar 2003, Anand wrote: > Wouldn't it be a nice idea to have constants in Python? IMO, no. (BTW, this has come up many times before - check the Google archives). > I think when programmers intend some of the variables to be const, the > behavior shouldn't be allowed to be altered. When I intend a variable to be constant it is spelled LIKE_THIS otherwise it is spelled likeThis This works very well in practice and I highly recommend it - no problems yet! :) > It would be nice to declare 'maxint' in sys to be a const rather than > allowing programmers to change the value and cause the program to fail > as a result of this change. I disagree. Assume you have a variable SOME_CONST. By it's spelling I can see that it is constant, so changing it is a no-no. Now, if I go and change it anyway, then one of these is probably true: #1 I know what I'm doing, and realize that changing it might be dangerous, but for some reason I need to change it anyway (e.g. I'm debugging a problem in a production system and changing this value will really help me out of a jam). #2 I am a sloppy programmer and lack the discipline to follow coding standards, good practicies, common conventions, etc. #3 I'm ignorant of the "all caps means constant" convention. If #1 is true, then not being able to change the "constant" is a real bummer, and really annoying. If #2 is true, then my sloppiness will be manifest in so many other areas that changing constants will be the least of my problems, and I'll weasle my way around all sorts of "best practice" fences you put up anyway. If #3 is true, it's trivial to educate me. At least in this respect (and I suppose others, like "private" members of classes), Python caters to the programmer in #1. Thank goodness it does not cater more towards the #2 programmer (something that would be especially annoying to the #1 type of programmers) it's no fun to be restricted because _somebody else_ is a bozo. -Dave From tjg at craigelachie.org Sat Mar 29 14:04:05 2003 From: tjg at craigelachie.org (Timothy Grant) Date: Sat, 29 Mar 2003 11:04:05 -0800 Subject: A bug I found in Python In-Reply-To: <20030329174134.GA21226@meson.dyndns.org> References: <20030329174134.GA21226@meson.dyndns.org> Message-ID: <200303291104.05791.tjg@craigelachie.org> On Saturday 29 March 2003 09:41 am, Jp Calderone wrote: > I have used Python for many minutes now, but I have recently discovered > some surprising behavior! > > When I attempt to add two integers together, the result is a third, > different integer! Saying you discovered a bug in Python and then not posting all your code or thoroughly explaining the unexpected result is not a particularly good way to win friends or influence people. I would suggest typing your code into the interactive interpreter and then cutting and pasting the surprising results. -- Stand Fast, tjg. Timothy Grant www.craigelachie.org From gh at ghaering.de Sat Mar 29 17:14:05 2003 From: gh at ghaering.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sat, 29 Mar 2003 23:14:05 +0100 Subject: Is Python overhyped (just like Java)? In-Reply-To: References: Message-ID: <20030329221405.GA12402@mephisto.ghaering.test> * Ajay na [2003-03-29 21:38 +0000]: > I want someone to give a solid and intelligent argument about why I > should switch from C++ to Python! I couldn't care less about which programming language you use. So I propose you do some internet research yourself. It's not like Python vs. C++ hadn't been discussed here in the past. Gerhard -- mail: gh at ghaering.de web: http://ghaering.de/ From donn at drizzle.com Fri Mar 14 00:50:17 2003 From: donn at drizzle.com (Donn Cave) Date: Fri, 14 Mar 2003 05:50:17 -0000 Subject: Has anyone created a simple POP3 and SMTP server using TWISTED? References: <0001HW.BA9660EB0012EC36F0407600@netnews.attbi.com> <1047595161mnewscandiazoo@attbi.com> Message-ID: <1047621015.523173@yasure> Quoth William Park : | Zoo Keeper wrote: |> BeOS is my favorite OS, what can I say? It is my preference. I also |> have a Mac running OS X, and I use Windows XP and HP Unix boxes at |> work. |> |> But I don't know what that has to do with my original question? | | Well, if you have to ask this question on Usenet, then writing your own | STMP/POP3 daemons from scratch may not be the best option for you. Ask on comp.lang.python, has anyone implemented SMTP or POP servers in Python? Who's obtuse here? | So, download Fetchmail/Sendmail/Gnu-pop3d, and compile. Lots of details | have been worked out in these programs over the years by many people. Oh, right. Sendmail wouldn't work for sure, and it's a terrible choice for a 3 person site anyway. Don't know about the other two, but I'd guess very strong odds of some platform incompatibility that would be the end for someone who only knows Python. A simplistic SMTP and POP3 implementation isn't a huge undertaking, might be a fun project. Donn From intentionally at blank.co.uk Tue Mar 11 06:46:55 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 11 Mar 2003 11:46:55 +0000 Subject: Summary of PEP 308 Vote for a Ternary Operator References: <3e6dba80$1_1@news.bluewin.ch> Message-ID: On Tue, 11 Mar 2003 11:29:16 +0100, "Samuele Pedroni" wrote: >I agree wholeheartedly, if that's not the interpretation that the vote >should receive, then the vote was BIASED. I think you may be overreacting. All the votes are available. If you are worried about the totalling, list what you think the totals should be and why. If your version has merit, I'm sure it will get noticed. It's one of the benefits of an open vote. From peter at engcorp.com Sun Mar 23 22:29:35 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Mar 2003 22:29:35 -0500 Subject: py2exe for Python2.2 looking for Python21.dll References: <6bd9f01b.0303231845.3224294d@posting.google.com> Message-ID: <3E7E7B9F.73E3D3B0@engcorp.com> sameer wrote: > > I am trying to compile my application to an exe using py2exe and > Python22. During the compilation, I get a missing dll error telling > me that Python21.dll could not be located. I have checked the windows > registry and there are no references to Python21.dll anywhere. I have > also uninstalled python22 and reinstalled it, and then reinstalled > py2exe for Python22, and I still get the same error. Does anyone have > any suggestions? As I recall, we encountered something similar, using a network installation of Python. Our approach has been to install under C: on one machine but then copy the directory to a network folder shared by everyone, and remove the registry entries from that machine. At one point, we had trouble using py2exe on that machine after upgrading to a new version, and eventually tracked it down to python DLLs that had been installed in C:\windows\system. Maybe removing those will help. -Peter From daniel.rawson.take!this!out! at asml.nl Wed Mar 5 08:19:18 2003 From: daniel.rawson.take!this!out! at asml.nl (Dan Rawson) Date: Wed, 05 Mar 2003 08:19:18 -0500 Subject: 'strip' documentation for beginners In-Reply-To: References: Message-ID: Gerrit Holl wrote: > Dan Rawson schreef op dinsdag 4 maart om 13:36:17 +0000: > >>The documentation for string.strip states that it can take an optional >>second parameter, but it doesn't appear to work: >> >> >>07:23:06 $ python >>Python 2.2.1 (#1, Sep 12 2002, 16:24:44) > > ~~~~~ > > >>Or did I miss something obvious??? I DID do a search in the What's New in >>the 2.2.2 documentation. > > > But you are running 2.2.1. Not sure whether that's the reason though. > > yours, > Gerrit. > It does work as advertised in 2.2.2. I also finally found it in the 2.2.2b1 section of Misc/NEWS (but NOT in the "What's New" section of the HTML / downloadable docs). I also figured out how to implement it with a translate() instead; always something new to learn ;-) Thanks for everyone's help! From snarflemike at yahoo.com Wed Mar 12 22:23:57 2003 From: snarflemike at yahoo.com (Mike Silva) Date: 12 Mar 2003 19:23:57 -0800 Subject: Flying With Python (Strong versus Weak Typing) References: <37a869bc.0303102102.4533973@posting.google.com> <3E6E9E4E.50405@removethis.free.fr> Message-ID: <20619edc.0303121923.5d744622@posting.google.com> laotseu wrote in message news:<3E6E9E4E.50405 at removethis.free.fr>... > > Second thing : > Ariane crashed because of a bug in an ADA module. ADA is very strongly > *and* statically typed. This is not correct. There was no bug in the software, it performed exactly as designed. The problem was a combination of brittle design (single point failure) and improper code reuse. To claim there was a bug is akin to changing a 5 Amp circuit to a 10 Amp circuit, and then blaming the 6 Amp fuse when it blows. > > Conclusion : your question doesn't make any sens, and the answer won't > help you. Choose whatever language seems the most suited for the task, > and test, test, test, and then test again. Test, test, test and then test again will, by itself, never be suitable for safety-critical applications. Mike From tebeka at cs.bgu.ac.il Tue Mar 25 07:10:44 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 25 Mar 2003 04:10:44 -0800 Subject: Passing params to single instance of wxApp References: <3088fc9a.0303241702.11bdbe2e@posting.google.com> Message-ID: <33803989.0303250410.35e12368@posting.google.com> Hello, > I want my app to only allow one instance, the problem is that it is > associated with a file type so when another of that file type is > opened I end up with two instances. I used the wxSingleInstanceChecker > to stop this from occuring but I really want to pass the params (i.e. > new filename) to the running app. Any ideas? I'd use some sort of RPC to notify the other application (TCP/IP with known port?) just before closing the new one. Ugly but should work. HTH. Miki From cpl.19.ghum at spamgourmet.com Fri Mar 21 03:24:21 2003 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Fri, 21 Mar 2003 09:24:21 +0100 Subject: Working with binary data, S-records (long) References: Message-ID: Hans Joachim, > Now my boss asked me to make a new version which offers a GUI > and runs under Windows 2000, XP as well. > ----------------------- > On my development machine (1.7 GHz) it's reasonably fast with a file > worth 100 KB. But I'm afraid it'll suck on our production machines, > which run at 166 MHz (give or take some). I see a quite big flaw _before_ your algorithm: Windows 2000 or Windows XP with a Python Programmed GUI on a 166MHz Computer will suck no matter what you optimize in your record-reading- algorithm. Harald From ny_times_ at hotmail.com Thu Mar 20 20:18:38 2003 From: ny_times_ at hotmail.com (Brian) Date: 20 Mar 2003 17:18:38 -0800 Subject: Help - python headers question. Message-ID: <5aa40724.0303201718.570d1d1@posting.google.com> Hello. I'm new to linux, just installed Mandrake 9. I have python 2.2, however when i went to install pygtk 1.99.15 it failed configure and said "error: could not find python headers." What does this mean and how can i fix it? I tried reinstalling python, which didn't help. Also, programs where i type python compile correctly using the python engine. thanks! From me at privacy.net Mon Mar 31 00:40:25 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Mon, 31 Mar 2003 17:40:25 +1200 Subject: Use Pyrex instead (Re: newbie at SWIG, help needed with typemaps) In-Reply-To: References: Message-ID: Josh wrote: > I hope this is not OT in this group. If it is, do let me know and I'll try > my luck elsewhere. Seems pretty much on-topic to me... > I have a simple C function. When called from a C > program, void carr is handed a properly malloc'ed double pointer and an int > len. carr then proceeds to fill up the first len locations of the double > array represented by double *sd. When called from python, I just want to > pass the len as in (in module trl) trl.carr(len). In that case, the wrapped > C function should then proceed to dynamically allocate the double array, > fill it up, convert it to a Python object, and return a list of len > elements. Instead of SWIG, you might prefer to use Pyrex to wrap your C code: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ This is exactly the sort of problem I designed Pyrex to solve. The Pyrex code for it would look something like this (warning, untested): cdef extern void *malloc(int) cdef extern void free(void *) cdef extern void carr(double *, int) def pycarr(int n): cdef double *a cdef int i a = malloc(n * sizeof(double)) carr(a, n) result = [] for i from 0 <= i < n: result.append(a[i]) free(a) return result I hope you'll agree that this is a LOT saner than messing about with SWIG! (A minor problem is that you can't currently call the Python function "carr" or it will conflict with the C one. That will be fixed in a later release...) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From peter at engcorp.com Thu Mar 6 22:47:00 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Mar 2003 22:47:00 -0500 Subject: Palm Conduit References: <3e67da95$1@news.terra.com.br> Message-ID: <3E681634.6EE56EB5@engcorp.com> Leonardo Santagada wrote: > > Does someone know how to do a palm conduit in python for windows? Maybe > someone knows a lib that can do that. Thanks What does http://www.google.ca/search?q=python+palm+conduit show you? From remi at remove-me.python-hosting.com Mon Mar 31 15:07:58 2003 From: remi at remove-me.python-hosting.com (Remi Delon) Date: Mon, 31 Mar 2003 22:07:58 +0200 Subject: [ANN] Python-Hosting.com: new Hosting Provider specialized in Python References: <3e885514$0$2719$626a54ce@news.free.fr> <7876a8ea.0303311127.56d89096@posting.google.com> Message-ID: <3e88a01f$0$2727$626a54ce@news.free.fr> > By the way, when you refer to Firebird as an "embedded" database, do > you really mean you're using it in embedded mode, or is it running as > a persistent server? If the latter, is it SuperServer or Classic? I mean using it in embedded mode, with the python wrapper kinterbasdb, like this: import kinterbasdb con = kinterbasdb.connect(dsn='/home/myLogin/test.db',user='sysdba', password='pass') cur = con.cursor() cur.execute("select * from people order by age") print cur.fetchall() So users can put the file containing their database data (ex: test.db) in their HOME directory and use kinterbasdb as they want. Regards, Remi. remi at remove-me.python-hosting.com ---------------------- Specialized python hosting: http://www.python-hosting.com Python application server: http://www.cherrypy.org Free CherryPy hosting: http://www.freecherrypy.org ---------------------- From peter at engcorp.com Thu Mar 20 13:58:49 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Mar 2003 13:58:49 -0500 Subject: Is Python the Esperanto of programming languages? References: <200303192233.30383.andy@wild-flower.co.uk> <8b5e42a6.0303192123.2f7b5187@posting.google.com> <3E79728C.AED36CCD@alcyone.com> <3E79A948.E6C688A3@engcorp.com> Message-ID: <3E7A0F69.2AF6DB4C@engcorp.com> Cliff Wells wrote: > > On Thu, 2003-03-20 at 03:43, Peter Hansen wrote: > > Erik Max Francis wrote: > > > > > > Alex Martelli wrote: > > > > > > > Levente Sandor wrote: > > > > > > > > > Searched the web for esperanto. Results 1 - 10 of about 1,260,000 > > > > > > > > Something strange here -- I'm seeing only 151 K hits... (?!) > > > > > > I'm getting 1.26 million as well. > > > > Google is screwed... I'm getting "about 188,000" right now... thought > > it might make a difference whether Google redirects you to a national > > version (www.google.ca for me, probably www.google.it for Alex) but > > it doesn't, and by using the numeric address for the .com version I > > was able to override this behaviour and it's the same: 188,000... > > Language preferences? Good thought, or even browser differences. Using IE 6.0 SP1 from a Canadian site and with "en-us" as the preferred language, I'm getting 204,000 hits today... Hmm... maybe just load on Google? It must surely be cutting short the search under heavy load conditions, so the "about 204,000" thing might be much different at other times. On the other hand, looking at the time of my above posting, I strongly doubt that's the case. Other ideas? -Peter From dave at boost-consulting.com Mon Mar 10 22:27:59 2003 From: dave at boost-consulting.com (David Abrahams) Date: Mon, 10 Mar 2003 22:27:59 -0500 Subject: Python Interpreter with multiple Python Programs References: Message-ID: Gerhard H?ring writes: > Anthony Irwin wrote: >> Hi, >> >> I have recently started learning Python and have a question about the >> interpreter, if I run multiple Python programs will the Python interpreter >> load for each program I run. >> >> e.g. If I run 4 Python programs will 4 Python interpreters load or 1 >> interpreter for all 4 programs. > > 4 interpreters will be loaded. Note that on some platforms that may mean you only have one shared copy of the Python code in main memory, though. -- Dave Abrahams Boost Consulting www.boost-consulting.com From gustav at morpheus.demon.co.uk Mon Mar 17 16:17:47 2003 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: Mon, 17 Mar 2003 21:17:47 +0000 Subject: LDAP server in Python References: Message-ID: <3cllelqc.fsf@morpheus.demon.co.uk> Michael Str?der writes: > Moore, Paul wrote: >> I'm looking at LDAP as a possible service for some projects, and >> I'm struck by the fact that I know pretty much nothing about it. >> On the basis that I always learn better by playing about with >> things rather than just reading about them, I'd like to set up a >> sandbox environment. > > Do you plan to develop an LDAP-enabled application? No, not really. > Then I'd recommend to run OpenLDAP 2.1.16 as test server because > it's the most strict LDAP server around. You will definitely learn > the right things. Hmm. I'm not sure "strict" is what I want. The background is that Oracle are moving their database naming service from a proprietary protocol (Oracle Names) to LDAP. The trouble is that (as is usual with Oracle) the documentation is a bit opaque, so I'd rather try it out and experiment. But Oracle's LDAP server takes a bit of setting up (specifically, it needs a server machine bigger than my laptop :-() so I thought I'd try something smaller and simpler for experimenting with. My idea was that a Python implementation would be helpful as I could follow the implementation if I needed to, to understand what was going on. > Hmm. Depends on what you're planning to do. If you plan to do serious > development of LDAP applications you SHOULD test against the full > stuff. As you see, it's pretty much the opposite. When (if) I go live, it will be with Oracle Internet Directory, or Active Directory, and I won't have much choice. I'm just trying to get a feel for whether what I can do with the client-side justifies the server-side pain, or whether I should stick with Oracle Names until it's finally desupported for good. Oracle Names is basically a fairly trivial name->value mapping, whereas LDAP looks far more complex. I'm not sure if I can justify the extra complexity. On the other hand, I may be able to do useful extra things with LDAP, such as storing extra data for other clients. At the moment, none of the "overview" documents on LDAP which I've seen have given me a feel for how to make "trivial" use of it (understandably, they focus on the richness of the structure, which is precisely what I'm not interested in...) Thanks for your help, I'll certainly look at the compatibility website you mentioned. Paul -- This signature intentionally left blank From me at privacy.net Tue Mar 18 22:34:38 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Wed, 19 Mar 2003 15:34:38 +1200 Subject: type(type) is an object, not an instance In-Reply-To: References: Message-ID: Sip wrote: > I don't know if this can be called a bug, but type(type) is the type > object, not an instance of it Actually, it's both! It's an instance of itself: Python 2.2 (#1, Jul 11 2002, 14:19:37) [GCC 3.0.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> isinstance(type, type) 1 -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From db3l at fitlinxx.com Tue Mar 25 11:29:37 2003 From: db3l at fitlinxx.com (David Bolen) Date: 25 Mar 2003 11:29:37 -0500 Subject: is win api available in native python References: <3e7e5a37_4@newsfeed> <33803989.0303240746.facc13@posting.google.com> <3e7faa23_4@newsfeed> Message-ID: "Phil" writes: > wouldn't that be the windows api extension program I mentioned. I > didn't want such a huge, but I'm sure useful, extension. Also I am > trying to stick to the non os specific python. Just to clarify, you're trying to stick to a non-OS specific routine in order to implement an OS-specific request? Sounds "ambitious". :-) Ok, hanging up a dynamically dialed connection or shutting down the system may conceptually be something that is common cross-platform, but the devil is in the details and I don't believe there's any high level common API to accomplish such tasks - with the possible each system may offer - in a generic way. BTW, you don't mention your Windows platform, but the InternetAutodialHangup API is a Windows CE specific API. I haven't worked on the CE platform, so I'm not certain what other limitations (if any) may exist with Python there. However, there are other RAS APIs (like RasHangup) that are more cross-version and would let your code operate on other Windows versions as well. If you really want to avoid win32all, there are some other options, but they're still going to be Windows-specific because of the nature of what you are trying to do (e.g., given that the routines you want to access are specific to Windows). 1. You could create your own extension for Python that strictly wrapped the win32 entry points you wanted. This would involve building your own custom extension and wrapping the functions in question. Then you could just import your module and use those functions. The resource overhead would be minimal (needing to include your pyd file) but you'd need a development environment to create the extension and you'd be maintaining non-Python code. 2. You could find external utilities (or write one) to call the APIs and then use them. I believe that even XP has an existing "rasdial" command that can kill an existing connection (execute "rasdial /d" on the system in question). And you can get a "shutdown" utility from several places, including the Windows resource kit. You could then simply execute those external utilities when you needed the functionality (using for example, os.system() or os.popen()). 3. You could use an existing add-on module such as calldll or ctypes to explictly load the relevant Win32 DLL and call the routine. This is effectively a generic way to accomplish (1) without having to write any extension module code on your own. calldll is an older module, with ctypes being more current, and more actively maintained. They both provide generic ways for loading and accessing entry points in Win32 DLLs (and it looks like ctypes is actually now cross-platform). calldll: http://www.nightmare.com/software.html (Alex Martelli put a 2.2 binary online at http://www.aleax.it/Python/calldll_22.zip) ctypes: http://starship.python.net/crew/theller/ctypes.html But to be honest, things work very smoothly with the win32all extensions, and they're so prevalent for any systems that really interact with the win32 environment at all with Python, that I wouldn't hesitate to install them. If you're worried about redistribution size, realize that if you wrap up a particular application you won't need the entire win32all package, but just a few pyds and dlls. In win32all, you'd accomplish the hangup with the win32ras.Hangup method (you can use win32ras.EnumConnections to get a handle for the active connection), and the shutdown with win32api.ExitWindows or win32api.ExitWindowsEx. > I was hoping python would have a way to call the loadlibrary function > and whatever mac and unix equivalent would be. More of a lowlevel os > starting point to execute dll functions. I am not familiar with unix or > mac but it seems like an obvious need. Not the whole api just a way to > build your own. That's more or less item (3) above, and it looks like recently ctypes even became cross platform (not that the methods you want to call are cross-platform), so I'd definitely suggest taking a look at it. -- -- 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 adalke at mindspring.com Sun Mar 2 14:35:11 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 2 Mar 2003 12:35:11 -0700 Subject: Found urllib strangeness with redirects - is this really a problem? References: Message-ID: John J Lee: > If anybody wants the 'right' behaviour (taking into account the > (universal) browser behaviour and careful reading of the HTTP RFCs (in > fact the most recent HTTP RFC is 2616)), ClientCookie already does this if > you use the urllib2-like callables. Ahh, my misunderstanding of the how the spec implies how to do things. Ignore my reponse. Andrew dalke at dalkescientific.com From andersjm at dancontrol.dk Thu Mar 27 03:36:34 2003 From: andersjm at dancontrol.dk (Anders J. Munch) Date: Thu, 27 Mar 2003 09:36:34 +0100 Subject: doing hundreds of re.subs efficiently on large strings References: <3E80CE1D.1000200@NOmyrealCAPSbox.com> <3e818b47$0$31942$edfadb0f@dread12.news.tele.dk> <3E82911D.3030807@NOmyrealCAPSbox.com> Message-ID: <3e82b7e9$0$31932$edfadb0f@dread12.news.tele.dk> "nihilo" wrote: > How do I use finditer to find the unmatched parts also (the stuff > between the matches)? It looks to me like it just gives you access to > the stuff that is matched, but maybe I'm missing something. Look at start() and end(). >>> s = 'hi nihilo' >>> for m in re.finditer('(n)|(o)', s): ... print m.start(), m.end() ... 3 4 8 9 >>> s[:3], s[3:4], s[4:8], s[8:9], s[9:] ('hi ', 'n', 'ihil', 'o', '') >>> - Anders From imbosol-1047402492 at aerojockey.com Tue Mar 11 12:44:10 2003 From: imbosol-1047402492 at aerojockey.com (Carl Banks) Date: Tue, 11 Mar 2003 17:44:10 GMT Subject: "is" and "==" References: Message-ID: Dagur P?ll Ammendrup wrote: > I was wondering when == should be used and when "is". I like using "is" > when comparing strings and stuff but maybe I shouldn't? Try this at the prompt: >>> "ab" is "a"+"b" 0 You should use "is" only when explicitly checking if a and b are same object (that is, same location in memory, and same .id()). Otherwise, use ==. -- CARL BANKS From noway at sorry.com Tue Mar 4 08:10:55 2003 From: noway at sorry.com (Giovanni Bajo) Date: Tue, 04 Mar 2003 13:10:55 GMT Subject: Can __iter__ be used as a classmethod? References: Message-ID: "Alex Martelli" ha scritto nel messaggio news:n519a.3620$zo2.111194 at news2.tin.it... > E.g., if X is a class, X.__iter__ affects iterations on INSTANCES > of X, *NOT* iterations on X itself; > the latter are instead affected > by type(X).__iter__, if any. type(X) is X's metaclass -- unless > it's a custom one, type(X) will be the built-in named 'type', which > has no special method __iter__. Let's talk about new-style classes only (otherwise I could blow a fuse before I understand something ;) Is it possible to add (class) methods to class objects by defining them in a custom metaclass, or is the metaclass used only to lookup special methods (__iter__, etc.) for operations executed on class objects? Since I define methods of the instances within the class (object's type) definition, I would think that I might define methods of the class objects within the metaclass (class' type) definition. Given: def A(object): def __iter__(cls): pass __iter__ = classmethod(__iter__) how do you classify (word joke not intended) the (rebound) __iter__? Is it a class method of class A? Is it still used for iterations on instances of A? How does the classmethod() affected the type and the semantic of __iter__? >Attributes that you look up on a specific object are not the >same thing as special-methods that are looked up (on the TYPE >of the object -- except for classic classes) by operations >that you perform on the object. Normal method calls use normal >attribute lookup. Probably I'm confused because to me: class B(object): def f(self): pass def __iter__(self): pass f and __iter__ seems to be of the same kind (type). But you say that B().f() is doing a lookup on the specific instance (and the lookup resolves to B.f), while iter(B()) is looked up on the TYPE of the object, but it resolves to B.__iter__ as well. So, if the lookup are performed on different entities, why do they resolve in the same way? Is it just because they are not rebound after the instance is created? Would that mean that rebinding B().__iter__ has no effect since B.__iter__ is always looked up when iterating over instances of B(), while B().f() can be freely rebound? Giovanni Bajo From just at xs4all.nl Fri Mar 21 10:18:47 2003 From: just at xs4all.nl (Just) Date: Fri, 21 Mar 2003 16:18:47 +0100 Subject: accessing file properties References: Message-ID: In article , kevin at fonner.net (Consistomagus) wrote: > I want to be able to access the properties of a file. Specifically > the Created Date and Time, Modified Date and Time, and Accessed Date > and Time. What would you guys figure to be the best most cross > platform way of doing this? os.stat() Just From tim.one at comcast.net Tue Mar 25 13:41:45 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 25 Mar 2003 13:41:45 -0500 Subject: Debug python for Windows? In-Reply-To: <49CCE87D4A3BD511B1C500D0B7B69C0601334F04@exchange.youmeus.com> Message-ID: [Sean Slattery] > Actually - the building bit is documented well enough (although I > will admit I didn't know about the Build->Batch... option in MSVC), > it's the installation that I was hoping for more direction on. Hmm. You didn't mention installation last time, and I'm unclear on your meaning. If you're just trying to test code, installation in any conventional sense isn't needed: the Python you just built runs fine from the PCBuild directory. No file copying, moving, or registration is needed. If you're building extension modules of your own, it's conventional to plant a copy of their DLLS in the PCbuild directory too (so the freshly built Python there can find them). > I'll just try to make it look like other installations of Python I've > seen: > > * create a top level Python directory and put the .exe's in there > * create a Python\libs and put the *.lib in there > * create a Python\DLLs directory and put the *.pyd and *.dll in there > * create a Python\include and put the *.h in there > > etc. etc. You could do that too, if you like. > I suspect there are some environment variables I need to set too The PLabs Python distribution doesn't need any envars set, nor does it need any registry settings. > - in order to get wxPython to compile ... That one I don't know anything about. From perverted_orc at softhome.net Mon Mar 10 14:13:32 2003 From: perverted_orc at softhome.net (Perverted Orc) Date: Mon, 10 Mar 2003 21:13:32 +0200 Subject: Wildcard for string replacement?!?! Message-ID: Hello everyone! I 'm working for over a week on this script but I can't make my way out. The whole idea is to replace (better say delete) anything that stands between the and tag of an html file. from string import * pname=raw_input("Give path\ :") #The path name where the original file is and the new to be saved fnameo=raw_input("Give file to change :") fnamen=raw_input("...Save As :") old_file=pname+fnameo #Joining path and file name new_file=pname+fnamen #Joining path and file name inp=open (old_file,'r') outp=open(new_file,'w') for line in inp.readlines(): nline=replace(line,"?????"," ") outp.write(nline) print "1 file changed and saved..." inp.close() outp.close() Can anyone tell me what to fill in the ????? area? I tried any possible combination with "." and "*" but didn't work. Please help!!! From gh at ghaering.de Wed Mar 19 13:57:47 2003 From: gh at ghaering.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Wed, 19 Mar 2003 19:57:47 +0100 Subject: Question regarding a recent article on informit.com In-Reply-To: References: Message-ID: <20030319185746.GC1361@mephisto.ghaering.test> * Ben S [2003-03-19 18:50 -0000]: > An article called "Examining Python 2.3: New Additions" on > www.informit.com had the following to say: > > "Python now includes iterators, generators, list comprehensions, nested > scopes, type unification-and complete Unicode compatibility. The older > functional programming style constructs, such as map, filter, reduce, > and lambda are deprecated, even if it's unlikely that they will > disappear. " > > Is this second sentence true, or is that just an opinion from someone someone == Guido > who favours the imperative style to the functional style? [...] s/imperative/imperative and OO/ Gerhard -- mail: gh at ghaering.de web: http://ghaering.de/ From h_schneider at marketmix.com Tue Mar 11 14:36:21 2003 From: h_schneider at marketmix.com (Harald Schneider) Date: Tue, 11 Mar 2003 20:36:21 +0100 Subject: os.startfile() on Linux ? References: Message-ID: Thanks a lot for all your replies -- covered and solved the problem completely! All the best, Harald "Harald Schneider" schrieb im Newsbeitrag news:b4khmn$d9f$02$1 at news.t-online.com... > Hi, > > is there a way to call a file with it's corresponding application, like > os.startfile() on Win32 does ? > E.g. os.startfile('page.html') brings up this document in the default web > browser. > > All the best, > Harald > > From andrew-pythonlist at puzzling.org Tue Mar 18 07:32:11 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 18 Mar 2003 23:32:11 +1100 Subject: generators and exceptions In-Reply-To: References: <20030315212905.GA3656@doublegemini.com> <20030317072755.GA9877@doublegemini.com> Message-ID: <20030318123211.GE22628@frobozz.local> On Tue, Mar 18, 2003 at 03:30:43PM +1200, Greg Ewing (using news.cis.dfn.de) wrote: > Andrew Bennetts wrote: > >But from which would you expect it to resume? Just before the exception > >was > >raised? Just after? What about try/except blocks? What if the exception > >was raised inside a function called by a generator? What about an > >exception > >thrown by a generator that your generator calls? > > It seems to me that what Mr. Evans wants is some way for > a generator to cause an exception to be raised in its > caller, without having to propagate the exception up > through its own stack frame first. > > Suppose there were a hypothetical "yield raise" statement > which did this, then he could write [snip] > As for how *useful* such a thing would be, I don't know. > I won't be leaping up to write a PEP, though... Me either. I suspect simply returning an Exception instance and letting the caller do an isinstance check for Exceptions is all that's really needed, and that's already catered for. -Andrew. From sross at connectmail.carleton.ca Sun Mar 9 19:46:50 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sun, 9 Mar 2003 19:46:50 -0500 Subject: ogg, UML, twisted vs. zope References: <3E6BE300.4090908@bitstream.net> Message-ID: <6ORaa.1700$Mz.97345@news20.bellglobal.com> "Harry LeBlanc" wrote in message news:3E6BE300.4090908 at bitstream.net... > Also, are there python object-modeling tools that are the equivalent of > java's ArgoUML project? (ArgoUML is a gui tool for building UML class > diagrams and automatically generating the java source code.) You could try this: http://pyut.sourceforge.net/ "PyUt is a little UML1.3 diagram editor (class diagram, use-case) with plugins support." """ Basic features UML class diagram, use-case editor Contextual help Cut-Copy-Paste Help Plugins Python generation + reverse engineering Java generation + reverse engineering C++ generation sql generation (soon) XMI import (Rational Rose - compatible) (export soon) XML import-export, proprietary format Ability to program your own plugins """ Sean From knightsofspamalot-factotum at gvdnet.dk Thu Mar 20 14:25:45 2003 From: knightsofspamalot-factotum at gvdnet.dk (Martin Christensen) Date: Thu, 20 Mar 2003 20:25:45 +0100 Subject: Is Python the Esperanto of programming languages? References: <200303192233.30383.andy@wild-flower.co.uk> <3E7908A7.CCEF27E8@alcyone.com> <3E791678.182F8916@alcyone.com> <7i1y1294g5.fsf@enark.csis.hku.hk> Message-ID: <87n0jpj0w6.fsf@gvdnet.dk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 >>>>> "Yoda" == Jedi Master Yoda writes: Yoda> Sincerely, Yoda> Kia Stulteco Hehe... tre amuza, sed mi kredas, ke li ne ekkomprenas. :-) Martin - -- Homepage: http://www.cs.auc.dk/~factotum/ GPG public key: http://www.cs.auc.dk/~factotum/gpgkey.txt -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: Using Mailcrypt+GnuPG iEYEARECAAYFAj56FbkACgkQYu1fMmOQldXJHgCgiLJZbWf/vr/HBH+UI16Q30Nu ZEkAnAtzPbqP35/9hQ2LPcIw78Y0pFp2 =LjMd -----END PGP SIGNATURE----- From skip at pobox.com Mon Mar 31 08:52:29 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 31 Mar 2003 07:52:29 -0600 Subject: Python Advocacy and "hard" data In-Reply-To: <3e8846ab$0$151$e4fe514c@dreader7.news.xs4all.nl> References: <3e8846ab$0$151$e4fe514c@dreader7.news.xs4all.nl> Message-ID: <16008.18461.893406.219822@montanaro.dyndns.org> Iwan> In other words, what I need is not apocryphal stories from the Iwan> converted but "objective" (haha) reports from institutions like Iwan> Gartner or statements from universitites or companies praising Iwan> Python's qualities. Iwan> Are these anywhere to be found? You mean, like here: http://www.python.org/Quotes.html ? Skip From bokr at oz.net Sun Mar 16 14:59:03 2003 From: bokr at oz.net (Bengt Richter) Date: 16 Mar 2003 19:59:03 GMT Subject: Flying With Python (Strong versus Weak Typing) References: <37a869bc.0303102102.4533973@posting.google.com> <3E6E9E4E.50405@removethis.free.fr> <3E6F0DFE.4AFA8037@engcorp.com> Message-ID: On Wed, 12 Mar 2003 15:53:45 -0600, Matthew Knepley wrote: >>>>>> ">" == Peter Hansen writes: > > >> Dennis Lee Bieber wrote: > >> > >> laotseu fed this fish to the penguins on Tuesday 11 March 2003 06:41 pm: > Second thing : > Ariane crashed because > >> of a bug in an ADA module. ADA is very strongly > *and* statically typed. > >> > > >> The module was fine -- for the previous generation of Ariane. > >> > >> If I read correctly, one of the reports available on-line, the closest one can come to is that the module which > >> failed was not coded to trap an exception condition and recover. > > >> There was a lengthy discussion of this in the Extreme Programming mailing list at one point. I can't recall the > >> conclusion, but after rereading your quotations it seems to me that this is a case where adequate testing could > >> have "easily" identified the problem. > > >> It would be interesting to know what tests where actually done, but my guess is that unit tests for the individual > >> routines involved was not one of them, or that those tests where quite inadequate (not checking behaviour in the > >> case of an out-of-bounds value, for example). > If you read the report cited closely, you will see that they did in fact identify > this location in their tests as something that could throw an out-of-bounds > exception (along with about 100 others), but chose not to protect it since the > cost of recoding was high. Some bets lose. > I find it surprising that (apparently, from what you describe) the software was not tested in a context accurately simulating the intended launch and perturbations around expected performance. I.e., it should be possible to build a computer-driven test stand where you could plug in the on-board computers and not have them "know" that they are not in an actually launched rocket, so you could have real-time virtual system dress rehearsals. Ditto for unit testing the culprit module. Regards, Bengt Richter From marcvanriet at yahoo.com Tue Mar 11 11:26:41 2003 From: marcvanriet at yahoo.com (Marc Van Riet) Date: 11 Mar 2003 08:26:41 -0800 Subject: GUI Toolkits(Python and XUL) References: <3E6A40CB.6010301@rsballard.com> Message-ID: If you're going for cross-platform then you might want to consider Qt. It's GPL'd on Linux, but you have to pay for it under Windows. I've used it under Linux, and it is really easy to use, with good screen editor, good arrangement of controls (e.g. what happens when a form is resided), good set of standard controls, ... Marc From BPettersen at NAREX.com Fri Mar 14 19:01:42 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 14 Mar 2003 17:01:42 -0700 Subject: Excel COM automation Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192022DDA86@admin56.narex.com> > From: Raymond Hettinger [mailto:vze4rx4y at verizon.net] > [..] > "Bjorn Pettersen" > > We have a trivially simple Python app in production that loads Excel > > through COM, opens an Excel file, and saves it as tab-delimited. Today > > we had a silent failure, and tracked it down to two instances of our app > > trying to use the Excel object at the same time. Is this supposed to > > work (and if so, what steps are we missing)? And if it's not supposed to > > work, is there a way to determine that the COM object is "busy"? > > -- bjorn > > Excel should respond to multiple COM requests; however, > you should do it in a threadsafe manner. > > Many types of access change Excel's state. For instance, > it is common to set an activesheet and then write to the > sheet, but another task may select another sheet leaving > the first task writing on the wrong tab. Thanks, that fixed the problem on my machine, but it still existed on the original developer's machine. The difference: I'm running 2.3a2, he's running 2.2.1. Using McMillan's Installer, I created an executable 2.3 version for him, which worked on his machine... -- bjorn From franck.lepoutre at caramail.com Fri Mar 21 08:21:20 2003 From: franck.lepoutre at caramail.com (francois lepoutre) Date: Fri, 21 Mar 2003 14:21:20 +0100 Subject: mod_python - life's not that easy References: Message-ID: <3e7b11ad$0$19444$79c14f64@nan-newsreader-02.noos.net> > I think that the mod_python manual way too brief. Sure > It doesn't explain anything in great detail, like how to start a subinterpreter for each > script. I can't find any mod_python tutorials or examples on the internet > either (most likely because I'm looking in the wrong places). Read the doc twice and read it carefully. I am a dummy not a techie. If i was able to do it, sure you should... > Is it possible to use mod_python like mod_php, so instead of starting > /usr/bin/python every time it would just process the python scripts as they > are requested? That is what is does :) > My application is very small scale. Other than the speed increase, what > other advantages are to using pyhton scripts as apache handlers? You will feel a change in perf if your script performs non-trivial tasks and request some kind of resource-buffering : - buffering data or html resources, - pre-loading database handlers and/or db content. If your app does not require this kind of stuff, i expect you can play the old cgi game, reloading the interperter rather than recycling it. Of course you may need a decent machine to play it this way. Fran?ois From m.schubert at sh.cvut.cz Tue Mar 11 17:49:10 2003 From: m.schubert at sh.cvut.cz (Marian Schubert) Date: Tue, 11 Mar 2003 23:49:10 +0100 Subject: libglade-2.0-0.dll References: Message-ID: "Steven Taschuk" wrote in message news:mailman.1047367817.14451.python-list at python.org... > Quoth Marian Schubert: > > have someone this file? > > Have you looked at ? sure, no compiled .dll there :/ cu, maio From abelikov72 at hotmail.com Thu Mar 27 02:02:59 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Thu, 27 Mar 2003 07:02:59 GMT Subject: Simple Python web development References: Message-ID: Does not meet requirements. >Try "Zope" -- http://www.zope.org > >Afanasiy wrote: >> Is there a Python web development solution which : >> >> * Uses the Apache web server >> * Does not depend solely on CGI or FastCGI >> * Requires only an Apache daemon, and no others >> * Does not require editing of *.conf or .htaccess every >> time you want to add another page to your web application. From skip at pobox.com Wed Mar 26 19:30:32 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 26 Mar 2003 18:30:32 -0600 Subject: Help me please : Rounding-down numbers In-Reply-To: <7b424d28.0303261608.47ba9dd3@posting.google.com> References: <7b424d28.0303261608.47ba9dd3@posting.google.com> Message-ID: <16002.17960.798796.85230@montanaro.dyndns.org> joseph> I have a floating number which I need to "round-down" to the joseph> nearest whole number. I am doing this by type-casting it as an joseph> "int". Would this work all the time ? It should. There is also the floor() function in the math module: >>> math.floor(4.71) 4.0 >>> int(4.71) 4 >>> 4.71 - int(4.71) 0.70999999999999996 >>> 4.71 - math.floor(4.71) 0.70999999999999996 Skip From chumphries at devis.com Thu Mar 13 10:08:12 2003 From: chumphries at devis.com (Chris Humphries) Date: Thu, 13 Mar 2003 10:08:12 -0500 Subject: 2 UK Jobs In-Reply-To: <7h3bs0fmqx7.fsf@pc150.maths.bris.ac.uk> References: <7h3bs0fmqx7.fsf@pc150.maths.bris.ac.uk> Message-ID: <3E709EDC.6000101@devis.com> i am available for python and unix related work: http://altertable.com/ChrisHumphriesResume.{html,doc} only in the us though :) (just in case there are people looking for more team members). Michael Hudson wrote: > Robin Becker writes: > > >>I saw this pair of jobs advertised. >> http://www.gojobsite.co.uk/showvac/3fGk0m/10429047/911177485 > > > Hey, I only have ten times the required experience with Python :-) > > Not looking for a job yet, though. > > Cheers, > M. > From mertz at gnosis.cx Sat Mar 8 12:26:17 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sat, 08 Mar 2003 12:26:17 -0500 Subject: OT: Programmers whos first language is not English References: <74ij6vcebl67dto60dun42hd625qrkmcv7@4ax.com> Message-ID: <5eia+kKkX82J092yn@gnosis.cx> Stephen Horne wrote previously: |In particular, I'm thinking of using XML - not as an AST |representation, but merely as a way of marking up source code. This |would require special editors, of course, but if WYSIWYG editors can |be created for HTML I don't see why programmers are still stuck in the |plaintext age. I would say that any programming language that requires a special editor is a truly dreadful idea that will die a deservedly early death. Either that, or it will be Lisp, and require emacs :-). With HTML, as with every other format, most tools that try to create a friendly face on the underlying source are awkward, buggy, do everything except the thing -you- have to get done, and will not run on whichever platform you need to work on. I cannot work with HTML outside of a plaintext editor at any length, nor would I want to. Yours, Lulu... P.S. That's not to say that allowing a few Unicode keywords is such a terrible idea. It does require an editor that can deal with them, but that is -less- specialized than editing XML; and there's more reason for general tools to allow that. -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad ---[ Postmodern Enterprises ]-------------------------- From bh at intevation.de Mon Mar 3 11:50:56 2003 From: bh at intevation.de (Bernhard Herzog) Date: 03 Mar 2003 17:50:56 +0100 Subject: Books Database References: Message-ID: <6qwujgcs27.fsf@salmakis.intevation.de> Eliran Gonen writes: > Hello ! > > I want to ask you what do you think is the best way to keep > a list of books with other data (such as year and author) in a > file ? One format I've been using for this kind of thing is a python source file which contains function calls looking something like this: Book(title = "Hitchhiker's Guide to the Galaxy", author = "Douglas Adams", year = "can't remember", note = "Don't Panic!") You can then parse it with execfile and a suitably defined function "Book". Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From whisper at oz.net Mon Mar 3 18:22:12 2003 From: whisper at oz.net (David LeBlanc) Date: Mon, 3 Mar 2003 15:22:12 -0800 Subject: Why no RE match of A AND B? In-Reply-To: Message-ID: > And now for a pragmatic point: if the & operator was ever so slightly > useful, or ever so slightly demanded, or ever so slightly easy to > implement, it would have surfaced in a certain language long before > now. > A certain molluskian by-product language seems to have Big Things in mind for REs in it's next incarnation, should it happen. The write-up is detailed and interesting. Dave LeBlanc Seattle, WA USA From bbondi at pacbell.net Mon Mar 3 19:14:57 2003 From: bbondi at pacbell.net (Bob) Date: 3 Mar 2003 16:14:57 -0800 Subject: Can Python be used to test Email API's Message-ID: Hello, I'm wondering about testing a new Email server and running tests using Python. Has anyone any knowledge about this use of Python? Thx From donn at drizzle.com Thu Mar 13 23:54:58 2003 From: donn at drizzle.com (Donn Cave) Date: Fri, 14 Mar 2003 04:54:58 -0000 Subject: Thread safety of the python API References: None <412a1fa3.0303131730.2ebe6238@posting.google.com> Message-ID: <1047617696.763635@yasure> Quoth sludin at ludin.org (Stephen Ludin): | I am developing an application that I may want to make scriptable with | python. If I do so I'd like to use the convenience of the Python API | in the rest of my application for containers and user defined method | dispatch. I am concerned though about using the API in a | multit-hreaded program. For example, a browse of intobject.c shows: | | static PyIntObject *free_list = NULL; | ... | PyObject * | PyInt_FromLong(long ival) | { | ... | if (free_list == NULL) { | if ((free_list = fill_free_list()) == NULL) | return NULL; | } | /* PyObject_New is inlined */ | v = free_list; | free_list = (PyIntObject *)v->ob_type; | ... | } | | The use of the linked list 'free_list' could result in a race | condition in MT code. There are a number of similar cases in the | objects defined in the Objects directory. | | I have not found much information on this, so I am wondering if I am | missing something. If all of my use was limited to embedded | interpreters, the global interpreter lock would take care of | synchronization, but I want to use it in the rest of my program as | well. Can you explain what that means, ``but I want to use it in the rest of my program''? Do you want to call PyInt_FromLong from outside the flow of control of the interpreter? That sounds like something one would not want to do, as I see Tim Peters has pointed out already. But nor does it sound like anything one would want to do, if you see what I mean. In my multithreaded applications, most of the action in any thread is outside of the interpreter, in the sense that a C++ library function is executing that was not specifically designed to be called from python (and in fact the threads were even started from that library, not by threadmodule.so.) While that's going on, the interpreter lock passes to some other thread, but that's fine because the library function is going to leave the python internals alone. When control returns to where we start doing python internals, it has to wait for the lock. Donn Cave, donn at drizzle.com From kdahlhaus at yahoo.com Mon Mar 24 08:36:08 2003 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 24 Mar 2003 05:36:08 -0800 Subject: Working with binary data, S-records (long) References: Message-ID: <283adf56.0303240536.23022d48@posting.google.com> FYI - I've a python utility that reports stats on S-Record files that you might find useful. It parses the file and prints a list of continuous memory regions, the program start address, any comment records, and a memory dump. You can download it from: http://members.nccw.net/kdahlhaus/python/python.html From irmen at -NOSPAM-REMOVE-THIS-xs4all.nl Thu Mar 6 20:32:50 2003 From: irmen at -NOSPAM-REMOVE-THIS-xs4all.nl (Irmen de Jong) Date: Fri, 07 Mar 2003 02:32:50 +0100 Subject: distutils changes my scripts when installing (python 2.2) Message-ID: <3e67f6c2$0$49111$e4fe514c@news.xs4all.nl> Hello using distutils from python 2.2 changes my scripts that I want it to copy. Some of them start with: #! /bin/env python as the first line. Instead of just copying them, distutils copies and adjusts the first line to #! /usr/bin/python That is not terrible ofcourse but I didn't expect this. I read somewhere that using the #! /bin/env blabla way of starting scripts on unix was preferable to directly calling the program that has to execute the script. But I don't know the reasons behind this. What do I lose by the change distutils decides to make for me? Can I somehow tell distutils not to make this change? Thanks Irmen de Jong From cben at techunix.technion.ac.il Tue Mar 11 14:43:58 2003 From: cben at techunix.technion.ac.il (Beni Cherniavsky) Date: Tue, 11 Mar 2003 21:43:58 +0200 (IST) Subject: Pre-PEP: Refusing to guess in string formatting operations Message-ID: Here is something I cooked a week ago but managed to post only now because it was buried in a damaged disk :-). Please comment on it. Also availiable on http://www.technion.ac.il/~cben/python/pep-strfmt.txt http://www.technion.ac.il/~cben/python/pep-strfmt.html -- Beni Cherniavsky , happy that cdrecord works in his linux - one less reason to reboot... PEP: XXX Title: Refusing to Guess in the String Formatting Operation Version: $Revision: $ Last-Modified: $Date: $ Author: Beni Cherniavsky Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 11-Mar-2003 Python-Version: 2.3 Post-History: 11-Mar-2003 Abstract ======== The `string formatting operation`_ - ``format % values`` - has a wart. In the face of non-tuple values, it assumes a singleton tuple around it. It's tempting to use this since singleton tuples look ugly but code using this easily breaks (when the single object happens to be tuple). This PEP proposes several ways to fix this wart. The problem was discussed repeatedly but the specific solutions proposed in this PEP need more feedback. Motivation ========== In the face of ambiguity, refuse the temptation to guess. -- The Zen of Python, by Tim Peters The simple use ``format % (val1, val2, ...)`` with a tuple is completely robust. However, since frequently there is only one value and singleton tuples are quite awkward to write and read, a shorthand is allowed - when the right object is not a tuple, it's interpreted as if it was wrapped in a singleton tuple. This shorthand is bad because: 1. When you pass a single object without the singleton tuple around it, your code will break it the object happens to be a tuple: >>> def decorate(obj): ... return '-> %s <-' % obj ... >>> decorate(1) '-> 1 <-' >>> decorate((1,)) '-> 1 <-' # instead of '-> (1,) <-' >>> decorate((1,2)) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in decorate TypeError: not all arguments converted during string formatting Your program can silently emit wrong results or crash. This is the classic example of the imposibility to create a single robust interface that will accept either an object or a sequence and do the right thing. Any attempt to do so invites bugs. This has bitten many Python newbies and was dicussed many times on comp.lang.python. 2. This temptation will exist forever under the current design. The purpose of this PEP is to provide altenative ways to format a single object that are as convenient as formating several objects, so that the temptation will disappear. 3. It is not possible to use sequences other than tuples (e.g. lists) for passing multiple values to the formatting operation, because the sequence is interpreted as a single object. For example, it's useful to be able to use a transparent debugging proxy that logs all accesses isntead of an object; if such a proxy for a tuple is used on the right side of a formatting operation, the transparency breaks. More generally, it's unpythonic to discriminate objects by actual type instead of the interface they implement. The formatting operator also has a third mode: when the right argument should be a mapping. This mode is triggered deterministically by the "%(...)..." syntax in the format rather than by checking the type of the right argument, so it doesn't need fixing. Single-value operator ===================== Specification ------------- Add a new string operator, ``/``, that will always accept a single value: >>> '-> %s <-' / 1 '-> 1 <-' >>> '-> %s <-' / (1 ,) '-> (1,) <-' To be always availiable, this would need to be duplicated as both ``str.__div__`` and ``str.__truediv__``. Rationale --------- This allows unambiguos expression of formatting with a single value, with minimal hassle when you change the code between one and several values. It's probably the least-intrusive fix for the problem. The ``/`` operator was choosen for this because this is the "closest relative" of ``%``. Mnemonic: ``/`` looks like a subset of ``%`` but with just one component :-). Downsides: it's an arbitrary punctuation; the mnemonic isn't better than perl's motivations for ``$]`` and friends... The div/truediv duplication is a hack that highlights the fact that this has nothing to do with division. Some people might start to wonder what ``//`` (floordiv) does with strings... (Should it do mapping formatting? I don't see the need - leave it to ``%``.) Deprecation of format % single-value ==================================== Once a unambiguos method to format a single value exist, there is little need (except for backward compatibility) for ``%`` to accept non-tuple right arguments. Thus it makes sense to deprecate this, eventually removing it completely. This will break a lot of existing code, not all of which is buggy, so it's better to proceed with this slowly. * As soon as a better alternative is implemented (2.3?), formating operations with non-tuple right argument should raise ``PendingDeprecationWarning`` (except for the "%(...)..." mode that expects mappings, of course). This is harmless (ignoring performance) and can be continued until everybody is educated and no newly written code uses it. * At some point (2.4? 2.x? 3.0?), the warning becomes ``DeprecationWarning``. At this point all the late adopters go over their code, perhaps fixing some instances of the single-values-happens-to-be-tuple bug in the process :-). * At the next stage, the guessing is completely dropped - you get a ``TypeError`` for non-tuples. * After this forced all uses of non-tuple values to disappear, it's possible to relax the demands and accept other seqeunces besides tuples. Since formatting access the values only seqeuncially, any iterable type can be accepted. This is a minor point in any case. Alphabetic Method ================= *This is not proposed as a sufficient solution but rather as an additional thing that can optionally be implemented. Actually the PEP author tends to think this is not needed but it is listed for completeness - perhaps others will like it more.* Specification ------------- Add a new string method with an alphabetic (non-magic) name that would accept a variable number of arguments (besides self) that are the values for the formatting operation: >>> '-> %s <-'.fmt(1) '-> 1 <-' >>> '-> %s %s <-'.fmt(1,2) '-> 1 2 <-' When the format selects values by names ("%(...)..."), there are several possible interfaces for passing the mapping (options 2 or 3 are preferred): 1. Keyword arguments: >>> '-> %(a)s <-'.fmt(a=1) '-> 1 <-' >>> '-> %(!@#$)s <-'.fmt(**{'!@#$': 1}) '-> 1 <-' 2. As a single mapping argument: >>> '-> %(a)s <-'.fmt({'a': 1}) '-> 1 <-' 3. Support both ways. Since this becomes very similar to the behaviour of the ``dict()`` constructor (since python 2.3), perhaps it makes sense to complete the similirity and also support a sequence of items as an argument: >>> # The above two ways work; in addition: >>> '-> %(a)s <-'.fmt([('a', 1)]) '-> 1 <-' All this could be easily implemented by just passing all arguments of the formatting method to ``dict()``. Note however, that when the argument is already a mapping (has a ``keys`` attribute), ``dict()`` should not be called on it, because that would copy the whole dictionary (and frequently big mappings are used when the format only accesses several keys). Suggested names for the new method: ``fmt``, ``format``, ``sprintf``. Rationale --------- * This notation works equally well for one and multiple values thanks to the call syntax of Python (at the price of some verbosity). This benefit will only be realised if either of the following happens: - Everybody completely switches to it and the % notation is deprecated - this doesn't look like a good idea. - The % notation is fixed by other means so that both notations are applicable at any situation (without dependence on the number of values), subject to the programmer's taste. That's why this solution is not sufficient in any case. * ``format.fmt`` looks more readable than ``format.__mod__`` when you need the bound method. * The duplication of operator functionality as an alphabetic method would not be without precedent. Some examples: - ``list.extend`` vs. ``list.__iadd__`` - ``dict.iterkeys`` vs. ``dict.__iter__`` - ``dict.has_key`` vs. ``dict.__contains__`` Note that in this case, the signature is not identical. * The use of keyword arguments for mapping-based formatting works in simple cases because the limitations on the keys are basically the same - they must be arbitrary strings. However: - Unicode formatting operations allow unicode strings as keys for selecting values, whereas keyword arguments are restricted to plain strings. Does anybody use unicode strings as formatting keys at all? - When you already have a mapping, you need to pass it using the ``**mapping`` syntax. This doesn't work for mappings that are not real dicts and it seems to go over all keys validating they are strings, which unnecesarily slows things down. Therefore supporting only the keyword arguments interface would be bad. * One alternative to an alphabetic method name is ``__call__``: >>> '-> %s <-'(1) '-> 1 <-' >>> '-> %s %s <-'(1, 2) '-> 1 2 <-' This has the same benefits of unambiguity inherited from the call syntax and is very concise. This is also its undoing: it's too cryptic. Using strings in function call position will deeply puzzle anybody unfamiliar with it. The idea was probably discussed and dismissed when ``%`` was originally introduced. Quoting PEP 234, on rejection of ``__call__()`` as alternative name for iterators' ``.next()`` method: ... there's a danger that every special-purpose object wants to use __call__() for its most common operation, causing more confusion than clarity. Backwards Compatibility ======================= The proposed addition(s) present no compatibility problems (unless somebody intentionally checks the absence of such method(s), in which case he doesn't deserve compatibility :-). The deprecation is estimated to affect a lot of code - there is hardly any Python programmer who has never used the single-value formatting shorthand. It is completely optional and can be done as slowly as needed to make the transition painless. There is probably some APIs out there with functions that accept a single value or a tuple and pass it to the formatting operation as-is. The deprecation will force them to either to break the API in this respect (possibly implementing alternatives similar to this PEP), which is a cleaner idea anyway, or explicitly implement compatible functionality, e.g.:: if isinstance(values, tuple): do_something(format % values) else: do_something(format % (values ,)) When the mapping-based formats should also be supported, some more code is needed... References ========== .. _String formatting operation: http://www.python.org/doc/current/lib/typesseq-strings.html Copyright ========= This document has been placed in the public domain. .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From clspence at one.net Mon Mar 10 12:01:10 2003 From: clspence at one.net (Chris Spencer) Date: 10 Mar 2003 11:01:10 -0600 Subject: uniquely identifying a machine... Message-ID: <97hp6vsg1daclecotuevtm3n581uhupkuk@4ax.com> This might not be a direct Python question, but I thought I'd pose it anyways. I have a need, for licensing purposes, to be able to uniquely identify a machine. For various policy reasons, we can not rely on the TCP/IP stack being active. So uniquely identifying a machine by IP address, machine name, or NIC address is not possible. Cross-platform is a plus, but definately not necessary. Anyone out there have any ideas? Chris. From adalke at mindspring.com Sun Mar 9 19:36:30 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 9 Mar 2003 17:36:30 -0700 Subject: A suggestion for a possible Python module References: Message-ID: Matt Gerrans: > while x > 999: > chunks.append( x - (x / 1000) * 1000 ) > x = x / 1000 See the divmod function for a way to make this easier >>> divmod(12345, 1000) (12, 345) >>> I would do it like this: while x >= 1000: x, remainder = divmod(x, 1000) chunks.append(remainder) The comparison to 1000 is mostly a preference, as I like having 1000 used twice, rather than 1000 used once and (1000-1) used in another place. Andrew dalke at dalkescientific.com From lucio at movilogic.com Fri Mar 28 16:29:58 2003 From: lucio at movilogic.com (lucio) Date: Fri, 28 Mar 2003 18:29:58 -0300 Subject: Metaphors and politics In-Reply-To: References: <1MudnTyOEK1mauGjXTWcqg@speakeasy.net> <3E835DC2.3678BD7F@engcorp.com> Message-ID: <3E84BED6.70706@movilogic.com> Terry Reedy wrote: >You mean like the 'anti-war' leaders who praise the thugs ruling North >Korea? >Perhaps you should visit Iraq and talk to the people like certain >ex-anti-war folks did > >He said that his talks with Iraqis convinced him that Saddam is "a >monster the likes of which the world had not seen since Stalin and >Hitler. He and his sons are sick sadists. Their tales of slow torture >and killing made me ill, such as people put in a huge shredder for >plastic products, feet first so [the torture masters] could hear their >screams as bodies got chewed up from foot to head." > > [snip] i promissed myself i would not comment on this, but i am weak. :) Disclaimer: i do belive saddam is no happy grandpa. We had a discussion the other day with my friends, so now i need to ask the following question: Who really belives that main reason of this war is the liberation of iraq? Lucio. From adam.albrechtas at equisure.ca Thu Mar 27 13:38:46 2003 From: adam.albrechtas at equisure.ca (Adam Albrechtas) Date: 27 Mar 2003 10:38:46 -0800 Subject: Building a Windows NT service with py2exe References: Message-ID: Doh! Note to self: the Python Reference manual is your friend.... Thanks Mark! Adam. Mark Hammond wrote in message news:... > Adam Albrechtas wrote: > > I have coded a Windows NT service in Python 2.2. The service works > > when running as a python script. I can use py2exe to roll it into an > > .exe without specifying that it is a service (which means that the > > .exe ultimately does not work but at least the process completes). > > When I use py2exe while specifying a service build I receive the > > following: > > ... > > File "", line 45 > > win32serviceutil.HandleCommandLine(NTAdminService) > > ^ > > SyntaxError: invalid syntax > > My guess is that your script file simply does not have a \n at the end > of the file. Python itself doesn't care about this, but exec does! From djmitchell at NOSPAM.optushome.com.au Fri Mar 21 23:30:23 2003 From: djmitchell at NOSPAM.optushome.com.au (David Mitchell) Date: Sat, 22 Mar 2003 15:30:23 +1100 Subject: Creating XML using Python Message-ID: Hello group, I'm trying to find options for creating XML documents using Python. There's any amount of options and documentation for *consuming* XML, but I'm having trouble finding options for *producing* XML. Well, I suppose "print" is an option... The problem I'm trying to solve involves collecting and collating lots of data from several different sources, and writing it out as one big XML file. The DTD I'm using is still a work-in-progress, and I'd like to be able to perform relatively minor surgery to my code as the DTD changes in order to bring the XML files I'm producing in sync with the revised DTD. Any pointers to relevant info would be appreciated. Regards Dave M. From gradha at titanium.sabren.com Mon Mar 10 15:41:43 2003 From: gradha at titanium.sabren.com (Grzegorz Adam Hankiewicz) Date: Mon, 10 Mar 2003 21:41:43 +0100 Subject: Wildcard for string replacement?!?! In-Reply-To: References: Message-ID: <20030310204143.GD20559@pedos.es> On Mon, Mar 10, 2003 at 09:13:32PM +0200, Perverted Orc wrote: > Hello everyone! > I 'm working for over a week on this script but I can't make my > way out. The whole idea is to replace (better say delete) anything > that stands between the and tag of an html file. Hmmm... I think you could load the whole html file as a single string, and use a multiline case insensitive regular expression (see re module documentation) with an expression like r'.*?' to detect the parts you don't want and substitute with ''. -- Please don't send me private copies of your public answers. Thanks. From reageer.in at de.nieuwsgroep Sun Mar 2 07:50:29 2003 From: reageer.in at de.nieuwsgroep (Rene Pijlman) Date: Sun, 02 Mar 2003 13:50:29 +0100 Subject: Simple question, how can i create a record? References: <1046608880.565095@seux119> Message-ID: <6dv36vovtdo3hvhue2l79obd2kocgi1fgc@4ax.com> EleKtR0: >i'm reading a good manual about Python to learn it. >it has an example where uses a module named "record" to import a class named >"record". >With record class i can create records on Python, but i'm not find the >record module. The manual should tell you where it is. >How can i create records on Python? What sort of records do you mean? Database records? If so, in what database? -- Ren? Pijlman Wat wil jij leren? http://www.leren.nl From me at privacy.net Thu Mar 13 22:42:02 2003 From: me at privacy.net (Greg Ewing (using news.cis.dfn.de)) Date: Fri, 14 Mar 2003 16:42:02 +1300 Subject: Flying With Python (Strong versus Weak Typing) In-Reply-To: References: <37a869bc.0303102102.4533973@posting.google.com> Message-ID: A. Lloyd Flanagan wrote: > You're undoubtedly right. Still, I now think the notion of type > should be 'an object which supports these operations', not 'an object > that inherits from this object (or objects)'. True, but that's a somewhat different issue. You could still have a parametric type system based around that notion of type, I think. Maybe. What I was trying to say is, if you think that static typing is a good thing at all, it's possible to make it parametric in a sane way (as opposed to the C++ way.:-) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bernt at tordivel.no Fri Mar 21 02:59:30 2003 From: bernt at tordivel.no (Bernt Ribbum) Date: Fri, 21 Mar 2003 08:59:30 +0100 Subject: Python/C API: Python class instance information in C? Message-ID: In a C module function, is it possible to extract information about a Python class instance being sent as argument? To explain a bit further... A C module (METH_VARARGS wrapper) function prototype looks something like PyObject *spam_func(PyObject *self, PyObject *args); The Python arguments are found (possibly inside a tuple) in "args", and I can handle this for standard Python types like ints, floats, etc., and also for types exported from my C module. What I stumble on, is Python code like this: import spam class X: pass x = X() spam.func(x) In this case I don't know how to extract information about the object. All I can find (from the C debugger) is that the object in question has an ob_type of _PyInstance_Type. (A call to PyInstance_Check() will return true, but unfortunately the documentation states "There are very few functions specific to instance objects". In fact, there is only the check function above and two New functions. Nothing else.) Is it possible for me to get more information here? I would like to know, at least, that this object is of type "class X" or similar. Any help appreciated :-) Thanks -- - Bernt --------------------------------------------------------------------------- TORDIVEL AS http://www.tordivel.no Storgata 20 0184 OSLO NORWAY Tel +47 2315 8700 Fax +47 2315 8701 Bernt Ribbum bernt at tordivel.no bernt.ribbum at ieee.org Direct: +47 2315 8714 Mobile: +47 906 106 85 --------------------------------------------------------------------------- From mlennert at club.worldonline.be Wed Mar 26 12:21:06 2003 From: mlennert at club.worldonline.be (Moritz Lennert) Date: Wed, 26 Mar 2003 18:21:06 +0100 (CET) Subject: writing to file very slow In-Reply-To: <20030326105513.J6746@localhost.localdomain> References: <41538.164.15.134.155.1048690460.squirrel@http://moritz.homelinux.or g> <20030326105513.J6746@localhost.localdomain> Message-ID: <42516.164.15.134.155.1048699266.squirrel@http://moritz.homelinux.or g> Thanks to Gustavo, Skip and Jack for your prompt answers, I've tried the different solutions you proposed, but unfortunately the time gain is not very important (maybe 30 secs). Tomorrow I'll try to figure out where the bottleneck is, but you've already helped me advance quite a lot in my understanding of how things should work (although I do have to do my homework on lambdas ;-) ), so thanks again. Moritz > On Wed, Mar 26, 2003 at 03:54:20PM +0100, Moritz Lennert wrote: >> Hello, >> >> I have written a cgi script that uses PyGreSQL to query a PostgreSQL >> database on the basis of the input of an html form. The results of the >> query are stored in a file for the user to download. >> >> Everything seems to work fine, except for the fact that writing the file >> is very slow (example: 4 minutes for 4 thousand lines). I've even had >> the >> problem that the program stopped writing the file before coming to the >> end >> of the results, then launches the same query again and starts writing a >> new file, which "crashes" again, triggering a new query, etc. >> >> I use the following modules: >> >> import cgi >> import os >> import _pg >> import string >> import tempfile >> >> And here is the relevant function for writing the file: >> >> def fichier_resultats(results): >> temdir="/tmp" >> tfilename = tempfile.mktemp('rec.txt') >> f=open(tfilename,'w') >> >> varnames="" >> for z in range(len(results.listfields())-1): >> varnames += str(results.fieldname(z))+'|' >> varnames += str(results.fieldname(len(results.listfields())-1)) >> f.write(varnames) >> f.write("\n") >> for x in range(results.ntuples()): >> var = "" >> for y in range(len(results.listfields())-1): >> var+=str(results.getresult()[x][y])+'|' >> var+=str(results.getresult()[x][len(results.listfields())-1]) >> f.write(var) >> f.write('\n') >> f.close() >> return(tfilename) > > What everyone else said plus, > you call getresult() alot, does it's return value ever change? > is it doing alot of work? you could call it just once > > if the list of fields never changes, just calculate the string once > and output it many times > > listfields() is used only for its length > > see my comment below, do you really only want to output the last > value in each row of getresult() ? > > modified function below (!warning, untested!) > I use lambdas unapoligetically, feel free to translate into list comps > > def fichier_resultats(results): > temdir="/tmp" > tfilename = tempfile.mktemp('rec.txt') > f=open(tfilename,'w') > > # you could also > varnames = '|'.join(map(lambda i: str(results.fieldname(i)), > range(len(results.listfields())))) > f.write(varnames) > f.write("\n") > gotten_result = results.getresult() # we only call this once > field_str = '|'.join(map(str, gotten_result[0])) > for row in gotten_result: > f.write(field_str) > f.write(row[-1]) # is this really what you want? translation of below > line > # var+=str(results.getresult()[x][len(results.listfields())-1]) > f.write('\n') > f.close() > return(tfilename) > > > -jackdied > > -- > http://mail.python.org/mailman/listinfo/python-list > From jwbaxter at spamcop.net Tue Mar 11 01:06:34 2003 From: jwbaxter at spamcop.net (John Baxter) Date: Mon, 10 Mar 2003 22:06:34 -0800 Subject: Recommended Linux Laptops, suppliers? References: <3e6a571b$1_1@spamkiller.newsgroups.com> Message-ID: In article , Nick Vargish