From mmower at novissio.com Sat Jun 28 16:13:31 2003 From: mmower at novissio.com (Matt Mower) Date: Sat, 28 Jun 2003 21:13:31 +0100 Subject: Have I broken my installation? References: Message-ID: On Sat, 28 Jun 2003 21:40:12 +0200, Andreas Jung wrote: >I think you should have installed a recent version of Expat. > You and Martin were both correct. This was the essential step. | | | Which is what I think Martin was expecting to see earlier. My thanks to you both. Regards, Matt From staschuk at telusplanet.net Mon Jun 9 15:05:37 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 9 Jun 2003 13:05:37 -0600 Subject: PEP 317: Eliminate Implicit Exception Instantiation In-Reply-To: <6qfzmjumq7.fsf@salmakis.intevation.de>; from bh@intevation.de on Mon, Jun 09, 2003 at 08:31:12PM +0200 References: <6qptlnux3w.fsf@salmakis.intevation.de> <6qfzmjumq7.fsf@salmakis.intevation.de> Message-ID: <20030609130537.I1359@tibia.amotlpaa.bogus> Quoth Bernhard Herzog: > Steven Taschuk writes: [using raise w/ traceback, without warnings, in all 2.x] > > This is a defect, but I couldn't come up with anything better when > > I was writing the PEP. > > The easiest would be to introduce the new syntax with the future > statement in 2.4 and start issuing warnings several releases later. > > I'd also recomment not issuing warnings about "raise SomeClass, val" in > 2.4 either except perhaps when explicitly switched on. Ah. Yes, a slower migration is certainly possible. One of my reasons for submitting the PEP was to find out how quickly such a change could occur -- you're not the only person to suggest it would have to be slower than I propose. [...] > > Part of my problem here is that I'm not > > familiar enough with real-life uses of the traceback argument. Do > > you use it? > > Yes, occasionally. I'd like to hear more about this -- in what circumstances, and to what end? -- 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 t_therkelsen at hotmail.com Tue Jun 10 10:50:39 2003 From: t_therkelsen at hotmail.com (Troels Therkelsen) Date: 10 Jun 2003 14:50:39 GMT Subject: Confusing behaviour relating to module objects being GCed. Message-ID: Hello helpful people at c.l.py :-) I'm having a problem in a large framework relating to using custom __import__ and reload hooks. I've been able to reduce the code that demonstrates this problem to this Python code (it probably can be reduced further by the more Python-savvy than yours truly): Python 2.3b1 (#1, Apr 27 2003, 22:07:38) [GCC 2.95.3 20010315 (release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import new >>> mone = new.module('mone') >>> mone.mtwo = new.module('mtwo') >>> mone.mtwo.var = 42 >>> exec "def func():\n print var\n delmtwo()\n print var\n" in mone.mtwo.__dict__ >>> def delmtwo(): ... delattr(mone, 'mtwo') ... >>> mone.mtwo.delmtwo = delmtwo >>> mone.mtwo.func() # FIRST CASE 42 None >>> mone.mtwo = new.module('mtwo') >>> mone.mtwo.var = 42 >>> exec "def func():\n print var\n delmtwo()\n print var\n" in mone.mtwo.__dict__ >>> keepref = mone.mtwo >>> mone.mtwo.delmtwo = delmtwo >>> mone.mtwo.func() # SECOND CASE 42 42 The problem is that after mone.mtwo.func() calls delmtwo() which removes the mtwo module from mone and thus reduces the ref-count to 0 (in the first case), func.im_func.func_globals starts showing a very peculiar behaviour. Basically, all of the module-level variable *names* stay, but all the *values* become None. As the second call to func() demonstrates, if I keep an 'external' ref to the module which is deleted from mone, everything is fine. I am at a loss explaining this behaviour, and I would greatly appreciate enlightment that either confirms that this is a bug, or explains why it isn't :-) Best regards, Troels Therkelsen From gerrit at nl.linux.org Sat Jun 21 17:31:34 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sat, 21 Jun 2003 23:31:34 +0200 Subject: "a in b" calls a.__cmp__, why? In-Reply-To: References: Message-ID: <20030621213134.GA9454@nl.linux.org> Terry Reedy wrote: > "Gerrit Holl" wrote in message > news:mailman.1056224677.5103.python-list at python.org... > > Why does a container-sequence's __contains__ call obj.__cmp__? > > Because 'in' is defined by equality, as determined by comparison > returning 0 or not , and not by identity. Ah, thanks... I'll override __eq__ then to compare by equality. > If you want identity in-ness, either program the search yourself or > use a list (or dict/set) of ids and search for id(item) in idlist. > > If your list is long (enough) and repeatedly searched, sorting and > using binsearch or making a set or dict for hash access will be > faster. I will try that. Thanks! yours, Gerrit. -- 168. If a man wish to put his son out of his house, and declare before the judge: "I want to put my son out," then the judge shall examine into his reasons. If the son be guilty of no great fault, for which he can be rightfully put out, the father shall not put him out. -- 1780 BC, 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 gh at ghaering.de Sun Jun 29 18:49:20 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 30 Jun 2003 00:49:20 +0200 Subject: Memory Address' of Python Objects In-Reply-To: References: <20030626131817.GA4097@nl.linux.org> <20030628133906.GA3705@nl.linux.org> Message-ID: Peter Markowsky wrote: > Hi all, > > I've been searching through the Python Essential Reference, and > python.org but I can't seem to find a way to get the memory address > for an object in python. Please help. How do you get the address of an > object in memory? id(obj) What do you intend to do with this information? If you want to use this to manipulate the object from outside Python, it's almost certainly the wrong way of doing it. -- Gerhard From staschuk at telusplanet.net Fri Jun 13 21:32:15 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Fri, 13 Jun 2003 19:32:15 -0600 Subject: getFoo1() vs. class.foo1 In-Reply-To: ; from manuelbastioniNOSPAM@tin.it on Fri, Jun 13, 2003 at 11:29:35PM +0000 References: Message-ID: <20030613193215.D2309@tibia.amotlpaa.bogus> Quoth Manuel: [...] > class VerySimple: > foo1 = 1 > foo2 = 2 > foo3 = 3 > etc... > > Any professional developers tell me that > I must use get and set (to private variable) > method instead. [...] Java programmers often do this, for two reasons that I know of: 1. Java encourages you -- by design -- to hide your data from other code, for fear that the other code will break you. (Python encourages a more trusting, friendly attitude.) 2. If you use separate get/set methods even for simple data, then you don't have to worry about API compatibility when the day comes that you want to make access to that data more complicated -- say, computing it on the fly instead of storing it, or logging all accesses, or whatever. (In Python this is no longer a big concern, since you can change a simple attribute into a property, leaving your API unchanged.) In short: don't do this in Python. In Java it's okay. -- Steven Taschuk staschuk at telusplanet.net "I tried to be pleasant and accommodating, but my head began to hurt from his banality." -- _Seven_ (1996) From guettli at thomas-guettler.de Mon Jun 9 07:13:48 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 9 Jun 2003 13:13:48 +0200 Subject: list.index In-Reply-To: <5.2.1.1.0.20030606154116.009ed760@pop3.zonnet.nl> References: <5.2.1.1.0.20030606154116.009ed760@pop3.zonnet.nl> Message-ID: <20030609111348.GA752@thomas-guettler.de> On Fri, Jun 06, 2003 at 03:49:58PM +0200, delphiro wrote: > First of all many, many thanks to the creators / maintainers of Python. > > Since my discovery of this holy grail I have a development time for platform indepandent software which is almost identical to what is possible with Delphi for Windows. It is realy a great language and easily learned with my C / C++ and mostly Object Pascal experience. THANKS! > > Now to the question... > > is this the easiest way to check for the existance of an item in a list? > it looks a bit weird to check a for a listitem by using a try..except block > > (code background; if the item is found the colour should change else the colour that was already given is ok) > [mycode] > try: > x = self.selected_points.index( self.pointmarker ) > colour = DEFAULT_SELECTED_POINT_COLOUR > except ValueError: > pass > [/mycode] Hi! For things like this I often use a dictionary with a list as value (not tested code): points={} #add point: old_value=points.get(mypoint) if not old_value: old_value=[] points[mypoint]=old_values old_values.append(mypoint) #get points which are at mypoint: mypoint_list=points.get(mypoint) thomas -- Thomas Guettler http://www.thomas-guettler.de From aahz at pythoncraft.com Tue Jun 10 00:57:49 2003 From: aahz at pythoncraft.com (Aahz) Date: 10 Jun 2003 00:57:49 -0400 Subject: PEP 317: Eliminate Implicit Exception Instantiation References: Message-ID: In article , Ed Avis wrote: > >Why not go further and make it look like a normal function call, that >can take zero one or two arguments? > > raise_stmt ::= "raise" "(" [expression ["," expression]] ")" > >No arguments - raise() - would re-raise the currently active >exception, and so on. Well, that would essentially make it no longer a statement. raise pretty much needs to remain a statement to fit in with the try/except control structure. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From jiwon at softwise.co.kr Thu Jun 19 23:47:50 2003 From: jiwon at softwise.co.kr (Jiwon Seo) Date: 19 Jun 2003 20:47:50 -0700 Subject: Alternatives to Python ? References: <3EF18A03.3050706@netspace.net.au> Message-ID: Gary Duncan wrote in message news:<3EF18A03.3050706 at netspace.net.au>... > There's been occasional not-unfavourable comments in this news-group > about the pros-and-cons of other so-called "high-level-languages" like > Ruby, and Haskell , and others too. > > I can't afford to buy more than one such book from the list of HLLs; > so what would you suggest ? > > > - Gary (currently reading "Don Qixote - for Dummies" - hilarious ) The question could be, why would you want to read such books? I assume that you want to read a book for concepts for programming rather for descriptions of language, for learning a new language should mean learning new ways of thinking, and in that case, I'd recommend you to read SICP. The examples in the book happens to be written in scheme, so you'll get to learn second oldest programming language in the world for a sort of bonus. But the real benefit is, you'll get to learn the ways of building programs, and to think with abstractions. If you've already read that book, you would not need to read a book for Haskell, or some other language. You would only need an online manual to get used to it. From mis6 at pitt.edu Tue Jun 10 13:12:42 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 10 Jun 2003 10:12:42 -0700 Subject: Rudeness with names (was Re: interpreted) References: Message-ID: <2259b0e2.0306100912.8946854@posting.google.com> Gerhard H?ring wrote in message news:... > Aahz wrote: > > Gerhard H?ring wrote: > >> [Aahz didn't like me calling anonymous posters "anonymous cowards"] > >>I too feel offended by: > >> > >>- anonymous posters > >>- top-posting > >>- broken quoting > >> > >>In one word: carelessness. > >> > >>Occasionally I will make originators aware of this. If you can't live > >>with this, feel free to killfile me. > > > > That's fine, and you may recall that I've made comments about top-posting > > and broken quoting in the past. But one needn't be rude and insulting > > when doing so, particularly in the first response to any given person -- > > that's not a "nudge". A better response would be something like, > > "Should I call you 'Ifman1'?" > > Ok, good point. Thanks for the constructive criticism. > > -- Gerhard I have seen Gerhard using "anonymous cowards" before and liked the joke. I didn't imagine it could be taken seriously as an offence. Especially since he was helpful with the posters. Actually, I was tempted to use the expression myself but at this point I don't think it would be a good idea. Anyway, I can always use "Should I call you 'Ifman1'?" ;-) Michele Michele From tim.golden at viacom-outdoor.co.uk Wed Jun 18 04:16:54 2003 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 18 Jun 2003 01:16:54 -0700 Subject: Error when accessing remote registry References: Message-ID: <8360efcd.0306180016.638b87e@posting.google.com> > c42 wrote > I'm using the following code to check the registry on a remote machine. > The code works fine when it hits a Windows 2000 Pro or > Windows XP Pro box, but crashes when it hits Windows NT4 workstation > (WindowsError: [Errno 87] > ----------------------------- > Sample code: > MachName = "TEST_1" > aReg = ConnectRegistry(MachName,HKEY_LOCAL_MACHINE) > aKey = OpenKey(aReg, r"SOFTWARE\\Network Associates\\TVD\\Shared > Components\\On Access Scanner\\McShield\\Configuration") > ----------------------------- [snip error] (btw, would be useful if you posted a piece of code that could just be dropped into an editor and run; it took me at least three seconds to work out that I needed to do a [from _winreg import *] first :) I don't have access to an NT4 machine here, but what jumps out at me at first is that you're doubling up the backslashes *within* a raw string. Is that intentional? It seems not to mind on my Win2k box (I tried it both ways) but maybe that's the problem. Ahh. Just tried it on an NT server; it _is_ the doubled backslashes. Try changing your OpenKey line to: aKey = OpenKey(aReg, r"SOFTWARE\Network Associates\TVD\Shared Components\On Access Scanner\McShield\Configuration") (blithely ignoring my own advice about posting runnable snippets. Oh well.) TJG From staschuk at telusplanet.net Mon Jun 9 13:29:07 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 9 Jun 2003 11:29:07 -0600 Subject: PEP 317: Eliminate Implicit Exception Instantiation In-Reply-To: ; from tjreedy@udel.edu on Mon, Jun 09, 2003 at 09:43:39AM -0400 References: Message-ID: <20030609112907.C1209@tibia.amotlpaa.bogus> Quoth Terry Reedy: > I would change 'raise_with_two_args' to something shorter, like > 'raise_instance' or even 'new_raise'. I'm open to such suggestions, but do note that almost all users will have no need for this future statement -- it's only useful to users who need the traceback argument. The present name is intended to suit such people, who will be adding it to deal with a warning that says "raising with three arguments will be impossible in the future". -- Steven Taschuk "[W]e must be very careful when we give advice staschuk at telusplanet.net to younger people: sometimes they follow it!" -- "The Humble Programmer", Edsger Dijkstra From andersjm at inbound.dk Sun Jun 1 12:40:56 2003 From: andersjm at inbound.dk (Anders J. Munch) Date: Sun, 1 Jun 2003 18:40:56 +0200 Subject: Is there a better way of coding this? References: Message-ID: "Edward C. Jones" wrote: > I wrote the following code so the writer of "Fgeti" could ignore some > subtle error processing. Can this code be rewritten without the template > and the exec? Yes. Use getattr, setattr and a nested function. Something like this: # very much untested code follows: def makeprop(getname, truename, funnanme): def fget(self): # Subtle error processing here. setattr(self, truename, getattr(self, funname)(self.data)) return getattr(self, truename) return property(fget, None, None) class X(object): i = makeprop('geti', '_i', 'Fgeti') ... - Anders From alexferri at email.it Fri Jun 6 12:02:36 2003 From: alexferri at email.it (Alex) Date: Fri, 06 Jun 2003 16:02:36 GMT Subject: SQLite Message-ID: Hi All, exists a software GUI to manage database SQLite? Thank you, Alex - Italy From edreamleo at charter.net Sat Jun 28 12:02:58 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Sat, 28 Jun 2003 11:02:58 -0500 Subject: Distutils directory questions References: Message-ID: I meant to say: recursive-include ../subdirectory file recursive-include file Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From nobody at nospam.net Thu Jun 5 15:04:18 2003 From: nobody at nospam.net (mrkurt) Date: Thu, 05 Jun 2003 15:04:18 -0400 Subject: GUI in Windows In-Reply-To: <0fttdvc2h72rt1tevpcfcpm9c5ba71ahr2@4ax.com> References: <0fttdvc2h72rt1tevpcfcpm9c5ba71ahr2@4ax.com> Message-ID: Take a look at wxPython: http://www.wxpython.org. It's a windowing toolkit for both Win32 and GTK on the *nix platforms. Lots of widgets, very popular with Python GUI developers. --mrkurt Afanasiy wrote: > On Wed, 28 May 2003 13:15:02 -0700, morden wrote: > > >>Suppose I need to do some GUI on Windows. My understanding is that >>pythonTk is flaky on Windows. My top requirement is >>that the toolkit is robust. The second requirement >>is that the widget set is large. >> >>I don't need anything fancy though, >>buttons, comboboxes, widgets for entering text/integers/date/time/etc, >>tables, groups, top and pull down menus. >> >>If it's portable it's a plus. >> >>Again, I want something with extensive track record and _very stable_ >>like pythonTk wrapper on UN*X platforms. > > > I just want to say it's hilarious how many questions this question brings. > From wrbt at email.com Mon Jun 9 12:44:06 2003 From: wrbt at email.com (Larry) Date: 9 Jun 2003 09:44:06 -0700 Subject: Python-ASP References: <3EE3394F.1050807@mxm.dk> Message-ID: <2ec1bc1c.0306090844.7f62c81@posting.google.com> Max M wrote in message news:<3EE3394F.1050807 at mxm.dk>... > Eugene C. wrote: > > Does anyone here use Python with ASP? If yes, then please tell me if you > > have experienced the problem below, and what, if any, were your solutions. > > You are probably not using the latest version of Win32. There was a > problem like that in earlier versions. Yup, ActiveState was (is?) known to have a flawed win32 package that causes this blank asp page drama. Get the goods from here: http://starship.python.net/crew/mhammond/win32/Downloads.html From wester at ilt.fhg.de Fri Jun 13 03:37:22 2003 From: wester at ilt.fhg.de (Rolf Wester) Date: Fri, 13 Jun 2003 09:37:22 +0200 Subject: How to pause within a thread Message-ID: Hi, I have a thread that is polling a server for completion of a routine. This thread should only consume little cpu time so I want to pause this thread between calls to the server. Is there any simple function for this or do I have to use a Timer object? Thanks in advance Rolf Wester From brjohan at email.com Sun Jun 1 17:19:16 2003 From: brjohan at email.com (Bror Johansson) Date: Sun, 1 Jun 2003 23:19:16 +0200 Subject: Pre Python Message-ID: Is Python's "predecessor" ABC (for MS-DOS) still available somewhere? I played with it more than ten years ago and would now like to have a look at it again. /BJ From wxyisok at hotmail.com Wed Jun 25 00:44:15 2003 From: wxyisok at hotmail.com (wang xiaoyu) Date: 24 Jun 2003 21:44:15 -0700 Subject: Only One Tkinter Entry can receive key event event in Linux RH8.0 Message-ID: Hello,everyone. my program runs well in windows,i use tkSimpleDialog to receive some input,but when i copy my program into Linux RH8.0,entrys in my tkSimpleDialog derived Dialog have a vital problem:only one entry can receive key event,'tab' key to navigate between entrys is not valid too,when i use mouse to focus a entry(which can not navigate through 'tag' key),no matter what key i pressed the entry receive no reply.But in window they are all works well. even the simplest python program like follow have the seem manner. from Tkinter import * r=Tk() Entry().pack() Entry().pack() r.mainloop() in above program only the second entry can receive key event.(but when i type program in Python environment it works well) I must say there is no fault the first time i run above program after i install ActivePython2.2 in my Linux.Both entry can receive key event.but after i do the following operations the problem occur. 1.install Pmw,i copy Pmw source code from windows python/lib/site-pages/Pmw directory 2.install Pil,copy windows source too 3.change site.py's encoding to 'u8' in order to support chinese text. 4.run my program and the problem occur 5.change site.py's encoding back to 'ascii' the problem remain 6.rpm -e ActivePython then delete All Pmw and Pil source code ,reinstall ActivePython ,nothing changed i must say i am a newhand in both python and linux,mybe there is fault in my operations.Maybe i install some packages in a wrong way. I think in linux,many people use ActivePython,Pmw,Pil and Tkinter,so i hope someone may have faced the same problem and can give me some suggestion. Best Regard wangxiaoyu From postmaster at bthub01.bt.com Mon Jun 2 04:00:35 2003 From: postmaster at bthub01.bt.com (postmaster at bthub01.bt.com) Date: Mon, 2 Jun 2003 09:00:35 +0100 Subject: Undeliverable: Re: 45443-343556 Message-ID: Your message To: N.Winton at axion.bt.co.uk Subject: Re: 45443-343556 Sent: Mon, 2 Jun 2003 03:59:46 +0100 did not reach the following recipient(s): N.Winton at axion.bt.co.uk on Mon, 2 Jun 2003 09:00:26 +0100 The recipient name is not recognized The MTS-ID of the original message is: c=gb;a=bt;p=bt;l=CBIBIPNT050306020800LH2B786P MSEXCH:IMS:EXCHANGE:BTHUB01:CBIBIPNT05 3550 (000B09B6) 550 5.1.1 ... User unknown -------------- next part -------------- An embedded message was scrubbed... From: python-list at python.org Subject: Re: 45443-343556 Date: Mon, 2 Jun 2003 03:59:46 +0100 Size: 1027 URL: From martin at v.loewis.de Sun Jun 8 02:37:25 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 08 Jun 2003 08:37:25 +0200 Subject: a = b = 1 just syntactic sugar? References: Message-ID: Ed Avis writes: > I'm not trying to attack the distinction between expressions and > statements. I know better than to do that. I am just asking, why is > it that the body of an anonymous function cannot contain statements? Because nobody can think of a clear, intuitive, and implementable grammar specification that allows otherwise. > Elsewhere in this thread I proposed using a simple_stmt as the body of > a lambda. Still, if you say there has been years of discussion I am > not so foolish as to think I've found the answer. Then your examples don't follow your proposal. A simple_stmt ends with a NEWLINE, whereas you did not put a newline at the end of the statement in your examples. Regards, Martin From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sun Jun 8 17:01:23 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sun, 08 Jun 2003 23:01:23 +0200 Subject: Compiling on XP home In-Reply-To: <6e77evc8iq5sb6i686qf8e7ccrsk2eledn@4ax.com> References: <6e77evc8iq5sb6i686qf8e7ccrsk2eledn@4ax.com> Message-ID: <3ee3a407$0$49113$e4fe514c@news.xs4all.nl> Tim Rowe wrote: > I'm running Python 2.2.3 on XP Home. I've just noticed that .pyc > files are not being created when I execute Python scripts. I'm > running as administrator in my own directory, so I have write > permission. Does anybody know what's happening? You have to import them instead of executing them directly: C:\> python script.py won't create a script.pyc. C:\> python -c "import script" will :-) --Irmen From vze4rx4y at verizon.net Fri Jun 13 02:49:03 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Fri, 13 Jun 2003 06:49:03 GMT Subject: Pseudo-indices -- PEP material? References: Message-ID: [Magnus Lie Hetland] > I've found I kind of like the capability of numarray to use sequences > as keys to arrays, e.g: I like it too. Rather, I like it in numarray and am -1 for having in the Python core. It represents a different style of thinking that is best left the numeric packages. 1) The pythonic way is less about reasoning with indicies and more about applying the conditions or logic that generate an array of indicies. Experience with APL and Matlab show code using index arrays is semi-easy to write, a little bit harder to read for your own code, and super hard to read in someone else's code. Look at the code inside meshgrid() or some of Matlab's other array index manipulators. A little aspirin is a must when dealing with this code. > >>> a > array([1, 2, 3, 4]) > >>> a[[1, 3]] > array([2, 4]) > >>> a[[0, 3]] = [5, 6] > >>> a > array([5, 2, 3, 6]) 2) Equivalent functionality is already available with very few keystrokes: >>> a = [1,2,3,4] >>> map(a.__getitem__, [1,3]) [2, 4] >>> map(a.__setitem__, [0, 3], [5, 6]) [None, None] >>> a [5, 2, 3, 6] > Does this seem like nonsense? Does anyone else like it? No me. > Is it worth > consideration as a PEP? > Maybe one should just use numarray for this > sort of thing in the first place? Yes!!! > (The reason I started thinking about > this is that I can't get any version of numarray to work with Py3b1 in Wow, Python 3.0 made it to beta before 2.3 got out. Go figure ;-) Raymond Hettinger From thomas.nuecker at web.de Fri Jun 27 06:16:10 2003 From: thomas.nuecker at web.de (=?ISO-8859-1?Q?Thomas_N=FCcker?=) Date: 27 Jun 2003 03:16:10 -0700 Subject: Compiling Python with Tkinter and win32gui Message-ID: <4b66f6d2.0306270216.2cc9f790@posting.google.com> Hello! I want to use Tkinter and win32gui with the python.dll. How do I have to configure the compilation and Python itself so i can use Tkinter and win32gui modules? Thomas N?cker From missive at frontiernet.net Thu Jun 19 18:06:37 2003 From: missive at frontiernet.net (Lee Harr) Date: Thu, 19 Jun 2003 22:06:37 GMT Subject: best idiom for wide try/except net? References: Message-ID: > The only workaround I've thought of is this, which looks a bit ugly to > me (it seems a shame to have to explicitly catch stuff I don't want): > > try: > # code that might have bugs > except (SystemExit, KeyboardInterrupt): > # exceptions I do not want to catch > throw > except: > # all other exceptions > sys.stderr.write(...) > traceback.print_exc(file=sys.stderr) > > Any suggestions? > That seems pretty nice to me, but I think you are looking for raise instead of throw. From robin at alldunn.com Thu Jun 19 19:54:19 2003 From: robin at alldunn.com (Robin Dunn) Date: Thu, 19 Jun 2003 16:54:19 -0700 Subject: [ANN] wxPython 2.4.1.2 Message-ID: <3EF24D2B.7050103@alldunn.com> Announcing ---------- I'm pleased to announce the 2.4.1.2 release of wxPython, now available for download at http://wxpython.org/download.php or http://sourceforge.net/project/showfiles.php?group_id=10718&release_id=166530 What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the popular wxWindows cross platform GUI library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit Microsoft Windows, most Linux or other unix-like systems, and Macintosh OS X. New with this release is an experimental build of wxPython using GTK+ 2.x for the underlying GUI platform and it is also built with UNICODE support turned on. The RPMs for this build were made on a Mandrake 9.1 system but should probably work on other distributions with very up to date libraries. If not, an SRPM is included that can be used to rebuild the RPM on your system. If you experiment with this build please send feedback to the wxPython-users mail list. The files are currently available only on the SourceForge download page, look for the wxPythonGTK2 files at the bottom: https://sourceforge.net/project/showfiles.php?group_id=10718&release_id=166532 Changes in 2.4.1.2 ------------------ Added wxScrolledPanel from Will Sadkin Added SetShape method to top level windows (e.g. wxFrame.) Changed wxSWIG to not generate Python code using apply, (since it will be deprecated in the future) wxSWIG will use spam(*args, **kw) syntax instead. Also changed the generated __repr__ methods to be a bit more informative. Made the version number information more robust and uh, informative. Also added asserts to check that the major.minor versions of wxPython and wxWindows match. Added the new wx "renamer" package that will dynamically import from the wxPython package and rename wxFooBar --> FooBar. That means that people can do imports without "import *" and can use names like wx.Frame instead of wx.wxFrame. This is phase 1 of a full transition to the new namespace. Updated Scintilla to 1.52. I also changed it to use wxListCtrl instead of wxListBox for the AutoComplete window, added the ability to use custom bitmaps in the margin and in the AutoComplete windows, and worked out how to do proper clipping of child windows on wxGTK. Patrick O'Brien's PyCrust package has been renamed to Py and now includes several new tools. As part of the change the location of the pacakge has changed as well, it is now accessible as "from wxPython import py" (or "from wx import py" using the new namespace.) There are still some transition modules in the wxPython.lib.PyCrust package that will issue a warning and then import what is needed from the new package. These will be removed in a future release. Added __nonzero__ method to wxTreeItemId, wxBitmap, wxImage, wxFont, and most other classes that have an Ok or IsOK method. This allows code like "if obj: ..." to be the same as "if obj.IsOk(): ..." Toolbars on wxMac can now have controls on them. Added wxPython.lib.analogclock module based on samples that were passed back and forth on wxPython-users a while back. Added masked edit controls (wxPython.lib.maskededit) by Jeff Childers and Will Sadkin. Updated wxTimeCtrl to use MaskedEdit. When the __class__ of a dead object is replaced with _wxPyDeadObject the __del__ of the original class is now called first. Added wxTreeListCtrl. (Looks like a wxTreeCtrl embedded in a wxListCtrl, but actually is just giving multiple columns to a wxTreeCtrl.) Added wxFutureCall, a subclass of wxTimer that makes it easy to delay a call to any Python callable object. Added wxPy versions of wxPrintPreview, wxPreviewFrame, and wxPreviewControlBar so they can be derived from in Python and be able to override the C++ virtual methods. Simplified how the wxSizer methods are wrapped, changed the name of the "option" parameter to "proportion" to match the docs ("option" is still accepted for compatibility, but this will go away in a future release,) SetItemMinSize can now take a wxSize (or 2-tuple) parameter, and Spacers can be specified with a wxSize (or 2-tuple) parameter Added wxCursorFromBits. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From ejy712 at comcast.net Sun Jun 15 12:24:08 2003 From: ejy712 at comcast.net (Ed Young) Date: Sun, 15 Jun 2003 12:24:08 -0400 Subject: Twisted - listenTCP and connectTCP on the same reactor? References: Message-ID: Problem solved, code is working, thanks for your help. I would post to the mailing list, but it is not searchable by Google (to the best of my knowledge). It's likely that other folks will have the same problems I have. Twisted is such a treat to use. I don't know if Python or Twisted are getting the most satisfied grins. Many thanks to both parties of developers (Python and Twisted)... On Sun, 15 Jun 2003 12:00:17 +1000, Andrew Bennetts wrote: > [While some Twisted developers do read comp.lang.python, you're usually > better off trying the twisted-python at twistedmatrix.com mailing list] > ---- answer and question cut ---- From justinjohnson at fastmail.fm Fri Jun 6 16:33:08 2003 From: justinjohnson at fastmail.fm (Justin Johnson) Date: Fri, 06 Jun 2003 14:33:08 -0600 Subject: XMLRPC Authentication In-Reply-To: <20030606201333.B5A7D338B@www.fastmail.fm> References: <3EE0B8B8.6070602@optonline.com> <20030606160231.6470A2026F@www.fastmail.fm> <20030606171737.0145427ED0@www.fastmail.fm> <20030606175450.CEB7032900@www.fastmail.fm> <20030606193428.612EC21EC9@www.fastmail.fm> <20030606201333.B5A7D338B@www.fastmail.fm> Message-ID: <20030606203309.03EB927CEA@www.fastmail.fm> I got it to work. The BasicAuthTransport code I got from a Zope posting had some variables missing. Had to add verbose as an option to the request method, as well as set a self.verbose variable in BasicAuthTransport. On top of that, I made some changes to the way BasicAuthXMLRPCRequestHandler decoded the autorization string. I'm gonna make this more robust, but it is working now. Attached is all of the working code, for anyone who has the same problems I did. Thanks everyone for all your help. -Justin On Fri, 06 Jun 2003 14:13:33 -0600, "Justin Johnson" said: > I'm getting closer. Now I'm getting the following error when trying to > connect via the client. > > [snip] > Traceback (most recent call last): > File "C:\share\python\uhg\uht\tsd\ClearCase\xmlrpc_client.py", line 7, > in ? > print server.runCmd("dir") > File "C:\Python23\lib\xmlrpclib.py", line 1021, in __call__ > return self.__send(self.__name, args) > File "C:\Python23\lib\xmlrpclib.py", line 1308, in __request > verbose=self.__verbose > TypeError: request() got an unexpected keyword argument 'verbose' > [/snip] > > I've my code. Any ideas. > > On Fri, 06 Jun 2003 13:34:28 -0600, "Justin Johnson" > said: > > Ahhh, okay.... > > > > So I would put code the do_POST to basically read the MD5 hashed > > userid:password, decrypt it, and verify that it is a valid user id and > > password? > > > > On Fri, 6 Jun 2003 14:00:15 -0700 (PDT), dave at pythonapocrypha.com said: > > > On Fri, 6 Jun 2003, Justin Johnson wrote: > > > > > > > How do you specify the login id and password required on the server side? > > > > The code I'm using is similar to the following. I'm obviously missing > > > > something here... :-( Thanks for your help. > > > > > > > > # Server code > > > > > > > > import SimpleXMLRPCServer > > > > from ccservice import CCService # A class providing methods for remote > > > > use > > > > > > > > server = SimpleXMLRPCServer.SimpleXMLRPCServer(("somehost", 8000)) > > > > server.register_instance(CCService()) > > > > server.serve_forever() > > > > > > Sorry for not more of a detailed answer, but subclass > > > SimpleXMLRPCRequestHandler and override the do_POST method sorta like > > > this psuedo-code > > > > > > def do_POST(self): > > > Look at self.headers['authorization'] > > > if missing or wrong: > > > self.send_response(401) > > > self.end_headers() > > > return > > > # Otherwise call original > > > return SimpleXMLRPCRequestHandler.do_POST(self) > > > > > > (where "missing or wrong" = do the inverse of what the client side does > > > to > > > create the Authorization header) > > > > > > -Dave > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- A non-text attachment was scrubbed... Name: BasicAuthTransport.py Type: application/unknown Size: 1149 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: myxmlrpc.py Type: application/unknown Size: 583 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: xmlrpc_client.py Type: application/unknown Size: 205 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: xmlrpc_server.py Type: application/unknown Size: 284 bytes Desc: not available URL: From mcherm at mcherm.com Wed Jun 4 11:04:46 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 4 Jun 2003 08:04:46 -0700 Subject: Changing python process name (or argv[0]) Message-ID: <1054739086.3ede0a8ec5f95@mcherm.com> Mike writes: > I think the functionality is desirable for some > (at least on Unix python), and this simple trick hardly warrants an extra > module if it is indeed acceptable in the python world. Mike, you have it exactly backwards. This simple trick hardly warrents inclusion in core Python when it can be implemented by an extra module. The fact that it _is_ a simple trick is a good reason to keep it as a module. The fact that it might not be portable to all operating systems is another good reason. Don't be afraid to use modules... that's what they're for! -- Michael Chermside From max at cNOvSisiPonAtecMh.com Wed Jun 11 15:46:51 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Wed, 11 Jun 2003 19:46:51 GMT Subject: Need urgent solution...................... References: <20030611181102.5745.84605.Mailman@mail.python.org> Message-ID: Ok, I am sorry I misunderstoon your point initially. The subject header is annoying, but it reflects the OPs situation, and if any of the Python gurus feels charitable this day they may read the "urgent" post first. m. -- ======================================== 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] "Joe Grossberg" wrote in message news:mailman.1055355627.11726.python-list at python.org... > We know your time is important. So is ours. Please post with a more > informative title next time (e.g. "How do I determine pixel width of > text in a Tkinter canvas?", and you'll be more likely to get helpful > answers. > > More info here: > http://www.catb.org/~esr/faqs/smart-questions.html#bespecific > > Good luck, > Joe > > -- > ---------------------------------------------------------- > Joe Grossberg :: Programmer :: jgrossberg at matrixgroup.net > http://www.matrixmaxx.net/ :: Custom Web Solutions and > Web-Based Association Management Software. > > > From kiko at async.com.br Fri Jun 27 22:57:24 2003 From: kiko at async.com.br (Christian Reis) Date: Fri, 27 Jun 2003 23:57:24 -0300 Subject: ExtensionClass/Persistent and __cmp__ is tricky Message-ID: <20030628025724.GA9873@async.com.br> So I read the docs on BTrees and `Total Ordering' at http://www.zope.org/Wikis/ZODB/guide/node6.html again. One of the key points here (as Tim pointed out) is that __cmp__ has to be carefully designed: If you want to use class instances as keys, and there's any possibility that the structure may be stored in a database, it's crucial that the class define a __cmp__() method, and that the method is carefully implemented. I'm fine with this, so I started some verification of the __cmp__ method on IndexedObject, our Persistent-derived class. The first, basic, test I did, however, bothers me because it seems to echo something similar to what Greg Ward suggested back in http://mail.zope.org/pipermail/zope-dev/2000-May/004420.html -- that cmp() is not completely compatible with ExtensionClass. Here's my (short) example: >>> from ZODB import Persistent >>> class Foo(Persistent): ... def __cmp__(self, other): ... print "Hi there" ... return cmp(self, other) ... >>> >>> f = Foo() >>> f < 1 Hi there [ repeated 21 times ] >>> f > 1 Hi there [ repeated 21 times ] >>> 1 < f 0 >>> 1 > f 1 This goes against what I understand of the cmp() protocol. The PSL docs say: __cmp__(self, other) Called by comparison operations if rich comparison (see above) is not defined. Should return a negative integer if self < other, zero if self == other, a positive integer if self > other. If no __cmp__() operation is defined, class instances are compared by object identity (``address''). (Note: the restriction that exceptions are not propagated by __cmp__() has been removed in Python 1.5.) Am I understanding this correctly? It seems you can't compare ExtensionClass with basic types; in Python 2.1.3 at least it appears to me that try_3way_compare doesn't want to call tp_compare on the second instance because it's not a PyInstance. PS: The interesting part is that it seems that comparing lists *does* work: >>> [] > f Hi there [ repeated 21 times ] 0 Which means I'm almost safe with using PersistentList, at any rate (which uses its List comparison). PPS: Anybody know why 21 times? Take care, -- Christian Reis, Senior Engineer, Async Open Source, Brazil. http://async.com.br/~kiko/ | [+55 16] 261 2331 | NMFL From xpm4senn001 at sneakemail.com Wed Jun 25 08:44:50 2003 From: xpm4senn001 at sneakemail.com (John Fitzsimons) Date: Wed, 25 Jun 2003 22:44:50 +1000 Subject: "Newbie" questions - "unique" sorting ? References: <8da5fvsnidpjtblgfj4484spso2t9e6r95@4ax.com> Message-ID: On Mon, 23 Jun 2003 20:35:59 -0700, "Cousin Stanley" wrote: Hi Cousin Stanley, >{ 1. Good News | 2. Bad News | 3. Good News } .... > 1. Good News .... > The last version of word_list.py that I up-loaded > works as expected with your input file producing > an indexed word list with no duplicates ... < snip > > That's 6.56 HOURS and un-acceptable performance !!!! I agree. :-) Very clever of you to have worked out how long it would take. I hope you didn't wait over 6 hours to find out !!! > word_list.py works quickly on smaller files, > but as coded, is an absolute dog for indexing > larger files .... Good. I was hoping it wasn't something that I had done wrong. :-) > 3. Good News .... > Since I FINALLY figured out that you're mostly interested > in just the URLs and not a general word list, > I coded a pre-process script to extract just the URLs > from the original input file .... > python url_list.py JF_In.txt JF_URLs.txt Unless I missed something it does lines starting ftp, http, BUT not lines that start www . Is that correct ? Or did I give you a file with no lines starting www ? < snip > >Let me know if this output looks closer to what you are after .... Very very good......and fast. If I can work out what happened to the www lines, and fix it, then everything will be great. I then hope to try this exercise using a different method to see if the numbers come up the same. Thank you for such excellent programming. :-) Regards, John. From michael at ida.his.se Tue Jun 10 02:28:32 2003 From: michael at ida.his.se (Michael Andersson) Date: Tue, 10 Jun 2003 08:28:32 +0200 Subject: Extending Python with C# and vice versa Message-ID: <3EE57A90.7080402@ida.his.se> Hi! I've heard of a project called Python for .NET that, as I understand it, can be used to extend Python with C# code. Has anyone tried this? Best regards, /Michael From mis6 at pitt.edu Thu Jun 5 13:02:06 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 5 Jun 2003 10:02:06 -0700 Subject: Tk vs wxPython ? References: <3edf4e92$0$24082@echo-01.iinet.net.au> Message-ID: <2259b0e2.0306050902.77397ccc@posting.google.com> "Rob Hall" wrote in message news:<3edf4e92$0$24082 at echo-01.iinet.net.au>... > >> IMHO, wxPython scores worse than both pygtk and pyqt. > > You make it sound that pyqt scores bad... pyqt rocks! I spend quite a > while last year coming to grips with wx, but after a day or two of qt I was > quite comfortable. IMHO qt IS the way to go. > > Rob Yeah, but installing Qt is not obvious at all. Last year I tried a couple of times ... ... and at the end I decided to use Tkinter ! Michele From khcarlso at bellsouth.net Thu Jun 5 10:21:02 2003 From: khcarlso at bellsouth.net (Kevin Carlson) Date: Thu, 05 Jun 2003 10:21:02 -0400 Subject: using urllib or httplib to post with ENCTYPE=mulitpart/form-data In-Reply-To: References: <87he751jla.fsf@pobox.com> Message-ID: <3EDF51CE.8030608@bellsouth.net> Ng Pheng Siong wrote: >According to Kevin Carlson : > >>I actually only need to send a couple of text inputs to the form, but no >>matter what, the host system acts like I input nothing into the form. I >>have tried this: >> > >Maybe the form has some Javascript that validates the data and invokes a >secret handshake, like sending extra hidden fields or returning a cookie? > Thanks for help on this one -- I got the first POST working. It was a problem with formatting the multipart/form-data. Once I got the proper format it worked fine. Interesting you should bring up cookies, though... The response from the POST returns a cookie that I need to pass along to the host on the subsequent request. I don't see and methods in httplib to deal with cookies directly, nor can I find any in the HTTPResponse.py source that allow me to extract the cookie from the response. I'm sure I'm missing something. Any additional pointers? Kevin From maxm at mxm.dk Thu Jun 26 15:57:35 2003 From: maxm at mxm.dk (Max M) Date: Thu, 26 Jun 2003 21:57:35 +0200 Subject: better way than: myPage += 'more html' , ... In-Reply-To: <3efb3248.316098305@news.pa.comcast.giganews.com> References: <3EF9CBCB.90305@yahoo.com> <3efb3248.316098305@news.pa.comcast.giganews.com> Message-ID: <3EFB502F.2010008@mxm.dk> Chuck Spears wrote: > I have a question with regards to the sprintf style of replacing > strings. I have a table in my HTML with a 50% width specifier. How > can i get the formatter to ignore it. For example in the example > below how can i code the 50% to be ignored? > > keep the "%s 50% %s" % ("a","b") Double the % "%s 50%% %s" % ("a","b") regards Max M From icarroll at pobox.com Tue Jun 3 05:54:57 2003 From: icarroll at pobox.com (W Isaac Carroll) Date: Tue, 03 Jun 2003 02:54:57 -0700 Subject: tuple to list to tuple conversion References: <20030603091833.M95008@ee.iitm.ernet.in> Message-ID: <3EDC7071.3030800@pobox.com> Vinoo vasudevan wrote: > Can someone tell me what I'm doing wrong here? > > I have a method that needs to call other methods like this: > def mymethod(self, methodname, params): > apply(methodname, params) > > params is already a tuple. I needed to add a few more parameters > inside 'mymethod' so I did this: > params = tuple((list(params)).append(something)) > when params is an empty tuple to begin with, the stmt sets it to None > instead of (something,) > However the following works regardless of whether params is empty: > x = list(params) > x.append(something) > params = tuple(x) The append() method modifies the list in-place and returns None in accordance with standard Python procedure. Instead of changing to a list, just create a new tuple by concatenation: def mymethod(self, methodname, params): apply(methodname, params+something) Just make sure that "something" is a tuple and everything will work fine. TTFN From gh at ghaering.de Mon Jun 16 10:00:42 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 16 Jun 2003 16:00:42 +0200 Subject: insert thousands separators In-Reply-To: References: <3EE9E548.9010701@isst.fhg.de> Message-ID: <3EEDCD8A.6000303@ghaering.de> Nick Vargish wrote: > ps. Looking at the library reference, it's not clear if there's an easy > way to extract the fractional portion of a float without hitting the > Standard Floating Point Problem: > >>>>v = 2312.3123123 >>>>v1 = int(v) >>>>v2 = v - v1 >>>>v2 > > 0.31231230000003052 If you need that, then a float is probably not the right data type. There are several implementations of arbitrary precision numbers out there. Some more fun with floats: #v+ >>> v - v1 0.31231230000003052 >>> s = str(v) >>> s '2312.3123123' >>> s[s.find("."):] '.3123123' >>> float(s[s.find("."):]) 0.31231229999999999 #v- So if you only want to print the fractional value, str() will do fine. But str() won't make floats capable of representing arbitrary numbers, either ;-) -- Gerhard From aldo at nullcube.com Mon Jun 2 03:19:47 2003 From: aldo at nullcube.com (Aldo Cortesi) Date: Mon, 2 Jun 2003 17:19:47 +1000 Subject: dictionary issue (and maybe PEP ... depending on the answer) In-Reply-To: <0wBCa.651$ig1.627675@newssrv26.news.prodigy.com> References: <0wBCa.651$ig1.627675@newssrv26.news.prodigy.com> Message-ID: <20030602071947.GA28853@nullcube.com> Thus spake dsavitsk (dsavitsk at ecpsoftware.com): > The issue is, this consistently returns the months in order. I don't see > any obvious reason that it does, but I can't get it to fail. So,I am > wondering if there is a reason, or is it serendipity. Pure, blind luck - you are simply seeing an artifact of the current Python implementation of dictionaries. You'll find that this behaviour disappears for larger dictionary sizes. It is also not guaranteed to exist in other versions of CPython or in alternative Python implementations. > Assuming that there is not a good reason, the PEP idea is adding a > sorted_keys() method to dictionaries which would just return the keys in > the same order they would be in by doing this. > > >>> l = d.keys() > >>> l.sort() > > > The advantage is that using dictionary keys in list comprehensions would > be easier, but other than that it is not too big a deal. Surely this doesn't warrant a PEP? You can easily define a little helper function, if you really find that you use list comprehensions on dictionaries often enough to make typing the two lines above cumbersome: def sortAndReturn(lst): lst.sort() return lst print [_months[i] for i in sortAndReturn(_months.keys())] Alternatively, you can use any of the various ordered dictionary implementations that are out there. One commonly cited one can be found here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747 Cheers, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com From alanmk at hotmail.com Sun Jun 22 07:34:49 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 22 Jun 2003 12:34:49 +0100 Subject: Choosing between two Jython books... References: Message-ID: <3EF59459.D7732CE7@hotmail.com> Marc Rochkind wrote: > I'm a very experienced programmer who knows both Python and Java, and I > thought I'd buy just one book on Jython, which sounds like something I'd > like to use. Hi Marc, Are you the Marc Rochkind who wrote "Advanced Unix Programming"? That was our course book for a "Systems Programming" course, when I was taking my Comp Sci degree back in the '80s. That was a great book, clear, concise and highly informative. > Which should I get: [of two jython books] I have both books. They were both inexpensive. > Jython Essentials (Pedroni & Rappin) I think that this is the more technical of the two books, since it is written by two people who regularly work on Jython internals. I found it extremely effective as a reference book, i.e. it contains all of the details that you need to design and implement jython/java systems. > Jython for Java Programmers (Bill & Bill) And this one takes more of a tutorial approach, albeit at a reasonably advanced level: the target audience is java programmers, so a fair degree of java and general programming knowledge is assumed. They both have pretty extensive coverage of jython and how it relates to Java, but I think that "Essentials" has the edge in terms of completeness of technical details and in terms of being authoritative. > I'm mainly interested in completeness and rigor... don't need a tutorial > approach. If those were my criteria, I would definitely pick "Jython Essentials". But the thing that *really* taught me about jython and jython/java integration was using jython to embed a scripting engine inside one of my java applications. Nothing like a real world tryout. Best wishes, and welcome to comp.lang.python. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From drs at ecp.cc Thu Jun 26 02:02:17 2003 From: drs at ecp.cc (drs) Date: Thu, 26 Jun 2003 06:02:17 GMT Subject: socket programming project Message-ID: Hi, I have a programming design question. I would like to do this in Python, but I am not even sure about what tools are proper or where to start reading. I am trying to make a small network system where several client computers connect to a server. each client can send messages to the server which must alert all of the clients of the information in the messages. Further, the server must be able to alert all connected clients about other occasional information. The total number of messages is low, however. for now, security is not an issue if that matters. I know a way to do this in win32 using dcom, but this seems sloppy, and i need it to run on freebsd and win32 at a minimum, and pocketPC if at all possible. I also thought about using ZEO coupled with a Queue class, but I am not sure about clients reacting to events in this case, or about ZODB/ZEO on pocketPC. (The specifics of the project are to make a wifi enabled jukebox out of an old freebsd computer hooked to my stereo which can be controlled by all of the other computers in the house. I did a previous version of this using SimpleHTTPServer, but this seems a dead end for forcing the playlist queue and such onto clients.) Any suggestions on how to start would be appreciated. Thanks, doug From jkraska at san.rr.com Wed Jun 11 00:46:50 2003 From: jkraska at san.rr.com (Courageous) Date: Wed, 11 Jun 2003 04:46:50 GMT Subject: Revised PEP 318 - Function/Method Decorator Syntax References: <20030610082514442-0400@braeburn.themorgue.org> <3EE654A5.1F158A91@alcyone.com> Message-ID: >To me, the [] are parentheses used as one might use >parentheses to enclose an annotation in English, and... Well, how about parentheses then? These appeal to Python's higher order semantics, where lists of things enclosed in parentheses are (generally) immutable. C// From unendliche at hanmail.net Wed Jun 4 23:00:54 2003 From: unendliche at hanmail.net (Seo Sanghyeon) Date: 4 Jun 2003 20:00:54 -0700 Subject: IDLE raw_input() and unicode Message-ID: <45e6545c.0306041900.7efc3406@posting.google.com> My setting is IDLE 0.8 on Python 2.2.2, WinXP. In case it's relevant, here's Korea. (Hangeul is Korean writing.) IDLE can print Hangeul just fine. (Note: my sitecustomize.py does sys.setdefaultencoding("utf-8"). In case it's relevant.) But IDLE fail to get Hangeul input with raw_input(). It baffles and prints out: Traceback (most recent call last): File "", line 1, in ? raw_input() TypeError: object.readline() returned non-string After some study, I found that it seems bulitin raw_input() does sys.stdin.readline() *AND* type-checking. (Whoa... since C code is involved, there's no traceback and I'm not sure. Should I read C code on Python CVS? *normal user shudder*) sys.stdin is replaced with an instance of PyShell.PyShell by IDLE. And readline() method of PyShell class does something I don't understand and does: ---- # PyShell.py around line 475 line = self.text.get("iomark", "end-1c") ... return line ---- PyShell inherits from OutputWindow and it in turn inherits from EditorWindow and EditorWindow initializes self.text as Tkinter.Text widget. And I don't know what the hell "self.tk.call(self._w, 'get', index1, index2)", that is, an implementation of Tkinter.Text.get(), does at all, but I assume it returns sort of "non-string". So I opened DOS command line window and started python. And typed: ---- import PyShell shell = PyShell.PyShell() shell.begin() shell.reading = 1 # Typing some Hangeul. In this case, the name of Python itself. shell.text.get('iomark', 'end-1c') ---- It prints out: u'\ud30c\uc774\uc36c\n'. So some sort of "non-string" is actually unicode. So... I suggest the following: 1) Make raw_input() able to return unicode. Why not? (But I suspect there may be some deep reason.) 2) Or, at least, make PyShell.readline() returns other than "non-string". I think just changing "return line" to "return str(line)" would do. (Make a change and try again.) Yes, it does. I googled with "IDLE raw_input unicode", and to my surprise, just few posts I found. Some German one posted raw_input() doesn't handle umlauts. So it seems this is quite general i18n problem. Should I submit... *normal user shudder* a patch? It's just one-line change... Or can someone do all unicode-IDLE-users a favor and submit a patch? I'm more than happy to hear something like "Yes, we know that, and it's all fixed on IDLE version >0.8, and with Python 2.3 you will have no problem." -- Seo Sanghyeon From missive at frontiernet.net Wed Jun 18 18:54:50 2003 From: missive at frontiernet.net (Lee Harr) Date: Wed, 18 Jun 2003 22:54:50 GMT Subject: Postgresql: plpython may be removed References: <200306181436.21252.scott_list@mischko.com> Message-ID: In article , Skip Montanaro: > > Scott> This thread is going on the Postgresql email list. It appears > Scott> that support for Python as a Postgresql scripting language will > Scott> not last unless some knowlegable folks can assist. > > How so? I use PostgreSQL from Python and have never heard of plpython. I > use psycopg which is well-supported, albeit not by the PostgreSQL folks. > Similarly, mysql-python (aka MySQLdb) is stable and widely used to talk to > MySQL databases even though it's not supported by the MySQL folks. I > suspect that sort of relationship is true of most packages and their Python > interfaces. > Postgresql allows internal database functions to be written in a variety of languages (C, python, perl, tcl, possibly others). I believe that is what they are talking about here. There is little chance of the python client libraries going away, but I think the use of python for internal functions is much more complex. From meisl at Mathematik.Uni-Marburg.de Thu Jun 5 09:12:51 2003 From: meisl at Mathematik.Uni-Marburg.de (Roman Meisl) Date: Thu, 05 Jun 2003 15:12:51 +0200 Subject: Python grammer and student projects In-Reply-To: <1054813689.3edf2df98ca60@mcherm.com> Message-ID: <3EDF5DF3.23189.55D82B@localhost> Hello Michael, Am 5 Jun 2003 um 4:48, schriebst Du (Michael Chermside): > I am actually rather dubious of your claim that there are problems > with the online-grammer. > [...] > I wonder if you're looking at a the wrong document (perhaps an outdated > one?) and there's a different (better) grammer specification someplace > else. Or perhaps there are interpretation problems. What kinds of issues > do you think you've found, and in what document? There are - as far as I've seen - two grammar versions First one can be accessed by http://www.python.org/doc/current/ref/grammar.txt within the Python Reference Manual For example this grammar isn't describing the symbols 'test' and 'testlist'. Further, by example following rule is correct but the fomulation is a bit sophisticated: or_expr ::= xor_expr | or_expr "|" xor_expr Expressing the same with or_expr ::= xor_expr ( "|" xor_expr)* would be easier to understand Some rules are a bit redundant and could be written more efficiently (e. g. funcname ::= identifier) The other version can be found within the sourcecode-package. As far as I've seen it is correct and formulations are less redundant and clearer. The problem is, that the online-grammar (first one) is found at first (by newbies, like me) > > I'm not learning python but I'm directing a students group which is > > developing a python-compiler for practice. > > Hey... that's exciting! I think it sounds like a great project. Yes it is a great project, but only in the sense of meaning lot of work ;-) > Can you > share any details? Who's working on this... what are their goals? I'm working to graduate as an scientific assistant at the Philipps- University of Marburg at the Department of Mathematics and Computer Science. This semester I've to conduct a lecture about compiler-building (german: Compilerbau) with some exercise. And this exercise tries to develop a hand-crafted Python compiler without using tools like lex and so on. My opinion is, that the resulting compiler can't compete by far with any other Python compiler, especially that from python.org. It's only for teaching the students how to develop a compiler "by hand" and how much work it is ;-) > Are > you just replacing the compiler (to produce python bytecode), or the > interpreter as well? (Or do you really mean a Python compiler in the > sense of python -> machine code?) The target isn't completely clear, yet. I think we wouldn't go as far to produce machine code, but we will see. > I wonder if there's > any chance of leveraging your students to contribute to contribute > something to core cPython itself. Just idle speculation, but I always > try to mention these kinds of things. Well, I can ask them if they're eager. Can you tell something about the problems/work there? > Yeah... one of Python's great strengths is the helpfulness of its > community. Welcome. Thank you, I appreciate that > PS: Feel free to CC python-list with your reply if you think it'd > be of general interest. [x] Done. I don't know if it's of general interest, but we will see. Bye, Roman -- PGP-Key available Kontakt: http://www.mathematik.uni-marburg.de/~meisl/kontakt.html From tjreedy at udel.edu Tue Jun 3 17:43:28 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 3 Jun 2003 17:43:28 -0400 Subject: Help with coroutine-based state machines? References: <3ED622CA.4B01E3C1@hotmail.com> <3ED76105.CB8F3ECF@hotmail.com> <3EDC69DF.A46A97D4@hotmail.com> <3EDD05FA.CDE86800@hotmail.com> Message-ID: "Alan Kennedy" wrote in message news:3EDD05FA.CDE86800 at hotmail.com... After reading your response to my response to your essay, I think we can combine ideas and converge on the following essentials, with implementation details left out: Traditionally, execution frames form a linear stack. With generators, there can also be a 'pool' of detached, suspended, ready-to-go frames that are not currently on the stack. The interpreter executes the code attached to the top frame of the stack. That code can bury its frame by calling another function, whose frame gets put on top. Or it can unbury the frame underneath by returning (or yielding), so that its frame get detached and deleted (or not). But it cannot directly replace itself (or its frame), such as with a co-routine call. However, we can similate such co-routine frame switching as follows: write a set of 'state' generators, giving each knowledge of the others it needs to know about. Instead of having them yield data (pass data through attributes or globals instead ), have them yield the generator method corresponding to the next state. Then support this set of state methods with a servant dispatch method/frame that sits under the changing top frame and that helps the state methods 'in effect' call each other by calling the state method yielded by each state on behalf of that yielding state. While mechanically the same, this is conceptually different from the typical generator usage in which the caller decides on the sequence of calls. By making the caller a servant, control is effectively passes to the callees. Terry J. Reedy From martin at v.loewis.de Tue Jun 24 15:46:20 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Jun 2003 21:46:20 +0200 Subject: Help: printing Unicode characters during telnet session In-Reply-To: References: Message-ID: Pekka Niiranen wrote: > Should I create python shell or is there any other way ? If, by "shell", you mean the Windows terminal window: This can only display a limited number of characters. This is not inherently a limitation of python, but of the terminal window - this system component uses a certain font, and that font only supports so many characters. To get support for more characters, you need to do a number of things: a) use a console font with more characters, e.g. Lucida Console, b) use a console code page that has all the characters that you want to display. c) tell the editor on the other end to convert the text file, for display, to the code page that your terminal supports There is nothing Python could do for you to improve this situation. You might consider using a different terminal emulation, though. Regards, Martin From mis6 at pitt.edu Tue Jun 10 12:02:15 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 10 Jun 2003 09:02:15 -0700 Subject: PEP 318 - Function Modifier Syntax References: <20030609081617512-0400@braeburn.themorgue.org> Message-ID: <2259b0e2.0306100802.c805a50@posting.google.com> Kevin Smith wrote in message news:<20030609081617512-0400 at braeburn.themorgue.org>... > This is the first draft of a PEP describing new syntax for applying > function modifiers (e.g. classmethod, staticmethod, etc). There is > currently no implementation of the proposed syntax (I have heard rumors > that the 'def foo(self) [...]' syntax has a patch somewhere, but I > haven't seen it yet). I have already received a few comments and will > revise the document soon. The latest version will always be available > at http://www.python.org/peps/pep-0318.html. > > > Function Modifier Syntax > ------------------------ I proposed some type ago to extend the notation for classes. For instance class C(A,B)[Traced,Syncronized]: pass would mean class C(A,B): __metaclass__=type("TracedSyncronized",(Traced,Syncronized),{}) For functions instead the interpretation would be def f(x,y)[traced,syncronized]: pass meaning (as in the current PEP) def f(x,y): pass f=traced(syncronized(f)) It is not perfect, since the interpretation of the syntax would differ for functions and classes, but who cares? "practicality beats purity" ;) Originally I wanted an "is" sugar class C(A,B) is Traced,Syncronized: pass def f(x,y) is traced,syncronized: pass which looks better but people protested that "is" has another meaning. Another possibility (suggested by Bengt Richter) would be class C(A,B) becomes Traced,Syncronized: pass def f(x,y) becomes traced,syncronized: pass Michele From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sun Jun 29 19:15:47 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 30 Jun 2003 01:15:47 +0200 Subject: To get all property of a class? In-Reply-To: References: Message-ID: <3eff7322$0$49112$e4fe514c@news.xs4all.nl> manuel wrote: > Exist a sintax like > > import Foo > for property in Foo > print property Yes, use __dict__, it contains the mapping of all attributes of an object (module, class, whatever) to their values: import os for (name,value) in os.__dict__: print name,"=",value --Irmen From rudy.schockaert at pandora.be Mon Jun 2 13:17:03 2003 From: rudy.schockaert at pandora.be (Rudy Schockaert) Date: Mon, 02 Jun 2003 17:17:03 GMT Subject: Some pythonic advice needed In-Reply-To: References: <2946028.1054494609@dbforums.com> Message-ID: andrew cooke wrote: > Rudy Schockaert writes: > >>I have received lot's of valuable inputs. Thank you all. > > > any chance of publishing what you finally produce? i once did > something similar when first learning spanish, but lost it long ago > (it didn't have support for multiple translations (or accents - i used > to use capitals for accented letters!)) - i think it might be a good > idea if i used one again (my spanish seems to be stuck at "good enough > to live here, but still sounding like a stupid gringo...") > > cheers, > andrew > I already planned to do that to get some feedback from the experts. I'm still learning you see. From gupt_vive at hotmail.com Sat Jun 14 06:13:48 2003 From: gupt_vive at hotmail.com (vivek kumar) Date: Sat, 14 Jun 2003 15:43:48 +0530 Subject: Hot to get Python executable's path ?? Message-ID: >On Saturday 14 June 2003 03:38 am, vivek kumar wrote: > > Hi all, > > > > I am writing a CGI app. I was trying to find out a way to change the >#! > > line in the CGI scripts for different platforms using an install script. > > TIA and Kind Regards > > Vivek Kumar > >The shebang only works on unix variant systems. Windows simply ignores it >and >goes by the filename extension instead. Hmm.., but on My windows 2k system I am using Apache and if I try to run script as CGI script without giving the shebang line it simply gives me 500 Internal Server Error with error [Sat Jun 14 15:38:44 2003] [error] [client 127.0.0.1] C:/Program Files/Apache Group/Apache2/htdocs/fireshop/environ.py is not executable; ensure interpreted scripts have "#!" first line [Sat Jun 14 15:38:44 2003] [error] [client 127.0.0.1] (9)Bad file descriptor: don't know how to spawn child process: C:/Program Files/Apache Group/Apache2/htdocs/fireshop/environ.py Anyway , I recently find out the solution. I tried sys.executable and it works on both windows and linux. So I think I can use it safely to substitute the shebang line. Am I right ?? Regards Vivek Kumar _________________________________________________________________ They're big & powerful. The macho mean machines! http://server1.msn.co.in/features/suv/index.asp SUVs are here to stay! From cmkleffner at gmx.de Thu Jun 26 10:32:59 2003 From: cmkleffner at gmx.de (cmkl) Date: 26 Jun 2003 07:32:59 -0700 Subject: MSYS / MINGW32 / PYTHON / SWIG References: Message-ID: <3b091a1c.0306260632.1e30096a@posting.google.com> "orion30" wrote in message news:... > I would like to know if somebody has successfully uses > SWIF using MSYS / MINGW32 / PYTHON. > > I tried to do it but apparently, I failed. > > Is there somebody who can help me and give a little example. > There is a little example in http://sebsauvage.net/python/mingw.html > but it's not working for me. > > At more, I would like to used the dll versions of the glibc. > How to proceed in order to build a module (using swig) which uses a such dll > ? > > Best regards I have no idea what the swif library could be, but in principle it is possible to wrap libraries written in C/C++ with swig to python. BTW: mingw32 uses Microsofts msvcrt.dll. This is the counterpart of the glibc on Linux. Of course the library does not have most of the posix functionality. If you use posix functions like fork you have to use cygwin instead of mingw. Can you tell what is not working for you with the example above? Carl From drs at ecp.cc Thu Jun 26 18:54:14 2003 From: drs at ecp.cc (drs) Date: Thu, 26 Jun 2003 22:54:14 GMT Subject: socket programming project References: <3efb62a5$0$49109$e4fe514c@news.xs4all.nl> Message-ID: "Irmen de Jong" wrote in message news:3efb62a5$0$49109$e4fe514c at news.xs4all.nl... > > If you don't care about the communication internals, (and it seems very > likely that you don't), try Pyro : http://pyro.sourceforge.net > > Pyro makes it VERY easy to build distributed object systems in Python. > (a basic client and server take no more than 5 to 10 lines of code, > of which only two or three are Pyro-specific). > > If you know DCOM, you know the basics of distributed object systems, > and you should feel at home very soon when using Pyro. > Not forgetting that it is tremendously easier to use than DCOM.. ;-) This looks really interesting. In COM, there is the concept of a single use server where every client shares the same instance. Python does not really support creating a single use DCOM server, at least not last time I looked into it. Is this something Pyro can easily do, or will I need to use a db of some sort to keep track of shared data? -doug From fredrik at pythonware.com Tue Jun 24 09:32:07 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 24 Jun 2003 15:32:07 +0200 Subject: Stroing tkinter screen as PNG file.............. References: <20030624130429.25639.qmail@webmail26.rediffmail.com> Message-ID: Suresh Kumar wrote: > I am using python/tkinter/windows. How to store tkinter canvas > screen as a PNG file? I have drawn some rectangles in my canvas > and i want to store it as a PNG file so that i can use it for > further processing. How can i do it? here's one way to do it: http://mail.python.org/pipermail/image-sig/2003-May/002292.html ImageGrab is part of the PIL library: http://www.pythonware.com/products/pil From johnf at jfcomputer.com Mon Jun 16 09:50:45 2003 From: johnf at jfcomputer.com (JOHN FABIANI) Date: 16 Jun 2003 06:50:45 -0700 Subject: [General lang] how to call a parent In-Reply-To: <20030616021955.GC24545@unpythonic.net> References: <20030616021955.GC24545@unpythonic.net> Message-ID: <1055771445.14524.8.camel@linuxsrv.jfcomputer.com> Thank you for the help. I think I understand. Now that I have the required tools I will start a small project. Thanks again. John On Sun, 2003-06-15 at 19:19, Jeff Epler wrote: > On Sun, Jun 15, 2003 at 11:01:46PM +0000, John Fabiani wrote: > > I'm just starting to use python and playing with the tools and the language. > > After building a few small windows (via BOA) I realized that I did not know > > how to create a class that allowed reuse in a general way. I was testing > > how classes are used. I was able create properties, call the __init__ of > > the parent class .etc But then I realized I did not have a way to call a > > parent of control - such as a container. Also I was not aware of "super". > > I'm guessing that will help. Still learning!!!!!!!!!!!! > > John > > Yeah. I didn't get in your first message that you were asking about the > inheritance tree -- I thought you were talking about parents in terms of a > tree-representation of an HTML document, for instance. > > You must use super() if you expect the inheritance graph to be a DAG instead > of a tree (i.e., there's a "diamond shape" hiding somewhere). For > instance, if you have > A > / \ > / \ > B C > \ / > \ / > D > class A(object): pass # super works only for "new-style objects" > class B(A): pass > class C(A): pass > class D(B,C): pass > then follwing the rule (for cooperative methods) "each subclass method calls > the method defined on each of its base classes" will get you into trouble: > D.f calls both B and C, which in turn gives *two* calls to A.f (not the one > call you'd expect). Super defines a strange-seeming order where each subclass > method calls *one* method defined on a base class, but the call may not be > to an ancestor class of the class making the call via super. Confused yet? > > Now, if you don't want to accomodate diamond-shape inheritance, then > there's a simpler way. Just call the method by referencing the class > attribute, and explicitly name self as the first argument: > >>> class A: > ... def f(self, arg): print "A.f(%r,%r)" % (self, arg) > ... > >>> class B(A): > ... def f(self, arg): > ... print "B.f(%r,%r)" % (self, arg) > ... A.f(self, "spam") # call parent method > ... > >>> o = B() > >>> o.f(37) > B.f(<__main__.B instance at 0x81d548c>,37) > A.f(<__main__.B instance at 0x81d548c>,'spam') > > Wondering about the diamond and super? Write the code yourself. The > cooperative call looks like this: > super(X, self).f(arg) > where X is the name of the class in which you're defining the method. > Remember, super only works when you make your classes new-style by deriving > from object. > > Jeff > From martin at v.loewis.de Sun Jun 8 19:25:04 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 09 Jun 2003 01:25:04 +0200 Subject: a = b = 1 just syntactic sugar? References: Message-ID: Ed Avis writes: > Are you sure? This is an excerpt from > : I see. In Grammar/Grammar, I have simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE Using grammar.txt instead, your specification is still underspecified. You mention some detection of ambiguities. How exactly would that work? For example, what is the meaning of a = lambda b : return b > 0 Also, what is the meaning of the statements inside the lambda expression, in particular of assignment and return statements? E.g. if I have x = lambda b:c=3 what happens if I invoke x(4)? What if x is x = lambda c:c=3 What is the meaning of continue inside lambda? Regards, Martin From bokr at oz.net Fri Jun 27 00:35:39 2003 From: bokr at oz.net (Bengt Richter) Date: 27 Jun 2003 04:35:39 GMT Subject: shebang strange thing... References: <3EF3A07B.A683F94F@alcyone.com> <3EF7A121.7B4C3775@alcyone.com> <3EF933AA.C16ADFE5@alcyone.com> Message-ID: On Fri, 27 Jun 2003 01:21:20 GMT, "Steve Holden" wrote: [...] > >Although in actual fact the KSR33 teletype did need a fifth of a second to >guarantee that the print head would have returned to the left margin from >column 72 haracters was a "feature". Sometimes you would (all right, *I* >would) depress the two keys in the wrong order, and the result was that you >would see a single character printed in the middle of the new line during >the "flyback" period. > Or for programmed output, you'd (ok, *I* would ;-) program a delay to allow for the flyback to complete after the line feed which IIRC could be done during flyback, since it didn't print anything. But I think we had flexowriters before we had KSR33s. At least I was personally introduced to flexowriters first. What I am trying to remember is how the Friden flexowriter that was connected to the LGP-30 I once coded for worked re CR/LF. It definitely had a moving carriage and moved like a typewriter, but ISTR that one key would do the CRLF. But there was more than one model, and I suspect there was one that had separate CR/LF codes/functions. Maybe one we used with a PDP-8 later ;-) Regards, Bengt Richter From andrew-usenet at lexical.org.uk Mon Jun 2 12:58:15 2003 From: andrew-usenet at lexical.org.uk (Andrew Walkingshaw) Date: 2 Jun 2003 16:58:15 GMT Subject: Python prob References: Message-ID: In article , BOCQUET Jean-Francois wrote: > > hello, > you want some help for your house work ? It seems that one of your = > friend was smarter than you to get help : see the post from "Scott = > Meyers" Scott Meyers is a very respected C++ author (who is teaching himself Python from the looks of things), it appears; this appears to be coincidence, not conspiracy! - A From max at ford-consulting.com Thu Jun 19 13:36:45 2003 From: max at ford-consulting.com (Max Barry) Date: Thu, 19 Jun 2003 10:36:45 -0700 Subject: TypeError: Value() takes at most 2 arguments (3 given) Message-ID: I am having problems calling a VB6 let property from a class in python. I get a TypeError: Value() takes at most 2 arguments (3 given). I presume the self is being passed as the 3rd argument. Here is an example of the class: class someclass: def foo(): self.test(somevbobject) def test(self, Result): Result.Value(1, 0) This is the VB property that python calls: Public Property Let Value(ByVal lngIndex As Long, ByVal sngNew As Single) ' Notice: presumed to be zero-based values msngValues(lngIndex + 1) = sngNew End Property Does anybody know how to resolve this problem? Thanks in advance, Max From eppstein at ics.uci.edu Fri Jun 20 01:14:37 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 19 Jun 2003 22:14:37 -0700 Subject: testing two lists for equality References: <3064b51d.0306191140.3d4094fe@posting.google.com> <3EF2169D.3590ECBD@engcorp.com> Message-ID: In article , "Raymond Hettinger" wrote: > Do you think docs should be changed from: > > Tuples and lists are compared lexicographically using > comparison of corresponding items. > > To: > ... compared by sequentially comparing corresponding items. > > Or something like: > > ...compared sequentially using comparison of corresponding items The difference is that "lexicographically" has a recognized precise mathematical meaning. Your alternatives don't convey that meaning to me unless you describe what you do with the results of the sequential comparisons, e.g. ...compared by comparing corresponding items, sequentially until an unequal pair is found, and using the comparison value from that pair. If all compared pairs are equal, the result is the same as if the lengths of the lists were compared. But that seems a bit cumbersome to me... -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From peter at engcorp.com Sat Jun 7 23:33:57 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 07 Jun 2003 23:33:57 -0400 Subject: Excuting scripts question References: <3EE26F88.C86E88BB@alcyone.com> <3EE28A13.65FD29DD@engcorp.com> Message-ID: <3EE2AEA5.8A63C18E@engcorp.com> Ken wrote: > > "Peter Hansen" wrote: > Do you have a web server running on it? > I installed IIS. (I am running Windows 2000 Pro) > I went into Control Panel/Admin Tools/Internet Information Services/Default > Web Site and go into properties. In the "Home Directory" tab, I went into > "Configuration". Clicked "Add", put in the path of python.exe executable > (C:\Python22\python.exe), extension "cgi" and pressed ok. Is this the right > way to do it? I am planning to run this Win2000 machine as a web server for > my cgi scripts that used to reside on a Unix machine. The script files and > HTML files are saved into the C:\Inetpub\wwwroot directory. Well, at least you're a step farther than I feared (i.e. not even having a server running). Unfortunately, you're basically asking a Win2K configuration question, and I can't help you there except to suggest you simplify the problem so that you don't involve your old scripts *and* the server *and* CGI and everything else. What's the simplest thing you can get working that demonstrates that the server is able to process CGI? After that it should be a simple matter to modify the settings to handle Python as well. -Peter From martin at v.loewis.de Sat Jun 21 16:57:40 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 21 Jun 2003 22:57:40 +0200 Subject: XML References: <3EF471BA.EE4F056@hotmail.com> Message-ID: Lee Harr writes: > How about email? Right. Or, uncertain: I would not consider a MIME message 7-bit plain text ASCII. Indeed, I would not consider an RFC 822 message plain text at all - the body might be plain text, but then, the body of an HTML file might also be be 'plain', in the sense it does not refer to multimedia/content... But your observation is right in principle: to really understand what the "most common text format in history" is, and to allow "7-bit plain text ASCII" as a candidate, one would need to specify, in more detail, what exactly that is. Regards, Martin From bokr at oz.net Thu Jun 19 16:51:04 2003 From: bokr at oz.net (Bengt Richter) Date: 19 Jun 2003 20:51:04 GMT Subject: use member functions to access data in Python classes? References: <3064b51d.0306180815.75869d6f@posting.google.com> Message-ID: On 18 Jun 2003 09:15:15 -0700, beliavsky at aol.com wrote: >In C++, it is generally recommended to declare the data within a class >private and to access the data using member functions. Do experienced >Python programmers usually use member functions to access data within >classes, or do they access the data directly? As others have mentioned, probably mostly directly, and not for privacy purposes. But sometimes it can be handy to make use of keyword args to set or update a dict-type attribute. E.g., x.d = {'a':1, 'b':'two'} can be spelled x.set_d(a=1, b='two') if x's class has the method def set_d(self, **d): self.d = d Of course a little function def mkd(**kw): return kw will allow you to write x.d = mkd(a=1, b='two') and preserve the option to change d smoothly to a property later, which might be a better choice sometimes. Regards, Bengt Richter From mis6 at pitt.edu Tue Jun 17 17:13:39 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 17 Jun 2003 14:13:39 -0700 Subject: feature request: mul References: <2259b0e2.0306110833.24b998cd@posting.google.com> Message-ID: <2259b0e2.0306171313.3648527a@posting.google.com> Jacek Generowicz wrote in message news:... > mis6 at pitt.edu (Michele Simionato) writes: > > > import operator > > multi_and=lambda it: reduce(operator.mul,it) > > if multi_and(condition): > > dosomething() > > > > but frankly it is too ugly for my taste. Having > > 'sum' and 'mul' the use cases for 'reduce' would > > drop, which I think is a good thing. > > You don't like abstraction ? 1. Specific answer for this case: As I said in the postscript, """I like the concept of reduce, but not the syntax, and that is the reason why I *never* use 'reduce' in my programs.""" I find the current syntax little readable. 'reduce' does not seems very abstrac to me. 2. General answer. No, I don't like abstraction for the sake of abstraction. I like abstraction when actually it is useful and help to explain/unify difficult concepts. I HATE abstraction when it is intended to complicate simple things or when you don't need it. On the other hand, excessive simplification is also to be avoided: Things should be made as simple as possible, but not simpler. A. Einstein From marcus at infa.abo.fi Thu Jun 12 05:28:01 2003 From: marcus at infa.abo.fi (Marcus Alanen) Date: 12 Jun 2003 12:28:01 +0300 Subject: can we have a filecmp.cmp() that accept a different buffer size? References: <3EE837DC.5080802@nospam.com> Message-ID: On Thu, 12 Jun 2003 08:20:39 GMT, Kendear wrote: >filecmp.cmp() uses a BUFSIZE of 8k to compare. >For files that are 500MB, the hard disk is really >busy, going back and forth, while my 512MB RAM is >sitting there, sipping margarita. Can we have a >version of filecmp.cmp() (and filecmp's other >methods) that accepts a BUFSIZE, such as 1MB or more? There are some issues with this. First, the stat() call of a file should give the "preferred" value of a buffer size in st_blksize. So if python follows this value, it _should_ already be a good enough value for most uses. Second, in practice some operating system kernels provide read-ahead of files, that is, they sends extra read requests to the hard drive so that future requests from the application don't have to wait so long. So using a BUFSIZE might do no good. Basically, setting the buffer size explicitely is probably a nice-to-have in the short run, but it belongs to the kernel side, IMHO. Regards, Marcus From llafba at gmx.net Thu Jun 12 10:31:47 2003 From: llafba at gmx.net (Tom) Date: Thu, 12 Jun 2003 16:31:47 +0200 Subject: index(x) References: <3EE884B6.3070105@gmx.net> Message-ID: <3EE88ED3.9090200@gmx.net> Hi Thomas, thanks for your code. It works perfectly for my purposes. Yes, I did read the tutorial, but your hint to check out the cookbook was exactly what I was looking for! Thank you. Regards, Tom Thomas G?ttler wrote: >Tom wrote: > >>Hi, >> >>I compare all items in a list with another value. There are always >>multiple matches. I need the list index of every match. But if I use >>index(x) it only returns the first match in that list. There is probably >>a similar command that does exactly what I want, but I can't find it. >> >> > >I would do it like this: >s="..a....a...a.a" >indexes=[] >for i in range(len(s)): > char=s[i] > if char=="a": > indexes.append(i) >print indexes > > > >>Talking about that: is there any good online help or something like >>that? I have the Python Library Reference, but I find that rather >>confusing and with very short explanations. I think they set it up the >>wrong way, because you already have to know the command you are actually >>looking for?! If I want to do something, I want to know which command I >>can use! So, is there any online help or something you can recommend? >> >> > >Did you read the tutorial? If you did and you need some more example code >have a look at the python cookbook. > > thomas > > > > > From exarkun at intarweb.us Sun Jun 22 19:36:52 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sun, 22 Jun 2003 19:36:52 -0400 Subject: Calling a function, arguments in a dict ?? In-Reply-To: References: Message-ID: <20030622233652.GA12439@meson.dyndns.org> On Mon, Jun 23, 2003 at 12:19:24AM +0200, Thomas Weholt wrote: > If I got a dictionary with a bunch of key/values I want to use as named > arguments for a function, how do I do that? > > Say we got a function a, takes three parameters; x,y,z. In my dictionary I > got {'z': 1, 'x': 2, 'y': 3}. How can I create some code that will call it > like this : > > a(z =1, x=2, y=3) d = {'z': 1, 'x': 2, 'z': 3} a(**d) Jp -- "One World, one Web, one Program." - Microsoft(R) promotional ad "Ein Volk, ein Reich, ein Fuhrer." - Adolf Hitler From ed at membled.com Sun Jun 8 06:51:50 2003 From: ed at membled.com (Ed Avis) Date: 08 Jun 2003 11:51:50 +0100 Subject: a = b = 1 just syntactic sugar? References: Message-ID: Steven Taschuk writes: > swap = lambda L,i,j: L[i], L[j] = L[j], L[i] As I mentioned elsewhere on this thread, lambda-functions could be parenthesized where this is necessary. The proposed change to have one-line statements instead of expressions inside lambda would not (AFAIK) make any parse that is currently unambiguous require parentheses; only some new cases such as your example with commas would need it. So swap = lambda L,i,j: (L[i], L[j] = L[j], L[i]) >>Elsewhere you don't have to care about the difference, because any >>expression can be used as an expression_stmt. > >But not the reverse -- statements cannot be used in expressions. >All of the following are illegal, for example: > > while print x: > # ... > > if del x[0]: > # ... > > y = 3 + 4*(assert x > 1) True... but somehow I recognized those as 'obviously unPythonic' and didn't even try to write any of them. Whereas for lambda it was a real surprise that the rules were different from ordinary function definitions. I don't know, maybe some other new Python programmers had a different experience and did have to deliberately unlearn such constructs. FWIW, the only one of those three that I miss is the second; it could be useful to have del x[y] from lists and dictionaries return a value, because it lets you easily check for unhandled keys: dict = {...} name = del dict['name'] age = del dict['age'] for k in dict.keys(): logging.warning('unhandled key ' + k) The idea is that if elsewhere in the program I add a new key but I forget to update this code to handle it, I'll get a warning. You can do this at the moment, of course, but with more lines of code. Anyway the syntax would have to be different since del would become a member function of the dictionary rather than a statement. >You don't usually need to think about the statement/expression >distinction, I agree, but *not* because they're interchangeable in >most contexts -- that's simply false. It's that the division between >them is almost perfectly done, I don't know about perfect - 'print' seems rather an anomaly, and assignment to list and dictionary elements is beginning to look like a strange special case - but I agree that most of the time it works fairly well. Lambda is the only real area where it starts to produce 'surprising' results, and that only because lambda is synactically restricted to contain only expressions. >If there is a problem here, imho it is that lambda makes people want >to put statements in expressions, thereby bringing to centre stage a >distinction which is usually unobtrusive. Anonymity is a red >herring; so are closures; the important point is that lambdas are >expressions and defs are statements. Well a named function has two halves: the 'def f: ...' which is a statement, and the use of the name 'f' which is an expression. Lambda combines both in one place. Letting it contain one-line statements seems like the best compromise between the two worlds. Expressions only is too counterintuitive IMHO. -- Ed Avis From list.adam at twardoch.com Wed Jun 4 05:52:00 2003 From: list.adam at twardoch.com (Adam Twardoch) Date: Wed, 4 Jun 2003 11:52:00 +0200 Subject: "select directory" dialog using win32all? Message-ID: I need to get the Windows system "select directory" dialog using win32all/ctypes. I know this is possible with tk (askdirectory) and wx (wxDirSelector) but I really need to do this without these libraries. Thank you in advance, Adam From Ludger.Humbert at cs.uni-dortmund.de Fri Jun 13 16:38:22 2003 From: Ludger.Humbert at cs.uni-dortmund.de (Ludger.Humbert) Date: Fri, 13 Jun 2003 22:38:22 +0200 Subject: Documentation Tool & UML In-Reply-To: References: Message-ID: <3EEA363E.405@cs.uni-dortmund.de> Yan Weng schrieb: >> And is there a tool available that can generate python code from an UML ? > I am curious about this, too. :) > http://pyut.sourceforge.net/ said they were on the way. But I am not sure > their current status. You may look at DIA for producing UML-Diagrams and saving them in XML-Format http://www.lysator.liu.se/~alla/dia and DIA2CODE to perform the remaining task http://sourceforge.net/projects/dia2code/ just my 2ct based on a strong Euro ;-) Ludger -- ______________________________________________________________________ _____ UniDo / Ludger University of Dortmund, LS Informatik XII ___/ / Humbert didactics of informatics \ \ / D-44221 Dortmund \__\/ Phone: +49 231 755 6141, Fax: +49 231 755 6116 Email: ludger.humbert at uni-dortmund.de ______________________________________________________________________ From fredrik at pythonware.com Tue Jun 24 15:52:37 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 24 Jun 2003 21:52:37 +0200 Subject: printing Unicode characters during telnet session References: Message-ID: Pekka Niiranen wrote: > Python's "print" does not seem to work for all characters :( maybe you should define "does not seem to work", so we don't have to guess... > Do not bother to point me to the existing FAQ and tutorials, because > they do not provide solutions for this problem (searched whole day > allready). do you get "ASCII encoding error: ordinal not in range(128)"? If so, Google returns 641 hits for that error message. The third hit is a "Python Unicode Tutorial" which shows you how to use the "encode" method to turn unicode strings into encoded 8-bit strings, suitable for printing... From dwblas at yahoo.com Mon Jun 2 21:36:22 2003 From: dwblas at yahoo.com (D.W.) Date: 2 Jun 2003 18:36:22 -0700 Subject: 123.3 + 0.1 is 123.3999999999 ? References: <3EC3BCCD.3090605@nospam.com> Message-ID: <895e4ce2.0306021736.13c657a5@posting.google.com> Good article. It is correct when it says that this happens in any language. I always thought it was common knowledge among programmers that "1" could be stored as 0.99999999999999999... It is also common knowledge (although I don;t know why or even if it is true) that this is a result from Intel's initial chip designs i.e. from the way that they store numbers. Hence the many commercial and some open-source math packages that take care of this. I don't know of any easy way to solve this except to round and convert to a string if you are going to store the data. That way, at least, you will be sure of the number of significant digits and therefore the reliability. D.W. > > The Python tutorial has the full story: > > http://www.python.org/doc/current/tut/node14.html > > > I just tried in Perl > > > > print eval("123.3") + 0.1; > > > > and it gives > > 123.4 > > Perl lies. So does Python, if you ask it to: > > >>> print eval("123.3") + 0.1 > 123.4 > >>> print float("123.3") + 0.1 > 123.4 > > From oki at gk-a.com Tue Jun 3 10:08:05 2003 From: oki at gk-a.com (oki mikito) Date: Tue, 3 Jun 2003 23:08:05 +0900 Subject: passing a shell argument In-Reply-To: <11629CCB-95C9-11D7-A50F-000393C7968E@gk-a.com> Message-ID: Hi, sorry for wating the bandwidth; I just found the solution myself: #!/usr/bin/python import sys arg1 = sys.argv[1] ..... ..... ..... On Tuesday, Jun 3, 2003, at 22:41 Japan, oki mikito wrote: > Hi > > I wonder if there's a simple way to pass a shell argument in a tcsh > environment... something like: > > [~/bin] moki% process1 ./*.txt > > I'm currently using `raw_input`, and at each execution of the python > script I type in the file name... & you know how painful it is. > > I looked into the os bunch & found nothing. Could someone guide me to > the correct path??? Thank you very much in advance! > > Yours, > > Oki Mikito > > == > Oki Mikito > GK Associates, Inc. > oki at gk-a.com > > > -- > http://mail.python.org/mailman/listinfo/python-list > > == Oki Mikito GK Associates, Inc. oki at gk-a.com From dwblas at yahoo.com Mon Jun 2 21:15:20 2003 From: dwblas at yahoo.com (D.W.) Date: 2 Jun 2003 18:15:20 -0700 Subject: 123.3 + 0.1 is 123.4 if using a variable References: <3EC3BCCD.3090605@nospam.com> Message-ID: <895e4ce2.0306021715.4cc0ba06@posting.google.com> Evidently, python has different rules for numbers entered in interactive mode. Try this little snippet or just using a float variable. It works both as a program and in interactive mode. x = 123.3 print x for j in range( 0, 3 ) : x += 0.1 print x Results: 123.3 123.4 123.5 123.6 Onward through the fog. D.W. A Puzzled User wrote in message news:<3EC3BCCD. 3090605 at nospam.com>... > In Python 2.2.2 > > >>> float("123.4")+0.1 > 123.5 > > >>> float("123.3")+0.1 > 123.39999999999999 > > >>> float("123.1") + 1 > 124.09999999999999 > > how come there are these inaccuracies? > > > -------------------------------- > P.S. > I just tried in Perl > > print eval("123.3") + 0.1; > > and it gives > 123.4 From leej at dsl.pipex.com Mon Jun 16 11:41:26 2003 From: leej at dsl.pipex.com (Lee John Moore) Date: 16 Jun 2003 15:41:26 GMT Subject: class variable declarations... References: <3EEDD509.890691F5@engcorp.com> Message-ID: One may as well begin with Peter Hansen's letter to comp.lang.python: [..] >> >> class SpeedTouchComm: >> "Interface with the SpeedTouch router" >> def __init__(self, connect, uid, pwd, rtuid, rtpwd): >> self.connect = connect >> self.uid = uid >> self.pwd = pwd >> self.rtuid = rtuid >> self.rtpwd = rtpwd [..] I've left the example in for reference. :-) > Not sure what you mean here. "Class attributes" would > normally mean attributes that are shared by all instances of a > class, as if you were to do "SpeedTouchComm.rtuid = rtuid" in > the above, instead of using "self" which refers to an > *instance*, not the class. I know. I'm referring to connect, uid, pwd, etc. as attributes of the SpeedTouchComm class. I referred to them as variables in a previous post (simply because I would refer to them as declared variables in a similar OP or C++ class), but I was told I should be calling them attributes. So that's where that came from. :-) > Also, what do you mean by "against the law"? I'm trying and failing at being humorous. ;-) What didn't 'feel' like good code is compounded by my difficulty in coming to terms with a language that doesn't require me to declare everything. The above example just doesn't feel very clean (to me), but then you consider it good coding style so I'm clearly just having difficulty adapting. ;-) > to be exactly how *all* Python code works, where you pass > values in to the __init__ method and it dutifully assigns them > to various names in self. I don't think you're being clear, > sorry. > > Maybe the short answer will do: there's nothing wrong with the > above. It even exhibits good coding style! :-) Phew. You're clearer and more concise than I'll ever be. Thank ye kindly for saying that. Did I mention that I love Python? And I've only been studying it on and off for ten days. Even my cron jobs have been ported just for the hell of it. ;-) -- "However far you may travel in this world, you will still occupy the same volume of space." - Traditional Ur-Bororo saying From peter at engcorp.com Thu Jun 5 14:01:02 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 05 Jun 2003 14:01:02 -0400 Subject: All the failed messages from python.org... References: Message-ID: <3EDF855E.6357A467@engcorp.com> Tamir Halperin wrote: > > I'm getting quite a few messages each day with message headers > very similar to the following ones. I'm only providing two examples I believe this started coincident with the sudden spread of a new email virus. Presumably the problem will dry up shortly. Until then, I'm just going to keep quietly hitting "k" (kill thread) and carry on reading the real stuff. If the problem persists for longer (I'm pretty sure it has been only a few days, not like a month or anything), then I would get more concerned. -peter From kmanley at yahoo.com Mon Jun 23 11:11:08 2003 From: kmanley at yahoo.com (kevin) Date: 23 Jun 2003 08:11:08 -0700 Subject: minidom toxml() not emitting attribute namespace qualifier Message-ID: Using Python 2.2.3, with this example code: import xml.dom.minidom XML = """\ """ dom = xml.dom.minidom.parseString( XML ) print dom.toxml() The output is missing the "myns" namespace qualifier on the "att" attribute. Can someone tell me what I'm doing wrong? Thanks, Kevin From Simon.Wittber at perth.maptek.com.au Mon Jun 30 00:51:18 2003 From: Simon.Wittber at perth.maptek.com.au (Simon Wittber (Maptek)) Date: Mon, 30 Jun 2003 12:51:18 +0800 Subject: console mp3->wav decoder for $indows or GUI one which supports console Message-ID: <20E0F651F8B82F45ABCBACC58A2D995B032AB6@mexper1> Hi Egor Bolonev, What is $indows? Sw. From norproaj at yahoo.com Mon Jun 16 09:54:02 2003 From: norproaj at yahoo.com (Dianne Combs) Date: Mon, 16 Jun 2003 06:54:02 -0700 (PDT) Subject: Media/The Northeast Progressive Advocate-Journal Message-ID: <20030616135402.1136.qmail@web41709.mail.yahoo.com> Here it is ... http://www.sfbaygazette.co-inc.com/ ... where some flowers and send the data ... the Tech Guy ...Progressive movement....See our sister paper....The Northeast Progressive Advocate Journal.. The movement is able to reach the East coast to the West coast.....Lets work together for a future for our children.....Thank you for your time....Dianne Combs/Editor and Feature Editor __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From kendear at nospam.com Tue Jun 3 05:48:52 2003 From: kendear at nospam.com (Kendear) Date: Tue, 03 Jun 2003 09:48:52 GMT Subject: easily immobilize PythonWin Message-ID: <3EDC6F0F.2010409@nospam.com> How come the following code can so easily immobilize PythonWin? (won't for IDLE) You can't go in the exec window and press CTRL-C Also, the last printed statement is always not shown. -- from time import sleep while 1: # do something print print "doing something" print "I am sleeping..." sleep(3) print "I just woke up" From grante at visi.com Fri Jun 20 11:43:05 2003 From: grante at visi.com (Grant Edwards) Date: 20 Jun 2003 15:43:05 GMT Subject: Python for Industrial Control References: <53a964f4.0306200718.f342995@posting.google.com> Message-ID: <3ef32b89$0$1381$a1866201@newsreader.visi.com> In article <53a964f4.0306200718.f342995 at posting.google.com>, raymond wrote: > I would like to hear from anyone who does use USB from Linux to > control any sort of industrial device. What were your experiences in > getting it to work?. I've done a fair bit of "USB stuff" under linux, but none of my apps know it's "USB stuff": Linux hides the fact that USB is invovled. The devices all look like normal tty or block devices (I'm using serial ports and mass storage devices). If you're using some other sort of USB device, I would expect that all you have to do is talk to the device driver using normal system calls: open, close, read, write, ioct.... -- Grant Edwards grante Yow! My face is new, my at license is expired, and I'm visi.com under a doctor's care!!!! From spro1 at uic.edu Sun Jun 1 19:38:42 2003 From: spro1 at uic.edu (Sam Pro) Date: 1 Jun 2003 16:38:42 -0700 Subject: Need help with a simple server Message-ID: I am trying to write my first simple server and would like some ideas on improving its stability and security. I want to write something that is as reliable and secure as possible and need to know what I need to look out for. After the code is complete I plan on writing a client and piping it through something like Stunnel (SSL). It would then be used for the exchange of classified data. My biggest consern at this point is that if I run nmap through the port that the server is running I get: Traceback (most recent call last): File "server.py", line 28, in ? input = conn.recv(1024) socket.error: (104, 'Connection reset by peer') I can't have the server crashing at something so trivial. It seems that the buffer isn't big enough to handle nmaps probe??? What should I do? What other input could cause a crash like that? As of now I am just learning Python so please forgive and point out any idiotic mistakes or retarded code. To login to my server telnet to it (port 55000) and issue "USER sam" and then "sam" when prompted for the password. After that you can issue "HELP" to get a list of commands. Thanks, Sam ----------START CODE----------- from socket import * HOST = 'localhost' # Symbolic name meaning the local host PORT = 55000 # Arbitrary non-privileged server WELCOMEMESSAGE = 'Greetings from SamServer V0.1\n' HELPMESSAGE = '''HELO - Display welcome message HELP - Display this command listing ECHO - Echo string (eg ECHO Hello world) QUIT - Exit session KILL - Terminate server ''' serverUp = 1 prompt = '->' s = socket(AF_INET, SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) while serverUp == 1: userAuth = 0 print 'Waiting for connection...' conn, addr = s.accept() print '+++Connected by', addr, '+++' while 1: # Login access cmdstr = '' command = 'NULL' conn.send(prompt) input = conn.recv(1024) command = input[0:4] if len(input[4:]) > 2: cmdstr = input[5:len(input[4:0])-2] if command == 'USER': if cmdstr == 'sam': conn.send('PASS: ') input = conn.recv(1024) if input[:-2] == 'sam': userAuth = 1 print 'Login success by:', cmdstr break else: print '***User', cmdstr, 'provided wrong password!', ' Tried:', input[:-2] break else: print '***User:', cmdstr, 'not found!' break else: print '***ISSUED COMMAND OTHER THEN \"USER\"!' break while userAuth == 1: # Command loop cmdstr = '' command = 'NULL' conn.send(prompt) input = conn.recv(1024) command = input[0:4] if len(input[4:]) > 2: cmdstr = input[5:len(input[4:0])-2] if command == 'HELO': conn.send(WELCOMEMESSAGE) if command == 'HELP': conn.send(HELPMESSAGE) if command == 'QUIT': break if command == 'ECHO': conn.send(cmdstr) conn.send('\n') if command == 'KILL': serverUp = 0 break print command, ' issued @ ', 'TIME', ' with ', cmdstr conn.close() print '---Connection closed to', addr, '---' From aahz at pythoncraft.com Tue Jun 17 20:35:24 2003 From: aahz at pythoncraft.com (Aahz) Date: 17 Jun 2003 20:35:24 -0400 Subject: Getting Instance of calling class References: Message-ID: In article , Steven Taschuk wrote: >Quoth Thomas G?ttler: >> >> I have a function called _() which prints >> strings according to the language of the user. >> >> I don't want to give this method the object which >> holds the language information every time I call it. >> >> How can I access the calling object? > >I'm not sure what you mean by "the calling object". sys._getframe >provides frames from further up the call stack, but I'm not sure >how this relates to what you want to do. > >It sounds a little like you want a dynamically scoped environment >containing (possibly among other things) localization information >for the current user. I suppose you could implement such a thing >by trolling through stack frames, but this seems a bit hackish. > >An alternative approach would be to pass _ into each function >which needs to produce output. _ could be a closure, > def makelocalizer(lang): > def _(s): > # return s in language lang > return _ >for example. This avoids passing the language to _, but adds >passing _ around. Does this help at all? Close. _() should be an attribute of the user object. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From lists at andreas-jung.com Tue Jun 24 06:08:27 2003 From: lists at andreas-jung.com (Andreas Jung) Date: Tue, 24 Jun 2003 12:08:27 +0200 Subject: d.keys() and d.values() In-Reply-To: <20030624100333.GA2595@nl.linux.org> References: <20030624100333.GA2595@nl.linux.org> Message-ID: <2147483647.1056456507@[192.168.0.102]> I don't think it is guaranteed but usually it works. Why don't you use d.items()??? -aj --On Dienstag, 24. Juni 2003 12:03 Uhr +0200 Gerrit Holl wrote: > Hi, > > is it guaranteed that dict(zip(d.keys(), d.values())) == d? > In words, do .keys() and .values() always have the same order? Is > it safe to rely on this? > > yours, > Gerrit. > > -- > 279. If any one by a male or female slave, and a third party claim it, > the seller is liable for the claim. > -- 1780 BC, 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/ > > -- > http://mail.python.org/mailman/listinfo/python-list From stardif10 at hotmail.com Thu Jun 5 04:30:11 2003 From: stardif10 at hotmail.com (Sam) Date: Thu, 05 Jun 2003 18:30:11 +1000 Subject: Screenshots Message-ID: <3EDEFF92.654485D1@hotmail.com> Hello all, I am looking for a way to take screenshots of the desktop. The files don't need to be opened or viewed, just saved with a filename the user gives. I'm developing this in a Windows environment. If you could give me any links or hints about this I would be most appreciative. Thanks for any help, Sam. From wweexxsseessssaa at telusplanet.net Sun Jun 15 21:08:56 2003 From: wweexxsseessssaa at telusplanet.net (John Hall) Date: Mon, 16 Jun 2003 01:08:56 GMT Subject: Python articles References: Message-ID: On Sun, 15 Jun 2003 18:58:48 -0300, Gustavo Niemeyer wrote: >> >[1] https://moin.conectiva.com.br/GustavoNiemeyer >> >> Your website is about 2 meters wide, but my monitor only about 300mm, >> so reading it is rather inconvenient. >> (IE V6 on Windows 2000 Pro) > >Thanks for notifying me about this. I'll try to fix it, >once I have access to such beast. :-) > BTW I noticed this on the first page only, Gustavo. -- John W Hall Calgary, Alberta, Canada. "Helping People Prosper in the Information Age" From mis6 at pitt.edu Thu Jun 19 17:32:19 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 19 Jun 2003 14:32:19 -0700 Subject: a clean way to define dictionary References: <3EEFEBFD.8090003@nospam.com> <2259b0e2.0306190831.63d42265@posting.google.com> Message-ID: <2259b0e2.0306191332.664300c0@posting.google.com> Alexander Schmolck wrote in message news:... > mis6 at pitt.edu (Michele Simionato) writes: > > Well, your timings are not all that meaningful because your code does nothing > and you only instance creation and not item access (which obviously also needs > to be overridden with python code). This was on purpose, I wanted to measure the slowdown due to "pure" subclassing, i.e. without doing anything to __getattr__ and __setattr__. > Anywhere, here is a real DefaultDict class > and some ad hoc timings, which show *10* fold slowdown for creation and 4 fold > for item access (the copy.copy call seems harmless performance-wise). > > class DefaultDict(dict): > r"""Dictionary with a default value for unknown keys.""" > def __init__(self, default, noCopies=False): > self.default = default > if noCopies: > self.noCopies = True > else: > self.noCopies = False > def __getitem__(self, key): > r"""If `self.noCopies` is `False` (default), a **copy** of > `self.default` is returned by default. > """ > if key in self: return self.get(key) > if self.noCopies: return self.setdefault(key, self.default) > else: return self.setdefault(key, copy.copy(self.default)) > > timings for python2.2 > > In [58]: timeCall(nTimes, 10000, dict) > Out[58]: 0.018522977828979492 > > In [59]: timeCall(nTimes, 10000, DefaultDict, 1) > Out[59]: 0.11231005191802979 > > In [47]: timeCall(nTimes, 10000, {'foo':0}.__getitem__, 'foo') > Out[47]: 0.012811064720153809 > > In [48]: timeCall(nTimes, 10000, DefaultDict(1).__getitem__, 'foo') > Out[48]: 0.045480012893676758 > > In [65]: timeCall(nTimes, 10000, DefaultDict(1,0).__getitem__, 'foo') > Out[65]: 0.04657900333404541 > > > What are your results for instance creation with this class? Maybe 2.3 is > noticeably faster? > > > 'as I should perform a series of tests; anyway, some simple experiment with attribute access gives me a slowdown of ~14 times. Quite a lot. However, my point was that you can bypass the Python 2.3 change in the dictionary constructor signature by overriding __new__ and *not* changing __getattr__. In this way, you don't have a performance problem. Of course, if you override __getattr__, there is an issue, but the issue would be the same with Python 2.2. I am curious to test the difference between Python 2.2 and 2.3; I will look at the instance creation time too, but this is less important than the access time, since typically I create a dictionary only once. Michele From mal at lemburg.com Tue Jun 3 03:18:06 2003 From: mal at lemburg.com (M.-A. Lemburg) Date: Tue, 03 Jun 2003 09:18:06 +0200 Subject: Oracle 9i Lite and ODBC In-Reply-To: <3edb17ba@cpns1.saic.com> References: <3edb17ba@cpns1.saic.com> Message-ID: <3EDC4BAE.9020809@lemburg.com> BDM wrote: > Has anyone been successful in getting python to connect to an Oracle 9i Lite > database via either the ODBC or mxODBC modules? I'm seeing a situation > where when attempting to make a connection, python goes into a continual run > state and never returns. Which platform is this and which ODBC drivers are you using ? -- Marc-Andre Lemburg eGenix.com Professional Python Software directly from the Source (#1, Jun 03 2003) >>> Python/Zope Products & Consulting ... http://www.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ EuroPython 2003, Charleroi, Belgium: 21 days left From heikowu at ceosg.de Mon Jun 2 15:04:39 2003 From: heikowu at ceosg.de (Heiko Wundram) Date: 02 Jun 2003 21:04:39 +0200 Subject: ANN: yawPyCrypto 0.0alpha4 Message-ID: <1054580679.26953.9.camel@d168.stw.stud.uni-saarland.de> yawPyCrypto (yet another wrapper for PyCrypto) aims to be a more full-featured PyCrypto wrapper than e.g. ezPyCrypto is. It allows you to use all standard functions ezPyCrypto offers, but with the difference that access to parts of the API is factored out into distinct classes. This enables features like multiple recipient specification of encrypted packets, ascii armoring using a custom armoring routine, and several other goodies which the interface of ezPyCrypto hides/doesn't allow. Another goodie is that all conversions string to tuple and reverse, which PyCrypto requires quite a few, are handled using a custom serializer, which is simple enough that there shouldn't be any security holes as when using Pickle (which ezPyCrypto uses for most of these operations). The current version of yawPyCrypto is the first real release. If the functionality that you find in the package suits you, I would ask you to give it a try and send me any bug reports/difficulties you experience while using it, so that I can work on stability (which has been left behind for security and functionality so far). More info, especially concerning the encoded stream layout, and additional specifications, can be found on the website. yawPyCrypto 0.0alpha4 URL: http://ph0enix.homelinux.org/~heiko Author: Heiko Wundram License: LGPL - Lesser General Public License Dependencies: - Python 2.2.2 (or later, it should be easy to make it available for Python versions 2.1 onwards, but I just don't have the time, and I use 2.2.2 here). - PyCrypto 1.9a6 (or later, which AFAICT has changed the interface to stream ciphers quite a bit, so I won't do any backports). Demo code is contained in the file itself, as functions _main*(). -- Heiko Wundram Universit?t 18 - Zimmer 2206 66123 Saarbr?cken - Germany From alanmk at hotmail.com Mon Jun 23 11:33:15 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 23 Jun 2003 16:33:15 +0100 Subject: minidom toxml() not emitting attribute namespace qualifier References: Message-ID: <3EF71DBB.321885B4@hotmail.com> kevin wrote: > Using Python 2.2.3, with this example code: [Code elided] > The output is missing the "myns" namespace qualifier on the "att" > attribute. Can someone tell me what I'm doing wrong? That's a bug in minidom. I reported it back in November 2002, but I wasn't precise enough about version numbers, so it went unaddressed. https://sourceforge.net/tracker/?func=detail&atid=106473&aid=637355&group_id=6473 I will update that bug report now that I can see for sure that the bug is still present in 2.2.3. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From johngale at canada.com Fri Jun 6 12:32:21 2003 From: johngale at canada.com (John Gale) Date: Fri, 06 Jun 2003 16:32:21 GMT Subject: LANGUAGE QUESTION??? References: <8dcf2300.0306040159.118c24e8@posting.google.com> Message-ID: Grant Edwards wrote in news:slrnbe01ur.cai.grante at localhost.localdomain: > In article , phil hunt > wrote: > >> A hammer is the best tool by far, we should use it for everything, >> and throw away all our screwdrivers. > > Ah, but the effects of a hammer when combined with a screwdriver far > surpasses the sum of the individual effects. Just remember never to > hammer a screwdriver into a CRT. > oops From ajc1961 at yahoo.com Wed Jun 11 15:06:53 2003 From: ajc1961 at yahoo.com (anthony) Date: 11 Jun 2003 12:06:53 -0700 Subject: Jython anyone? Message-ID: Does anyone have strong feelings one way or another regarding Jython? I just started playing around with it, but the limited online discussions and the sort have me wondering if it's worthwhile. Any thoughts? Anthony From fredrik at pythonware.com Fri Jun 27 12:49:38 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 27 Jun 2003 18:49:38 +0200 Subject: Possible project - Python mail proxy to do greylisting, etc. References: Message-ID: Richie Hindle wrote: > async and Twisted are basically > the same thing. yeah, but one of them comes with more hype. From dave at boost-consulting.com Mon Jun 16 11:59:47 2003 From: dave at boost-consulting.com (David Abrahams) Date: Mon, 16 Jun 2003 11:59:47 -0400 Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> <1055736914.49032@yasure> Message-ID: "Donn Cave" writes: > Quoth danb_83 at yahoo.com (Dan Bishop): > | beliavsky at aol.com wrote in message news:<3064b51d.0306151228.22c595e0 at posting.google.com>... > ... > |> Thus, if I define a function correl(x,y) to compute the correlation of > |> two vectors, which makes sense to me only if x and y are 1-D arrays of > |> real numbers, > | > | But what kind of real numbers? IEEE double-precision? Or might you > | someday need a correl function that works with ints (e.g., to compute > | Spearman's correlation coefficient), or arbitrary-precision floats, or > | BCD numbers, or rational numbers, or dimensioned measurements? > | > | As long as your number classes have +, -, *, /, and __float__ (so > | math.sqrt works) defined correctly, you don't have to rewrite your > | correl code to support them. THAT is the beauty of dynamic typing. > > Or the beauty of static typing. In a rigorously statically typed > language like Haskell, you'd write your function more or less the > same as you would in Python, but the compiler would infer from the > use of +, -, etc. that its parameters are of type Num, and you would > be expected to apply the function to instances of Num - any numeric > type. Anything else is obviously an error, and your program won't > compile until it makes sense in that respect. > > One would think from reading this thread that this would be good > for safety but hard to program for, but it's actually the opposite. > I'm told that type checking is practically irrelevant to safety > critical standards, because the testing needed to meet standards > like that makes type correctness redundant. But the compiler cleans > up lots of simple errors when you're writing for more casual purposes, > and that saves time and possibly embarrassment. I find that static typing makes a big difference for two things: 1. Readability. It really helps to have names introduced with a type or a type constraint which expresses what kind of thing they are. This is especially true when I am coming back to code after a long time or reading someone else's work. Attaching that information to the name directly is odious, though, and leads to abominations like hungarian notation. 2. Refactoring. Having a compiler which does some static checking allows me to make changes and use the compiler as a kind of "anchor" to pivot against. It's easy to infer that certain changes will cause compiler errors in all the places where some corresponding change needs to be made. When I do the same thing with Python I have to crawl through all the code to find the changes, and a really complete set of tests often take long enough to run that using the tests as a pivot point is impractical. -- Dave Abrahams Boost Consulting www.boost-consulting.com From rmunn at pobox.com Mon Jun 2 12:16:05 2003 From: rmunn at pobox.com (Robin Munn) Date: Mon, 02 Jun 2003 16:16:05 GMT Subject: (no subject) References: Message-ID: Vijay Anand R. wrote: > This is a multi-part message in MIME format. [snip 300+ lines of ugly HTML for a six-line question] Ewwwww. *PLEASE* turn off HTML in your E-mail or Usenet client software. I didn't even bother trying to read your post, since it had gotten so badly mangled; I'm sure others had the same reaction. Plain text is by far the best way to ask questions on this newsgroup. If you need help switching your mail/news client to plain text, this site: http://www.expita.com/nomime.html has tips on how to do that in just about any program; click on yours from the list. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From sebastien.hugues at swissinfo.org Tue Jun 17 05:29:04 2003 From: sebastien.hugues at swissinfo.org (Sebastien Hugues) Date: Tue, 17 Jun 2003 11:29:04 +0200 Subject: Python 2.2.2 win32 build Message-ID: <3EEEDF60.9090005@swissinfo.org> Hi, I built Python 2.2.2 dll and exe under win32 using Visual Studio and now i wonder how i could make a distribution from my build. The official distribution uses Wise, but i didn't see and config file for Wise in the package... Any ideas ? Thanks in advance Regards Sebastien From staschuk at telusplanet.net Sat Jun 21 10:54:33 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Sat, 21 Jun 2003 08:54:33 -0600 Subject: unittest and automatically firing off tests In-Reply-To: ; from tomas@fancy.org on Fri, Jun 20, 2003 at 09:57:37PM -0700 References: Message-ID: <20030621085433.A370@tibia.amotlpaa.bogus> Quoth Tom Plunket: [...] > 1) Why in the name of all that is holy does unittest.main() throw > regardless of tests passing? unittest.main is not intended for use other than if __name__ == '__main__': unittest.main() and in this use, raising SystemExit is fine. > 2) Why can't I readily pass a list of tests to unittest.main()? > (I mean, besides the fact that it's not implemented; was this > a concious ommision?) unittest.main is just a convenience function for the most common case; if you want fancier things, you'll have to write them yourself. The module does have facilities to make this easy: def suite(dirname): """Create a TestSuite for the test files in the given directory.""" suite = unittest.TestSuite() for filename in glob.glob(os.path.join(dirname, 'test_*.py')): modname = os.path.splitext(os.path.basename(filename))[0] modfile = file(filename) try: mod = imp.load_module(modname, modfile, filename, ('.py', 'r', imp.PY_SOURCE)) finally: modfile.close() modsuite = unittest.defaultTestLoader.loadTestsFromModule(mod) suite.addTest(modsuite) return suite if __name__ == '__main__': runner = unittest.TextTestRunner() result = runner.run(suite('.')) if result.wasSuccessful(): sys.exit(0) else: sys.exit(1) (Untested.) > 3) I feel like I should automatically batch up tests and fire > them off to unittest.run() or something similar. Is this as > straight-forward and easy, and could I batch them all into one > mega-suite? Are there any reasons why I wouldn't want to do > that? Putting all your tests in a suite and running that suite is entirely proper. See above. -- Steven Taschuk "[W]e must be very careful when we give advice staschuk at telusplanet.net to younger people: sometimes they follow it!" -- "The Humble Programmer", Edsger Dijkstra From cnetzer at mail.arc.nasa.gov Fri Jun 6 02:29:15 2003 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: 05 Jun 2003 23:29:15 -0700 Subject: Postfix/Prefix Operators (++,--) In-Reply-To: <1054878539.22405.4.camel@mylinuxsite.com> References: <1054878539.22405.4.camel@mylinuxsite.com> Message-ID: <1054880955.542.31.camel@sayge.arc.nasa.gov> On Thu, 2003-06-05 at 22:49, hostmaster wrote: > Python doesn't seems to support postfix/prefix operators (e.g. i++, > --i). Why? Because it doesn't need them, and they cause a lot of problems in C and C++. Those languages need them because of the way their looping constructs work. One has to do lots of pointer arithmetic or indexing in C/C++, where the postfix and prefix operators work well. But they can easily be used to make non-portable, undefined behavior happen in the code. Python has 'for' loops that automatically iterate over sequences, and so doesn't really need the prefix and postfix operators. It avoids their complexity entirely. They are rarely missed by those who have adjusted to Python. When you need to increment a variable, you can do this: a += 1 When you need to iterate over a sequence, use a 'for' loop: seq = ["a", "b", "c"] for char in seq: print char No incrementing necessary. -- Chad Netzer (any opinion expressed is my own and not NASA's or my employer's) From mchermside at ingdirect.com Thu Jun 19 13:06:40 2003 From: mchermside at ingdirect.com (Chermside, Michael) Date: Thu, 19 Jun 2003 13:06:40 -0400 Subject: a clean way to define dictionary Message-ID: <7F171EB5E155544CAC4035F0182093F0018329DF@INGDEXCHSANC1.ingdirect.com> Skip Montanaro wrote: > > >> In 2.3, you can express this as dict(foo=1, bar='sean') without a > >> need to define a function for the purpose. > > Alexander> Yuck! This seems like a really bad idea to me. This > Alexander> effectively makes it impossible to specify any options > (such Alexander> as initial size, default value etc.) > > I don't see that the behavior of dict() affects your ability to define the > behavior of a subclass. Alex Martelli replies: > To play devil's advocate -- it does so by Liskov substitution principle > (if all keywords must be passed untouched to built-in dict to emulate > its behavior, you can't steal some of them to control your subclass's, > within the constraint of being able to drop your subclass in lieu of > dict into an existing piece of code without breaking it). Please help me understand this. I thought LSP said essentially that INSTANCES of the subclass should be drop-in replacements for INSTANCES of the superclass. But the constructor is really not a property of INSTANCES... it's clearly a property of the class itself. So... am I missing something here? -- Michael Chermside PS: I do agree that it's mildly annoying for subclassing dict, and that it's mildly useful for brevity & clarity in declaring some dicts, and that if anyone actually OBJECTS (which I don't) that python-dev is the place to speak up pretty-darn-quick. ----- mandated disclaimer below ----- 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 v.wehren at home.nl Thu Jun 19 15:06:25 2003 From: v.wehren at home.nl (vincent wehren) Date: Thu, 19 Jun 2003 21:06:25 +0200 Subject: TypeError: Value() takes at most 2 arguments (3 given) References: Message-ID: "Max Barry" schrieb im Newsbeitrag news:mailman.1056044255.14205.python-list at python.org... > I am having problems calling a VB6 let property from a class in python. I > get a TypeError: Value() takes at most 2 arguments (3 given). I presume the > self is being passed as the 3rd argument. Here is an example of the class: > > class someclass: > def foo(): How's about: def foo(self): self.test(somevbobject) Regards, Vincent Wehren > self.test(somevbobject) > > def test(self, Result): > Result.Value(1, 0) > > > This is the VB property that python calls: > Public Property Let Value(ByVal lngIndex As Long, ByVal sngNew As Single) > ' Notice: presumed to be zero-based values > msngValues(lngIndex + 1) = sngNew > End Property > > Does anybody know how to resolve this problem? > > Thanks in advance, > Max > > > > > From staschuk at telusplanet.net Sun Jun 8 02:27:29 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Sun, 8 Jun 2003 00:27:29 -0600 Subject: a = b = 1 just syntactic sugar? In-Reply-To: <3EE25DE1.5010408@geekabytes.net>; from junk@geekabytes.net on Sat, Jun 07, 2003 at 03:49:21PM -0600 References: <3EE25DE1.5010408@geekabytes.net> Message-ID: <20030608002729.A3370@tibia.amotlpaa.bogus> Quoth junk: [...] > If you care, I wrote a little function that will return the current > function within a block. This means, you can have anonymous recursive > functions like this: > > import selfref > factorial = lambda x: ((x==0)*1) or (x * selfref.myself(x-1)) This is certainly clever, but imho good style demands writing even so simple and familiar a function more directly. Besides the simple loss of clarity, I don't see how (without helper functions defined more sensibly) you'd add a check to the above that x >= 0 (raising a ValueError if it isn't). Or a docstring, for that matter. I can't think offhand of a useful recursive function simple enough to be clear when written this way; in other words, I can't think of a case where I'd actually use this. > Here is the code: > > def myself(*args): > prevFrame = sys._getframe(1) > myOwnCode = prevFrame.f_code > myOwnFuncObj = new.function(myOwnCode, globals()) > return myOwnFuncObj(*args) > > The only thing this doesn't do is to capture default arguments!!! [...] I don't see the problem with default arguments: >>> f = lambda a, b=5: (b<1 and 1 or a*selfref.myself(a, b-1)) >>> f(3) 243 Am I missing something? Keyword arguments are definitely missing, of course, but that lack is easily remedied: def myself(*args, **kwargs): prevFrame = sys._getframe(1) myOwnCode = prevFrame.f_code myOwnFuncObj = new.function(myOwnCode, globals()) return myOwnFuncObj(*args, **kwargs) I'm fairly sure you don't want to use globals() here, though. Here's why: >>> import selfref >>> x = 3 >>> f = lambda n: n < 1 and 1 or x + selfref.myself(n-1) >>> f(2) Traceback (most recent call last): [...] NameError: global name 'x' is not defined What you want is, I expect, prevFrame.f_globals. -- Steven Taschuk staschuk at telusplanet.net "I may be wrong but I'm positive." -- _Friday_, Robert A. Heinlein From m at moshez.org Thu Jun 12 13:45:18 2003 From: m at moshez.org (Moshe Zadka) Date: 12 Jun 2003 17:45:18 -0000 Subject: SocketServer - Connection Reset By Peer (Randomly) In-Reply-To: <36%Fa.387$5e4.12506@nnrp1.ozemail.com.au> References: <36%Fa.387$5e4.12506@nnrp1.ozemail.com.au> Message-ID: <20030612174518.30743.qmail@green.zadka.com> On Thu, 12 Jun 2003, "Graeme Matthew" wrote: > I am using Python's SocketServer.ThreadingTCPServer. It all works fine up to > a point. ... > I can sometimes submit the webpage (controller.py) 10 times without an > Internal Server Error, and sometimes 3, its random, the http log files says: > > > File "/www/bi/cgi-bin/controller.py",line 30, in ? > response = sock.recv(1024) > socket.error: (104, 'Connection reset by peer') It looks like you have a problem with the application server: it closes the connection down. socket.recv dutifully informs you of that. So, the application server is what I suspect. You have not shown any code from it, so it is hard to pinpoint your problem. One question: why are you using a home-grown solution for passing objects between Python applications instead of using something like Pyro, CORBA, Twisted's perspective broker or XML-RPC? You are usually better off *not* reinventing wheels. Further debugging tips: take the webserver out of the question by making controller.py be a command line script, and run it in a tight loop. Then, put lots and lots of prints in your application server (or maybe run it under PDB, though it might get tricky with threads) to see where the problem is. But, again, my suggestion: go with tried and true solutions. -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From max at cNOvSisiPonAtecMh.com Wed Jun 11 15:25:24 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Wed, 11 Jun 2003 19:25:24 GMT Subject: Need urgent solution...................... References: <20030611181102.5745.84605.Mailman@mail.python.org> Message-ID: I am not sure what's not specific enough about the OP's q-n. I understand the q-n fine (anthough I am not able to answer it in terms of TkInter). Perhaps you should refer to this: http://www.catb.org/~esr/faqs/smart-questions.html#bespecific -- ======================================== 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] "Joe Grossberg" wrote in message news:mailman.1055355627.11726.python-list at python.org... > We know your time is important. So is ours. Please post with a more > informative title next time (e.g. "How do I determine pixel width of > text in a Tkinter canvas?", and you'll be more likely to get helpful > answers. > > More info here: > http://www.catb.org/~esr/faqs/smart-questions.html#bespecific > > Good luck, > Joe > > -- > ---------------------------------------------------------- > Joe Grossberg :: Programmer :: jgrossberg at matrixgroup.net > http://www.matrixmaxx.net/ :: Custom Web Solutions and > Web-Based Association Management Software. > > > From mhammond at skippinet.com.au Fri Jun 13 06:30:25 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 13 Jun 2003 10:30:25 GMT Subject: MSW crash with In-Reply-To: <246a4e07.0306120739.74dd977a@posting.google.com> References: <246a4e07.0306120739.74dd977a@posting.google.com> Message-ID: <5JhGa.3746$GU5.51113@news-server.bigpond.net.au> Frank Millman wrote: > Can anyone explain what is going on? Thanks in advance. It smells like a reference count bug in the ODBC module. What win32all version are you using? I have no database to test against, but if you can reduce it down to the absolute minimum code needed to crash, I may still be able to find it. If you have an old win32all or ActivePython, please check the date - a quick check of the log for the ODBC module shows the following checkin: revision 1.5 date: 2001/06/18 06:57:21; author: mhammond; state: Exp; lines: +7 -7 Patches from Alex Martelli that solves some crashes under error conditions. A later ODBC module may fix your problem. Mark. From P.Schnizer at nospam.gsi.de Tue Jun 3 11:55:02 2003 From: P.Schnizer at nospam.gsi.de (Pierre Schnizer) Date: 03 Jun 2003 17:55:02 +0200 Subject: wxPython + wxGrid + data shape change. Message-ID: <871xybqhpl.fsf@smtp.gsi.de> Dear all, I am using a wxGrid and a grid.wxPyGridTableBase to display data to the user. These data consist of a list of arrays. Each array is one column. At startup the size of the grid matches the data size. Now the user can add columns to the grid. How do I trigger the grid to display a new column? I am using wxPython 2.4.0.2 together with python2.2.1 on a debian stable. My GTK version is 1.2.10. Thank you for your help in advance. Yours sincerely Pierre -- Remove nospam for a direct reply From jdhunter at ace.bsd.uchicago.edu Thu Jun 26 22:37:57 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 26 Jun 2003 21:37:57 -0500 Subject: stupid question about os.listdir In-Reply-To: (Jason Kratz's message of "Fri, 27 Jun 2003 02:25:16 GMT") References: Message-ID: >>>>> "Jason" == Jason Kratz writes: Jason> oops. almost forgot. if I run interactively in the python Jason> interpreter it works as I expect. its when doing 'python Jason> script.py' from the command line that it only uses the Jason> current directory. Code, we need more code. Please post an example, your platform, and python version. The following works for me on linux w/ python2.2 called as > python scriptname.py import os print os.listdir('/home/jdhunter') print os.listdir('/home/jdhunter/python') and the same script (w/ different test paths) works on win32 w/ python 2.2. JDH From mmaru at attcanada.ca Mon Jun 23 23:31:05 2003 From: mmaru at attcanada.ca (Mulugeta Maru) Date: Mon, 23 Jun 2003 22:31:05 -0500 Subject: Python and Jython Message-ID: My background is Java. I would like to know the difference between Python and Jython. Are they different languages? Should I learn Python first and then Jython? The reason I would like to learn the language is to use it with Java. I just spend one hour on a Python tutorial - the language is just a thing of beauty! From pinard at iro.umontreal.ca Fri Jun 27 07:47:13 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois_Pinard?=) Date: 27 Jun 2003 07:47:13 -0400 Subject: Activating `-i' from inside a script? In-Reply-To: References: Message-ID: [Fernando Perez] > Fran?ois, you might want to look at ipython's embedding. [...] After > checking your trigger condition, an ipshell() call will load ipython in > the current data context. I did not think about loading `ipython' after the fact. The nice thing about your idea is that my co-workers are already used to IPython, so it would be natural for them to find themselves in that interaction context. Thanks for replying! :-) -- Fran??ois Pinard http://www.iro.umontreal.ca/~pinard From donald.welch.nospam at hp.com Fri Jun 6 13:47:09 2003 From: donald.welch.nospam at hp.com (djw) Date: Fri, 06 Jun 2003 10:47:09 -0700 Subject: Directory & File Monitoring References: <6f8cb8c9.0306060731.21813c29@posting.google.com> <3EE0D056.288CC1F4@engcorp.com> Message-ID: Peter Hansen wrote: > Steve wrote: >> >> Hi; >> >> I would like to write a python script for windows 2000 that will log >> who/what touches a particular file in a particular directory. >> >> Is this possible with python alone or do I need to access some Windows >> api( and which one?)? > > Probably not possible with Python alone, and certainly not something > that will be portable (not that you seem to mind). > > Can you define what "touch" means? Do you mean even looking at the > file, or do you mean in the more technical sense of the "touch" > utility, where at least the timestamp is modified? Or do you just > want to know if the contents are actually changed? What about if > the file is deleted? > > Also, what do you mean by "who" and "what"? The name of the > application that is doing the touching, and the userid of the > authenticated user who is running that application? > > Maybe even more useful would be for us to understand better why you > want to do this. It's an unusual thing to want to do at the user > level (i.e. not as part of an OS security/logging feature) and > maybe there's a better solution. > > -Peter Would this work for you? http://sysinternals.com/ntw2k/source/filemon.shtml Not Python, but it accomplishes what you are after. Don From duduca007 at yahoo.com Tue Jun 10 15:02:06 2003 From: duduca007 at yahoo.com (Carlos Moreira) Date: Tue, 10 Jun 2003 12:02:06 -0700 (PDT) Subject: You know you're a Pythonista when.. In-Reply-To: <16102.10640.855883.967908@montanaro.dyndns.org> Message-ID: <20030610190206.54459.qmail@web11407.mail.yahoo.com> --- Skip Montanaro wrote: > > ... > > >> 3) Discovering filter() and map(). > > >> 4) Fortifying classes with __setattr__() and > friends. > > >> 4.5) Leaving if:, elif:, and else: on their > own lines for fear of > >> scorn or deprecation. > > 5) Discovering list comprehensions and then > dumping filter() and map(). 6) Belive that "self" is not ugly :))) []'s Cadu Moreira #000101 GoboLinux User __________________________________ Do you Yahoo!? Yahoo! Calendar - Free online calendar with sync to Outlook(TM). http://calendar.yahoo.com From max at alcyone.com Mon Jun 9 19:02:13 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 09 Jun 2003 16:02:13 -0700 Subject: PEP 318 - Function Modifier Syntax References: <20030609081617512-0400@braeburn.themorgue.org> Message-ID: <3EE511F5.92F88F71@alcyone.com> Beni Cherniavsky wrote: > In the latter case you don't need new builtins at all. Just > compile:: You don't need it for the `as' case, either. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ You are free and that is why you are lost. \__/ Franz Kafka From adalke at mindspring.com Wed Jun 4 12:34:17 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 4 Jun 2003 10:34:17 -0600 Subject: Fixed-length fields in Martel References: Message-ID: Michael Schmit: > > Do you mean my Martel, the regexp parser which generates SAX events? > > Yes. So people are actually using it. Cool! > What would you suggest for processing this tabular data? The desired output > would be a table (list of lists). Naming each column might be too > complicated for many columns. Pass the whole table as event and disassemble > in the ContentHandler? Pass lines as events? This would make the > ContentHandler to disassemble the table again. How to avoid this > redundancy? What do you need the output to look like? You could name everything the same ("field") if it's inappropriate to name every field different. You could push the parsing into the ContentHandler (I've got some experimental code in the lastest Martel to allow content handlers to say they are willing to do extra processing, for performance sake.) Also, take a look at the "LAX" content handler, included with Martel. It's meant to be a simple way to read lists of fields from flat XML reords and helps with columnar data. > Validity: > If the lines have no fixed part (like "ATOM") the combination of fixed_width > expressions matches any line of appropriate length. How to make that more > robust. Require whitespace separation between columns? So fixed number of characters in a field plus whitespace between them? Re("[^\s]{6}") + Re("[ \t]+") + .... + AnyEol() This reads 6 non-space characters followed by one or more spaces or tabs, etc. and then the newline. Andrew dalke at dalkescientific.com From tylere at hotpop.com Tue Jun 3 08:51:49 2003 From: tylere at hotpop.com (Tyler Eaves) Date: Tue, 03 Jun 2003 12:51:49 GMT Subject: Exception - how to ignore it ? References: Message-ID: Helmut Jarausch wrote: > Hi, > > is it possible for an exception handler > to just e.g. print something and set some > global flags but then to have the script > continue just after the statement which > raised the exception? > > Thanks for a hint, > > Helmut Jarausch > > Lehrstuhl fuer Numerische Mathematik > RWTH - Aachen University > D 52056 Aachen, Germany Sure try: a = 4 / 0 except: print 'Ooops!' From troy at gci.net Fri Jun 27 02:09:44 2003 From: troy at gci.net (Troy Melhase) Date: Thu, 26 Jun 2003 22:09:44 -0800 Subject: Activating `-i' from inside a script? References: Message-ID: >> Is there a way for a script to activate the effect of the `-i' option, > something like this might work: > > if discrepancy and sys.stdin.isatty(): > import code; code.interact(local=globals()) Fran?ois, Fredrik: I thought this would work, but it doesn't: import os if __name__ == '__main__': discrepancy = True if discrepancy: os.environ['PYTHONINSPECT'] = "why yes, i'd like that" A quick read of Modules/main.c shows that the environment variable is checked at program start, not at end. Maybe this is a bug? -troy From mis6 at pitt.edu Sun Jun 8 08:21:41 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 8 Jun 2003 05:21:41 -0700 Subject: a = b = 1 just syntactic sugar? References: Message-ID: <2259b0e2.0306080421.4a5fa99d@posting.google.com> Ed Avis wrote in message news:... > Of course it seems a little clunky to define these > functions with a name that is then never used except to return them > anonymously I have recently come to the habit of calling "_" my anonymous functions (especially in closures). It is very unobstrusive, clear, and save me the effort of thinking if I should name the internal function wrap, wrapper, wrapped, on any other similar verbose combination ;) Michele From evan at 4-am.com Fri Jun 27 13:58:31 2003 From: evan at 4-am.com (Evan Simpson) Date: Fri, 27 Jun 2003 12:58:31 -0500 Subject: Possible project - Python mail proxy to do greylisting, etc. In-Reply-To: References: Message-ID: <3EFC85C7.3090703@4-am.com> Richie Hindle wrote: > Spambayes (a Python Bayesian spam filter, see www.spambayes.org) has a > Python SMTP proxy Ah, thanks. I knew it had POP3 and IMAP proxies, but not SMTP. I was obviously not clear enough when I said "project like this", though. Python code to proxy SMTP isn't hard to come by, but I was talking about a Python proxy that does interesting things with the data provided by HELO, RCPT TO, and MAIL FROM. In particular, I'm interested in making it very easy to experiment with various greylisting, tarpitting, and sender validation configurations. I could certainly start from Spambayes' code, or just use async, but I'm also interesting in judging Twisted for myself. Cheers, Evan @ 4-am From bsimuyandi at africonnect.com Fri Jun 13 04:37:57 2003 From: bsimuyandi at africonnect.com (Ben Simuyandi) Date: Fri, 13 Jun 2003 09:37:57 +0100 Subject: Newbie: changing an attribute of objects in a list References: <20030611120656.F1157@tibia.amotlpaa.bogus> <20030612111547.B902@tibia.amotlpaa.bogus> Message-ID: I'm very sorry about the confusion. It comes from mistyping, and not thinking through my problem. The first problem is from me not entering the number correctly. As you say, it should be a.order = 8 and g.order =9. As for the second problem, this is because I had not thought about *exactly* what I want. What I would like is for the .age to be compared if any items have matching .order values, and the object with the larger .age value to have its .order value increased by one. for example: if d.order and e.order match compare d.age and e.age if d.age > e.age d.order = d.order + 1 else if d.age < e.age e.order = e.order + 1 But after that, all objects with a .order value matching or greater than the changed .order value with have to be increased by one as well, so that all items still have a unique .order value. I don't actually need to compare .age values any more. example: (second example from previous email). "Steven Taschuk" wrote in message news:20030612111547.B902 at tibia.amotlpaa.bogus... > Quoth Ben Simuyandi: > > Example objects in a list [a,b,...,i]: > [...] > > Thanks! > > There's two things I don't understand in your examples. One in > each, tidily enough. > > In the first example, where all items start with .order == 1 and > the output is supposed to be > > a.age == 100 a.order == 9 > b.age == 200 b.order == 6 > c.age == 300 c.order == 5 > d.age == 400 d.order == 4 > e.age == 500 e.order == 3 > f.age == 600 f.order == 2 > g.age == 50 g.order == 9 > h.age == 700 h.order == 1 > i.age == 150 i.order == 7 > > why do a and g get the same .order? I'd expected that we want > g.order == 9 and a.order == 8. > > Then the second example, where we start with > > [...] > d.age == 400 d.order == 4 > e.age == 500 e.order == 4 > f.age == 600 f.order == 5 > g.age == 50 g.order == 6 > h.age == 700 h.order == 7 > i.age == 150 i.order == 8 > > and are to produce > > [...] > d.age == 400 d.order == 4 > e.age == 500 e.order == 5 > f.age == 600 f.order == 6 > g.age == 50 g.order == 7 > h.age == 700 h.order == 8 > i.age == 150 i.order == 9 > > Again the handling of g puzzles me. Here's my thinking: > > 1) d and e both have order 4; since d.age < e.age, we let d have > order 4 and bump e up to order 5. > > 2) Then e and f both have order 5; since e.age < f.age, we let e > have order 5 and bump f up to order 6. > > 3) Then f and g both have order 6. In the example posted, f gets > order 6 and g gets bumped up to order 7. But f.age > g.age, so I > expected g to take precedence for order 6. > > What's going on here? I'm baffled. > > -- > Steven Taschuk staschuk at telusplanet.net > "[T]rue greatness is when your name is like ampere, watt, and fourier > -- when it's spelled with a lower case letter." -- R.W. Hamming > > -- > http://mail.python.org/mailman/listinfo/python-list > From peter at engcorp.com Thu Jun 5 14:11:20 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 05 Jun 2003 14:11:20 -0400 Subject: Loop over list of pairs References: Message-ID: <3EDF87C8.A3D6679B@engcorp.com> Thomas G?ttler wrote: > > What is the prefered way of loop over > a list like this? > mylist=[1, "one", 2, "two", 3, "three"] >>> def divide(s, n): ... return [s[i:i+n] for i in xrange(0, len(s), n)] ... >>> mylist = [1, 'one', 2, 'two', 3, 'three'] >>> >>> for left, right in divide(mylist, 2): ... print left, 'is', right ... 1 is one 2 is two 3 is three -Peter From dave at boost-consulting.com Wed Jun 18 22:59:47 2003 From: dave at boost-consulting.com (David Abrahams) Date: Wed, 18 Jun 2003 22:59:47 -0400 Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> <1055736914.49032@yasure> <3EEDEDBE.BCB56D6E@engcorp.com> <873ci7o7c0.fsf@pobox.com> <87ptlbml4b.fsf@pobox.com> Message-ID: Steven Taschuk writes: > Quoth John J. Lee: >> Steven Taschuk writes: > [...] >> > But I find it greatly eases >> > debugging and one-off data munging tasks. >> >> That's what I was referring to, and I assume David too. If any >> function or class is more than say 5 lines, I use emacs. [...] > > Hm... then I think I'm missing something. > > When debugging, all the substantial code is written elsewhere; I > just import it and fiddle. When data munging, I load the data > into memory and fiddle. Each fiddle is almost invariably a single > line of code, so errors are not big setbacks. These lines invariably turn into regression tests, so I want to be working from my IDE anyway. Doctest rules! >> [...] It's still >> convenient, but can be replaced quite easily with a good IDE, I think. > > I'm not sure how an IDE would help with interactive data-munging, > unless it provides an environment very similar to the one which > the interactive prompt provides. Edit test script, run python on it, repeat... -- Dave Abrahams Boost Consulting www.boost-consulting.com From peter at engcorp.com Thu Jun 5 07:56:30 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 05 Jun 2003 07:56:30 -0400 Subject: a = b = 1 just syntactic sugar? References: <38ec68a6.0306031913.3600bc16@posting.google.com> <3EDD6610.3CABE86A@engcorp.com> <38ec68a6.0306041832.4b0817e5@posting.google.com> Message-ID: <3EDF2FEE.7D031B68@engcorp.com> Asun Friere wrote: > > ? a = 556; b = 556 > ? a is b > 1 Hmm? That one surprises me. I wonder how the compiler is treating that line... I would have though ; basically had the same effect as a line seperator. -Peter From suresh_vsamy at rediffmail.com Tue Jun 24 09:04:29 2003 From: suresh_vsamy at rediffmail.com (Suresh Kumar) Date: 24 Jun 2003 13:04:29 -0000 Subject: Stroing tkinter screen as PNG file.............. Message-ID: <20030624130429.25639.qmail@webmail26.rediffmail.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From beliavsky at aol.com Wed Jun 11 19:12:38 2003 From: beliavsky at aol.com (beliavsky at aol.com) Date: 11 Jun 2003 16:12:38 -0700 Subject: vector subscripts in Python? Message-ID: <3064b51d.0306111512.7701dbbc@posting.google.com> Does Python have the equivalent of "vector subscripts" of Fortran 95? The code below illustrates what I am looking for -- with better syntax. def subscript(xx,ii): # return the elements in xx subscripted by ii y = [] for i in ii: y.append(xx[i]) return y ii = [0,2] xx = [1,4,9] print subscript(xx,ii) # returns [1, 9]; in F95, "print*,xx(ii)" is analogous From mertz at gnosis.cx Sun Jun 1 22:56:21 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sun, 01 Jun 2003 22:56:21 -0400 Subject: Defensive programming References: <7xptlxq2yz.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote previously: |I think there's something to be said for using collision resistant |hashes whenever any kind of hash is needed. Why fall back on the OS |to get you out of trouble, when you can avoid getting in trouble in |the first place? I haven't read the papers yet though. Well... for Python, I'd rather have a hash with excellent typical case performance than a typically slower one with more collision resistance. If my normal, non-DoS programs run a bit faster, that's something I experience every day... if those (very) few of them that have conceivable DoS exposure do badly under attack... well, that's bad, but probably best addressed otherwise. Yours, Lulu... -- 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 djc at object-craft.com.au Thu Jun 19 07:27:59 2003 From: djc at object-craft.com.au (Dave Cole) Date: 19 Jun 2003 21:27:59 +1000 Subject: ANNOUNCE: JOTWeb 1.11, preview of new web application system. In-Reply-To: <20030619102215.GC23876@tummy.com> References: <20030617162210.GB5896@tummy.com> <1055884182.1169.11.camel@emilio> <20030619102215.GC23876@tummy.com> Message-ID: >>>>> "Sean" == Sean Reifschneider writes: Sean> On Wed, Jun 18, 2003 at 08:44:27PM +1000, Dave Cole wrote: >> Or you could use one of the application classes to reduce the code >> needed for each page. Assuming you have more than one page in the >> application. Sean> There were no examples demonstrating that... One thing I have discovered is it takes a lot more effort to document these toolkits and build examples than it does to build the actual toolkit. Sean> Sure, I'd love to spend a couple of weeks getting really Sean> familiar with all the different web application frameworks out Sean> there so that I could really make an informed decision based on Sean> the implementation of a represenative application. However, if Sean> I had 3 months off work I'm not sure I'd spend it re-writing a Sean> web app a dozen times... :-) Can't argue with that. If I was to guess the outcome of the investigation you would probably find that each toolkit had strengths and weaknesses. You would also probably find that most (if not all) had a niche where they were better than all of the others. >> When it comes down to it, the number of lines in a trivial >> application is not why you use toolkits and frameworks. You use a >> framework to help construct a complex application. Sean> Adding complexity to every page in a complex application is also Sean> a serious problem. It means that every time I have to look at Sean> some page code, I have to understand what's going on in this Sean> setup code. It also means that if I set up one page that has Sean> different setup code, I'm likely to miss it unless I read all Sean> the code fairly carefully. Again there is no argument here. I might add that if the setup is not purely exposing data to the templating then there is no way that the toolkit will be doing that work for you. That means that the code has to be provided by the application and has to reside somewhere. If I read your comment correctly you are making the point that it is preferable to glue the pieces of application code together by references in the templates: which then implicitly imports code.py and invokes currenttime() In Albatross the glue at that level is all in Python, and in your application. This means that you have to do a little more work in locating the code that provides the currenttime() function. No big deal really. from myapp.utils.code import currenttime def page_display(ctx): ctx.locals.currenttime = currenttime ctx.run_template('time.html') The the template calls the function (if you want to do it that way). In Albatross the toolkit locates and loads the single Python module that is responsible for responding to a browser request. Once that module has been loaded the application programmer is then responsible for importing all of the other Python code used to respond to the request. >From your example above, JOTWeb takes a much finer grained approach in that the template identified by the browser request pulls in Python code fragments from a namespace structured by the file system. Sean> I *LIKE* systems that take care of the common things for you. One of the most difficult decisions I faced when building Albatross was deciding what to make implicit and what to leave to the developer. When you make something implicit you remove some flexibility from the application developer. I imagine you wondered from time to time when building JOTWeb whether or not something should be implicit. - Dave -- http://www.object-craft.com.au From tchur at optushome.com.au Tue Jun 17 17:09:42 2003 From: tchur at optushome.com.au (Tim Churches) Date: 18 Jun 2003 07:09:42 +1000 Subject: ANNOUNCE: JOTWeb 1.11, preview of new web application system. In-Reply-To: <20030617162210.GB5896@tummy.com> References: <20030617162210.GB5896@tummy.com> Message-ID: <1055884182.1169.11.camel@emilio> On Wed, 2003-06-18 at 02:22, Sean Reifschneider wrote: > Welcome to the first wide-spread announcement of my latest project: JOTWeb. > > JOTWeb is a system for developing dynamic web sites using a combination > of HTML+TAL/TALES/METAL and Python, with mod_python for integrating with > Apache. Benefits include good documentation, a fairly simple and > intuitive design, and powerful yet easy to use session and form > processing. > > More information including "why another one", examples, and more is > available at: > > http://jotweb.tummy.com/ > At the above site you explain: "Why Another WebApp? The short answer is that I couldn't really find another web application system that I felt comfortable with. They were either too heavy-weight, didn't work as I expected them or didn't fit my development model, were not well enough documented, etc... " Just out of interest, what didn't you like about Albatross ( http://www.object-craft.com.au/projects/albatross/ )? Superficially at least, Albatross seems to look a lot like JotWEB, in its templating syntax, underlying architecture and light weight. No criticism of your decision to develop another Pythonic WebApp framework is intended - the more the merrier - but as a user of Albatross I am genuinely interested in what you thought isn't right with it. -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From justinjohnson at fastmail.fm Tue Jun 17 21:43:03 2003 From: justinjohnson at fastmail.fm (Justin Johnson) Date: Tue, 17 Jun 2003 19:43:03 -0600 Subject: pack and unpack problems Message-ID: <20030618014303.0DCCB269AC@www.fastmail.fm> Hi, I've been trying to do some work with struct's pack and unpack. I'm having a hard time though, because I'm used to perl's sizes, but things aren't working as expected in python. In perl I could do... my ($a, $b) = unpack 'xxNxxH8', $data; So I tried to convert it to python as... a, b = unpack('xxLxx8c', data) Note I used c instead of H cause I wasn't sure what to replace H with. I get the following error... exceptions.ValueError: unpack tuple of wrong size struct.calcsize('xxLxx8c') returns 18, which is the amount of bytes in "data", at least I think so. I'm not sure what's going on here. Anybody have any advice on this? Thanks. -Justin From listbox at cybereal.org Sat Jun 14 05:51:06 2003 From: listbox at cybereal.org (Zac Jensen) Date: Sat, 14 Jun 2003 03:51:06 -0600 Subject: Execute a process as a specific user In-Reply-To: <3EEAEBE1.3010800@wanadoo.es> References: <3EE9E547.9040209@wanadoo.es> <3EEAEBE1.3010800@wanadoo.es> Message-ID: <200306140351.08929.listbox@cybereal.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Saturday 14 June 2003 03:33 am, Maurix wrote: > Hi, > Thanks but... it didn't work!! > Is better if I explain what i'm tring to do, > I want to connect to the X server from the console but the > Xlib say that i don't have the permission if i'm root! > I use the commando of Tkinter: tk=Tkinter.Tk(":0.0") > ( ??way if i'm the boss??) > So i tryed to make this making a su to the user fo X server > and it work perfectly!! Now i don't want to depend on "su" program > and i tryied this command, set(e)uid and set(e)grp, but can't connect > to the X-server anyway: client is not authorized > My question is, exist a more elegant way to make this: a script > that show a Tk window from the console, a script that stay in > background for all the time. > I'm afraid that i'm out of theme here because is a problem of > Xservers but, please, if anyone have make somting like this help > me. It is an X server issue, which is easily solved, while logged in as the user you are running the Xserver as... just run xhost +localhost ; or xhost + +root either of these will solve your issue. A more general but less safe (unless you have a trustworthy firewall) is to run xhost + which will allow all clients without trouble. - -Zac -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) iD8DBQE+6vAKV3L7YsSif1URApqKAJ9u5jHwe4A6qJYBiT+nLlCaVarsdgCgh2cK WsrlVDkyJXxhZg1so6K2JQA= =LP4M -----END PGP SIGNATURE----- From andreas at andreas-jung.com Fri Jun 20 03:51:51 2003 From: andreas at andreas-jung.com (Andreas Jung) Date: Fri, 20 Jun 2003 09:51:51 +0200 Subject: Run a linux program through python In-Reply-To: References: Message-ID: <2147483647.1056102711@[10.19.128.17]> Inside an ExternalMethod: import os os.system('your_program') Check the mailinglist archive. This question has been answered a dozen of times. -aj --On Freitag, 20. Juni 2003 9:29 Uhr +0200 Gunnar Staff wrote: > I would like ti run a linux program through a > python script. Do enyone know the syntax for > running a OS program from python? > > Assume I'll run > $ convert fromfile tofile > > Gunnar > -- > http://mail.python.org/mailman/listinfo/python-list From danieljng at yahoo.com Thu Jun 12 04:09:37 2003 From: danieljng at yahoo.com (Daniel) Date: 12 Jun 2003 01:09:37 -0700 Subject: Python Regex Newbie- matching substrings Message-ID: <798d4337.0306120009.46cdef2a@posting.google.com> Hi, I would like my regex to detect that a month (any month) is in the following line, returning the index of the start of the match: Jun 05 14:40:26 2003 ..... So far, I've tried: months = re.compile('(Jan)') searchResult = months.search('abcJan') print searchResult.start() -Which works for just 'Jan' of course, and it correctly prints '3'. How do I get it to work for all months? I tried: months = re.compile('[(Jan)(Feb)(Mar)]+') -but that regex is too 'greedy' ie. matches too easily- I think it matches the individual letters in each of Jan, Feb, Mar instead. Thanks, Daniel. From delphiro at zonnet.nl Thu Jun 26 13:14:50 2003 From: delphiro at zonnet.nl (delphiro) Date: Thu, 26 Jun 2003 19:14:50 +0200 Subject: boa constructor - run script/output In-Reply-To: <3EFAE800.6080406@gmx.net> References: <3EFAE800.6080406@gmx.net> Message-ID: <20030626191450.057182c3.delphiro@zonnet.nl> problem 1) It sounds like you need to import your script import your_script_name and attach an event to the function that you want to call from within your script for example; yourscript.py contains function 'DoThis()' in gui class: import yourscript.py some event def OnButtonMyButtonDown(self,event): yourscript.DoThis() 2) You will have to edit your script in a way that it knows where to send it's output. This means you will have to pass a widget (like wxTextCtrl) to your script and output the messages to that widget. The best way to actualy learn wxPython for me was to study the examples. They realy make things clear for almost any widget! Hope this helps, Rob -- [-------------delphiro-------------] [-- http://pyciv.sourceforge.net --] [----------------------------------] From nav at adams.patriot.net Tue Jun 10 15:00:33 2003 From: nav at adams.patriot.net (Nick Vargish) Date: 10 Jun 2003 15:00:33 -0400 Subject: You know you're a Pythonista when.. References: Message-ID: bitbucket at safe-mail.net (poiboy) writes: > 4.5) Leaving if:, elif:, and else: on their own lines for fear of > scorn or deprecation. Going through my own programs and making sure I did the same with try:, a couple of months after a misguided attempt to make my style look like the examples in the Cookbook. In addition: Trying to write a Perl text filter for some coworkers, to be run on a system without Python, and finding it _very_ hard going. (I used to write Perl for a living, so this was amazing to me.) Feeling somewhat outraged that someone would want to add ++foo to Python. 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 khcarlso at bellsouth.net Wed Jun 4 16:28:20 2003 From: khcarlso at bellsouth.net (Kevin Carlson) Date: Wed, 04 Jun 2003 16:28:20 -0400 Subject: using urllib or httplib to post with ENCTYPE=mulitpart/form-data Message-ID: <3EDE5664.2090508@bellsouth.net> Hi, I am trying to post to a form using httplib or urllib. I have done this successfully before with httplib, but when the enctype must be multipart/form-data, things go awry. I tried using a header {'Content-Type' : 'multipart/form-data', ...} that I encode with urlencode and then pass to the HTTPConnection.request method, but the server is returning a code indicating a bad request. I have done a lot of troubleshooting on this and the encoding type is the only remaining issue. Can anyone shed some light on how to accomplish a POST of this type? Thanks, Kevin From clifford.wells at attbi.com Sat Jun 14 01:22:15 2003 From: clifford.wells at attbi.com (Cliff Wells) Date: 13 Jun 2003 22:22:15 -0700 Subject: why does python execute line bye line as im coding????????? In-Reply-To: <20030613235210.11559.00000446@mb-m13.aol.com> References: <20030613235210.11559.00000446@mb-m13.aol.com> Message-ID: <1055568135.6522.2.camel@localhost.localdomain> On Fri, 2003-06-13 at 20:52, L48R4T wrote: > im just going through the python for beginrers tutorial and all was cool untill > i stated trying to do thing s like > input = name("whats your name") > print "hello "name > > the above example would execute after i hit return on the first line. not > giving me the chance to input the second line of code ??????????????????? > any help wi=ould be a blessing thanks Mistakes or omissions in the above code aside, if you are typing code into the interactive interpreter, then it executes each line as you type it. This is useful for testing things out. If you want to write an entire program and execute it all at once, you need to use a text editor (preferably emacs) to create the file (something like "myprogram.py") and then use the command "python myprogram.py" to run it. Regards, -- Cliff Wells From x at x.com Sat Jun 21 23:23:36 2003 From: x at x.com (Peter Brown) Date: Sun, 22 Jun 2003 13:23:36 +1000 Subject: mod_python hell in Apache/Windows XP References: <6GTIa.32066$111.24282@news04.bloor.is.net.cable.rogers.com> Message-ID: <3ef52138$1@usenet.per.paradox.net.au> Same here, Uninstalled everything, and then reinstalled using Python 2.2.3 instead of Puython 2.3 and all works fine. Peter "Tim" wrote in message news:ZwZIa.162283$3Sm.70490 at news01.bloor.is.net.cable.rogers.com... > Thanks for your encouragement. I was making attempts until 3am last night > with no luck. Somehow all the install/uninstalls must have got things > confused. I uninstalled everything, and then: > > 1. installed apache > 2. Installed Python 2.2 > 3. Installed mod_py > > did the little test program and voila -> "Hello World." > > Any advice on the best way to configure for CGI is much appreciated... > > Thanks again, > T > > PS: the weird thing is that the mod_python installer said it could not find > the module os (wrong!--it's there), and yet everything is working...weird! > :-) > > > ----- Original Message ----- > From: "Jaros?aw Zabie??o" > Newsgroups: comp.lang.python > Sent: Saturday, June 21, 2003 8:39 AM > Subject: Re: mod_python hell in Apache/Windows XP > > > > On Sat, 21 Jun 2003 07:19:30 GMT, "Tim" > > wrote: > > > > > I've read all the posts and tried just about everything. No matter what, > > > Apache says it can't find the mod_python module! > > > > Get the installer from > > http://www.modpython.org/ and run it. > > > > Your mod_python.so should be instaled at YourApachePath/modules > > > > Add the follwing lin to your httpd.conf file: > > > > LoadModule python_module modules/mod_python.so > > > > Restart Apache. It works. > > > "Jaros?aw Zabie??o" wrote in message > news:t7k8fv4mtcju19oeu9cetos78mf2atu5ic at 4ax.com... > > On Sat, 21 Jun 2003 07:19:30 GMT, "Tim" > > wrote: > > > > > I've read all the posts and tried just about everything. No matter what, > > > Apache says it can't find the mod_python module! > > > > Get the installer from > > http://www.modpython.org/ and run it. > > > > Your mod_python.so should be instaled at YourApachePath/modules > > > > Add the follwing lin to your httpd.conf file: > > > > LoadModule python_module modules/mod_python.so > > > > Restart Apache. It works. > > > > From jdhunter at ace.bsd.uchicago.edu Thu Jun 26 13:11:57 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 26 Jun 2003 12:11:57 -0500 Subject: Standard ways to get union, intersection, difference of lists? In-Reply-To: ("Steve Holden"'s message of "Thu, 26 Jun 2003 12:38:48 GMT") References: Message-ID: >>>>> "Steve" == Steve Holden writes: Steve> Not necessarily: I believe you can just pick up the sets Steve> module from CVS and run it under 2.2+. I just tried import sets from the 2.3b1 distribution under python 2.2, but it failed with an ImportError trying to load itertools. I believe itertools is a C module, so perhaps it is not so straightforward to use sets from 2.2? John Hunter From dave at technopagan.org Thu Jun 12 01:27:50 2003 From: dave at technopagan.org (David E. Smith) Date: Thu, 12 Jun 2003 05:27:50 +0000 Subject: 2nd CFV: comp.databases.berkeley-db Message-ID: <1055395670.28364@isc.org> LAST CALL FOR VOTES (of 2) unmoderated group comp.databases.berkeley-db Newsgroups line: comp.databases.berkeley-db The Berkeley DB libraries. Votes must be received by 23:59:59 UTC, 24 Jun 2003. This vote is being conducted by a neutral third party. Questions about the proposed group should be directed to the proponent. Proponent: Philip Greer Proponent: Dave Segleau Votetaker: David E. Smith RATIONALE: comp.databases.berkeley-db 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'). Discussion pertaining to the library occurs on many other other Usenet forums. Often writings are specific to berkeley-db itself and does not pertain to the subject matter of the group the discussion falls within. Not only would a berkeley-db specific forum provide a central location for todays frequent Usenet users, it would also provide an on-line research tool for those seeking on-line issue assistance with the library. Entities such as Google will provide archives of group postings, and search tools for those seeking answers to berkeley-db questions - drawing those on-line that were not aware of the Usenet group (or of net news as a whole). >From the "Berkeley DB Reference Guide: Introduction": '[berkeley-db] runs under almost all UNIX and Linux variants, Windows, and a number of embedded real-time operating systems. It runs on both 32-bit and 64-bit systems. It has been deployed on high-end Internet servers, desktop machines, and on palmtop computers, set-top boxes, in network switches, and elsewhere.' As well, berkeley-db has been a tool available to the programming community for over ten years and is used on a global scale with over 200 million installations. The need for an on-line, central location for community discussions has been long standing. Usenet is the best tool to fulfill this need and allows addressing this need on a global scale. CHARTER: comp.databases.berkeley-db The newsgroup comp.databases.berkeley-db is a news forum devoted to the discussion of the berkeley database management library. Discussion entails, but is not limited to: its usage in all programming languages that can utilize it, bugs, patches, tricks, techniques, support, announcements; all in a free and open atmosphere. All postings should be in ordinary text format only. Postings of binaries (or encoding thereof) is highly discouraged. Cross-posting of articles irrelevant to the berkeley database library is also discouraged. The berkeley-db newsgroup is not moderated. Therefore it is up to the global user base to police its usage. END CHARTER. IMPORTANT VOTING PROCEDURE NOTES: READ THIS BEFORE VOTING The purpose of a Usenet vote is to determine the genuine interest in reading the proposed newsgroup, and soliciting votes from uninterested parties defeats this purpose. Do *not* distribute this CFV; instead, direct people to the official CFV as posted to news.announce.newgroups. Distributing specific voting instructions or pre-marked copies of this CFV is considered vote fraud. This is a public vote: All email addresses, names and votes will be listed in the final RESULT post. The name used may be either a real name or an established Usenet handle. At most one vote is allowed per person or per account. Duplicate votes will be resolved in favor of the most recent valid vote. Voters must mail their ballots directly to the votetaker. Anonymous, forwarded, or proxy votes are not valid, nor are votes mailed from WWW/HTML/CGI forms (which should not exist). Votes from nonexistent accounts or with munged, spam-blocked, or undeliverable addresses are invalid and will NOT be counted. Please direct any questions to the votetaker at HOW TO VOTE: Extract the ballot from the CFV by deleting everything before and after the "BEGINNING OF BALLOT" and "END OF BALLOT" lines. Don't worry about the spacing of the columns or any quote characters (">") that your reply inserts. Please, DO NOT send the entire CFV back to me! Fill in the ballot as shown below. Please provide your real name (or established Usenet handle) and indicate your desired vote in the appropriate locations inside the ballot. Examples of how to properly indicate your vote: [ YES ] example.yes.vote [ NO ] example.no.vote [ ABSTAIN ] example.abstention [ CANCEL ] example.cancellation DO NOT modify, alter or delete any information in this ballot! If you do, the voting software will probably reject your ballot. When finished, MAIL the vote to Just "replying" to this message should work, but check the "To:" line. Votes mailed to any other email address, including that of the votetaker, will NOT be counted. If you do not receive an acknowledgment of your vote within three days contact the votetaker about the problem. You are responsible for reading your ack and making sure your vote is registered correctly. If these instructions are unclear, please consult the Introduction to Usenet Voting or the Usenet Voting FAQ at http://www.stanford.edu/~neilc/uvv. ======== BEGINNING OF BALLOT: Delete everything before this line ======= .----------------------------------------------------------------------- | 2ND CALL FOR VOTES: comp.databases.berkeley-db | Official Usenet Voting Ballot [CDB-42-2] (Do not remove this line!) |----------------------------------------------------------------------- | Please provide your real name, or your vote may be rejected. Established | Usenet handles are also acceptable. Place ONLY your name (ie. do NOT | include your e-mail address or any other information; ONLY your name) | after the colon on the following line: Voter Name: | Insert YES, NO, ABSTAIN, or CANCEL inside the brackets for each | newsgroup listed below (do not delete the newsgroup name): Your Vote Newsgroup --------- ----------------------------------------------------------- [ ] comp.databases.berkeley-db ======== END OF BALLOT: Delete everything after this line ============== DISTRIBUTION: This CFV will be posted to the following newsgroups: news.announce.newgroups news.groups comp.databases comp.lang.perl.misc comp.lang.python Pointers to the CFV will be posted to the following newsgroups: alt.perl comp.lang.java.databases comp.lang.perl.modules comp.mail.imap comp.mail.sendmail comp.unix.programmer From peter at engcorp.com Fri Jun 20 23:21:38 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 20 Jun 2003 23:21:38 -0400 Subject: os.listdir() References: Message-ID: <3EF3CF42.CCEF2DA9@engcorp.com> Hans Nowak wrote: > > manuel wrote: > >>If you can't "import os" in Blender, something is wrong... > > > This might work: import the nt module (it's built-in), then use nt.listdir. In which case "import nt as os" _might_ be good for portability. Otherwise you'd be sprinkling nt.listdir's around and confusing anyone trying to read the code. -Peter From artyprog at wanadoo.fr Sat Jun 21 11:21:02 2003 From: artyprog at wanadoo.fr (Salvatore) Date: Sat, 21 Jun 2003 17:21:02 +0200 Subject: dynamic creating of class In-Reply-To: References: Message-ID: Jaros?aw Zabie??o wrote: > Is there a possibility for Python to dynamic binding of class? I can > do it in PHP but I do not know how to make the same in Python. > Look at the following example: I had the same problem and I don't remember who gave me the solution. The idea is to use 'eval' class A: def __init__(self): self.class_name = 'A' class B: def __init__(self): self.class_name = 'B' choosed_class = 'A' choosed_class += '()' instance_of_choosed_class = eval(choosed_class) Thanks to the one who gave me the solution :-) Regards Salvatore From sismex01 at hebmex.com Thu Jun 5 16:59:20 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 5 Jun 2003 15:59:20 -0500 Subject: Loop over list of pairs Message-ID: > From: Alexander Schmolck [mailto:a.schmolck at gmx.net] > Sent: Thursday, June 05, 2003 3:58 PM > > Thomas G?ttler writes: > > > Hi! > > > > What is the prefered way of loop over > > a list like this? > > mylist=[1, "one", 2, "two", 3, "three"] > > you could use this: > > def xgroup(iter,n=2): > """ > >>> list(xgroup(range(9), 3)) > [(0, 1, 2), (3, 4, 5), (6, 7, 8)] > """ > last = [] > for elt in iter: > last.append(elt) > if len(last) == n: yield tuple(last); last = [] > Since 'n' is known from the start you don't need to test against it, nor build a list piecemeal. Something like this seems a bit more solid: def xgroup(Iterable, group=2): """Return a groupwise iterator for Iterable.""" Iterator = iter(Iterable) Length = range(group) while 1: yield [ Iterator.next() for i in xrange(group) ] hth! -gca Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From peter at engcorp.com Sat Jun 14 05:20:09 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 14 Jun 2003 05:20:09 -0400 Subject: raw strings under windows References: Message-ID: <3EEAE8C9.FE8BF18@engcorp.com> "Cecil H. Whitley" wrote: > > When doing the following: > > #!/usr/bin/env python > > path = r"c:\python23\" > > I get a syntax error, unexpected EOL with singlequoted string. It was my > (mis?) understanding that raw strings did not process escaped characters? > Of course > path = "c:\\python23\\" Alternative that almost always works just fine as well: path = "c:/python23/" Try it... unless you're passing it to a command via os.system(), or doing direct string comparisons on paths without first using os.normpath() you likely won't encounter a problem. Windows internally allows forward slash most of the time; in the DOS prompt it does not. -PEter From amk at amk.ca Mon Jun 23 09:47:23 2003 From: amk at amk.ca (A.M. Kuchling) Date: Mon, 23 Jun 2003 08:47:23 -0500 Subject: FOAF-parser?? References: Message-ID: On Sat, 21 Jun 2003 13:14:00 +0200, Thomas Weholt <2002 at weholt.org> wrote: > Tramp[2] and RDFLib, but they don't seem to fit the task somehow. All I want > is to parse a FOAF-file and get a list of persons back, each person may > again have a list of persons he/she knows etc. My attempts so far has been a > terrible mess of SAX, pulldom and rdflib. You shouldn't need to mess with SAX and pulldom at all; rdflib will take care of the parsing for you. For example: from rdflib.triple_store import TripleStore from rdflib.nodes import URIRef from rdflib import const ts = TripleStore() ts.parse_URI('http://www.amk.ca/amk.rdf') # Get all subjects whose type is the FOAF Person class; returns a generator gen = ts.subjects(const.TYPE, URIRef('http://xmlns.com/foaf/0.1/Person')) # Convert generator to a list L = list(gen) I don't list anyone I know in my FOAF file, but finding my school affiliations is a similar task: amk = L[0] schools = ts.objects(amk, URIRef('http://xmlns.com/foaf/0.1/schoolHomepage')) list(schools) is then ['http://www.dawsoncollege.qc.ca/', 'http://www.mcgill.ca']. The current CVS version of RDFLib has rearranged things a bit, and I forget if I'm running the CVS or the last stable version, so the code above may need some tweaking. Still, figuring out the information you need shouldn't be a very difficult task, whatever version of rdflib you're trying to use. --amk From frobozz_electric at hotmail.com Thu Jun 12 09:52:59 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 12 Jun 2003 13:52:59 GMT Subject: PEP318: property as decoration References: <20030611184025.GB5575@nl.linux.org> Message-ID: "Gerrit Holl" wrote in message news:mailman.1055410883.13759.python-list at python.org... > Such a hack isn't that hard of course. > I solved it by adding "d=" just before my docstring: I see ... So > Sean Ross wrote: > > def foo(): "foo's doc string" ... > > fdoc = "foo" > > return fget, fset, fdel, fdoc > Gerrit Holl wrote: > Make that: "return fget, fset, fdel, __doc__" was not what you really wanted. You wanted: def foo(): fdoc="foo's doc string" ... which is what I started with?! Heh. ;) >__doc__ > doesn't need to stay anyway, because this outer function gets overwritten > by the property. Personally, I liked the idea of being able to use a proper doc string to document my property-maker function "foo", i.e., def foo(): "proper doc string goes here" ... which I can then quietly pass along to the property "foo" that will overwrite this function. Is it necessary? Nope. I already had it working without this. Is it neat? Yep. It grabs hold of the function *inside* of the function. That is so cool! Should it be done? Probably not...but that wasn't the point of the exercise. The only real reason I made it was to see if I could. > The only place I use frames is in by debug() function: this way, it > prints the function and lineno of the caller, which easy's debugging. Well, technically, "this" can be used in debugging (if made more robust with regard to class lookup) to inspect your function by asking it things: like this().__name__, this().__doc__. Anyway, thanks for your earlier suggestion re: __doc__, it provided me with a few minutes of amusement cobbling together "this()". I don't think it should be used, but I did enjoy trying to make it work. From ray at rays-web.com Fri Jun 13 05:19:19 2003 From: ray at rays-web.com (Ray Smith) Date: 13 Jun 2003 02:19:19 -0700 Subject: long-term release schedule? References: Message-ID: <5654fff9.0306130119.209b6605@posting.google.com> Tim Peters wrote in message news:... > [Ray Smith] > > ... > > I guess the "angle" of my question was it Guido and his team didn't > > get commercial backing to continue development of Python how would it > > effect the growth and commercial support of Python?? > > Well, how *has* it affected it? Nobody has had a full-time job working on > Python since BeOpen.com folded. Zope Corporation has been very generous in > funding Python work beyond the minimum that Zope Corp needs for its own > plans, but all of us at PythonLabs spend nearly all our paid time directly > on Zope-related work now (most of which uses Python, but decreasingly little > of which develops Python anymore). For example, follow the bug and patch > trackers on SourceForge, and you'll see that the sum of Python work done by > Guido and his crew is dwarfed by the work done by others, and that's been so > for a long time now. Wow, obviously you guys inparticular plus the community in general are doing alot more work than I realised. I guess I can set myself a long term challenge ... to actually fix / document / or contribute in some way to Python!!! Regards, Ray Smith From ianb at colorstudy.com Thu Jun 5 00:53:21 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 04 Jun 2003 23:53:21 -0500 Subject: girl scout badge In-Reply-To: References: Message-ID: <1054788800.681.26.camel@lothlorien> On Wed, 2003-06-04 at 23:28, sam420 wrote: > I'd like a simple python program to help organize my girl scout badge > info. I want a GUI interface that would have different button for each > badge, i.e., if I hit the communication button, the communication > requirements would pop up. Or if I hit the weather badge button, the > requirements for the weather badge would pop up. I'd like to start > with 6 badges. I'll type the requirements in the data (?) file, but > you would have to create the actual file and show me where to type the > requirements in. Can anyone help? I am a newbie =) This seems like something that is really best done as a web page, doesn't it? But if you are really just looking to try your hand at a programming task, I don't want to spoil your fun ;) This might not be the best place to start, a text-only program is usually much easier to start with. If you want to try a GUI, I think PythonCard (pythoncard.sf.net) is exactly the sort of environment that would work well for this. They have tutorials and other documentation. Ian From guettler at thomas-guettler.de Tue Jun 24 10:51:50 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Tue, 24 Jun 2003 16:51:50 +0200 Subject: Choosing the right database-system for a small project References: Message-ID: Thomas Weholt ( PRIVAT ) wrote: > I've got a rather small project, small in the sense that there's not a lot > of different tables needed in the database/storage-system, but there will > be alot of data and the clients must be able to scan thru huge amounts of > data very fast ( Not serial scanning, but lookups by key, preferrably > several keys pr record, ie. I need to lookup people both by SSN and by > first/last-name etc. ) Hi! Why not use ZODB? The BTrees module gives you a dictionary-like object which can store your list even when it is bigger than the available memory. The drawback is, that you need to pack the database from time to time if you change objects. thomas From Matthews at heyanita.com Mon Jun 16 19:44:01 2003 From: Matthews at heyanita.com (Matthew Shomphe) Date: Mon, 16 Jun 2003 16:44:01 -0700 Subject: Possible bug in setting Windows file permissions? (os.chmod() not working properly?) Message-ID: <8C50918F08A109479D62BAE0F1AB9546D6463F@lionking.HANA> Gus, Thanks for the information. I thought this was the case as well. However, in the book (below), it says: ---------------------------------------------------- chmod(path, mode) Changes the mode of path. mode has the same values as described for the open() function. UNIX and Windows. ---------------------------------------------------- Beazley could full well be wrong (sorry, David! ;). In the on-line documentation (http://www.python.org/doc/current/lib/os-file-dir.html) it says: ------------------------------------------------------------------------ chmod(path, mode) Change the mode of path to the numeric mode. Availability: Unix, Windows. ------------------------------------------------------------------------ However, I don't see a description of the values for "mode". I could only deduce the numeric value required to get read/write permissions by checking the permissions of a file that I knew to be both readable & writable: ========================= from stat import * print os.stat('myReadAndWriteFile.txt')[ST_MODE] ========================= I can use the numeric value I grabbed from the above output to set permissions. However, setting permissions using these raw numeric values strikes me as A Bad Thing(TM). It doesn't make the code portable. And who knows what Redmond will do in the future? Let me make my inquiry clearer (I hope): (1) What are the values expected for the second argument to os.chmod()? (2) Are these values platform independant? (3) Is it documented anywhere? Thanks for your help! M@ PS. I'm using python2.3b1 -----Original Message----- From: Gus Tabares [mailto:gus.tabares at verizon.net] Sent: Monday, June 16, 2003 4:30 PM To: Matthew Shomphe; python-list at python.org Subject: RE: Possible bug in setting Windows file permissions? (os.chmod() not working properly?) Matt, I do believe os.O_RDWR is specifically for the open() function. Check out the bottom of this page: http://www.python.org/doc/current/lib/os-fd-ops.html HTH, Gus -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org]On Behalf Of Matt Shomphe Sent: Monday, June 16, 2003 7:18 PM To: python-list at python.org Subject: Possible bug in setting Windows file permissions? (os.chmod() not working properly?) I noticed an error when trying to change the file permissions for a file on a Windows (2K) machine. I'm using David Beazley's excellent "Python Essential Reference, 2nd. Ed." as a reference. According to the book (p. 186 for those following along at home), it should be used thusly: import os os.chmod('myReadOnlyFile.txt', os.O_RDWR) Where for os.O_RDWR, you could have any of the modes specified on p. 184. In other words, all the same bitwise-or modes for opening a file. What happens with the above code is: nothing at all. However, the following code *will* work to change a file to be accessible: import os os.chmod('myReadOnlyFile.txt', 33206) So, either I am using the os.chmod() function incorrectly, or there is something wrong elsewhere. Any hints on what's to be done? M@ -- http://mail.python.org/mailman/listinfo/python-list From aleax at aleax.it Mon Jun 16 04:54:23 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 16 Jun 2003 08:54:23 GMT Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> <3eece571$0$49110$e4fe514c@news.xs4all.nl> Message-ID: <3BfHa.95965$pR3.2057696@news1.tin.it> martin z wrote: >> You *can* test the types of the arguments yourself, inside >> the function. But this is regarded bad practice amongst Python >> programmers, for the above mentioned reasons. > > On this subject, is there a way to test not the specific type, or simply > the > protocol an object supports? String, int, etc. I want to make a function > do one thing with a numeric-type object and a different thing with a > string-type object. It depends, of course, on what you want "numeric-type" and "string-type" to mean. For my purposes, I've found the following very simple "protocol testing" functions work just fine: def isStringLike(s): try: s+'' except: return False else: return True def isNumberLike(s): try: s+0 except: return False else: return True I haven't actually used the second one very often; perhaps it might give problems with e.g. "number-vector" types that let you perform SOME number-like operations (such as "add a scalar to each item") but not others. The first one I use regularly and still find preferable to e.g. "isinstance(s, basestring)" which doesn't classify as "string like" such obvious cases as instances of UserString.UserString. Of course, this overall approach does depend on an underlying assumption that types are defined "sensibly" -- e.g. that if a type is string-like enough to let you concatenate its instances to a string, then it will also be string-like enough from other points of view. I have not found that to be a problem in practice. Alex From a_salnikov at yahoo.com Fri Jun 6 16:18:52 2003 From: a_salnikov at yahoo.com (Andy Salnikov) Date: Fri, 6 Jun 2003 13:18:52 -0700 Subject: Numeric don't compare arrays correctly References: <3EDFBACD.2090802@wanadoo.es> Message-ID: "Alexander Schmolck" wrote in message news:yfsbrxbufxn.fsf at black132.ex.ac.uk... > Maurix writes: > > > Hi to all, > > I'm new in python world and in this group too so, nice to meet you all ;-) > > I have a problem with Numeric: (linux, python2.2, numeric 21.0) > > > > It seem that don't compare correctly arrays. > > > > See at this session: > > > > >>> a=array([1.1,2.2,3.3,4.4,5.5]) > > >>> print 2. > This is just a python wart, reflecting the unhappy interaction between two > sometimes convinient but somewhat messy language features. > > Feature 1: > > a < b < c in most programming languages is the same as (a < b) < c. Python > instead treats such chained comparisons specially to make them behave as is > typical in (the somewhat messy) standard math notation. > > So ``1 < 3 < 4`` is False and not True, because it is treated as > ``1 < 3 and 3 < 4``. > '1 < 3 and 3 < 4' cannot be False like '1 < 3 < 4` (in Python at least). Problem is in comparing apples and oranges, objects can be in any order w.r.t. numbers. Andy. From a.schmolck at gmx.net Tue Jun 17 20:33:17 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 18 Jun 2003 01:33:17 +0100 Subject: preventing creation of instance References: <3EEFA09F.43409D6A@engcorp.com> Message-ID: Peter Hansen writes: > Mirko Koenig wrote: > > > > I have a class with a 'static' list of names to control if every instance > > of the class has a different name. > > > > class test: > > names = [] > > def __init__( self, name ): > > ... > > > > Is it possible to chech in init if the given name exists in names and > > then destroy itself. So that it will be not possible to create an > > instance of this class, if the given name is existing. > > > > adam = test( "adam" ) # should work > > eve = test ( "adam" ) #should then not work. eve should be None. > > I believe raising any exception in __init__ is the way to prevent > the creation of the object. I don't think you can do this with > a technique that returns None, unless you are actually calling > a factory function which internally attempts to create the object > and catches the exception thrown, returning None if it happens. >>> class Test(object): ... def __new__(cls): return None ... >>> Test() >>> see http://www.python.org/2.2/descrintro.html#__new__ 'as From MK at foo.com Fri Jun 13 09:46:40 2003 From: MK at foo.com (MK) Date: Fri, 13 Jun 2003 15:46:40 +0200 Subject: Placing controls, wxWindows Message-ID: I have problems while placing wxNotebook in a wxPanel. For the time being I'm using self.SetDimensions(0, 0, 1000, 600) ... in my wxNotebook-derived class, but obviously that's not what I want. If I omit the line above, then my notebook shrinks to about 100x20 pixels. (I can barely see the tabs!) Does anybody know how can I have my wxNotebook adjust its size automatically, relatively to its parent wxPanel? Thx, The hierarchy is: wxFrame wxPanel wxNotebook From staschuk at telusplanet.net Thu Jun 26 10:19:53 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 26 Jun 2003 08:19:53 -0600 Subject: lists and tuples In-Reply-To: <20030626131817.GA4097@nl.linux.org>; from gerrit@nl.linux.org on Thu, Jun 26, 2003 at 03:18:17PM +0200 References: <20030626131817.GA4097@nl.linux.org> Message-ID: <20030626081953.A956@tibia.amotlpaa.bogus> Quoth Gerrit Holl: > one of the things I have never understood in Python was why tuples > exist. There is a FAQ entry about this: [...] > > As a general guideline, use tuples like you would use structs in C > > or records in Pascal, use lists like (variable length) arrays. [...] > To make it more confusing, Guido wrote: > > Tuples are for heterogeneous data, list are for homogeneous data. > > Tuples are *not* read-only lists. [...] > But this very FAQ entry was also written by Guido van Rossum. > This FAQ entry does not use tuples for heterogeneous data. It does, actually, though this use of the term "heterogeneous" can be confusing. (I know it confused me when I first read it.) A couple tests: Is seq[1:] conceptually the same kind of thing as seq itself? If so, seq should be a list; if not, a tuple. Would it make sense to sort or use max on the sequence? If so, a list; if not, a tuple. Examples: A list of URLs: If you chop off the first element, it's still a list of URLs. max(listofURLs) gives you the lexicographically last of the URLs. The time tuples used by the time module: If you chop off the first element, you don't have a time tuple anymore. Sorting would be useless, as would max(time.localtime()), both because the items in the tuple are not conceptually comparable. This has nothing to do with whether the elements of the sequence are of heterogeneous types; it has to do with whether their conceptual roles are heterogeneous. The FAQ's example -- points represented as (x, y) tuples -- is heterogeneous in this sense. Note also that the sentence stating tuples : structs :: lists : arrays (preserved above) reflects the same idea. > What is the difference between immutable and read-only? None. (Well, "immutable" is slightly more precise. It directly states the essential point -- object cannot be changed -- without reference to any notion of "read" and "write" operations.) -- Steven Taschuk w_w staschuk at telusplanet.net ,-= U 1 1 From bokr at oz.net Fri Jun 6 16:43:39 2003 From: bokr at oz.net (Bengt Richter) Date: 6 Jun 2003 20:43:39 GMT Subject: id(a) == id(b) and a is not b --> bug? References: Message-ID: On Fri, 6 Jun 2003 13:51:15 +0000 (UTC), Joshua Marshall wrote: >Steve McAllister wrote: >>> If any kind of computation is performed in the arguments, the property >>> you assume may not hold. > >> And exactly why is { >> 'foo' is 'foo' is 'foo' is 'foo' >> } always true? This is quite surprising compared to { >> [] is [] >> } ... >> Why are not new string literals dynamically created? > >Strings are immutable, so the interpreter is free to use these strings >in multiple places. It's an optimization--it would also be correct if >"'foo' is 'foo'" were false. For some meaning of "correct." IWT old-style string exceptions would break. Regards, Bengt Richter From joconnor at nets.com Wed Jun 4 18:30:11 2003 From: joconnor at nets.com (Jay O'Connor) Date: Wed, 04 Jun 2003 15:30:11 -0700 Subject: Tk vs wxPython ? References: Message-ID: <20030604.153007.243268139.11567@nets.com> In article , "Aur?lien G?ron" wrote: > I'm sure beginners would come to love Python even faster if they could > truly create their first GUI in minutes. I'm voting for wxPython to > replace Tk in the future Python distribution. > > Any comments on this ? Anyone else want to vote ? I had such a bad experience using TCL on one job that I rufuse to use Tk, simply because of the association :) -- Jay O'Connor http://www.r4h-music.com "God Himself plays the bass strings first, when He tunes the soul" From mike at nospam.com Wed Jun 25 19:40:40 2003 From: mike at nospam.com (Mike Rovner) Date: Wed, 25 Jun 2003 16:40:40 -0700 Subject: parsers / lexers usable from Python and Java (and C++/C)? References: <87brwnb1ay.fsf@pobox.com> <87of0m8k60.fsf@pobox.com> Message-ID: John J. Lee wrote: > "Mike Rovner" writes: > >> John J. Lee wrote: >>> Are there any parser / lexer generators useable from both CPython >>> and Java? >> >> PLY (http://systems.cs.uchicago.edu/ply/) implemented entirely in >> Python, so it might be possible to use it from both implementations >> of Python. > > No, I really did mean CPython and Java, not CPython and Jython. Your goal is a little vague for me. Jython IS java. > ... wrapping C++ (even generated C++) in an > automated way without pain seems unlikely. Take a look at boost.python pyste. Mike From rolf.herter at web.de Tue Jun 3 16:33:26 2003 From: rolf.herter at web.de (Rolf Herter) Date: Tue, 03 Jun 2003 22:33:26 +0200 Subject: PIL textfont Message-ID: Hello I try to create text with PIL, but I can't find the PILfonts or an fontdirectory that works with PIL Maybe someone has an idea thanks -- Rolf Herter From kendear at nospam.com Wed Jun 18 00:50:24 2003 From: kendear at nospam.com (Kendear) Date: Wed, 18 Jun 2003 04:50:24 GMT Subject: a clean way to define dictionary References: <3EEFEBFD.8090003@nospam.com> Message-ID: <3EEFEF90.4000703@nospam.com> Kendear wrote: > > i hope to define a dictionary this way: > > lst = """ > a 1 > foo 3 > bar 234 > joe 321 > """ > > lst = lst.split() > > now lst refers to ['a', '1', 'foo', '3', 'bar', '234', 'joe', '321'] > i want to do something like > > dict = {} > for key, value in lst: > dict[key] = eval(value) > > > but key, value is not for taking 2 > items at a time, but take a tuple > and unpacking it... > > is there a way for the "for" > to take 2 items at a time? > > or is there a more common way to define a dictionary > without all the punctuation marks? of course, it can be done as for i in range(0, len(lst), 2): dict[lst[i]] = eval(lst[i+1]) but is a little messy... is there a cleaner way? From ed at membled.com Mon Jun 9 02:48:20 2003 From: ed at membled.com (Ed Avis) Date: 09 Jun 2003 07:48:20 +0100 Subject: a = b = 1 just syntactic sugar? References: Message-ID: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) writes: >As a starting point, you should observe that the current Python >parser is a LL(1) parser. Hmm, I worry that my proposal requires more than one token of lookahead, and so would not be implementable with the current parser. -- Ed Avis From sebastian.tusk at silver-style.com Mon Jun 23 10:40:24 2003 From: sebastian.tusk at silver-style.com (Sebastian Tusk) Date: Mon, 23 Jun 2003 16:40:24 +0200 Subject: memory leak "import random" Message-ID: <009b01c33995$6628dc10$5000a8c0@codersebastian> Hi, i have a problem with the following code snippet. #include "Python.h" // python 2.2.3 int main( int argc, void** argv ) { while(1) { Py_Initialize(); if(PyRun_SimpleString( "import string" )) { return -1; } Py_Finalize(); } return 0; } It seems that there is a memory leak as the reserved memory grows eternally. Do i have something wrong or is this a known issue. Regards, Sebastian From nosp at m.needed Thu Jun 26 10:00:57 2003 From: nosp at m.needed (Steve McAllister) Date: Thu, 26 Jun 2003 16:00:57 +0200 Subject: Is it possible to write a Audio CD Player by using python only? In-Reply-To: References: Message-ID: > Is it possible to write a Audio CD Player by using python only? Of course. But ... shall you reinvent the powder? Cannot you simply interface, for instance, libcdaudio? From andy47 at halfcooked.com Thu Jun 5 06:02:11 2003 From: andy47 at halfcooked.com (Andy Todd) Date: Thu, 05 Jun 2003 11:02:11 +0100 Subject: Updating SQL table problems with python In-Reply-To: <3eddacbe$0$31519$5a62ac22@freenews.iinet.net.au> References: <3eddac41$0$31519$5a62ac22@freenews.iinet.net.au> <3eddacbe$0$31519$5a62ac22@freenews.iinet.net.au> Message-ID: DJ wrote: > Realised when posting this that title value is misspelt > That was not the error though :) > > "DJ" wrote in message > news:3eddac41$0$31519$5a62ac22 at freenews.iinet.net.au... > >>Hi there, >> >>I get a Syntax error from this following SQL statement: >> >>file_open = urllib.urlopen(url) >>xmldoc = minidom.parse(file_open) >>file_open.close() >>blah = xmldoc.toxml() >>title = minidom.parseStrin(blah).getElementsByTagNam('title') >> >>connection = gadfly.gadfly("portal", "dbase") >>cursor = connection.cursor() >>for x in title: >> j = x.firstChild.data >> j = j.encode('ascii', 'replace') >> cursor.execute("update items set title = '%s' where title = > > 'Title'" > >>% j) >> connection.commit() >> >>As you can tell, im parsing a xml RSS feed and updating items table. Im >>trying to replace >>default value of 'Title' with the title from the RSS feed. >>The update statement is givng me the syntax error >>I cant see whats wrong >> >>Need some help >>Thanks in advance >>Adam >> > What error message are you getting? The only thing that I can see which *might* be causing you trouble is your use of the 'format' paramstyle rather than the prescribed 'qmark' style. If you change your execute statement to; cursor.execute("update items set title=? where title='Title'", (j,)) You may get a different outcome. For a definition of the different paramstyles, check the DB-API specification at http://www.python.org/peps/pep-0249.html For a description of how to use dynamic values in Gadfly, see http://gadfly.sourceforge.net/gadfly.html#dynamic-values Regards, Andy From staschuk at telusplanet.net Wed Jun 18 11:38:47 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 18 Jun 2003 09:38:47 -0600 Subject: "Invert" regular expression matching In-Reply-To: <3e1d17c2.0306170321.d90c573@posting.google.com>; from martink@cnb.uam.es on Tue, Jun 17, 2003 at 04:21:26AM -0700 References: <3e1d17c2.0306170321.d90c573@posting.google.com> Message-ID: <20030618093847.C637@tibia.amotlpaa.bogus> Quoth Martin Krallinger: > I would be pleased if anyone has allready developed a python > program / module to "invert" regular expressions. [...] > , (which )?(is )?required (for|to|in) [...] > , which is required for > , is required for > , which is required in > etc,......... [...] I don't know of anything which does exactly that, but you might be able to adapt Jeff Epler's Novelwriting tool to your purposes: (It generates random text matching a user-specified grammar.) -- Steven Taschuk staschuk at telusplanet.net Every public frenzy produces legislation purporting to address it. (Kinsley's Law) From skip at pobox.com Tue Jun 17 08:40:50 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 17 Jun 2003 07:40:50 -0500 Subject: analyzing lock contention in multi-threaded app? Message-ID: <16111.3154.71808.325818@montanaro.dyndns.org> I was reading the PEP 319 thread on python-dev yesterday and a question popped into my brain with recurs (to me) from time-to-time. Is there a decent way to analyze a multi-threaded app for lock contention? Let me make this more concrete. I have an XML-RPC server which contains a handful of threading.RLock objects to protect shared data and one Queue.Queue object with a max size of 5 which maintains a pool of database connections. All my acquire() and get() calls are of the blocking variety. Is there some way to reasonably monitor lock contention? I currently have a method which returns lock status: def get_lock_info(self): return { 'query_lock': self.query_lock._RLock__block.locked(), 'sql_lock': self.sql_lock._RLock__block.locked(), 'namemap_lock': self.namemap_lock._RLock__block.locked(), 'top_50_lock': self.top_50_lock._RLock__block.locked(), 'log_lock': self.log_lock._RLock__block.locked(), 'conn_pool': self.conn_pool.empty(), 'dump_lock': self.dump_lock._RLock__block.locked(), } Since it doesn't lock anything itself, it is guaranteed to not block. (Of course, it might occasionally return incorrect data as well, but I'm hoping to examine trends.) I have a little script which executes the above call periodically and tells me if a lock is locked or the queue is empty. While useful to a certain degree, it doesn't tell me if any other acquire() or get() calls have blocked. What other techniques are available to monitor the lock contention of their multi-threaded apps? Thx, Skip From gerrit at nl.linux.org Thu Jun 26 09:18:17 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 26 Jun 2003 15:18:17 +0200 Subject: lists and tuples Message-ID: <20030626131817.GA4097@nl.linux.org> Hi, one of the things I have never understood in Python was why tuples exist. There is a FAQ entry about this: http://www.python.org/cgi-bin/faqw.py?req=show&file=faq06.015.htp This says: > This is done so that tuples can be immutable while lists are mutable. > > Immutable tuples are useful in situations where you need to pass a few items to a function and don't want the function to modify the tuple; for example, > > point1 = (120, 140) > point2 = (200, 300) > record(point1, point2) > draw(point1, point2) > > You don't want to have to think about what would happen if record() changed the coordinates -- it can't, because the tuples are immutable. > > On the other hand, when creating large lists dynamically, it is absolutely crucial that they are mutable -- adding elements to a tuple one by one requires using the concatenation operator, which makes it quadratic in time. > > As a general guideline, use tuples like you would use structs in C or records in Pascal, use lists like (variable length) arrays. I don't really understand this. In this example, record() probably refers to an arbitrary function. But I would think that a programmer knows what such a function is doing... If record or draw changes its arguments, it should be documented as such: and passing a read-only object won't solve the problem because the code will raise an exception then. To make it more confusing, Guido wrote: > Tuples are for heterogeneous data, list are for homogeneous data. > Tuples are *not* read-only lists. ...and: > I've been saying this for years whenever people would listen But this very FAQ entry was also written by Guido van Rossum. This FAQ entry does not use tuples for heterogeneous data. What is the difference between immutable and read-only? The performance issue would be solved by a .readonly() method or similar: like sets have. I don't understand. I really don't understand. yours, Gerrit. -- 243. As rent of herd cattle he shall pay three gur of corn to the owner. -- 1780 BC, 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 aleax at aleax.it Wed Jun 18 04:22:06 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 18 Jun 2003 08:22:06 GMT Subject: a clean way to define dictionary References: <3EEFEBFD.8090003@nospam.com> <3EEFEF90.4000703@nospam.com> Message-ID: Bryan wrote: ... > dict(zip(lst[0::2], map(eval, lst[1::2]))) Note: 2.3 only -- lists didn't support extended-slicing in Python 2.2. > also, i don't think it's a good idea to use dict as a variable name since > dict is a python type. Very good advice! If you use dict as a local name, you shadow the buit-in name 'dict' and therefore cannot any more call it e.g. in order to generate a new dictionary, as above. Alex From wilkSPAM at OUTflibuste.net Tue Jun 10 16:36:28 2003 From: wilkSPAM at OUTflibuste.net (Wilk) Date: 10 Jun 2003 22:36:28 +0200 Subject: win32all : msaccess example References: Message-ID: <877k7t7jqr.fsf@flibuste.net> "Federico" writes: > Please can someone give me an example on how to have and modify msaccess > data? You'll find examples in the unitest of http://adodbapi.sourceforge.net/ -- William Dode - http://flibuste.net From tim.one at comcast.net Sun Jun 1 15:19:55 2003 From: tim.one at comcast.net (Tim Peters) Date: Sun, 01 Jun 2003 15:19:55 -0400 Subject: Defensive programming In-Reply-To: <87k7c5of76.fsf@acooke.org> Message-ID: [andrew cooke] > i suppose the best idea would be to read the papers... Yes . > ...without doing so, i would guess that they advocate using one-way > hashes (like those used in cryptography) so that it is difficult to > find a text that gives a specific hash. Nope, they advocate picking a *different*-- but still cheap --hash function every time the program starts. General ways to do this have been studied extensively, under the general name "universal hashing", starting about 20 years ago. Picking a new hash function requires a little crypto-strength randomness at the start, so that the hash function being used can't be guessed from, e.g., the time the program started. I advocate using app-appropriate data structures instead (e.g., many mapping gimmicks have worst-case log-time behavior on insertion and lookup, and aren't vulnerable to any set of keys; OTOH, with very rare exceptions they have much worse expected-case behavior than hash tables -- pick your poison based on what's fatal to your app). From staschuk at telusplanet.net Tue Jun 10 11:23:01 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 10 Jun 2003 09:23:01 -0600 Subject: Factorials In-Reply-To: <84fc4588.0306100413.1125d1ee@posting.google.com>; from pythonguy@Hotpop.com on Tue, Jun 10, 2003 at 05:13:46AM -0700 References: <3ee1e6f1@shknews01> <84fc4588.0306100413.1125d1ee@posting.google.com> Message-ID: <20030610092301.D374@tibia.amotlpaa.bogus> Quoth Anand Pillai: [...] > def fac1(x): return reduce(lambda x, y: x*y, (range(x+1))[1:]) Note that you can skip the slice by calling range appropriately: range(x+1)[1:] == range(1, x+1) -- Steven Taschuk "[W]e must be very careful when we give advice staschuk at telusplanet.net to younger people: sometimes they follow it!" -- "The Humble Programmer", Edsger Dijkstra From pythonguy at Hotpop.com Thu Jun 5 07:55:17 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 5 Jun 2003 04:55:17 -0700 Subject: Help with dictionary References: <9afd3f36.0306042301.5243a9e8@posting.google.com> Message-ID: <84fc4588.0306050355.1454a1ff@posting.google.com> I dont get what you mean by 'sorting' a dictionary. You can sort a list or an array because there is a specific order in these structures. But I dont see any point in trying to sort a dictionary. The following code will give you a list with the keys sorted as you need it: d={(1, (21353, 21418)): 3900, (2, (53006, 53164)): 3800, (0, (19697, 19763)): 4100} newd=d.keys() l=list(newd) l.sort() lnew=[] for key in l: lnew.append((key,d[key])) print lnew # You get the output [((0, (19697, 19763)), 4100), ((1, (21353, 21418)), 3900), ((2, (53006, 53164)), 3800)] Now if you try to get the dictionary of this, "logically" you should expect {(0, (19697, 19763)): 4100, (1, (21353, 21418)): 3900, (2, (53006, 53164)): 3800} But what you get is, print dict(lnew) {(0, (19697, 19763)): 4100, (2, (53006, 53164)): 3800, (1, (21353, 21418)): 3900} I dont see any point in trying to spend time over this problem. Instead use the sorted list for your purposes and finally create the dictionary using dict() if you want the keys sorted. If there was any need for a 'sorted dictionary' the language designers would have provided that. Anand Pillai iamshady at rediffmail.com (Jim Shady) wrote in message news:<9afd3f36.0306042301.5243a9e8 at posting.google.com>... > Hello, > > I have a dictionary of the sort: > > {(1, (21353, 21418)): 3900, (2, (53006, 53164)): 3800, (0, (19697, > 19763)): 4100} > > I need to re-sort this dictionary with the first element of the tuple > in the keys. A sorted dictionary of the above would be: > > {(0, (19697, 19763)): 4100, (1, (21353, 21418)): 3900, (2, (53006, > 53164)): 3800} > > Could somebody help me with the algorithm/logic to accomplish this? > > Thanks in advance! > > Jim From stevesusenet at yahoo.com Wed Jun 18 21:27:10 2003 From: stevesusenet at yahoo.com (Steve) Date: 18 Jun 2003 18:27:10 -0700 Subject: Is python good for making database work short? Message-ID: <6f8cb8c9.0306181727.9c86095@posting.google.com> Hi; Today at work I got an impressive demonstration. There was a database mess that had to be cleaned up fast. One part of the problem involved copying tables from one database on one server, to another database on another server. To do it in Java would have been a bazillion lines of code. I would have had to written code to: 1. connect to the parent database 2. a sql statement to get the data 3. intermediarly store the results 4. close the parent connection 5. open the connection to the child database 6. a sql statement with 50 column names to create a blank table 7. code to transfer the stored data into the new table 8. close the connection A coworker who is a foxpro nut did all of this in about 3 lines of code. I was very impressed, and I plan to learn foxpro since the job has legacy apps written in it. However I was wondering if python could have made this job this easy. Does python make manipulating databases and data short work? Part of the program we had to make also required doing many queries to check the integrity of the data, and if it wasn't kosher, store the bad data to a table for examination later. In foxpro it was one line of code to save the query into a table. In java it would have been another trek like the one I described above. Java is great for a lot of stuff, but the jdbc is basically just a pipe into the database to pass sql through with a lot of gymnastics to get the sql into, massaged and out of the pipe. Anyway, I would love to have an open source, multiplatform tool that could match foxpro in ease of database manipulation. Is python it? Steve From 2002 at weholt.org Tue Jun 17 09:55:58 2003 From: 2002 at weholt.org (Thomas Weholt ( PRIVAT )) Date: Tue, 17 Jun 2003 15:55:58 +0200 Subject: The beauty of Python References: Message-ID: Well, I was hoping for smaller examples, not too advanced things, more stuff you'll find in any programming language, stuff python has solved in a particulary elegant way. I got Python Cookbook and look thru it to see if I find anything fitting my requirements. Thanks. Thomas "Max Khesin" wrote in message news:UxEHa.72090$4_1.16936489 at twister.nyc.rr.com... > how about activestate.com 's python cookbook - lots of great and prectical > examples there! > > -- > ======================================== > 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] > > > "Thomas Weholt ( PRIVAT )" <2002 at weholt.org> wrote in message > news:yrEHa.7094$Hb.127911 at news4.e.nsc.no... > > I'm trying to promote Python as an elegant, easy-to-read and intuitive > > language at work and to my programming-buddies. I thought it would be nice > > to have a webpage with examples of the beauty of Python, showing small > > snippets of code solving real-world problems or tasks. If anybody has any > > such examples to offer, I'd be very gratefull. And if it turns out to be > any > > interest for this in this group, I'll collect the source-snippets and put > > them on the net. > > > > Best regards, > > Thomas Weholt > > > > > > From donn at drizzle.com Fri Jun 20 00:55:55 2003 From: donn at drizzle.com (Donn Cave) Date: Fri, 20 Jun 2003 04:55:55 -0000 Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> <3EECED65.ACF1A6B7@engcorp.com> <3EEE3036.1080105@removeme.free.fr> Message-ID: <1056084953.994309@yasure> Quoth "Greg Ewing (using news.cis.dfn.de)" : | David Abrahams wrote: |> I don't have any first-hand experience, but the experience of friends |> of mine who have used Haskell is that it can be exceedingly difficult |> to locate the source of a type error when it does occur, since the |> inference engine may propagate the "wrong" type back much further than |> the source of the error. | | I played with HUGS intensively for a while some time back, | and I can attest that this is indeed a problem. I was led | to the conclusion that the only way to retain my sanity | was to provide an explicit type declaration for every | function. | | This has two benefits -- it helps the compiler catch | type errors early enough to actually give you a useful | error message, and it helps to document the code. | | But if you're doing that, you don't get much benefit | from type inference, raising the question of whether it's | worth the effort of designing a compiler that can do it | at all. There's a huge difference between optional type annotation and a system that requires you to declare the type of every single thing. The latter is a big nuisance, and far from helping to document the code it buries the sense of what the function is doing in a lot of trivia about its parts. Donn Cave, donn at drizzle.com From maschio_77 at hotmail.com Tue Jun 10 16:13:44 2003 From: maschio_77 at hotmail.com (Federico) Date: Tue, 10 Jun 2003 22:13:44 +0200 Subject: win32all : msaccess example Message-ID: Please can someone give me an example on how to have and modify msaccess data? Thanks From aahz at pythoncraft.com Sat Jun 21 19:09:08 2003 From: aahz at pythoncraft.com (Aahz) Date: 21 Jun 2003 19:09:08 -0400 Subject: Is o.__dict__ = {} valid? References: Message-ID: In article , Edward K. Ream wrote: > >3. If o.__dict__ = {} is not valid, is there any standard way to get the >same effect quickly? o.__dict__.clear() -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Usenet is not a democracy. It is a weird cross between an anarchy and a dictatorship. From pxtl at hotmail.com Mon Jun 9 11:10:27 2003 From: pxtl at hotmail.com (martin z) Date: Mon, 09 Jun 2003 15:10:27 GMT Subject: Call a Python file with parameters Message-ID: I've asked this before, but last time I was too vague. So, I've got a simpler request: I want to write and call Python files as if they were functions. The problem is simple: if you write a Python file with only a def-statement, you don't get a file you can run with arguments - you get a file that builds a function. If you use the argc and argv syntax, you get a file you can run with arguments, but the arguments are strings. Basically, I want to have a Python file that, when I compile it, I get nothing but a function, or something I can use like a function, that I can shove a parameter tuple into. Instead I get a code object (no argument tuple) or a module (containing functions). Can anyone help? From peter at engcorp.com Fri Jun 6 22:11:59 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 06 Jun 2003 22:11:59 -0400 Subject: Postfix/Prefix Operators (++,--) References: <3EE05E36.40DF739F@engcorp.com> <3EE0B4D5.736EE894@engcorp.com> <3EE0D19C.7D7FFCA0@engcorp.com> Message-ID: <3EE149EF.73C7373F@engcorp.com> John Roth wrote: > > "Peter Hansen" wrote in message > news:3EE0D19C.7D7FFCA0 at engcorp.com... > > Joshua Marshall wrote: > > > >>> c = 1 > > > >>> a = c++ > > > >>> a > > > 1 > > > >>> c > > > 2 > > > > Except that that violates a fundamental aspect of Python, which while > > I can't describe it in the best technical terms as I don't ever work > > at the compiler level, could be said as "you are rebinding a name (c) > > without using an assignment statement". > > Well, let's see. The "def", "class" and "import" statements all (re)bind > names. So do several of the builtin functions (setattr() comes to mind > immediately.) I figured my inability to use the proper technical terms would cause trouble. I think Joshua has the best perspective: the fundamental aspect of Python which is being violated here is that of not rebinding things in an expression. The examples you give are not expressions so I think they still fit in the Python mould. I'll comment on Joshua's exception in a response to his message... -Peter From m at moshez.org Mon Jun 2 13:34:39 2003 From: m at moshez.org (Moshe Zadka) Date: 2 Jun 2003 17:34:39 -0000 Subject: Blogging Software In-Reply-To: References: Message-ID: <20030602173439.21700.qmail@green.zadka.com> On 2 Jun 2003, ngps at netmemetic.com (Ng Pheng Siong) wrote: > Which others are there, please? Is there a website or three that lists > these? There's pybloxsom, and also http://moshez.org/discuss/software.html -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From mail at manuelmgarcia.com Sun Jun 15 23:52:10 2003 From: mail at manuelmgarcia.com (Manuel M Garcia) Date: Mon, 16 Jun 2003 03:52:10 GMT Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> Message-ID: Bruce Eckel wrote about shifting your programming mindset from 'strong typing' to 'strong testing' http://mindview.net/WebLog/log-0025 Manuel From pythonidae_olivaceous at hotmail.com Sun Jun 8 21:54:26 2003 From: pythonidae_olivaceous at hotmail.com (Ben Minton) Date: Mon, 9 Jun 2003 01:54:26 +0000 (UTC) Subject: Newbie Question re Python 2.2.2 WIN References: Message-ID: a wrote in news:Xns9394A8AABA933abc at 194.106.32.13: > http://www.ibiblio.org/obp/thinkCSpy/ > thanks sfb ... i thought that might be the case, but wasn't sure. at the python shell .... with the >>> what is the command to bring run an python script, say my_first_script.py? Is there another way, perhaps just going into the folder where the scripts are stored and clinking on the file name while, the python engine is running? cheers, Ben From ellisonh at prodigy.net Sun Jun 8 19:49:32 2003 From: ellisonh at prodigy.net (Homer Ellison) Date: Sun, 8 Jun 2003 16:49:32 -0700 Subject: Strange problem with notebook computer Message-ID: <001401c32e18$9c123e80$afee7b43@homer3cq9tc2v2> Hello, I'm new to Python (and many years out of programming until now). I'm having a strange problem as I program and troubleshoot Python on my notebook computer. Often when I am troubleshooting code, the mouse pointer freezes. Sometimes even the keyboard freezes. The problem persists when I reboot. The only way I have found to be able to stop the problem is to turn it off and unplug it; remove the battery and floppy drive modules (this may not be necessary); remove the cover over the memory card; let the system cool down; and put it back together and start up again. I do not have this problem when I'm running other software, only Python. Is there a possibility that somehow Python or the code I'm writing in Python is causing my notebook computer to overheat? I can't imagine why this would be, but I can't figure out what else might be causing the problem. Any ideas? Thank you, Homer -------------- next part -------------- An HTML attachment was scrubbed... URL: From staschuk at telusplanet.net Fri Jun 13 14:39:19 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Fri, 13 Jun 2003 12:39:19 -0600 Subject: why 'lambda' and 'reduce'? In-Reply-To: ; from news@manuelmgarcia.com on Fri, Jun 13, 2003 at 12:28:11AM +0000 References: <84fc4588.0306112339.10a4012b@posting.google.com> Message-ID: <20030613123919.B1448@tibia.amotlpaa.bogus> Quoth Manuel Garcia: [...] > I shouldn't feed a troll, but this reply is just too delicious. The > author claims the code is unobfuscated, [...] In fact, I wrote: "while it is obfuscated, it is not very artistically obfuscated". > [...] but the nature of how all 5000 > digits are kept accurate are obfuscated from him. Indeed, perhaps you concealed how the error control works more cleverly than you concealed how everything else works. That *I* don't understand the error control, however, is hardly compelling evidence that it is cleverly obfuscated; rather, it is evidence that I am ignorant of numerical analysis, as admitted in my review. [...] -- 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 matthew.rapoport at accenture.com Wed Jun 4 10:21:36 2003 From: matthew.rapoport at accenture.com (Matt Rapoport) Date: 4 Jun 2003 07:21:36 -0700 Subject: Passing an Event from a Thread to its Caller References: <4150f6c8.0306021120.7b70d981@posting.google.com> <4150f6c8.0306030833.2dd4fc9b@posting.google.com> Message-ID: <4150f6c8.0306040621.14a28c3d@posting.google.com> > Why not simply have your thread log the error? > Argg, I hate it when I over-complicate things. Thanks for the help Mark. And thanks in general for the win32 extensions! From ahaas at airmail.net Tue Jun 3 17:03:14 2003 From: ahaas at airmail.net (Art Haas) Date: Tue, 3 Jun 2003 16:03:14 -0500 Subject: [ANNOUNCE] Seventh development release of PythonCAD available Message-ID: <20030603210314.GN663@artsapartment.org> I'd like to announce the seventh development release of PythonCAD, a CAD package for open-source software users. As the name implies, PythonCAD is written entirely in Python. The goal of this project is to create a fully scriptable drafting program that will match and eventually exceed features found in commercial CAD software. PythonCAD is released under the GNU Public License (GPL). PythonCAD requires Python 2.2. The interface is GTK 2.0 based, and uses the PyGTK module for interfacing to GTK. The design of PythonCAD is built around the idea of separating the interface from the back end as much as possible. By doing this, it is hoped that both GNOME and KDE interfaces can be added to PythonCAD through usage of the appropriate Python module. Addition of other interfaces will depend on the availability of a Python module for that particular interface and developer interest and action. The seventh release adds the ability to draw tangent construction circles against one or two other construction objects, and the ability to easily draw a construction line tangent to two construction circles. The drawing of parallel construction lines has been simplified with the addition of a menu choice for doing this task. There are numerous internal code cleanups and revisions, and a large number of changes that moved more code into the interface neutral code directory. These code changes will hopefully make it easier for developers to add new interfaces to PythonCAD. Many bug fixes and code improvements have been added as well. PythonCAD now also has the first iteration of a command interpreter thanks to the work of David Broadwell. Future releases of PythonCAD will build on the work he has contributed to make it easier to use PythonCAD by typing commands in the entry field at the bottom of the screen. Between the sixth and seventh release a mailing list for developing and using PythonCAD has been set up thanks to Barry Warsaw. The mailing list home is found at: http://mail.python.org/mailman/listinfo/pythoncad This page has instructions for joining the mailing list and web archives of the list postings. I'd like to publicly acknowledge and thank the developers and maintainers of PyChecker for the work they've done in developing this most useful tool. PyChecker is an effective tool for identifying errors in Python code, and I've been using it more and more. PyChecker gets a big recommendation from me and so I say thank you to the people who make it available. http://pychecker.sourceforge.net/ Visit the PythonCAD web site for more information about what PythonCAD does and aims to be: http://www.pythoncad.org/ Come and join me in developing PythonCAD into a world class drafting program! Art Haas -- Man once surrendering his reason, has no remaining guard against absurdities the most monstrous, and like a ship without rudder, is the sport of every wind. -Thomas Jefferson to James Smith, 1822 From bdeck at lycos.co.uk Wed Jun 4 07:13:35 2003 From: bdeck at lycos.co.uk (deckerben) Date: Wed, 4 Jun 2003 13:13:35 +0200 Subject: PythonD: 4Suite or Twisted? Message-ID: <3eddd372$0$16609$9b622d9e@news.freenet.de> Greetings! Which web server software would be more appropriate for a DOS (long filename enabled) environment? I have seen 4suite and Twisted. Twisted seems to offer a lot of other networking tools (like telnet and news services) but some of the admin parts require GTK :-( 4Suite runs already except for the manager, which requires threads. 4Suite also seems to have more comprehensive XML tools, which I like. Ben From andrew-pythonlist at puzzling.org Wed Jun 11 04:59:35 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 11 Jun 2003 18:59:35 +1000 Subject: Revised PEP 318 - Function/Method Decorator Syntax In-Reply-To: <20030611013918.GA2113@frobozz> References: <20030610082514442-0400@braeburn.themorgue.org> <20030610142845.4540.qmail@green.zadka.com> <20030611013918.GA2113@frobozz> Message-ID: <20030611085935.GG2113@frobozz> On Wed, Jun 11, 2003 at 11:39:18AM +1000, Andrew Bennetts wrote: > On Tue, Jun 10, 2003 at 02:28:45PM -0000, Moshe Zadka wrote: > > > > Wouldn't it be more readable (:)) if you did > > > > class _EvilProperty(type): > > .... > > class EvilProperty: > > __metaclass__ = _EvilProperty > > > > class C(object): > > class x(EvilProperty): > > def get(self): > [...etc...] > > No, it wouldn't be more readable, because it wouldn't work... But this would: ---- class _EvilProperty(type): def __new__(cls, name, bases, d): if d.get('__metaclass__') == _EvilProperty: return type.__new__(cls, name, bases, d) else: return property(d.get('get'), d.get('set'), d.get('del'), d.get('__doc__')) class EvilProperty: __metaclass__ = _EvilProperty class C(object): class x(EvilProperty): """An evil test property""" def get(self): print 'Getting' return 1 def set(self, value): print 'Setting to', value c = C() print c.x c.x = 5 print C.x.__doc__ ---- :) Ta-da! Easy, clean-looking properties, no new syntax required ;) -Andrew. From icarroll at pobox.com Thu Jun 26 23:25:53 2003 From: icarroll at pobox.com (W Isaac Carroll) Date: Thu, 26 Jun 2003 20:25:53 -0700 Subject: List of lists References: Message-ID: <3EFBB941.8000307@pobox.com> Mike wrote: > Ok, I'm doin an exercise and I need to expand on test.py. I'm pretty much > done with the exercise except I need to print out the questions and answers > that are in the function. > > here is the snippet: > > def get_questions(): > return [["What color is the daytime sky on a clear day?","blue"],\ > ["What is the answer to life, the universe and > everything?","42"],\ > ["What is a three letter word for mouse trap?","cat"]] > > How do I get the lists from this? questions = get_questions() print questions[0][0] # print first question (color of sky) print questions[0][1] # print first answer ("blue") TTFN From akineko at pacbell.net Wed Jun 4 01:10:04 2003 From: akineko at pacbell.net (Aki Niimura) Date: 3 Jun 2003 22:10:04 -0700 Subject: TkInter/McMillan installer question. Message-ID: Hello everyone, I'm trying to create a MS-Windows executable from my Python Tkinter script using McMillan Installer script. It worked very nicely. I was very amazed as I had so many disappointments with Python/Windows environment. However, I tried to assign a icon file using --icon file.ico option. It didn't honor the option. Using --debug option, I found the following message: ignoring icon and version resources = platform not capable I'm creating the exe file under Windows XP Home (with Cygwin). Did anybody suceed to use --icon option under Windows XP? If the Installer cannot assign the icon, is there any way to assign the icon afterward? Any suggestions, comments are highly appreciated. Best regards, Aki Niimura From jerf at jerf.org Tue Jun 10 23:37:42 2003 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 11 Jun 2003 03:37:42 GMT Subject: unittest: Dynamically creating tests Message-ID: I have some code that has 16 possible ways of executing (four binary parameters). The parameters are such that I can relatively easily write a test file that will generate 16 tests to test each combination, for complete coverage of all the space. (I'm enjoying the meta-ness of this because I may personally only use 3 or 4 of the combinations, but in theory all 16 are potentially useful. By carefully writing my tests I can ensure they all work with reasonable probability and much less then 16 times the effort.) My problem is that I'm having trouble writing the tests in such a way that they execute. Consider the following simplified code that demonstrates what I am trying to do: ------------------- import unittest tests = unittest.TestSuite() for i in range(5): class NextTest(unittest.TestCase): def testEquality(self): self.assert_(1 == 1) tests.addTest(NextTest) if __name__ == '__main__': unittest.main() ------------------- I can't seem to figure out how to get this to do what I want to do, which is run the 5 tests in the subsequent NextTest classes that are created. The code above would be ideal if it worked, but it only runs the last instance of the NextTest and ignores the "tests" test suite, which is less then ideal. I also tried ending the file with ------------------- if __name__ == '__main__': tr = unittest.TestResult() tests.run(tr) ------------------- but that results in ------------------- Traceback (most recent call last): File "testtest.py", line 18, in ? tests.run(tr) File "/usr/lib/python2.2/unittest.py", line 339, in run return self(result) File "/usr/lib/python2.2/unittest.py", line 345, in __call__ test(result) File "/usr/lib/python2.2/unittest.py", line 155, in __init__ testMethod = getattr(self, methodName) TypeError: attribute name must be string ------------------- which doesn't make much sense to me. My requirement is that the test classes can be generated dynamically; I really don't care how they are aggregated or how they are run, as long as they *are* run. Does anybody know the best way to do this? (On a side note, is there a way to programmatically add something to the *current* module, while it's being created? I tried adding the classes w/ different names into the current module space, which would probably be a solution to this problem, but I couldn't figure out how. I'm looking for something like setattr(__module__, name, obj) Starting the file off with "import filename", where filename was the name of the file, seemed promising but did not actually work; it seems there's a seperate module object created when that is hit which is later overwritten by the real "filename" module when Python is done creating it.) From skip at pobox.com Thu Jun 12 17:43:17 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 12 Jun 2003 16:43:17 -0500 Subject: Bug in v1.5.2 Websucker GUI? In-Reply-To: References: <7isqqi$8ki@vern.bga.com> Message-ID: <16104.62453.153275.971509@montanaro.dyndns.org> Anton> Thanks for pointing me to that page. However I don't like it Anton> (understatement deleted). Anton> a) "SourceForge will not allow you to submit a new bug report Anton> unless you're logged in. " Anton> Then why is Python bugtracking hosted on that site? This has nothing to do with SourceForge. It's a policy decision which was made by those of us who actively work on the Python code base. You used to be able to submit bug reports anonymously, but many people submitted incomplete reports without leaving any contact information. There was no way to get back in touch with these people to get the rest of the information needed to reproduce and/or correct the bug (what version of Python? what platform? test case? etc.). The only thing we could do was hope that someone could reproduce the bug and embellish the report or add a comment to the report asking for more input and hope that the original submitter revisited the report on his own later. Since the posting was anonymous he'd never be notified by email that a comment had been attached to his bug report. If such a bug report languished, after several months of silence there was no choice but to close the bug. By requiring you to login to SourceForge, we can get back to you if we need more information. Anton> b) If I want to save the page to my harddisk for future reference Anton> it makes my explorer crash because of some illegal operation. That sounds like a bug with Internet Explorer. Try another browser. Anton> c) If want to browse the bug reports by date descending, I get an Anton> error "The page cannot be displayed". That may be a SourceForge bug. You should submit a bug report to them. Don't submit it to the Python bug tracker. We don't fix the SF code. Anton> d) There's a trick to still save a page: View the page as Anton> "source", then save it from notepad with ending html. If I do Anton> this and later open the page when I'm offline, I get an error Anton> like: "no access to \\sfads.osdn.com\7.html" . It's always nice to have a workaround. Skip From peter at engcorp.com Tue Jun 3 20:51:50 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 03 Jun 2003 20:51:50 -0400 Subject: calldll References: Message-ID: <3EDD42A6.3D45B60E@engcorp.com> Vincent L wrote: > > I'm searching for the python binary module "calldll.pyd" for python > 2.3 (for Win32 platform)? (and the file npstruct.pyd) > > Where I can find this file? I believe the best answer might be "use ctypes instead". You probably found this: http://www.nightmare.com/software.html from which you can infer that calldll is not supported any more. (I'm not sure that's the case... and of course the source is available so you could presumably make it run under Python 2.3 yourself.) On the other hand, http://starship.python.net/crew/theller/ctypes/ is the place to go for something that appears to be supported, although depending on your needs it may not be quite mature enough yet. It has been described as "experimental" in the past, although that label seems to have been removed from the web page... I haven't gotten around to trying it yet, myself. -Peter From dave at boost-consulting.com Wed Jun 18 22:55:03 2003 From: dave at boost-consulting.com (David Abrahams) Date: Wed, 18 Jun 2003 22:55:03 -0400 Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> <3EECED65.ACF1A6B7@engcorp.com> <3EEE3036.1080105@removeme.free.fr> Message-ID: Alex Martelli writes: > David Abrahams wrote: > >> Alex Martelli writes: >> >>> But this has little to do with the need of 'type declarations'. I >>> suspect that a statically typed language would also be better off >>> without them, relying on type inferencing instead, a la Haskell (and >>> Haskell's typeclasses to keep the inferencing as wide as feasible), >>> for example. But I have no research to back this up;-). >> >> I don't have any first-hand experience, but the experience of friends >> of mine who have used Haskell is that it can be exceedingly difficult >> to locate the source of a type error when it does occur, since the >> inference engine may propagate the "wrong" type back much further than >> the source of the error. > > Surely the compiler should easily be able to annotate the sources with > the information it has inferred, including, in particular, type > information. Oh, yes, IIUC it does: what you get is a long nasty thing which resembles more than anything a C++ template instantiation backtrace. > Thus it cannot possibly be any harder to identify the error point than > if the same type declarations had been laboriously, redundantly written > out by hand -- except, at worst, for a slight omission in the tool of a > feature which would be easily provided. No, if you "laboriously, redundantly" write out the type declarations by hand you get precise feedback about the location of a type mismatch. >> Furthermore, if you do everything by inference you lose the >> explanatory power of type declarations. > > I think I know where you're coming from, having quite a past as a > static-type-checking enthusiast myself, but I think you overrate the > "explanatory power of type declarations". > > What I want to be able to do in my sources is assert a set of facts > about "and at this point I know X holds". Much of what's in X is captured by type information. > Sometimes X might perhaps be of the form "a is of type B", but > that's really a very rare and specific case. Much more often it > will be "container c is non-empty", "sequence d is sorted", "either > x=z>=y", and so on, and so forth. Those assertions are *chock full* of type information: the type of c is a container the type of d is a sequence the type of a is indexable the types of x and y have a particular ordering relationship and so on and so forth. Type declarations don't have to identify concrete types; they can identify concepts, constraints, and relationships. > Type declarations would have extraordinary "explanatory power" if > and only if "a is of type B" was extraordinarily more important than > the other kinds of assertions, and it just isn't -- even though, by > squinting just right, you may end up seeing it that way by a sort of > "Stockholm Syndrome" applied to the constraints your compiler forces > upon you. Suggesting that I've grown to love my shackles is a little bit insulting. I have done significant programming in Python where I didn't have static typing; I've gotten over my initial reactions to the lack of static checks and grown comfortable with the language. Purely dynamic typing works fine for a while. I have seen real problems develop in my code that static type checking would have prevented. It's not an illusion that static types help (a lot) with certain things. The type information is at least half of what you've written in each of those assertions. I use runtime assertions, too, though often I use type invariants to constrain the state of things -- because it makes reasoning about my code *much* easier. An ultra-simple case: it's great to be able to use an unsigned type and not have to think about asserting x >= 0 everywhere. > Types are about implementation No, they're about a relationship between an interface and semantics. Most people leave out the semantics part when thinking about them, though. > and one should "program to an interface, not to an implementation" > -- therefore, "a is of type B" is rarely what one SHOULD be focusing > on. In a modern type system, "a is of type B" mostly expresses an interface for a and says nothing about implementation per se. It does say something about the effects of using that interface, though that part is harder to formalize. However, with a nod to "practicality beats purity:" People don't usually think in these abstract terms about most of their code, and rigorously documenting code in terms of interface requirements is really difficult, so most people never do it. It's a poor investment anyway because *most* (not all) Python code is never used generically: common interfaces for polymorphic behavior are generally captured in base classes and a great deal of code is just operating on concrete types anyway. The result is that there are usually no expression of interface requirements at all in a function's interface/docs, where in the *vast* majority of cases a simple (non-generic) type declaration would've done the trick. [Without the expression of interface requirements, the possibility to use the function generically is lost, for all intents and purposes] So, while I buy "program to an interface" in theory, in practice it is only appropriate in a small fraction of code. > Of course, some languages blur the important distinction > between a type and a typeclass (or, a class and an interface, in > Java terms -- C++ just doesn't distinguish them by different > concepts Nor does most of the type theory I've seen. > so, if you think in C++, _seeing_ the crucial distinction may be > hard;-). I know what typeclasses and variants are all about. > "e provides such-and-such an interface" IS more often interesting, but, > except in Eiffel, the language-supplied concept of "interface" is too > weak for the interest to be sustained -- it's little more than the sheer > "signature" that you can generally infer easily. E.g.: > > my procedure receiving argument x > > assert "x satisfies an interface that provides a method Foo which > is callable without arguments" > > x.Foo() > > the ``assert'' (which might just as well be spelled "x satisfies > interface Fooable", or, in languages unable to distinguish "being > of a type" from "satisfying an interface", "x points to a Fooable") > is ridiculously redundant, the worse sort of boilerplate. Only if you think that only syntax (and not semantics) count. It's not just important that you can "Foo()" x, but that Fooing it means what you think it does. > Many, _many_ type declarations are just like that, particularly if > one follows a nice programming style of many short > functions/methods. At least in C++ you may often express the > equivalent of > > "just call x.Foo()!" > > as > > template > void myprocedure(T& x) > { > x.Foo(); > } In most cases it's evil to do this without a rigorous concept definition (type constraint) for T in the documentation. Pretty much all principled template code (other than special cases like the lambda library which are really just for forwarding syntax) does this, and it's generally acknowledged as a weakness in C++ that there's no way to express the type constraints in code. > where you're basically having to spend a substantial amount of > "semantics-free boilerplate" to tell the compiler and the reader > "x is of some type T" Where are you claiming the expression of the type of x is in the code above? I don't see it. > (surprise, surprise; I'm sure this has huge explanatory power, > doesn't it -- otherwise the assumption would have been that x was of > no type at all...?) This kind of sneering only makes me doubt the strength of your argument even more. I know you're a smart guy; I ask you to treat my position with the same respect with which I treat yours. > while letting them both shrewdly infer that type T, whatever it > might be, had better provide a method Foo that is callable without > arguments (e.g. just the same as the Python case, natch). Only if you consider the implementation of myprocedure to be its documentation. > You do get the "error diagnostics 2 seconds earlier" (while compiling > in preparation to running unit-tests, rather than while actually > running the unit-tests) if and when you somewhere erroneously call > myprocedure with an argument that *doesn't* provide the method Foo > with the required signature. But, how can it surprise you if Robert > Martin claims (and you've quoted me quoting him as if I was the > original source of the assertion, in earlier posts) Hey, sorry, I just let Gnus do its job. If the quote attributions were messed up then someone messed them up before me. > that this just isn't an issue...? It doesn't surprise me in the least that some people in the Python community claim that their way is unambiguously superior. It's been going on for years. I wanted to believe that, too. My experience contradicts that idea, unfortunately. > If the compilation takes 3 seconds, then getting the error > diagnostics 2 seconds earlier is still a loss of time, not a gain, > compared to just running the tests w/o any compilation;-)... Comprehensive test suites can't always run in a few seconds (the same applies to compilations, but I digress). In a lot of the work I've done, testing takes substantially longer, unavoidably. A great deal of this work is exactly the sort of thing I like to use Python for, in fact (but not because of the lack of type declarations). If compilation is reasonably fast and I have been reasonably conscientious about my type invariants, though, I *can* detect many errors with a static type system. But more importantly, I can come back to my code months later and still figure out what's going on, or work with someone else's code without losing my way. Isn't that why we're all using Python instead of Perl? > I do, at some level, want a language where I CAN (*not* MUST) make > assertions about what I know to be true at certain points: > 1. to help the reader in a way that won't go out of date (the assert > statement does that pretty well in most cases) > 2. to get the compiler to to extra checks & debugging for me (ditto) > 3. to let the compiler in optimizing mode deduce/infer whatever it > wants from the assertions and optimize accordingly (and assert is > no use here, at least as currently present in C, C++, Python) Those are all the same things I want, and for the same reasons. What are we arguing about again? > But even if and when I get such a language I strongly doubt most of > my assertions will be similar to "type declarations" anyway... Oh, there it is. Well, if the language has a weak notion of type, then you're probably right. -- Dave Abrahams Boost Consulting www.boost-consulting.com From staschuk at telusplanet.net Sun Jun 8 12:21:37 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Sun, 8 Jun 2003 10:21:37 -0600 Subject: a = b = 1 just syntactic sugar? In-Reply-To: ; from ed@membled.com on Sun, Jun 08, 2003 at 11:51:50AM +0100 References: Message-ID: <20030608102137.C3782@tibia.amotlpaa.bogus> Quoth Ed Avis: > Steven Taschuk writes: > > > swap = lambda L,i,j: L[i], L[j] = L[j], L[i] > > As I mentioned elsewhere on this thread, lambda-functions could be > parenthesized where this is necessary. The proposed change to have > one-line statements instead of expressions inside lambda would not > (AFAIK) make any parse that is currently unambiguous require > parentheses; only some new cases such as your example with commas > would need it. So > > swap = lambda L,i,j: (L[i], L[j] = L[j], L[i]) Note that this does not match your proposed syntax lambda_form ::= "lambda" [parameter_list]: simple_stmt since assignment statements may not be parenthesized. Also, although I know next to nothing about the parser implementation, I'd think it parses simple_stmt greedily. If that is so, the change you propose would break the parsing of lambda x: x, 3 since the whole "x, 3" would be greedily consumed as a simple_stmt. (I'm just guessing, of course, but at least in a half-educated way; note in Grammar/Grammar that the present rule for lambda lambdef: 'lambda' [varargslist] ':' test uses 'test', while simple_stmt simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE small_stmt: expr_stmt | print_stmt | [...] expr_stmt: testlist (augassign testlist | ('=' testlist)*) uses 'testlist', which is testlist: test (',' test)* [','] . I'd think this would affect the handling of commas in lambdas in a backwards-incompatible way.) > > [...] Anonymity is a red > >herring; so are closures; the important point is that lambdas are > >expressions and defs are statements. > > Well a named function has two halves: the 'def f: ...' which is a > statement, and the use of the name 'f' which is an expression. Lambda > combines both in one place. [...] I do not find this a useful way to describe the situation. That a name bound to an object (whether by def statement or otherwise) can be used in an expression tells us nothing about the syntax for creating the object, nor about the object itself. You can do the same with a lambda-created function, after all: foo = lambda x: 2*x # create function object, bind name 'foo' to it print foo(3) # use 'foo' in expression or, indeed, any object whatsoever. The point under discussion is the function-creating text; for lambdas that is an expression, and for defs it is a statement. I regret that you think it's harping, but ultimately that's why lambda is restricted to expressions -- being an expression itself, it may only contain expressions (barring significant and, imho, likely-to-be-problematic changes to the grammar). > [...] Letting it contain one-line statements > seems like the best compromise between the two worlds. Expressions > only is too counterintuitive IMHO. I disagree, as I'm sure you've realized by now. Certainly I don't expect allowing statements in expressions to work out well -- even if restricted to simple_stmt, and even with parentheses. For example, the circumstances under which you'd need parentheses seem much more complicated to explain than the difference between expressions and statements. But I'm willing to be convinced otherwise. A working patch would probably convince me; so probably would a thorough analysis of the syntactical issues. Once I'm convinced it's feasible, I might reject it on aesthetic grounds, of course. :) -- Steven Taschuk staschuk at telusplanet.net "Our analysis begins with two outrageous benchmarks." -- "Implementation strategies for continuations", Clinger et al. From tim at remove_if_not_spam.digitig.cix.co.uk Wed Jun 25 07:39:06 2003 From: tim at remove_if_not_spam.digitig.cix.co.uk (Tim Rowe) Date: Wed, 25 Jun 2003 12:39:06 +0100 Subject: WTF is Fibonnacci References: <7inIa.55233$Io.5225846@newsread2.prod.itd.earthlink.net> Message-ID: On Sat, 21 Jun 2003 19:08:22 GMT, "Byron Morgan" wrote: >1 11 21 1112 3112 211213 312213 212223 114213 > >Or at least I think that is it. I'd not seen that one before, but it's clearly related to the now fairly well-known: 1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211 ... Exercise: prove that no digit higher than 3 can appear in that series... From tungwaiyip at yahoo.com Thu Jun 26 17:39:11 2003 From: tungwaiyip at yahoo.com (Tung Wai Yip) Date: Thu, 26 Jun 2003 14:39:11 -0700 Subject: add empty directory using zipfile? References: Message-ID: <4cnmfvkvg6bbf4t6nmtrg5nc764fe02dkk@4ax.com> On Thu, 26 Jun 2003 03:40:01 -0400, Oren Tirosh wrote: >On Thu, Jun 26, 2003 at 04:31:37AM +0000, JanC wrote: >> Tung Wai Yip schreef: >> >> > Can I add empty directory using zipfile? When I try to add a directory >> > it complains that it is not a file. >> >> ZIP files can't contain directories, only files and the paths to those >> files. A workaround might be to put an empty file in the directory. > >ZIP files *can* contain directories. They are described as zero-length >files with some flag set. I don't see any specific API for this in >zipfile.py but I think that if you pass a ZipInfo record with the right >values to ZipFile.writestr it should probably work. Consult the >documentation of the zip format or just create a zip containing an empty >directory with any zip utility look at the ZipInfo using zipfile.py. > > Oren I reverse engineered a zip file. Looks like I can save an empty directory by setting zipinfo.external_attr as 48 (at least for Windows 2000). z = zipfile.ZipFile("new.zip","w") zinfo = zipfile.ZipInfo("empty/",(2002,12,31,23,59,59)) zinfo.external_attr = 48 z.writestr(zinfo, "") I guess zipfile should be enhanced to save empty directory too. Wai Yip Tung From gsmatthew at ozemail.com.au Thu Jun 5 08:23:46 2003 From: gsmatthew at ozemail.com.au (Graeme Matthew) Date: Thu, 5 Jun 2003 22:23:46 +1000 Subject: Python & CGI. HELP please... References: Message-ID: I scratching my head and thinking back to when I did this in perl, cant you just: print "Content-Type: application/pdf\n\n" #you need 2 returns here #read file as binary and print to screen #lets say read file into a variable called content print content > print "Content-Disposition: attachment; filename=%s\n" % "Jay Dorsey" wrote in message news:mailman.1054814129.25949.python-list at python.org... > On Thursday 05 June 2003 05:57, Enrico Morelli wrote: > > Have you tried opening the file up before you write the headers, so you can > obtain the length, then specifying a "Content-length: %d" % len(l) in the > headers? > > Jay > > > I'm trying to write a script to be able to download/upload files > > through web pages. > > The upload script works fine but the download no. > > When I download a file (pdf for example) using this script, I'm unable > > to open it in local using acroread because at the end of the document I > > found some html rows :-|| > > These rows are some html code inside of the script that I use to > > display errors. > > > > Follow the method that I use to download files: > > > > def download(self, fullname, file): > > print "Content-Type: application/download" > > print "Content-Disposition: attachment; filename=%s\n" % > > file try: > > f=open(fullname, "rb") > > l=f.read() > > sys.stdout.write(l) > > f.close() > > sys.exit() > > except: > > msg="An error occurred during file transfer." > > Display(msg, "") > > sys.exit() > > -- > Jay Dorsey > jay at jay dorsey dot com > > From jtauber at jtauber.com Sun Jun 22 07:42:15 2003 From: jtauber at jtauber.com (James Tauber) Date: Sun, 22 Jun 2003 19:42:15 +0800 Subject: GUI interactive prompt with non-text output References: <000601c33834$e935fc30$a300a8c0@emilio> Message-ID: <20030622114215.EB48236370@www.fastmail.fm> On Sun, 22 Jun 2003 15:07:14 +0800, "James Tauber" said: > I've started diving into the PyCrust/Py stuff from wxPython (thanks for > the pointer) and it looks like I should be able to do what I want by > modifying PyShell. Actually, this assumes that wxStyledTextCtrl supports embedded non-text widgets, which I'm not sure it does. Time for me to switch over to the wxPython list, unless someone here knows if wxStyledTextCtrl can support embedded non-text widgets. James -- James Tauber http://jtauber.com/ From gerrit at nl.linux.org Wed Jun 4 10:42:22 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 4 Jun 2003 16:42:22 +0200 Subject: [OT] Re: LANGUAGE QUESTION??? In-Reply-To: References: <8dcf2300.0306040159.118c24e8@posting.google.com> Message-ID: <20030604144222.GA2552@nl.linux.org> Aahz schreef op woensdag 4 juni om 16:21:18 +0000: > Gerrit Holl wrote: > > > >Smalltalk isn't practical. > > That's not quite true. I know plenty of Smalltalk programmers who would > disagree, and Squeak is making some inroads. OK, I'm sorry. I was only mimicing what I have once heard people say, and I shouldn't do that. I once heard that sockets don't exist but if it isn't true than I'm gone. Sorry! yours, Gerrit. From bdeck at lycos.co.uk Tue Jun 10 18:18:20 2003 From: bdeck at lycos.co.uk (deckerben) Date: Wed, 11 Jun 2003 00:18:20 +0200 Subject: Porting Python References: <2986845.1055280214@dbforums.com> Message-ID: <3ee657b4$0$16588$9b622d9e@news.freenet.de> "DB_RobertP" wrote in message news:2986845.1055280214 at dbforums.com... > Does anyone know if there are any useful links to places that document > the porting process of Python to other platforms? If anyone is > familiar with > python porting, any pointers would be helpful. I'm new to python and Hello Robert, I came to this site about a year ago 'looking for a scripting language' to replace my slow-moving batchfiles. I still wanted a DOS based solution, so using DJGPP, I did several quick and dirty ports... one of which was Python. I was not familiar with Python at all, then. After having recieved a lot of good advice here and from the DJGPP folks, the port grew and became successful. Thousands of people have since visited http://members.lycos.co.uk/bdeck to read about and download PythonD (I'm not kidding). The policy I recommend is: 1. Start with a good development platform and C compiler. This was the most critical descision for the DOS port. 2. Know exaclty which posix functions your platform supports, and which ones they don't. Understand how the python source code works. 3. Offer features. If you don't have them, find them. Example: PythonD's popularity rocketed when we made the first release that supported dynamic linking and the building of distutils scripts. 4. Port a clean package. Identify bugs ASAP and move quick to fix them. Run the test suite (regrtest.py). 5. Use your own software. I myself do all my python programming with PythonD, and all scripts I write were tested using PythonD. 6. Let others know. Even the best port won't do anyone any good, if they don't know it's out there for them. Set up a website, or at least use someone else's (that's what I first did, too). Hope this helps a bit. Best wishes. Ben From shlomme at gmx.net Sun Jun 8 10:44:25 2003 From: shlomme at gmx.net (Torsten Marek) Date: Sun, 08 Jun 2003 16:44:25 +0200 Subject: locale.py strangeness Message-ID: Hi list, I experienced some strange behaviour with locale.py from Python 2.2.3. The output of the following code snippet ## -- start -- ## #!/usr/bin/env python import os import locale pa = "?n" pb = "oo" locale.setlocale(locale.LC_ALL, "") print locale.strcoll(pa, pb) locale.setlocale(locale.LC_ALL, os.getenv("LANG")) print locale.strcoll(pa, pb) ## -- end -- ## is 135 -1 but according to the documentation of locale.getdefaultlocale, the results should be the same. My locale setting (in "LANG") is "de_DE at euro" (which is not support in Python earlier than 2.2.3), and if I run locale.setlocale(locale.LC_ALL, locale.getdefaultlocale()) , a locale.Error is thrown. Can somebody verify this behaviour and give some hints about that? TIA Torsten From hannibalkannibal at yahoo.no Sun Jun 22 13:03:10 2003 From: hannibalkannibal at yahoo.no (Eirik) Date: Sun, 22 Jun 2003 19:03:10 +0200 Subject: "eval" function Message-ID: How can I do what I would do like this: set a 12 set b 144 eval a*a == b in Tcl? -- From bignose-hates-spam at and-zip-does-too.com.au Wed Jun 18 21:16:18 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Thu, 19 Jun 2003 01:16:18 GMT Subject: Freedom vs popularity References: Message-ID: On Thu, 19 Jun 2003 09:20:48 +1000, Delaney, Timothy C (Timothy) wrote: > From: Ben Finney >> [GPL as possible explicit waiver of copyright] >> Thanks for the FUD, but no thanks. > > No FUD, no ability to support anything. Then please change your description of the supposed problem when you discuss it, because the GPL is provably not an "explicit" waiver of copyright. > Personally, the only thing I have against the GPL is that in practical > terms it restricts the amount that code licensed under it is used. > BSD-style licenses allow far greater usage of code, and as a result > such code does get used more. That's fine. The purpose of a copyleft license like the GPL is not to promote the widest use of the code; it is to promote the greatest freedom for users of the code, and to encourage more free software to be written and distributed. The BSD license, on the other hand, is designed for those who want their code to be used as widely as possible, and don't care whether their software will become part of a non-free program. > I prefer that my code, where possible, be used by as many people as > possible. Then a BSD license sounds best for your purposes. My purposes, on the other hand, place freedom ahead of popularity, so I prefer the GPL. We're both writing free software. Share and enjoy. -- \ "Truth: Something somehow discreditable to someone." -- Henry | `\ L. Mencken | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From zathras at thwackety.com Fri Jun 13 15:58:18 2003 From: zathras at thwackety.com (Michael Sparks) Date: Fri, 13 Jun 2003 20:58:18 +0100 Subject: insert thousands separators In-Reply-To: <3EE9E548.9010701@isst.fhg.de> References: <3EE9E548.9010701@isst.fhg.de> Message-ID: <200306132058.20766.zathras@thwackety.com> On Friday 13 June 2003 15:52, Marcus Bergmann wrote: ... > how can I insert thousands separators into an integer or a string, e.g. > 1000000 to 1.000.000? A "correct" way: >>> import locale >>> locale.getlocale(locale.LC_NUMERIC) ['en_GB', 'iso8859-1'] >>> locale.format("%d",1000000,1) '1,000,000' A way of doing it without division: def commafy(num,sep=",",floatsep="."): convert,nonIntPart,r = num,None,"" if not isinstance(num,int): convert=int(num) nonIntPart=num-int(num) revd=str(convert)[-1::-1] l=len(revd) for i in xrange(0,l,3): r += revd[i:i+3] if i>> commafy(1000000) '1,000,000' Michael -- Ask five economists and you'll get five different explanations (six if one went to Harvard). -- Edgar R. Fiedler From sholden at holdenweb.com Tue Jun 24 08:13:58 2003 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 24 Jun 2003 12:13:58 GMT Subject: SocketServer class - basis problem References: <63701d2f.0306231709.7990d916@posting.google.com> Message-ID: "lebo" wrote in message news:63701d2f.0306231709.7990d916 at posting.google.com... > So I'm new to this python stuff - and this has me stumped > [sample code] > > Why does s.recv() hang the client? It seems like server is not > handing back "blah", but I'm sure it is.....this should be > easy...(sigh) If you're going to OSCON you might like to sign up for the Python Network Programming tutorial - see http://conferences.oreillynet.com/cs/os2003/view/e_sess/4165 This tutorial is intended to help network programming beginners to write their own networking code. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From demanzano at playstos.com Tue Jun 10 09:12:01 2003 From: demanzano at playstos.com (Alessandro de Manzano) Date: Tue, 10 Jun 2003 15:12:01 +0200 Subject: simple, old-style graphic ? References: Message-ID: "Bengt Richter" wrote in message news:bc43oc$ql1$0 at 216.39.172.122... > >I accept any hints and suggestions :) > > > Have you looked at the tkinter demos that come with the source distribution? > (the source distribution is worth downloading, if you haven't). No I have not yet looked at it. I'll do, since many people kindly indicated it to me ;-) > minimal win32 windows and graphics functionality, perhaps by interfacing class > methods to the windows stuff running in a separate machine thread via queues and/or > shared memory with locks, etc. to pass data. Yup, maybe a module/extension just over Win32 GDI functions, very "low level" very custom, but definetely not easy nor quick to write ;-) :( I'll take a look at TKinter and pyGame as seems to be the most quoted approches for a problem like mine. Many many thanks to you all ! :-) -- bye! Alessandro de Manzano Playstos - TIMA SpA Milano, Italy http://www.playstos.com From g2h5dqi002 at sneakemail.com Thu Jun 19 22:59:06 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Fri, 20 Jun 2003 14:59:06 +1200 Subject: Feature Structures in Python (Part II) In-Reply-To: References: Message-ID: James Tauber wrote: > if type(object1) == type(object2) == dict: A more modern way to write this is if isinstance(object1, dict) and isinstance(object2, dict): which will also work if the objects happen to be subclasses of dict. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From aryal at ameritech.net Mon Jun 16 21:54:02 2003 From: aryal at ameritech.net (Anoop Aryal) Date: Tue, 17 Jun 2003 01:54:02 GMT Subject: Bug (??) in the time module? Message-ID: <_wuHa.4165$87.2880721@newssrv26.news.prodigy.com> Hi, i'm not sure if this is the right place to post it. if it's not, i would appriciate it if you could point me to the right newsgroup. i had needed to do some time manipulation -- take the unix time value, convert it to localtime (human readable format), save it to a text file. later, read it from the text file, convert it back to unix time format for comparisions. it seems that in this round trip, i'm ahead by an hour. i'm guessing it's got something to do with daylight savings. but here's the code that illustrates the problem: --------------------------- #!/usr/bin/python import time thetime = time.time() timeString = time.ctime(thetime) print timeString timeTuple = time.strptime(timeString) print timeTuple thetime2 = time.mktime(timeTuple) timeString2 = time.ctime(thetime2) print timeString2 ----------------------------- and here's the output i get: Mon Jun 16 10:45:50 2003 (2003, 6, 16, 10, 45, 50, 0, 167, 0) Mon Jun 16 11:45:50 2003 ---------------------------- i'm on python 2.2.2 on an up2dated rh9. i've used localtime() etc in place of ctime(). but can't figure this one out. it's good up to the tuple returned by strptime(). i would assume that both mktime() and ctime() (i think the culprit here is mktime()) would 'do the right thing' without extensive parameter passing for this type of default conversions... it this a bug? thanks, anoop aryal at ameritech.net From jepler at unpythonic.net Mon Jun 23 11:10:09 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 23 Jun 2003 10:10:09 -0500 Subject: memory leak "import random" In-Reply-To: <009b01c33995$6628dc10$5000a8c0@codersebastian> References: <009b01c33995$6628dc10$5000a8c0@codersebastian> Message-ID: <20030623151008.GB4459@unpythonic.net> On Mon, Jun 23, 2003 at 04:40:24PM +0200, Sebastian Tusk wrote: > Hi, > > i have a problem with the following code snippet. I can reproduce some sort of memory leak here too, running 2.2.2-26 as packaged for RedHat 9. Note that the seemingly equivalent python -c "while 1: import string" doesn't leak... implying the problem is with PyRun_SimpleString, not import. Jeff From spahievi at vega.bg Thu Jun 19 14:38:34 2003 From: spahievi at vega.bg (Niki Spahiev) Date: Thu, 19 Jun 2003 21:38:34 +0300 Subject: 2D Graphics Libraries for python? In-Reply-To: <5.2.0.9.0.20030619085208.00b257d8@pop.hurrah.com> References: <5.2.0.9.0.20030619085208.00b257d8@pop.hurrah.com> Message-ID: <893946374.20030619213834@vega.bg> 6/19/2003, 19:38:14, Ken Seehof wrote: KS> - Beziers KS> - Antialiasing (lines and beziers) KS> - Transparent bitmaps KS> - Portable (unix, linux, mac, windows) KS> - Can be painted in a wxPython window Check chaco also new PIL IIRC -- Best regards, Niki Spahiev From johnp at reportlab.com Wed Jun 4 10:18:24 2003 From: johnp at reportlab.com (John Precedo) Date: Wed, 4 Jun 2003 15:18:24 +0100 Subject: Reference for learning/using python & COM In-Reply-To: Message-ID: > Can anyone recommend a reference for using python with the Common > Object Model (COM) in Windows? It sounds like this is what you need: Python Programming on Win 32 by Mark Hammond and Andy Robinson The review on Amazon says: In lieu of a general language tour, this book centers on practical tips and examples for using Python on Windows... You'll learn how to write COM servers in Python and then how to script them in Visual Basic (used here to build user interfaces) and how to control Word and Excel with OLE Automation in Python. One standout example looks at building and printing accounting reports in Office 2000 using Python as the script language. http://www.amazon.com/exec/obidos/tg/detail/-/1565926218/qid=1054736091/sr=1 -2/ref=sr_1_2/102-7242781-2828114?v=glance&s=books - John From sholden at holdenweb.com Fri Jun 27 10:48:42 2003 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 27 Jun 2003 14:48:42 GMT Subject: Exposing object model in Python? References: Message-ID: "MK" wrote ... > "Steve Holden" wrote > > > If you can get a look at "Python Programming on Win32" by Mark Hammond and > > Andy Robinson that will show you a number of ways to do this, including > > writing a COM server in Python and providing Python scripting facilities > to > > your users. > > > Is COM platform-specific? I believe it is, but I may be wrong. > (Anyway I'm sure it's platform specific, no matter what MS says.) > If it is platform-specific, then that's not what I need. > I'd like to expose my object model on every Python-enabled > platform. > In which case look at the bit about providing scripting facilities (the Effbot has pointed the way). You're right, COM is platform-specific, despite MS protestations. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From tebeka at cs.bgu.ac.il Thu Jun 26 02:10:21 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 25 Jun 2003 23:10:21 -0700 Subject: wxPython.Fit() is funky. References: Message-ID: <33803989.0306252210.46acf16@posting.google.com> Hello Tom, > Unfortunately, this behavior means that Fit() is > nearly useless for me. I just started doing this wx and Python > stuff, and every window that I create in my recent project needs > to be sized based on the content. The way Fit() works is making > me actually compute the size of the content myself. It's not > hard, but it is tedious when the library tells you that this > functionality is available. Why don't you use sizers? (http://www.lpthe.jussieu.fr/~zeitlin/wxWindows/docs/wxwin40.htm#wxboxsizer) They save you from doing all this stuff by yourself. HTH. Miki From staschuk at telusplanet.net Mon Jun 9 12:44:37 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 9 Jun 2003 10:44:37 -0600 Subject: Prolog-style unification? In-Reply-To: ; from simonb@webone.com.au on Sun, Jun 08, 2003 at 12:28:17PM +1000 References: Message-ID: <20030609104437.E778@tibia.amotlpaa.bogus> Quoth Simon Burton: > On Sat, 07 Jun 2003 14:38:40 -0600, junk wrote: [...] > > while Father(X,Y): > > print X, Y > > Know about iterators? > > i'd like to see > for x,y in Father(): > print x, y It's not clear how you'd do any more complex query with such a scheme. What if you want grandfathers of Seth, for example? The original allows for the possibility of something like Father(X, Y) & Father(Y, "Seth") for example. -- Steven Taschuk "[W]e must be very careful when we give advice staschuk at telusplanet.net to younger people: sometimes they follow it!" -- "The Humble Programmer", Edsger Dijkstra From donn at drizzle.com Sun Jun 15 00:24:28 2003 From: donn at drizzle.com (Donn Cave) Date: Sun, 15 Jun 2003 04:24:28 -0000 Subject: Reading from a FIFO, burning CPU References: Message-ID: <1055651067.371761@yasure> Quoth "Elmar W. Hoefner" : | I tried to continuously stream a FIFO into my python script. | I was successful so far, but the performance is not acceptable: If I start | the script, it eats 99% of my CPU cycles. Can anyone give me a hint how to | change this? | fifo=open("/test_fifo", "r") | while 1: | line=fifo.readline() | # to stop the repeated printing of " '' " while nothing is in the fifo: | if line != '': print line | | Anything better? I'm sure there is, any help is most appreciated! (Google | didn't help me, nor did the archives of this group...) I reckon the other process wrote to the fifo, and then closed it. In the somewhat obnoxious logic of fifos, that means that you should see an end of file, and you do -- that's what end of file looks like. You may close the fifo, and open it again and resume reading. Your reads will "block" until data is ready. You only need to re-open the fifo when you encounter end of file (zero length string.) Donn Cave, donn at drizzle.com From p-abel at t-online.de Thu Jun 5 06:07:22 2003 From: p-abel at t-online.de (Peter Abel) Date: 5 Jun 2003 03:07:22 -0700 Subject: Help with dictionary References: <9afd3f36.0306042301.5243a9e8@posting.google.com> Message-ID: <13a533e8.0306050207.9247fac@posting.google.com> iamshady at rediffmail.com (Jim Shady) wrote in message news:<9afd3f36.0306042301.5243a9e8 at posting.google.com>... > Hello, > > I have a dictionary of the sort: > > {(1, (21353, 21418)): 3900, (2, (53006, 53164)): 3800, (0, (19697, > 19763)): 4100} > > I need to re-sort this dictionary with the first element of the tuple > in the keys. A sorted dictionary of the above would be: > A dictonary can't be sorted. If it once is, it happens by chance. > {(0, (19697, 19763)): 4100, (1, (21353, 21418)): 3900, (2, (53006, > 53164)): 3800} > > Could somebody help me with the algorithm/logic to accomplish this? What you have to do is to put the items of a dictionary into a list which you can sort. >>> myDict={(1, (21353, 21418)): 3900, (2, (53006, 53164)): 3800, (0, (19697,19763)): 4100} >>> myDict {(2, (53006, 53164)): 3800, (0, (19697, 19763)): 4100, (1, (21353, 21418)): 3900} >>> myItems=myDict.items() >>> myItems.sort() >>> myItems [((0, (19697, 19763)), 4100), ((1, (21353, 21418)), 3900), ((2, (53006, 53164)), 3800)] >>> Regards Peter > > Thanks in advance! > > Jim From db3l at fitlinxx.com Thu Jun 5 12:01:58 2003 From: db3l at fitlinxx.com (David Bolen) Date: 05 Jun 2003 12:01:58 -0400 Subject: PythonD: 4Suite or Twisted? References: <3eddd372$0$16609$9b622d9e@news.freenet.de> <%RlDa.239$R44.10990@nnrp1.ozemail.com.au> <3mmDa.18175$8g5.301248@news2.e.nsc.no> <3EDE1F04.30539A1A@engcorp.com> Message-ID: Moshe Zadka writes: > On 04 Jun 2003, David Bolen wrote: > > > Just one small comment, since I generally don't see it mentioned in > > postings about Twisted - the underlying protocol support for internet > > components appear robust in terms of TCP support, but we found that > > UDP support was much weaker when we last looked at Twisted (not too > > long ago). > > These kinds of comments really should exact numbers. UDP was specifically > marked "unstable" in Twisted 1.0. Since then it has been revamped, and > seems to be working pretty well. Do you have any specific lacks or > complaints about UDP in Twisted? I'm not sure that making a comparison between robust and weaker necessarily requires numbers (unless you're saying that UDP support in Twisted really isn't weaker than TCP), since it's just intended to be a general comment and not a set of metrics to base a decision on. But since you asked :-) First, I'll re-iterate that I'm not knocking Twisted - it's an impressive framework. However, the last time we specifically tried Twisted out for one of our applications - a distributed processing system - was probably around January/February - it's true that this was probably 1.0 (or 0.99.4 which was really close to 1.0). At that time, a big item that showed up was that the perspective broker, a key reason for looking at Twisted, didn't support UDP. The developer doing the testing also had problems getting some of the higher level objects and/or samples to function when trying to convert them from TCP to UDP, including some issues with the IReactorUDP class (sorry, but I don't have hard notes on that handy). We then noticed the various UDP classes generally marked as unstable, and figured they weren't quite as well supported within the core framework. I assumed it was most likely due to lack of real need by current Twisted users, which I'm certainly not complaining about, but it wasn't worth our pursuing, since we had our own code base we could also work from as an alternative. I checked back last month (version 1.0.4) and saw the twisted.internet.udp class was still marked as "unstable" in the documentation and IReactorUDP as semi-stable. This still seems true with 1.0.5 on the web site, and there aren't many UDP related comments in the change log. While reviewing the documentation (then and now) I think one item that struck me is the protocol structure where just about everything lies beneath the twisted.internet.protocol.Protocol class (which inherits from twisted.internet.protocol.BaseProtocol), and that class is often used as central to higher level functionality. And the peer class twisted.internet.protocol.ProcessProtocol also inherits from BaseProtocol. Stuff layered above this really seems geared towards this Protocol class - for example, twisted.internet.protocol.Factory is designed to create subclasses of Protocol, and the Factory is what is used by many higher level system objects like the perspective broker. True, I don't think the implementation of Factory prevents you from using a class not beneath Protocol, but then the users of the factory will generally blow up when they try to use a method in the Protocol interface that might not be present. All of this is really nice and well-structured, at least without UDP. UDP is twisted.internet.protocol.DatagramProtocol, but that doesn't even inherit from BaseProtocol, much less be a subclass of protocol. And because it's not a subclass of Protocol it doesn't get to play equally in a lot of the higher level support of Twisted. Once you start getting into the higher order framework objects that layer on top of all of the factory and protocol work beneath, UDP starts to feel like the odd man out. As a trivial example, take the "echoserv.py" example. I can't see why that example can't become a UDP example just by changing the "listenTCP" call to "listenUDP". However, because the example server is a subclass of Protocol, and the UDP DatagramProtocol class is going to call "datagramReceived" rather than Protocol's "dataReceived" it doesn't work. But there's no reason it couldn't, since at that level of abstraction, UDP and TCP could be treated equally. Now in recent versions of Twisted, there is a new echoserv_udp.py example whose sole difference is to inherit from DatagramProtocol and change the single method in the server to datagramReceived. I think my conclusions at the time were that the Protocol class was really a StreamProtocol class in disguise, and there was probably no top level "protocol" abstraction in the system. Datagram and Stream protocols can be like night and day at the protocol level, but there's also a lot of commonality that ought to be able to permit some of the higher level framework functionality to work in either case. The documentation doesn't tend to highlight TCP versus UDP differences, but just uses the factory and protocol level, so it's not generally clear where something won't work in both cases. I just ended up feeling like trying to use UDP for a complex application with Twisted (as opposed to a dedicated UDP protocol implementation like DNS) was swimming against the tide. I think that's still a valid state of affairs at the moment. > (Note that currently Twisted.Names is an authoritative DNS for a domain > with no problems, and DNS is a UDP-based protocol) Right, it's a UDP based _protocol_, but not a UDP based "application", so it doesn't need much from Twisted other than it's pure asynchronous message loop. For me, that wasn't the attraction and potential of Twisted for us (we have plenty of async loops of our own around :-)), but the support layers above that all working together. -- David From MK at foo.com Fri Jun 13 07:17:44 2003 From: MK at foo.com (MK) Date: Fri, 13 Jun 2003 13:17:44 +0200 Subject: OnFileOpent(self, event): Message-ID: [new to python] Hi group, I just picked up Python two days ago and it's fucking true - one is really more productive with it. It's simply amazing. Love at the first sight, I can tell ya. I have a question. How can I programmatically invoke the following function: def OnFileOpen(self, event): For now, it gets called whenever I select File->Open menu, but I'd like to invoke it in my code. I'm using Python 2.2 and wxPython 2.4 on Win 2000. Thx, From pxtl at hotmail.com Mon Jun 9 22:28:18 2003 From: pxtl at hotmail.com (martin z) Date: Tue, 10 Jun 2003 02:28:18 GMT Subject: Call a Python file with parameters References: Message-ID: <6nbFa.42656$3Sm.2416@news01.bloor.is.net.cable.rogers.com> > def function(a, b): > '''This function exists to confuse you.''' > print 'A is', b > print 'B is', a > > import sys > sys.modules['file'] = function > del sys This is, of course, the obvious way. Another way is the from statement. The problem is that this is clumsy and not good. I was hoping for a more streamlined approach to the concept. Some way to make some sort of "module header" where the module itself takes the parameters. > So, we see that it is possible. Is it desirable? Only if you wish to > confuse readers of your code (including, possibly, yourself) and write code > that is of generally poor quality due to its pointless use of wierd magicks. Of course, that's why I was asking - I was hoping for a better approach. The reason I ask this is because I'm using Python in a heavily embedded environment in which each function stands alone and each function is interchangeable. The functions are fetched out of the database as files. These files could be text or compiled PyC (probably will arrive as pair to encourage editing). Hence, keeping the code atomic at a function level is needed. The method you describe above is inappropriate because the code must be run once to build the function, and then the function retrieved. What would be ideal would be to run the code once with the parameters. Martin. From maney at pobox.com Sun Jun 1 22:21:00 2003 From: maney at pobox.com (Martin Maney) Date: Mon, 2 Jun 2003 02:21:00 +0000 (UTC) Subject: Python Bible recommendations? References: Message-ID: Lee John Moore wrote: > I've got my feet wet with python by following a few online > tutorials, but can't help feeling I'm 'missing a few links'. > For that reason, I'm 90% decided upon buying David Brueck's > "Python Bible". I intentionally haven't looked at the other replies; based on past experience this should be the contrarian review of the "Bible". > I want to avoid the 'Teach Yourself...' titles because they > focus too much on aspects I'm already familiar with as a > programmer of other languages (C, C++ & Pascal amongst others). > > Would other users of the group recommend this 'bible' or > something else, for somebody like me just getting his feet wet? I bought the "Bible" on the strength of favorable mentions in online reviews and was quite disappointed. Mind you, what I was looking for was a solid *reference* book; tutorial content wasn't particularly desired. What I *should* have done was pickup the second edition of Beazley's _Python: Essential Reference_, but in the end I was swayed by the desire to get a different author's view of things. As a reference book, I found the "Bible" to be incomplete in annoying and important ways. One that I recall was the coverage of apply() and the new, improved f(*args, **kwargs) syntax. I only managed to find the "Bible's" coverage because I already knew an alternate keyword or two to try; when I found it, it mentioned only the "args", with no mention of passing in keywords args through apply, and no sign of the new syntax at all... new in 2.0, IIRC, and this "Bible" claims to cover version 2.1 There were other problems - modules only partially described (wonder if that was more issues with describing older versions?), more missing or unfindable features. All of which is kind of sad, because the quality of the coverage of what is there - and that seems to be a large portion of the language - seems pretty good. In particular, my impression is that the "Bible" has more examples of usages than Beazly; of course, it's a considerably larger and more unwieldy volume in consequence. I'm not sure what level of material would be best for you. Your remarks about not wanting another "quickie introduction to stored-program computer systems" suggests that you might enjoy the _Python Cookbook_. And you certainly ought to take a look at the new Nutshell book, even though its heft makes the "Nutshell" appelation seem ironic. OTOH, if you really want the "Bible", I have a copy, little used and in good condition, that I would part with cheaply. Ghu knows it's doing nothing for me but using up space. Come to think of it, I owe the "Bible" some thanks for driving me back to the online docs often and desparately enough that I finally got the hang of finding things in them... From jdhunter at ace.bsd.uchicago.edu Thu Jun 26 10:16:03 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 26 Jun 2003 09:16:03 -0500 Subject: lists and tuples In-Reply-To: <20030626131817.GA4097@nl.linux.org> (Gerrit Holl's message of "Thu, 26 Jun 2003 15:18:17 +0200") References: <20030626131817.GA4097@nl.linux.org> Message-ID: >>>>> "Gerrit" == Gerrit Holl writes: Gerrit> I don't understand. I really don't understand. For me, the most important distinction is that because lists are mutable, they cannot be used as keys in a dictionary. Because tuples are immutable, they can. d = {} l = [1,2] t = (1,2) d[l] = 'Nope' # TypeError: list objects are unhashable d[t] = OK' I find myself using tuples very often as keys for dictionaries. John Hunter From g2h5dqi002 at sneakemail.com Tue Jun 10 22:33:11 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Wed, 11 Jun 2003 14:33:11 +1200 Subject: a = b = 1 just syntactic sugar? In-Reply-To: References: Message-ID: Martin v. L?wis wrote: > I think it is as easy as this: > > - Replace a construct FOO* with FOO_seq, and define > > FOO_seq: /* empty */ > | FOO FOO_seq > > - Replace a construct [FOO] with FOO_opt, and define > > FOO_opt: /* empty */ > | FOO I don't think it's *quite* that easy, because pgen will accept something like FOO = A B C | A B D whereas if you naively re-wrote that as FOO = X | Y X = A B C Y = A B D pgen would complain that the first sets of X and Y are not disjoint. So you can't just blindly turn parts of the REs into non-terminals -- some refactoring may be needed to get the result to be an LL(1) grammar. A proof would be required that this refactoring is always possible. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From gerrit at nl.linux.org Thu Jun 5 12:50:14 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 5 Jun 2003 18:50:14 +0200 Subject: Using metaclasses to make super more beatiful Message-ID: <20030605165014.GA4538@nl.linux.org> Hi, as demonstrated by Guido's paper[0], a relatively simple metaclass can make the use of super a lot more beatiful: 97 >>> class autosuper(type): 97 ... def __init__(cls, name, bases, dict): 97 ... super(autosuper, cls).__init__(name, bases, dict) 97 ... setattr(cls, "super", super(cls)) 97 ... 98 >>> class A: 98 ... __metaclass__ = autosuper 98 ... def f(self): return "A" 98 ... 100 >>> class B(A): 100 ... def f(self): 100 ... return self.super.f() 100 ... 101 >>> B() <__main__.B object at 0x403b3c6c> 102 >>> B().f() 'A' Why doesn't type include the behaviour of autosuper by default, so that each class can use self.super or self.__super__ so that using super is easier? And, is it convention not to use Capitalization for metaclasses? In three examples, Guido doensn't do it in his paper[0]! [0] http://www.python.org/2.2.3/descrintro.html#metaclasses yours, Gerrit. -- 39. He may, however, assign a field, garden, or house which he has bought, and holds as property, to his wife or daughter or give it for debt. -- 1780 BC, 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 peter at engcorp.com Wed Jun 4 12:32:04 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 04 Jun 2003 12:32:04 -0400 Subject: PythonD: 4Suite or Twisted? References: <3eddd372$0$16609$9b622d9e@news.freenet.de> <%RlDa.239$R44.10990@nnrp1.ozemail.com.au> <3mmDa.18175$8g5.301248@news2.e.nsc.no> Message-ID: <3EDE1F04.30539A1A@engcorp.com> "Thomas Weholt ( PRIVAT )" wrote: > > Just a warning; when you mention "threaded" and "webserver" in this group in > the same sentence, you'll probably get several replies telling you that > threaded webservers scale badly and that you should look at ( you guessed > it ) Twisted or Medusa. With the added caveat that some folks claim Medusa is no longer supported. As the asyncore and asynchat modules are now part of the standard distribution, I'm uncertain whether that's the case. (I thought anything like that in the standard package had to be supported by someone... maybe it's just that Medusa is no longer being actively developed.) > Twisted are slowly getting a proper documentation together and that would > make it a killer package for web/internet-based projects. It still seem a > bit bloated and some of the code is labeled unstable, yet the the package > seem to be marketed as complete and stable. I keep seeing things like "It > should really be re-written/re-factored " etc. in the twisted-mailing-list. > But all in all, as I said before, I think Twisted might be the new killer > app if the development-team keeps the development progress they seem to have > at the moment. Keep in mind the idea that Twisted is actually a meta-framework, or, if you will, a framework core plus many services built on that framework. The parts are highly modular, however, so there is no reason to consider "instability" (and that means it is changing rapidly, not necessarily that it is bug-ridden) in one area to be a reflection on the quality of other areas. The core internet components, for example, are quite robust already, and you will rarely see messages about rewriting/refactoring those pieces. -Peter From benoit.besse at club-internet.fr Wed Jun 18 02:14:40 2003 From: benoit.besse at club-internet.fr (Benoit BESSE) Date: Wed, 18 Jun 2003 08:14:40 +0200 Subject: Python 2.3 + mysql? References: Message-ID: <3ef00340$0$14316$7a628cd7@news.club-internet.fr> See http://www.zope.org/Members/adustman/Products/MySQLdb for Zope/Python/MySQL See also the andy's page : http://starship.python.net/crew/adustman/ "Chris Stromberger" a ?crit dans le message de news:d1avevkfg5puhepurr8o0tipkcktn1b600 at 4ax.com... > Is there a mysql module that works with Python 2.3? I don't see one > listed at sourceforge. > > Thanks. From martin at v.loewis.de Sun Jun 29 23:41:44 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 30 Jun 2003 05:41:44 +0200 Subject: get_file_size References: Message-ID: "Egor Bolonev" writes: > How about that? > f=open('1','wb') > f.write(something) > print len(f) > Should I close file for get it size or should I write a C-like function with > seek(end),tell, seek(old)? No. You should use os.fstat, or os.stat if you still remember the file name. Regards, Martin From alanmk at hotmail.com Tue Jun 3 11:00:51 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 03 Jun 2003 16:00:51 +0100 Subject: Exception - how to ignore it ? References: <3EDCA806.6060701@skynet.be> Message-ID: <3EDCB823.EE5DE10@hotmail.com> Helmut Jarausch: >>> is it possible for an exception handler >>> to just e.g. print something and set some >>> global flags but then to have the script >>> continue just after the statement which >>> raised the exception? vivek kumar wrote: >> If you know exactly where and which statement is raising exception or Helmut Jarausch: > No, that was the question. > > Say an exception is raised at many places and I don't want > to change the code. Then I believe the answer is a definitive NO. The relevant section of the python language reference is http://www.python.org/doc/current/ref/exceptions.html which says: "Python uses the 'termination' model of error handling: an exception handler can find out what happened and continue execution at an outer level, but it cannot repair the cause of the error and retry the failing operation (except by re-entering the offending piece of code from the top)." "continuing execution at an outer level" also means that you can't resume to the statement immediately after the one that caused the exception, i.e. try: x = 1/0 itIsNotPossibleForThisToBeExecuted('WithoutCodeRestructuring') except ZeroDivisionError, zde: print "Got an exception: %s" % str(zde) So if you're not willing or able to restructure your code, then you're out of luck :-( regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From peter at melchart.com Wed Jun 4 05:30:12 2003 From: peter at melchart.com (Peter Melchart) Date: Wed, 04 Jun 2003 09:30:12 GMT Subject: nntplib body question References: <879Da.1139848$uT2.175876@news.easynews.com> <7xhe7678dk.fsf@ruckus.brouhaha.com> Message-ID: > Well, you could drop the connection after you've read enough lines. > If it's a several megabyte message and you want just a few lines, that > may be a win. that's exactly what i want to do. but when i call nntpconn.body(id) it retrieves the whole body. how can i cut the connection after a certain amount of bytes. a kind of network-callback would be nice that is called after reading 1K or so, so i can skip the rest after 1 read 100 lines or so... is there anything like that ? the thing is, that i dont want to retrieve the whole article. cheers, Peter From stevewilliams at wwc.com Tue Jun 24 10:58:23 2003 From: stevewilliams at wwc.com (Steve Williams) Date: Tue, 24 Jun 2003 14:58:23 GMT Subject: Choosing the right database-system for a small project In-Reply-To: References: Message-ID: Thomas Weholt ( PRIVAT ) wrote: > I've got a rather small project, small in the sense that there's not a lot > of different tables needed in the database/storage-system, but there will be > alot of data and the clients must be able to scan thru huge amounts of data > very fast ( Not serial scanning, but lookups by key, preferrably several > keys pr record, ie. I need to lookup people both by SSN and by > first/last-name etc. ) > I use Firebird (1.0) with Kinterbasdb in a system which installs easily and runs on Windows XP, Windows 98, Linux RH 8.0, and Windows 95. (The screens are wxPython). I use a variable length version of Russell Soundex for person retrievals (Last Name + FirstName), 'name contains' for organization retrievals, and indexes for SSN and 'other key' retrievals I have always liked Firebird/Interbase because it requires no administration, has elegant stored procedures, great transactional processing, and is open source. http://firebird.sourceforge.net/ http://kinterbasdb.sourceforge.net/ If you try Firebird, have a look at IBExpert. Great for debugging and general poking around the database. The personal edition is free. http://www.ibexpert.com/ From walter at livinglogic.de Tue Jun 10 15:48:21 2003 From: walter at livinglogic.de (=?ISO-8859-15?Q?Walter_D=F6rwald?=) Date: Tue, 10 Jun 2003 21:48:21 +0200 Subject: Html: replacing tags In-Reply-To: <2972888.1055030986@dbforums.com> References: <2972888.1055030986@dbforums.com> Message-ID: <3EE63605.8090302@livinglogic.de> Andrei wrote: > Hello, > > I'm working on an RSS aggregator and I'd like to replace all img-tags in > a piece of html with links to the image, thereby using the alt-text of > the img as link text (if present). The rest of the html, including tags, > should stay as-is. I'm capable of doing this in what feels like the dumb > way (parsing it with regexes for example, or plain old string splitting > and rejoining), but I have this impression the HTMLParser or htmllib > module should be able to help me with this task. > > However, I can't figure out how (if?) I can make a parser do this. Does > the formatter module fit in here somewhere? The docs, the effbot's guide > and the posts regarding html only seem to highlight getting data out of > the html (retrieving links seems particularly popular), not replacing > tags with other ones. You might want to use XIST for that. Code that does what you want with with the Python homepage could look like this: --- from ll.xist import parsers, converters from ll.xist.ns import html def fiximg(node): if isinstance(node, html.img): node = html.a(node["alt"], href=node["src"]) return node e = parsers.parseURL("http://www.python.org", tidy=True) e = e.mapped(fiximg) print e.asBytes() --- HTH, Walter D?rwald From staschuk at telusplanet.net Tue Jun 17 12:24:32 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 17 Jun 2003 10:24:32 -0600 Subject: Getting Instance of calling class In-Reply-To: ; from guettler@thomas-guettler.de on Tue, Jun 17, 2003 at 09:17:53AM +0200 References: Message-ID: <20030617102432.C716@tibia.amotlpaa.bogus> Quoth Thomas G?ttler: > I have a function called _() which prints > strings according to the language of the user. > > I don't want to give this method the object which > holds the language information every time I call it. > > How can I access the calling object? I'm not sure what you mean by "the calling object". sys._getframe provides frames from further up the call stack, but I'm not sure how this relates to what you want to do. It sounds a little like you want a dynamically scoped environment containing (possibly among other things) localization information for the current user. I suppose you could implement such a thing by trolling through stack frames, but this seems a bit hackish. An alternative approach would be to pass _ into each function which needs to produce output. _ could be a closure, def makelocalizer(lang): def _(s): # return s in language lang return _ for example. This avoids passing the language to _, but adds passing _ around. Does this help at all? -- 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 martin at v.loewis.de Mon Jun 16 16:37:13 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 16 Jun 2003 22:37:13 +0200 Subject: Possible install bug in Python 2.3b1? (Python 2.2 still in the registry) References: <5ab0af73.0306161041.203f6378@posting.google.com> Message-ID: MatthewS at HeyAnita.com (Matt Shomphe) writes: > Is this a bug that should be reported? I think the copies in ControlSetxxx are expected: these are "last-known-good" backup registry copies. The other values should probably be corrected; please submit a bug report. Regards, Martin From fjanoos at yahoo.com Sat Jun 7 04:30:29 2003 From: fjanoos at yahoo.com (FJ) Date: Sat, 7 Jun 2003 14:00:29 +0530 Subject: Why python Message-ID: Hey guys, not trying to rake up anything new here. I'm trying to convince a friend to move from some ol' language (perl) to python. does anybody know of any good articles i can ask him to read (my own powers of persuasion being very limited) ? -fj From peter at engcorp.com Sat Jun 7 11:57:35 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 07 Jun 2003 11:57:35 -0400 Subject: Bug? print statement ends with ',' print a new line References: <3ee1c3bb@shknews01> Message-ID: <3EE20B6F.B26AA6C7@engcorp.com> Lu wrote: > > C:\FAT32\py>type counter.py > import sys > import threading > > class Counter: > def __init__(self,count=0): > self.count=count > def start(self): > if self.count>0: > print self.count,'.', > self.count-=1 > t=threading.Timer(1,self.start) > t.start() > elif self.count==0: > print self.count > > counter=Counter(int(sys.argv[1])) > counter.start() > > C:\FAT32\py>counter.py 5 > 5 . > 4 . 3 . 2 . 1 . 0 I don't actually know what you're trying to do, but I don't think it matters because you very likely have a race condition. That's because you are executing the print statements from two places, the main thread and the timer thread that you start up (or is it multiple timer threads?... as I said, I'm not even going to try to decipher the intent). Note that "print" is not an atomic operation. In fact, each item that is printed is, I believe, a separate set of operations (one to retrieve the string representation, one to do the actual printing). Also, there is the "softspace" mechanism which likely leads to additional bytecode operations inside the same print statement. With all that, and multiple threads involved, you should expect to see unexpected results. :-) -Peter From woooee at yahoo.com Tue Jun 24 19:39:21 2003 From: woooee at yahoo.com (Curly Joe) Date: Tue, 24 Jun 2003 16:39:21 -0700 (PDT) Subject: 1== 1 is False? Message-ID: <20030624233921.92963.qmail@web20508.mail.yahoo.com> Not sure what you mean by more exactness, and why rounding wouldn't work as in x = 2.260212 y = 2.260212 print "%f and %f are " % (x, y), ##--- round to 3 digits if round(x, 3) == round(y, 3) : print "Equal to 3 decimals" else : print "Not Equal" x += 0.000001 print "%f and %f are " % (x, y), if round(x, 3) == round(y, 3) : print "Equal to 3 decimals" else : print "Not Equal" This prints: 2.260212 and 2.260212 are Equal to 3 decimals 2.260213 and 2.260212 are Equal to 3 decimals This is one of the things that we have to learn to live with in a binary number system as far a I know, just like we have to truncate/round numbers like 10/3 or 10/6 in our base 10 system. > > What do i have to do, if i need "more" exactness? > > I have for example the problem with the > representation of 2.3 or 2. > 7: > > >>> 2.3 > > 2.2999999999999998 > > >>> 2.7 > > 2.7000000000000002 > > This is a really strange behaviour! > > > > Thomas > > -- __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From mhammond at skippinet.com.au Tue Jun 3 19:14:36 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 03 Jun 2003 23:14:36 GMT Subject: Passing an Event from a Thread to its Caller In-Reply-To: <4150f6c8.0306030833.2dd4fc9b@posting.google.com> References: <4150f6c8.0306021120.7b70d981@posting.google.com> <4150f6c8.0306030833.2dd4fc9b@posting.google.com> Message-ID: Matt Rapoport wrote: > Mark, thank you very much for your reply. I think I understand what > you're saying but the part I'm not so sure about is how do I get my > thread to trigger the event. > > The thread just creates an object that I wrote called "client". > Basically all I want is for the client to pass errors up to my service > so that I can log them. Can I set an event in the client code and > wait for it in the service code? Or should I alter the client's > constructor to accept an event so that I can have the service pass the > event to it? > An event is generally used for synchronization between threads. Generally, one thread will "wait" for the event. Whenever some other thread "sets" the event, that first thread will wake up and do whatever the event means to it. Why not simply have your thread log the error? Mark. From pcurran at intraspect.com Tue Jun 24 12:28:04 2003 From: pcurran at intraspect.com (Peter Curran) Date: 24 Jun 2003 09:28:04 -0700 Subject: Python and Jython References: Message-ID: Hello - I think either way is fine. I learned python (aka c-python) first, then jython. I work with a product that embeds jython as a mechanism for writing scripts against a java api, so I use jython every day, but I write all of my code in pythonwin (from a company called active state) which is designed for python not jython. The bummer about this is that I can't debug my jython scripts in pythonwin live against the java server, but pythonwin makes it worthwhile with some nice frills such as indentation guides, syntax colorizing, some intellisense, an interactive window, and a syntax checker - so when I deploy for interpretation by jython my code is 99% OK. The point is that I use a c-python ide for jython and it makes almost no difference, so I don't think it matters which you learn first. As a java programmer you'll probably find that jython is a great RAD tool - you may even start to write everything in jython first! Btw, Pythonwin is free - or it used to be, go to www.activestate.com Happy coding. "Mulugeta Maru" wrote in message news:... > My background is Java. I would like to know the difference between Python > and Jython. Are they different languages? Should I learn Python first and > then Jython? The reason I would like to learn the language is to use it with > Java. > > I just spend one hour on a Python tutorial - the language is just a thing of > beauty! From bokr at oz.net Wed Jun 11 16:36:38 2003 From: bokr at oz.net (Bengt Richter) Date: 11 Jun 2003 20:36:38 GMT Subject: Looking for the greatest negative float value References: Message-ID: On Wed, 11 Jun 2003 18:52:17 +0200, "Gilles Lenfant" wrote: >Hi, > >I need the same as... > >import sys >negmaxint = - sys.maxint -1 > >... but for float data > >any hint ? > To get what you want (wyw) maybe you have to compute it. E.g., >>> fmin = -1.0 >>> while 1: ... fnext = fmin*2.0-1.0 ... if fnext==fmin: break ... wyw = fmin ... fmin = fnext ... >>> `wyw` '-8.9884656743115795e+307' I'm not sure how portable this is, but the actual value can surely vary according to platform. I suppose you could set up a site-specific initialization to put such a value as sys.minfloat if you wanted to. The timbot will have the best info ;-) Regards, Bengt Richter From mertz at gnosis.cx Sat Jun 21 12:51:30 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sat, 21 Jun 2003 12:51:30 -0400 Subject: XML References: <3EF471BA.EE4F056@hotmail.com> Message-ID: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) wrote previously: |martin at mira:~> locate .html|wc | 41104 41104 2425699 |martin at mira:~> locate .txt|wc | 7958 7963 389013 Perhaps you missed the extensions *.mbox and *.news? (or whatever style your MUA uses). I just read a couple dozen 7-bit ASCII documents on c.l.py before getting to Martin's 7-bit ASCII document arguing against the prevelance of 7-bit ASCII documents (and I haven't even opened my favorite HTML viewer for the day yet). 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 gh at ghaering.de Wed Jun 18 04:16:48 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 18 Jun 2003 10:16:48 +0200 Subject: recv In-Reply-To: <3EF0163E.4010204@uni-koblenz.de> References: <3EF0163E.4010204@uni-koblenz.de> Message-ID: <3EF01FF0.8070301@ghaering.de> Oleg Seifert wrote: > Hallo Leute, > > habe eine kleine Frage: > > Ich soll mit Python eine Netzwerkanfrage senden und eine Antwort > ausgeben. Daf?r habe ich folgenden Skript geschrieben: """ Hi folks, I have a little question: I'm supposed to send a network request using Python and print a response. I've written the following script for this: """ > ------------------------------------- > from socket import * > > def read(): > print s.recv(1024) > > > s = socket(AF_INET, SOCK_STREAM) > s.connect(("localhost", 99)) > > s.send("loadGraph(\"g.g\");\n") > read() > s.close() > ------------------------------------- > Die Anfrage wird gesendet und die Antwort kommt auch an, aber von dem > Antwort erscheint immer nur eine Zeile. Die Antworte sind auch > unterschiedlich, sie k?nnen verschiedene Zeilenanzahl haben. Wie kann > ich unabh?ngig von einer Antwortstruktur, ganze Antwort ausgeben ? """ The request is sent and the response arrives as well, but from the response I only ever see one line. The responses are different as well, they can have different number of lines. How can I print the whole response, independent of the structure (numer of lines) of the response? """ If you want to roll your own protocol, you need to design it in a way such that the client *can* know when a response is finished. Also it's easier to make the socket a file and read from that. Here's a snippet from the module smtplib in the standard library that shows how it's can be done: #v+ if self.file is None: self.file = self.sock.makefile('rb') while 1: line = self.file.readline() if line == '': self.close() raise SMTPServerDisconnected("Connection unexpectedly closed") if self.debuglevel > 0: print 'reply:', `line` resp.append(line[4:].strip()) code=line[:3] # Check that the error code is syntactically correct. # Don't attempt to read a continuation line if it is broken. try: errcode = int(code) except ValueError: errcode = -1 break # Check if multiline response. if line[3:4]!="-": break #v- Continuation lines look like these: #v+ 250-mail.w-koerting.de 250-PIPELINING 250-SIZE 10240000 250-ETRN 250-AUTH LOGIN PLAIN CRAM-MD5 GSSAPI DIGEST-MD5 250-AUTH=LOGIN PLAIN CRAM-MD5 GSSAPI DIGEST-MD5 250-XVERP #v- Then comes a line in a different format so the SMTP client knows it's the last one in the response: #v+ 250 8BITMIME #v- HTH & HAND, -- Gerhard From max at alcyone.com Thu Jun 5 04:41:51 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 05 Jun 2003 01:41:51 -0700 Subject: Totally Confused: Passing variables to functions References: Message-ID: <3EDF024F.C306402F@alcyone.com> Chuck wrote: > I've hit a stumbling block while trying to pick up Python. I've > googled > around, and I don't think I'm the first to have this question, but I > haven't > been able to find an answer that explains things for me. The difference you've found is that lists are mutable but integers are not. So modifying a mutable object in a function causes changes as seen by the caller (since it's the same object on both sides), but rebinding an immutable object doesn't, since all names are local (except when set off by the "global" statement). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ You're a fighter, so fight / Wake up and live \__/ Sweetbox From peter at engcorp.com Mon Jun 9 16:49:52 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 09 Jun 2003 16:49:52 -0400 Subject: Hardware take on software testing. References: <2ae25c6b.0306060450.78e988f9@posting.google.com> <3EE0CF2B.57F474E4@engcorp.com> <2ae25c6b.0306061721.148300a@posting.google.com> <3EE14F0A.3D1E1887@engcorp.com> <2259b0e2.0306091158.701ed82a@posting.google.com> Message-ID: <3EE4F2F0.2EC4FBA5@engcorp.com> Michele Simionato wrote: > > Nevertheless, I think you are a little bit too enthusiastic. Perhaps. We'd have to define how much is "too much", however, before that could be debated. :-) > I am referring to statements like "with XP and TDD, you generally > expect to have *no* bugs" and "you have effectively 100% code coverage". We find we achieve 100% code coverage on code that is purely test-driven, and we _do_ expect no bugs. We find them from time to time, of course, but actually expecting them cause us unnecessary stress and waste our time. If we expected lots of bugs, we'd probably waste a large portion of our time planning formal code reviews, trying to do tests with randomized inputs, and other such things. Those might be "nice" to have, in theory, but with so few bugs *actually found* we don't believe the benefits would outweigh the costs, and so we continue to "expect" no bugs, even though from time to time we find them. Make any sense? I should have said "you should expect no bugs", and didn't mean to imply you will never have them. > My concern is that it is effectively *impossible* to write a comprehensive > sets of tests. I believe that's as seen from a traditional testing point of view. We don't write sets of tests: we write one test, then we write the code necessary to pass that test, then we clean things up and carry on. Nothing more. If we attempted to write a comprehensive set of tests for a bunch of code we'd already written, we'd quickly go mad... *and* we'd find all kinds of areas where our tests were not adequate or where we had less than 100% coverage. The key difference is in the nature of the code developed with the TDD approach versus what we pump out without it. With the latter approach, you *need* a comprehensive set of tests to be confident it works right. And as you say, that's an impossibility. With TDD, you only write what you've already tested, and you constantly refactor to remove duplication, and the resulting code often bears little resemblance to code that is just hacked out the typical way. I still consider it magic, personally, but the code I write with TDD rarely has bugs, so I can only point to what works, even if I can't explain the theory. (Kent Beck's a freakin' genius is one possible theory, I suppose.) > You cannot imagine and tests all the possible usages of > a piece of code you write, unless it is trivial. You cannot imagine and > tests all the possible abuse your future user could perform. You cannot > never be 100% sure of the correctness of your programs in all situations. All true. But with TDD, you can be quite sure that your code passes all the tests you've written, and as long as you don't find yourself writing code that shouldn't be there, adding functionality that you don't need yet because you haven't written a test for it, you won't often find yourself bothered by the probability that there is, in fact, a bug somewhere in there. I wouldn't suggest this level of unconcern for pacemaker software, I assure you, but we're not working in an area that requires quite that much rigor. > If it was so, Python (which is developed using LOTS of tests) would be > bug free. I'd say Python has had lots of tests developed _for_ it, but by no means was it written test-first. I don't it's fair to compare the current codebase against a purely imaginary one that I suppose would have resulted had TDD been used to develop Python. > This is not the case, because of the subtle bugs you cannot prevent > at writing time and that are discovered after months or years of usage. Unit > testing is extremely effective againsts simple bugs (similarly to the compiler > step in a compiled language, but much more effective), but it is powerless > (actually in some case it helps, but I am considering the really hard bugs > here) to prevent subtle bugs, exactly because they are subtle, i.e. you > haven't thought of a test able to discover them when you first wrote the > program. Of course, once the subtle bug has been discovered (maybe by your > users), tests helps a LOT in tracking it and fixing it. I definitely won't argue against the fact of subtle bugs that are extremely hard to catch with any testing done in advance. It's just not a good idea to write code that is prone to such problems, however, so I'd encourage a different approach to writing code, which does not lead to such problems very often. > Let me take a concrete example, i.e. my recipe to solve the metaclass > conflict I posted recently. Here the script is less than 20 line long. > However, I cannot simply write a comprehensive test suite, since there > are TONS of possibilities and it is extremely difficult for me to imagine > all the use cases. I can write a big test suite of hundreds of lines, > but still cannot be completely sure. I cannot spend weeks in writing the > test suite for 20 lines of code! But those 20 lines were not written test-first. If you were to imagine only *one* specific use case, the most important one for your own purposes, and write a single test that exposes the most obvious and easiest aspect of that one use case, and then implemented just enough code to pass that one single test, how certain would you be that the code had lots of bugs? If you repeated that step over and over again, constantly retesting, refactoring, and only adding code that already had a test for it, do you think you'd be quite so unsure about it? Now I grant that if someone comes along and uses that 20 lines, no matter how many tests you've written for it, in a way you haven't envisioned (and which is therefore not covered by your tested use cases), then you might start to sweat, and even _expect_ bugs. I'm not sure you should, because the code is probably extremely well- designed and robust at that point, but it's possible the new type of use will expose an edge case you hadn't quite noticed or something. So you write another test to catch it, refactor the code again, and go back to sleep. > These are really exaggerations in my view. But maybe it is good to > exaggerate a bit if this serves to convert more and more people ;) That much is true, of course. For those who don't know this approach, I'll happily make it explicit: making sweeping claims and polarizing statements is a hallmark of XP proponents, but we assume the audience is adult enough to take such claims with a grain of salt and investigate the merits of the claims for themselves. The extreme nature of the claims is no doubt intended (whether intentionally or not) to encourage just that kind of skeptical investigation and the resulting debate, to test the strength of the process. If I just went around saying "yeah, TDD is nice, but it won't solve _all_ your problems", perhaps nobody would pay attention, and that would, for them, be a shame I believe. :-) -Peter From rimbalaya at yahoo.com Mon Jun 30 23:43:27 2003 From: rimbalaya at yahoo.com (Rim) Date: 30 Jun 2003 20:43:27 -0700 Subject: Identity inconsistency and unification of types and classes Message-ID: <6f03c4a5.0306301943.d822a6d@posting.google.com> Hi, With the great unification of types and classes, what will happen to the following identity inconsistency? >>> class myint(int): pass ... >>> a=int(1); b=int(1) >>> a is b 1 >>> a=myint(1); b=myint(1) >>> a is b 0 Thanks - Rim From uwe at oss4u.com Mon Jun 9 14:45:14 2003 From: uwe at oss4u.com (Uwe C. Schroeder) Date: Mon, 09 Jun 2003 11:45:14 -0700 Subject: py2exe and dynamic modules Message-ID: Hi, I checked everything and it seems I'm the only one trying to do this. I have a large application that dynamically loads plugins. There is no way I can say at runtime what names the plugins have, so loading them statically is not an option. The plugins are quite simple and contain one class only. With a full python installation it's no problem to load them using __import__. However in a py2exe deployment the importer is replaced, so __import__ won't work anymore. Also the directory where the plugins are stored is user dependant (on windows in the profile tree) and is determined at runtime. The plugins don't even exist at application start, they are transfered on request. What I can say is that for one user the directory is always the same. Is there a way to deploy this using py2exe (or whatever, although I like py2exe for it's simplicity) ? I can modify the program to store the plugins in a fixed place - but I don't like this too much since then deploying it on *nix is a hassle for access right reasons. Is there any way to tell py2exe's importer to look in a certain directory ? as said: currently I just add the directory to sys.path and do an __import__. Any hints ? Thanks UC -- Open Source Solutions 4U, LLC 2570 Fleetwood Drive Phone: +1 650 872 2425 San Bruno, CA 94066 Cell: +1 650 302 2405 United States Fax: +1 650 872 2417 From andrew-usenet at lexical.org.uk Mon Jun 16 13:36:59 2003 From: andrew-usenet at lexical.org.uk (Andrew Walkingshaw) Date: 16 Jun 2003 17:36:59 GMT Subject: Loop from 'aaaa' to 'tttt' ? References: <3EEDFD89.CD2677D8@engcorp.com> Message-ID: In article <3EEDFD89.CD2677D8 at engcorp.com>, Peter Hansen wrote: > >>>> set = 'acgt' >>>> sets = [''.join(a,b,c,d) for a in set for b in set for c in set for d in set] >>>> sets > ['aaaa', 'aaac', 'aaag', 'aaat', 'aaca', 'aacc', 'aacg', 'aact', 'aaga', 'aagc', > 'aagg', 'aagt', 'aata', 'aatc', 'aatg', 'aatt', 'acaa', 'acac', 'acag', 'acat', > ...[snip]... > 'ttgg', 'ttgt', 'ttta', 'tttc', 'tttg', 'tttt'] > >:-) Lovely! I knew there must be a list-comprehension based answer. There was a similar thread back in 2001, which contained the following answers to the related problem of "find the combinations of the members of n variable-length lists": def CartesianProduct(alist): res = [] if len(alist) < 2: for x in alist[0]: res.append([x]) else: tails = CartesianProduct(alist[1:]) for x in alist[0]: for t in tails: res.append([x]+t) return res print CartesianProduct(["a","c","g","t" for x in range(4)]) being David Ullrich's recursive solution. My non-recursive solution was deliberately contrary at the time, and hasn't aged well :) Anyway, the OP appears to be doing bioinformatics, so the general case might be useful to him later... - Andrew -- Andrew Walkingshaw | andrew-usenet at lexical.org.uk From jdhunter at ace.bsd.uchicago.edu Mon Jun 30 11:58:15 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 30 Jun 2003 10:58:15 -0500 Subject: Idiomatic way of repeating items in a sequence. In-Reply-To: (anlri@wmdata.com's message of "30 Jun 2003 04:26:17 -0700") References: Message-ID: >>>>> "alr" == alr writes: alr> reduce(lambda l, i: l + i, [[item] * repetitions for item in This doesn't look too bad to me, but perhaps list comprehensions are clearer? seq = ['a', 'b', 'c'] print [x for x in seq for x in seq] From bignose-hates-spam at and-zip-does-too.com.au Mon Jun 16 21:43:25 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Tue, 17 Jun 2003 01:43:25 GMT Subject: Python as a Language Choice References: Message-ID: Tim Rowe wrote: > Cousin Stanley wrote: >> o Large and diverse set of Application Programming Interfaces >> available in many areas ... > > Not really a factor for me; I just as often use a plain text editor. I think you're thinking of IDEs (Integrated Development Environments), not APIs. > One factor for me that isn't in your list is the extensive > availability of libraries such as numeric and the XML stuff. That's what he meant by Application Programming Interface (API). -- \ "When I get real bored, I like to drive downtown and get a | `\ great parking spot, then sit in my car and count how many | _o__) people ask me if I'm leaving." -- Steven Wright | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From aahz at pythoncraft.com Thu Jun 19 16:17:21 2003 From: aahz at pythoncraft.com (Aahz) Date: 19 Jun 2003 16:17:21 -0400 Subject: Tiger Hash Function in Python References: Message-ID: In article , Mirco Romanato wrote: > >I'm thinkering with Python to build an utility (more specs at the end >of the post) and I need to utilize the Tiger Hash function. >I have not MSVC and run a Win box with the last Cygwin and Python >2.2.3. > >There is any module that compile automagically with Cygwin, or a >module that don't need to be compiled, only installed? Why not write a Tiger hash module yourself? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From g2h5dqi002 at sneakemail.com Mon Jun 9 23:16:42 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 10 Jun 2003 15:16:42 +1200 Subject: Tkinter: Do you really need a "root"? In-Reply-To: References: Message-ID: > In article , > bobsmith327 at hotmail.com (Bob Smith) wrote: >>from Tkinter import * > >>root = Tk() >>app = Frame(root) >>root.mainloop() >> >>But do I really need root?... Yes. This is an annoying quirk of Tk. If you don't explicitly create a root window, Tkinter will create one for you, but one must exist. You can hide it if you want, though, by doing root.withdraw(). -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From goodger at python.org Mon Jun 16 14:37:39 2003 From: goodger at python.org (David Goodger) Date: Mon, 16 Jun 2003 14:37:39 -0400 Subject: Observer Pattern (if you got some spare time) In-Reply-To: <3eee0283$1_1@news.vo.lu> References: <3eee0283$1_1@news.vo.lu> Message-ID: Docutils uses an Observer pattern in a couple of places: docutils.utils.Reporter, and docutils.statemachine.StateMachine. They're very simple implementations, but I think that's the beauty of Patterns in Python: most of the implementation details become unnecessary. -- David Goodger http://starship.python.net/~goodger Projects: * Python Docutils: http://docutils.sourceforge.net/ (includes reStructuredText: http://docutils.sf.net/rst.html) * The Go Tools Project: http://gotools.sourceforge.net/ From mlh at furu.idi.ntnu.no Wed Jun 4 16:21:26 2003 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Wed, 4 Jun 2003 20:21:26 +0000 (UTC) Subject: Efficient data flow between orthogonal C extensions? Message-ID: I'm about to write a component-based data flow program, and I'm pondering the design, partly when it comes to efficiency. Basically, the system will instantiate a set of objects, set up in a directed network-like structure, and they will pass data among themselves in a stream-like fashion. Performance may not be an issue to begin with, and most components will probably be written -- or at least prototyped -- in Python. However, if certain components perform hard computations, it should be possible to replace them with extension objects written in C (or C++ or Fortran or whatever). What I have described so far shouldn't be hard to achieve. However, I have one addition requirement: If one object is passing data to another, and both are written in C, the data passing should be as efficient as possible. In other words, going through a data-passing mechanism that is written in Python would be undesirable -- or so I think. The exact format of the data may be modified according to the mechanism chosen. The simplest solution I've found so far is to pass chunks (arrays) of c structs. Then I _can_ simply go through Python, and efficiency can be had by lumping may structs together (i.e. the arrays have varying lengths). In other words, a form of buffering. One drawback with this is that it may require quite a bit of parameter tuning and tradeoffs (e.g., buffer length vs. idle time). A possibly obvious solution would be to write a C API for the extension objects, and for the objects to interact directly. The problem with this is that all the extensions would (as I understand it) have to know about each other (in the form of #import statements), and that is clearly undesirable. Each extension should only need to know what it is told by the main coordinating system (which is written in Python). Are there any existing (hopefully elegant) solutions for this sort of thing? Any ideas? I know I may be getting ahead of myself, thinking about optimization before I've implemented anything, but I believe this may turn out to be an important part of the basic design... :) - M -- Magnus Lie Hetland "In this house we obey the laws of http://hetland.org thermodynamics!" Homer Simpson From cer1969 at hotmail.com Tue Jun 17 16:39:45 2003 From: cer1969 at hotmail.com (cer1969 at hotmail.com) Date: 17 Jun 2003 13:39:45 -0700 Subject: You know you're a Pythonista when.. References: Message-ID: <74500692.0306171239.b8fc748@posting.google.com> Carlos Moreira wrote in message > > >> 3) Discovering filter() and map(). > > > > >> 4) Fortifying classes with __setattr__() and > > friends. > > > > >> 4.5) Leaving if:, elif:, and else: on their > > own lines for fear of > > >> scorn or deprecation. > > > > 5) Discovering list comprehensions and then > > dumping filter() and map(). > > 6) Belive that "self" is not ugly 7) You start writing a simple script and when you are finished you realize that you have a library From ed at membled.com Sat Jun 14 09:25:52 2003 From: ed at membled.com (Ed Avis) Date: 14 Jun 2003 14:25:52 +0100 Subject: a = b = 1 just syntactic sugar? References: Message-ID: "Terry Reedy" writes: >You can read but not rebind variable in outer scope. But this works: > >def make_counter(): > counter = [0] > def incr(): > counter[0] += 1 > return counter[0] > return incr >>>> c1=make_counter() >>>> c2=make_counter() >>>> print c1(), c1(), c2(), c2() >1 2 1 2 Yes. A similar technique can be used to simulate closures in other languages, for example in C++ #include struct incr { int* c; incr(int *c) :c(c) {} int operator() { return ++c; } }; typedef int *fi(); fi make_counter() { int* counter = new int; return incr(counter); } int main() { c1 = make_counter(); c2 = make_counter(); std::cout << c1() << c1() << c2() << c2() << std::endl; return 0; } (Sorry, my compiler is playing up so I have not tested the above code.) The point is that you have to wrap the integer explicitly in some kind of container, you can't just 'capture' a variable without doing anything extra and proeed to play about with its value from other scopes. A local variable is strictly local to the block that contains it (in C++, it will be destroyed on exit from the block) and you can't make it break free and swim about attached to some closure just by returning a function that uses it. -- Ed Avis From sismex01 at hebmex.com Thu Jun 26 16:45:56 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 26 Jun 2003 15:45:56 -0500 Subject: How to memoize functions? Message-ID: > From: Chris Reedy [mailto:creedy at mitretek.org] > Sent: Jueves, 26 de Junio de 2003 03:29 p.m. > > The obvious way to memoize a function would be to keep a > dictionary with keys being tuples (or maybe dictionaries) > of previous argument lists and values being the results of > the previous computations. > > Unfortunately, this will really mess up garbage collection, since > objects that are arguments could never be collected. Why is this an objection? What kind of objects are in the argument tuples? If storing the tuples is a problem, you could use instead the hash value for the tuple; if you can be sure that no collisions will occur, just change the above implementation: class MemoizeFunction: hashfunc = hash def __init__(self, function): self.function = function self.memo = {} def __call__(self, *args): h = self.hashfunc(args) if h not in self.memo: self.memo[h] = self.function(*args) return self.memo[h] So now the argument tuples won't be stored, only their hash. Now, having the correct hash function is important. > > Something like weakref.WeakKeyDictionary seems to be the > obvious solution. > And, it's a whole new and improved can of worms. What happens when a weakref dies? You have to delete the memo dictionary's relevant entry, right? So, when any of the argument objects leave scope and die, your memo dies also. :-/ > > However, a WeakKeyDictionary won't work since it can't > use a tuple as a key, and wouldn't do the right thing, > even if it could. > Yup. > > The only solution I've got so far is to implement a new > class, imitating WeakKeyDictionary. I started down this road, > but the implementation started getting a little involved, > since I needed two dictionaries, one for the argument list > -> result mapping and one to keep track of which objects > appear in which argument lists (since an argument > tuple must be deleted when _any_ of its arguments becomes garbage). > Yup. > > So ... does anyone have any suggestions and/or has anyone > already done something like this (I couldn't find anything > in the cookbook at ActiveState). > Seems to me that the best approach is to generate a hash function from the argument tuple, and memoize in base of that hash value. I don't think weakrefs will help you much here. :-( > Thanks in advance, Chris > -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From martin at v.loewis.de Sun Jun 8 19:35:45 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 09 Jun 2003 01:35:45 +0200 Subject: a = b = 1 just syntactic sugar? References: Message-ID: Ed Avis writes: > I've given several examples, a possible grammar rule (use simple_stmt) > and a semantics (the same as a named def). That would be an incompatible change. Currently x = lambda:2 print x() prints "2". Under your change, this would be the same as def anon(): 2 x = anon print x() so it would print "None" instead. Regards, Martin From peter at engcorp.com Wed Jun 18 12:45:39 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 18 Jun 2003 12:45:39 -0400 Subject: use member functions to access data in Python classes? References: <3064b51d.0306180815.75869d6f@posting.google.com> Message-ID: <3EF09733.E66F9995@engcorp.com> beliavsky at aol.com wrote: > > In C++, it is generally recommended to declare the data within a class > private and to access the data using member functions. Do experienced > Python programmers usually use member functions to access data within > classes, or do they access the data directly? I follow the conventional approach used even by the Python libraries, which have proven to be quite effective :-), by just accessing most data directly. If the type of access involved is more complicated that getting or setting, I naturally provide a method to perform the operation instead. Note that the latest versions of Python have "properties" which will allow you to combine the best (?) of both worlds by writing code as though it had direct access but which actually calls methods under the table. -Peter From h_schneider at marketmix.com Sat Jun 14 02:26:16 2003 From: h_schneider at marketmix.com (Harald Schneider) Date: Sat, 14 Jun 2003 08:26:16 +0200 Subject: Python Coredump on FreeBSD References: <0pCdnbUTkYU6W16jXTWcow@speakeasy.net> Message-ID: > I hope this means your failing sre samples now work too? Yes they do -- thanks! :-) --Harald From dave at nullcube.com Thu Jun 5 04:38:01 2003 From: dave at nullcube.com (Dave Harrison) Date: Thu, 5 Jun 2003 18:38:01 +1000 Subject: Totally Confused: Passing variables to functions In-Reply-To: References: Message-ID: <20030605083801.GA1238@dave@alana.ucc.usyd.edu.au> Just as a side mention you might also be in a class, in which case the 'global' (read class-wide) variable is accessed as self.variableName being forced to reference with self is a useful bug stopper if you want - for some reason - to have a local variable with the same name as the global variable. eg. where the global variable arg has been defined as 2 def foo(self, arg): return arg+self.arg print 'Global : '+str(self.arg) self.foo(2) print 'Local plus Global : '+str(foo) Michael Mayhew (mayhew at cis.ohio-state.edu): > Howdy, > > To address the first problem, the following sample worked for me: > > def blah(arg): > arg[:] = [] > return arg > > I think the reason is that using the slice operation, you are still, as you > noticed, using methods on the "object reference" and so can change the > mutable object in place. > > For the second example, this sounds like a question of scope as v is > declared in your global scope, but arg is local to the function. If you > wanted to change v itself in the function blah, you would write > > def blah(): > global v > v = v + 1 > > v = 1 > blah() > Now v equals 2! > > If you wanted to simply change the local function reference to v, you would > have to return the result and assign it to v, like so: > > def blah(arg): > arg = arg+1 > return arg > > v = blah(v) > Now v equals 2! > > > I hope this helps somewhat, > > Michael > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From jimmy at retzlaff.com Thu Jun 19 06:55:24 2003 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Thu, 19 Jun 2003 03:55:24 -0700 Subject: Binary adresse for localhost Message-ID: Benoit BESSE (benoit.besse at club-internet.fr) wrote: > for "224.4.0.1" the binary adresse is 0xe0040001L. > What is the corresponding convertion for 127.0.0.1. I'll offer a few approaches in the hopes of making this somewhat Python related. :) >>> import socket >>> socket.inet_aton('224.4.0.1') '\xe0\x04\x00\x01' >>> socket.inet_aton('127.0.0.1') '\x7f\x00\x00\x01' >>> map(hex, [127, 0, 0, 1]) ['0x7f', '0x0', '0x0', '0x1'] >>> '0x%.2x%.2x%.2x%.2x' % (127, 0, 0, 1) '0x7f000001' Jimmy From ulope at gmx.de Mon Jun 9 11:24:48 2003 From: ulope at gmx.de (Ulrich Petri) Date: Mon, 9 Jun 2003 17:24:48 +0200 Subject: Call a Python file with parameters References: Message-ID: "martin z" schrieb im Newsbeitrag news:Dr1Fa.38532$j9%.18920 at news04.bloor.is.net.cable.rogers.com... > I've asked this before, but last time I was too vague. So, I've got a > simpler request: I want to write and call Python files as if they were > functions. The problem is simple: if you write a Python file with only a > def-statement, you don't get a file you can run with arguments - you get a > file that builds a function. If you use the argc and argv syntax, you get a > file you can run with arguments, but the arguments are strings. Basically, > I want to have a Python file that, when I compile it, I get nothing but a > function, or something I can use like a function, that I can shove a > parameter tuple into. Instead I get a code object (no argument tuple) or a > module (containing functions). > ------- # cat func.py def somefunc(blah1, blah2): return (blah1, blah2) # cat prog.py import func print func.somefunc(1,2) ------------------- HTH Ciao Ulrich From gerrit at nl.linux.org Tue Jun 3 17:53:44 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 3 Jun 2003 23:53:44 +0200 Subject: long-term release schedule? Message-ID: <20030603215344.GA15000@nl.linux.org> Hi, does a long-term release schedule exist? I know that, after Python 2.3, Python 2.4 will follow. I have also read that between minor releases, 18-24 months are spent, which means that only by the end of 2004 Python 2.4a1 is to be released. But what comes after Python 2.4? 2.5 or 3.0? Is this written down or summarized somethere? yours, Gerrit. From suresh_vsamy at rediffmail.com Sat Jun 14 13:27:20 2003 From: suresh_vsamy at rediffmail.com (Suresh Kumar) Date: 14 Jun 2003 17:27:20 -0000 Subject: Canvas rectangle filling Message-ID: <20030614172720.24578.qmail@webmail18.rediffmail.com> Thanks Daniel, Thanks for your timely help. I got it. I created a "xmb" file and filled my rectangle. Still i have some problems that i would like to bring your attention. i have created a stack of rectangles all of same size, say 200 pixel wide and 100 pixel height. Each rectangle is given some color and stipple to "gray75". Then i placed some samll rectangles of some size, say 50 pixel wide and 50 pixel height , on each bigger rectangle and assigened some color and stipple to "lines.xbm". I got the o/p such that the smaller rectangles are filled with "line.xbm". But the samller rectangles are looking so transparent. It means, all areas other than ocupied by "line.xbm" is filled with bigger rectangle's color. My requirement is, all smaller rectangles should be filled with "lines.xbm" and they should not be transparent. My coding is as follows: self.canvas.create_rectangle ( 100,100,200,200, fill='blue', stipple='gray75) self.canvas.create_rectangle( 100,200,200,300,fill='red', stipple="gray50") self.canvas.create_rectangle((100,300,200,400, fill='black', stipple="gray25") ######### Small rectagnles self.canvas.create_rectangle(100,150,150,200, fill='black', stipple="@line.xbm") self.canvas.create_rectangle(100,250,150,300, fill='black', stipple="@line.xbm") I attached my required o/p in this mail as "sample.gif". Have a look and give me your suggestion and me let me how to avoid transparancy. With regeards, V.Suresh Kumar. On Thu, 12 Jun 2003 Abel Daniel wrote : >Suresh Kumar wrote: > > Hi, > > Iam using python/tkinter/pmw in windows. > > Most of graphics languages provides facility to fill the rectangcle with > > horizantal/vertical lines. I know that in tkinter we can fill the canvas > > rectangle's interior using "stipple". But my customer is expecting the > > rectangles to be filled with diagnal/vertical/horizantal lines. Is > > there any direct way is available in tkinter/Pmw to fill the rectangle with > > lines? > > or i have to use "create_line" command explicitly? >Well, creating the lines invidually is an option, but i think it's a >rather poor one. You would have to figure out the endpoints of each >line, which might work for rectangles, but will get almost impossible >for circles, or arcs. >(Not to mention that you would be creating a lot of lines, which i guess >would impact performance.) > >I think the best idea would be to use stipple with custom bitmaps. For >example the following xbm file will create diagonal lines: >----8<---- >/* Created with The GIMP */ >#define lines_width 16 >#define lines_height 16 >static unsigned char lines_bits[] = { > 0x11, 0x11, 0x22, 0x22, 0x44, 0x44, 0x88, 0x88, 0x11, 0x11, 0x22, 0x22, > 0x44, 0x44, 0x88, 0x88, 0x11, 0x11, 0x22, 0x22, 0x44, 0x44, 0x88, 0x88, > 0x11, 0x11, 0x22, 0x22, 0x44, 0x44, 0x88, 0x88 }; >----8<----- >Copy-paste this into a file, call it 'lines.xbm', and use it like: >canvas.create_rectangle(100,100,150,150, stipple='@lines.xbm', fill='black') > >There might be two problems: >1) path to the xbm files. If you put your xbm files somewhere else than >the current directory, I think you will have to use the full path, like: >... stipple='@/path/to/file.xbm' ... >Which might complicate the matters as you have to keep track of where >your xbm files are, and use the appropriate path. > >2) creating the xbm files themselves. If you only need some options like >'diagonal lines, close the each other' or 'vertical lines, far apart' >you could create some xbm files, and only provide those. (Essentially >hardcoding thos patterns.) If you need more flexibility, like 'lines at >60 degrees angle, 2 pixels wide and 7 pixels apart' you will have to >generate xbm files on the fly. A way of pipeing the xbm data would come >handy in this case, but I don't know if such exists. You might have to >save the generated xbm data to be able to pass the filename to tkinter. >I think generating the xbm files on the fly will be pretty easy, as they >are simply black&white bitmaps. > >According to >http://www.pythonware.com/library/tkinter/introduction/x2861-options.htm >which is describing the options of arc object: >"As of Tk 8.0p2, the stipple option is ignored on the Windows platform. >To draw stippled pieslices or chords, you have to create corresponding >polygons." > >But I think that doesn't affect other objects. (I didn't test on Windows) > >Abel Daniel > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: sample.gif Type: image/gif Size: 2723 bytes Desc: not available URL: From woooee at yahoo.com Wed Jun 18 18:28:35 2003 From: woooee at yahoo.com (Curly Joe) Date: Wed, 18 Jun 2003 15:28:35 -0700 (PDT) Subject: Algorithm help per favore Message-ID: <20030618222835.74642.qmail@web20505.mail.yahoo.com> Correct me if I'm wrong, but doesn't the compiler break all of these solutions down into approximately the same thing? The compiler has to physically step through the list one by one no matter how you phrase the code, so there would be no gain in speed. There might be a small speedup for larger lists if you placed the previous element in a variable and compare the variable to this element, because then the compiler would only have to access one element instead of two elements in each pass. But aside from that it seems that it is all window dressing IMHO. I'm no expert on lists. Good question though. > --- In python-list at yahoogroups.com, wrbt at e... > (Larry) wrote: > > I need to take a list (probably 20k to 40k > elements) of numbers and > > remove consecutive duplicates. Non consecutive > duplicates are ok. > > > > Example: [6,3,3,3,5,7,6,3,4,4,3] => > [6,3,5,7,6,3,4,3] > > > > The 3 and 6 can appear more than once in the > result set because > > they're separated by another value. Obviously this > is trivial to > > accomplish by walking thru the list and building a > new one (or yanking > > elements out of the existing one) but I'm curious > if anyone knows of a > > more clever way, with speed being a goal more than > memory usage. > > -- > > > http://mail.python.org/mailman/listinfo/python-list > __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From jcazier at decode.is Tue Jun 10 12:02:35 2003 From: jcazier at decode.is (jean-Baptiste Cazier) Date: 10 Jun 2003 09:02:35 -0700 Subject: Rsh and background execution PB Message-ID: Hi ! I am trying to run a python script in the background executing regurlary a remote command. However if I try to run the script in the background, it is suspended as soon as it starts. But it works fine in the foreground. Below is a simplified version of the problem ------------------------------- #!/usr/bin/python import os import string def main(): print "start rsh" # os.system('rsh lcs301 "ls" ') try: lines = string.split(os.popen('rsh lcs301 "ls|head" ').read(),'\n') except : print "error" for i in lines[:-1]: print i return 0 if __name__ =="__main__": main() --------------------------------- And the command line looks like this: No problem in foreground: ~/devel/queue $ pb.py start rsh 41256904005028C06DB9DE8487E42B69C1256C2A0048FE7A_VT367501_C300Z_A2_GM1_0409.pdf 718913.lcs3.ER 718913.lcs3.OU 718937.lcs3.ER 718937.lcs3.OU AgronomDanisco.doc C11-markers-f-JB.xls C11.map CS-2002-17.ps CazierNIHBio_JT.2.doc But in the background: ~/devel/queue $ pb.py & [1] 24541 ~/devel/queue $ start rsh [1]+ Stopped pb.py ~/devel/queue $ fg pb.py 41256904005028C06DB9DE8487E42B69C1256C2A0048FE7A_VT367501_C300Z_A2_GM1_0409.pdf 718913.lcs3.ER 718913.lcs3.OU 718937.lcs3.ER 718937.lcs3.OU AgronomDanisco.doc C11-markers-f-JB.xls C11.map CS-2002-17.ps CazierNIHBio_JT.2.doc Any solution to the problem ? Thanks Kve?ja Jean-Baptiste From tjreedy at udel.edu Sun Jun 8 14:59:55 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 8 Jun 2003 14:59:55 -0400 Subject: imghdr.what failed to identify JPEG References: Message-ID: "Steven Taschuk" wrote in message news:mailman.1055086335.1441.python-list at python.org... > Quoth Arsenal: > [...] > > Bytes [6:10] for my 52 jpg files are 'Exif'. So if imghdr.what adds > > this additonal check, all of my jpgs would be correctly identified. > > That would be easy enough to implement, but I really have no idea > whether it would be the Right Thing. > > The docs explicitly say that 'jpeg' is returned for JFIF JPEGs; > not, that implies, for EXIF JPEGs. I don't know what the > differences between these standards are, nor whether or to what > extent imghdr.what ought to be sensitive to the distinction. This strikes me as something reasonable to submit an SF patch or bug report for. TJR From ee01b092 at ee.iitm.ernet.in Sun Jun 8 22:28:41 2003 From: ee01b092 at ee.iitm.ernet.in (Vinoo vasudevan) Date: Mon, 9 Jun 2003 07:58:41 +0530 Subject: the 'in' operator and class instances Message-ID: <20030609021857.M75806@ee.iitm.ernet.in> Hi, Thanks all for replying to this question. Just a few comments. As for as the GeometricShape example is concerned that class has to implement __contains__ anyway, so this would override the default behaviour namely memebership testing w/o any problems. The fact that redefining __contains__ would mean we lose the ability to use 'in' to check for membership and would have to fall back on hasattr(..) means this ain't a good idea. Thanks for pointing this out. My reason for asking this question is cos I thought it would make the syntax a little more convenient. As a newbie after using 'in' with nearly all the basic types it just felt "logical" :-) to write "... if member in instance: ... ". Vinoo P.S. Sorry I can't enclose the previous mails in this thread as I deleted them by mistake. From staschuk at telusplanet.net Sun Jun 29 14:48:33 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Sun, 29 Jun 2003 12:48:33 -0600 Subject: Re/Unresolved bug? In-Reply-To: <006e01c33dd4$1f3d54a0$6401a8c0@boxen>; from sabu@pure-elite.org on Sat, Jun 28, 2003 at 08:19:35PM -0400 References: <001c01c33d4d$453a9870$6401a8c0@boxen> <20030628072655.A379@tibia.amotlpaa.bogus> <006e01c33dd4$1f3d54a0$6401a8c0@boxen> Message-ID: <20030629124833.A487@tibia.amotlpaa.bogus> Quoth Xavier: [top-posting fixed] > From: "Steven Taschuk" > > Could you post a minimal example of code which provokes this > > behaviour? [...] > Thanks for your reply. Here is the exact, waiting to be fixed code: > http://sabu.net/routekill.py That is very far from a minimal example. What you should do is cut out some code, verify that the problem still exists, and repeat until you can't cut out anything without making the problem go away. Doing so has two advantages: first, a short example is much more likely to provoke responses here, and second, the process itself might teach you what the problem is. Having had some spare time today, I've done this for you. Here's the (not *quite* minimal, actually) result: def addroutes(IP, METHOD): global METHOD def main(): global VERBOSE VERBOSE = '1' global VERBOSE print 'foo' On my machine, with 2.2.2 this code issues the SyntaxWarning and then segfaults, and on 2.3 issues the SyntaxWarning and dies without printing 'foo'. There are two things wrong with this code. To get it running, first remove the second global statement for VERBOSE. Once that's done, the code will start producing SyntaxError: name 'METHOD' is local and global Thus the second thing you need to do is to decide whether you want METHOD to be an argument to addroutes() or a global variable to that function, and then either remove the global statement or emend the argument list. Once you've done these two things the code will run; I leave determining whether it works to you. (Python's reaction to this code *is* buggy -- it seems that the SyntaxWarning interferes with the SyntaxError somehow. (My original suspicion that the SyntaxWarning was irrelevant was wrong.) I'll be looking into this today.) -- 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 peter at engcorp.com Mon Jun 16 22:10:34 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 16 Jun 2003 22:10:34 -0400 Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> <3EECED65.ACF1A6B7@engcorp.com> <3EEDEC19.CA5786DC@engcorp.com> Message-ID: <3EEE789A.3DD19DA4@engcorp.com> Ben Finney wrote: > > You, the programmer (or team of programmers) will never run the program > the same way as the customer will, except by blind accident. You can't > know what the customer will do with it ahead of time, and neither can > the customer. Bonus: XP specifies an "on-site customer" who pretty much does just what you suggest. > Testing cannot try more than a miniscule fraction of the combination of > inputs and usage that the customers will subject it to. Quite debatable. Automated acceptance tests, by definition, cover the bulk of the functionality that has been designed in, since the only functionality that's supposed to be designed in (under XP) is that which is *required* by the acceptance tests. Anything not covered by tests was therefore put added inappropriately by an over-zealous developer. (Again, an obvious simplification, but not much of one.) > Automated testing, carefully thought out, can increase this fraction > significantly; but "run the software before you give it to the customer" > is a laughably inferior way of finding bugs. I agree, that would indeed be a laughable, not to mention ineffective, approach. -Peter From lorenzo at mysurname.net Sat Jun 14 10:30:12 2003 From: lorenzo at mysurname.net (Lorenzo Bolognini) Date: Sat, 14 Jun 2003 14:30:12 GMT Subject: wxPython download Message-ID: Hi all, didn't know how to report it to the wxPython coders but it seems (at least to me and someone else) that wxPython downloads (all versions) aren't working @ sf.net Thank You, Lorenzo From alex_nanou at pochtamt.ru Fri Jun 6 13:12:59 2003 From: alex_nanou at pochtamt.ru (Alex A. Naanou) Date: 6 Jun 2003 10:12:59 -0700 Subject: Postfix/Prefix Operators (++,--) References: <1054878539.22405.4.camel@mylinuxsite.com> Message-ID: Peter Slizik wrote in message news:... [...] > Gur Mra bs Clguba, ol Gvz Crgref > > Ornhgvshy vf orggre guna htyl. > Rkcyvpvg vf orggre guna vzcyvpvg. > Fvzcyr vf orggre guna pbzcyrk. > Pbzcyrk vf orggre guna pbzcyvpngrq. > Syng vf orggre guna arfgrq. > Fcnefr vf orggre guna qrafr. > Ernqnovyvgl pbhagf. > Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf. > Nygubhtu cenpgvpnyvgl orngf chevgl. > Reebef fubhyq arire cnff fvyragyl. > Hayrff rkcyvpvgyl fvyraprq. > Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff. > Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg. > Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu. > Abj vf orggre guna arire. > Nygubhtu arire vf bsgra orggre guna *evtug* abj. > Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn. > Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn. > Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr! Hint: try using the "rotor" module on the string... :) ...you will definitely know allot more about why people like python!! Best Regards... Alex. From sismex01 at hebmex.com Thu Jun 5 10:40:49 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 5 Jun 2003 09:40:49 -0500 Subject: Loop over list of pairs Message-ID: > From: Kevin Carlson [mailto:khcarlso at bellsouth.net] > Sent: Thursday, June 05, 2003 9:41 AM > > Thomas G?ttler wrote: > > >Hi! > > > >What is the prefered way of loop over > >a list like this? > > mylist=[1, "one", 2, "two", 3, "three"] > > > > How about this: > > for i in range(0, len(mylist), 2) : > print mylist[i], mylist[i+1] # or whatever you want to do.. > > HTH, > > Kevin > How about this: from __future__ import generators def Pairs(iterable): """Returns pairwise iterator""" I = iter(iterable) while 1: yield I.next(), I.next() for p in Pairs(mylist): print p --gca -- Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From eat at joes.com Thu Jun 26 23:06:04 2003 From: eat at joes.com (Jason Kratz) Date: Fri, 27 Jun 2003 03:06:04 GMT Subject: stupid question about os.listdir In-Reply-To: References: Message-ID: Ben Finney wrote: > On Fri, 27 Jun 2003 02:22:36 GMT, Jason Kratz wrote: > >>os.listdir takes a pathname as an arg but it doesn't actually list the >>contents of the dir I pass in. > > > Please reduce the problem to a simple script that others can examine, > and post it here. If the behaviour is as you say, it should be only a > few lines long: > > import os > os.listdir( 'somethingyouthinkshouldwork' ) > Ben...I tried the above in a new script file (with print os.listdir) and it works as I thought my other should. Which means i'm doing something wrong when passing the path in to my function but I'm not sure what. ugh. From rowen at cesmail.net Tue Jun 24 15:13:38 2003 From: rowen at cesmail.net (Russell E. Owen) Date: Tue, 24 Jun 2003 12:13:38 -0700 Subject: cvs checkout question Message-ID: I'm trying to check out the current Python (read only) via anonymous cvs as per the instructions on the "Development Tools" page and it's failing % cvs -d:pserver:anonymous at cvs.python.sourceforge.net:/cvsroot/python login (all one one line) (Logging in to reowen at cvs.python.sourceforge.net) CVS password: but regardless of what password I try I get one of two messages: cvs [login aborted]: authorization failed: server cvs.python.sourceforge.net rejected access or cvs [login aborted]: recv() from server cvs.python.sourceforge.net: Connection reset by peer I have a sourceforge account, so I also tried logging in as me and that didn't work any better. Any hints? I'm on a MacOS X machine in case that matters, but I have checked stuff out from other cvs servers. -- Russell From ianb at colorstudy.com Tue Jun 10 19:15:24 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 10 Jun 2003 18:15:24 -0500 Subject: PEP 318 - Function Modifier Syntax In-Reply-To: <3EE6646E.47555429@alcyone.com> References: <3EE65444.907E6D87@alcyone.com> <3EE6646E.47555429@alcyone.com> Message-ID: <1055286924.683.58.camel@lothlorien> On Tue, 2003-06-10 at 18:06, Erik Max Francis wrote: > I think that's a good summary. `is' sounds like a declaration, whereas > `as' sounds more like declaring properties, which is what we're doing. > Ideal would be a new keyword that really says what we mean, like `has', > but the inertia against adding new keywords makes that scenario far less > likely. "Has" doesn't seem good, because it implies that the function has a property (of being a classmethod or something), when in fact the function is being replaced/wrapped. Ian From hannibalkannibal at yahoo.no Sun Jun 22 10:02:48 2003 From: hannibalkannibal at yahoo.no (Eirik) Date: Sun, 22 Jun 2003 16:02:48 +0200 Subject: Tkinter problem References: Message-ID: "Chad Netzer" skrev i melding news:mailman.1056276938.31254.python-list at python.org... > > > How can I make it wait until I press the button before the message in the > > label comes? > > By making a function that sets the text, and then passing that function > to the button 'command' option. NOTE - you pass the function to the > 'command' option, you do NOT call the function and pass the results to > the 'command' option. ie: > > import sys > from Tkinter import * > > def my_test_callback(): > global root > root.t.set("Test-Text") > > if __name__ == '__main__': > root = Tk() > root.t = StringVar() > > root.l1 = Label(root, textvariable = root.t) > root.b1 = Button(root, text = "Button", command = my_test_callback) > root.bE = Button(root, text = "End", command = sys.exit) > > root.l1.grid() > root.b1.grid() > root.bE.grid() > > root.mainloop() > > > > If you haven't seen it already, I recommend: > > http://home.att.net/~stephen_ferg/thinking_in_tkinter/ > > -- > Chad Netzer > > What does the "if __name__=='__main__':" mean? I do not fully understand this example. From tjreedy at udel.edu Tue Jun 10 12:35:20 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 10 Jun 2003 12:35:20 -0400 Subject: When do ActivePython update? References: Message-ID: <0K2dnQ8d2MpVlXujXTWcpQ@comcast.com> "Hyperion" wrote in message news:bc4mvv$j7l$1 at news6.svr.pol.co.uk... > Just wondering when ActivePython updates there version of python to the > latest version-build. > > Python is now 2.2.3 is it not? Less than two weeks ago, I believe. AP2.2.2 was out within a month of the 2.2.2 release, so give them another week or two. TJR From peter at engcorp.com Sun Jun 15 18:05:29 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 15 Jun 2003 18:05:29 -0400 Subject: popen3 child_stdin References: Message-ID: <3EECEDA9.62F25005@engcorp.com> ddoc wrote: > > popen3(cmd[, mode[, bufsize]]) Executes cmd as a sub-process. Returns the > file objects (child_stdin, child_stdout, child_stderr). Availability: Unix, > Windows. New in version 2.0. > > I may be having a moment of brain fade, but I can't see how I get hold of > child_stdin etc, having started up a DOS program with popen3 If you mean you don't understand what the docs are telling you, then this example based on the above text might help: childStdin, childStdout, childStderr = popen3(cmd, mode, bufsize) The return value is expressed as a tuple of three elements.... -Peter From CousinStanley at hotmail.com Tue Jun 17 12:42:14 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Tue, 17 Jun 2003 09:42:14 -0700 Subject: Python as a Language Choice References: <2ec1bc1c.0306161417.7f890a66@posting.google.com> Message-ID: | Here's one more. =) | Dave ... Glad to find other local users ... | I've been happily writing Python for almost two years. | I'm a dinosaur-aged programmer, but have been coding Python for just over a year ... | Went to ASU for Computer Science and graduated in Fall of 2001. I did a couple of days post-installation training and configuration for the ASU CS dept on the Multics systems that Honeywell donated to ASU back in 1981 or 1982 ... can't remember which year ... I don't know how long the Multics machine lasted at ASU, but it sure would be nice to have access to it now as there are no other surviving Multics systems that I know of ... http://www.multicians.org/ | I now work in Scottsdale and just bought a house | in North Phoenix. Are you working in Python ??? I'm a South-Side-Rat living just off Central about a mile north of South Mountain ... -- Cousin Stanley Human Being Phoenix, Arizona From pythonguy at Hotpop.com Thu Jun 26 11:48:33 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 26 Jun 2003 08:48:33 -0700 Subject: Reading a binary file References: <3EFAA842.1070505@semafor.ch> <20030626083305.GF17335@frobozz> Message-ID: <84fc4588.0306260748.39ff6707@posting.google.com> You need to convert the hex to int with radix 16. c='a' h=binascii.hexlify(c) d=int(h, 16) Anand Pillai Sorin Marti wrote in message news:... > Hi Andrew, > > Thanks for your answer! > > Andrew Bennetts wrote: > > On Thu, Jun 26, 2003 at 10:01:06AM +0200, Sorin Marti wrote: > > > >>But now I need the hex values of the binary file. > > > > You can get the hex value of a 1-character string with hex(ord(char)), e.g.: > > > > >>> char = 'a' > > >>> hex(ord(char)) > > '0x61' > > > > That is not exactly what I meant. I've found a solution (a is the binary > data): > > b = binascii.hexlify(a) > > For example it gives me C8 which is a HEX-Value. How to change this one > into a decimal? (The decimal should be 130, right?) > > Thanks in advance > > Sorin From alanmk at hotmail.com Thu Jun 5 11:38:55 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 05 Jun 2003 16:38:55 +0100 Subject: proxy to monitor http requests References: Message-ID: <3EDF640F.89817FB6@hotmail.com> Achim Domma wrote: > I want to analyze how differnet soap libs build their xml messages. To do > this I want to put a proxy between my calling code and the server to display > the requests and responses. Does something like that already exists in > python? I answered a similar question a few days ago. http://tinyurl.com/djvz -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From jason at tishler.net Tue Jun 3 11:58:33 2003 From: jason at tishler.net (Jason Tishler) Date: Tue, 03 Jun 2003 11:58:33 -0400 Subject: Imaging-1.1.4 on Cygwin (Re: Can PIL be installed under Cygwin?) In-Reply-To: <200306022329.IAA20935@suzuki611.ngo.okisoft.co.jp> References: <20030602120330.GA2044@tishler.net> <200306022329.IAA20935@suzuki611.ngo.okisoft.co.jp> Message-ID: <20030603155833.GA1556@tishler.net> SUZUKI Hisao, On Tue, Jun 03, 2003 at 08:29:36AM +0900, SUZUKI Hisao wrote: > In <20030602120330.GA2044 at tishler.net>, Jason Tishler wrote: > > AFAICT, Chuck and your procedure (and patch) are essentially the > > same. The only extra steps that his one had are: > > > > 1. creating some missing symlinks > > 2. rebasing the system to prevent the known Cygwin fork() > > problem > > > > Step 1 may have been obviated by the newer Cygwin Tcl/Tk packages > > and Step 2 is likely necessary with your approach too. > > No, step 2 is not necessary with my approach. OK, but if you use Cygwin Python, shared extensions, and fork(), then you will need to rebase your DLLs sooner rather than later. > The key difference is not to import _tkinter in my setup.py. Oops, I missed that! Anyway, that's cheating! :,) BTW, rebasing is much easier now that I contributed the rebase package to the standard Cygwin distribution: http://www.tishler.net/jason/software/rebase/rebase-2.2.README Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From pyth at devel.trillke.net Mon Jun 30 09:57:21 2003 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 30 Jun 2003 15:57:21 +0200 Subject: Newbie: "compiling" scrips (?) In-Reply-To: <3EF9CBD8.F3AFF856@hotmail.com>; from alanmk@hotmail.com on Wed, Jun 25, 2003 at 05:20:40PM +0100 References: <3EF9CBD8.F3AFF856@hotmail.com> Message-ID: <20030630155721.A6906@prim.han.de> Alan Kennedy wrote: > There are many pieces to what the PyPy people are trying to do, and they have a > lot of work to do building the separate pieces, with nothing to show until it's > all ready to fit nicely together. But I think their overall model looks > promising. So hopefully, with the description above, you'll be in a better > position to understand the content of these links. > > http://codespeak.net/moin/pypy/moin.cgi/PyPythonCore > http://codespeak.net/moin/pypy/moin.cgi/ObjectModel > http://codespeak.net/moin/pypy/moin.cgi/BytecodeCompiler > http://codespeak.net/moin/pypy/moin.cgi/BytecodeInterpreter > > For a look at the kinds of tricks that optimising interpreters can use, in the > java world, take a look over this link > > http://java.sun.com/products/hotspot/docs/whitepaper/Java_Hotspot_v1.4.1/Java_HSpot_WP_v1.4.1_1002_1.html > > Looking at the PyPy object model, I can't help but wonder how they're going to > deal with continuations? (If full integration of stackless is the intention). Hi Alan, The current idea is to implement "stackless" (or continuations) at the code-generation level. The idea is that instead of causing "interpreter-recursion" when calling a function in python we setup a data structure and issue a "goto" to the main-loop which then dispatches the next runnable frame. Doing this manually at the C-level (or Python-level for that matter) is tedious and error-prone. That's why we will try to get our code-generator to do this for us. Ergo you can't see it in our PyPy object model because it's not there yet :-) The current plan is to head for a first code-generator on the next PyPy-Sprint probably in Berlin end of September. cheers, holger From andrew-pythonlist at puzzling.org Wed Jun 18 09:51:53 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 18 Jun 2003 23:51:53 +1000 Subject: How to recognize a generator function? In-Reply-To: <200306180321.35471.tecnic@codidoc.com> References: <200306180321.35471.tecnic@codidoc.com> Message-ID: <20030618135153.GA6354@frobozz> On Wed, Jun 18, 2003 at 03:21:35AM -0700, Oscar Rambla wrote: > > Hi, > > I'm not been able to find a solution to the following: > > How to recognize if a function is a generator function before calling it? How do you know what *any* function returns before you call it? -Andrew. From bignose-hates-spam at and-zip-does-too.com.au Thu Jun 26 21:48:14 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 27 Jun 2003 11:38:14 +0950 Subject: List of lists References: Message-ID: On Fri, 27 Jun 2003 01:44:42 GMT, Mike wrote: > How do I extract a list of lists from a user defined function Depends how that function is returning its values. The most obvious, and simplest way to do what you describe, is to have the function return a list of lists, as its return value. If you mean something else, you'll have to be more descriptive of what you actually want to do. > and print the results as strings for each list? The 'repr()' method of any object will return a printable string of the object's representation. -- \ "Kill myself? Killing myself is the last thing I'd ever do." | `\ -- Homer, _The Simpsons_ | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From chris.lyon at spritenote.co.uk Fri Jun 13 07:02:59 2003 From: chris.lyon at spritenote.co.uk (Chris Lyon) Date: 13 Jun 2003 04:02:59 -0700 Subject: Scanning for local servers, getting a broadcast address References: Message-ID: Again much thanks for the help here is my present code I would appreciate any comments. I would have liked to have used the write list of the select statement but I found that If I did that the routine never exited because the write thread is always ready and the timeout doesn't start. I could clear the write list inside the while but wouldn't I still be in a loop if I couldn't write in the first place? Anyway here they are:- remote server code:- import socket import select myname = socket.getfqdn(socket.gethostname()) s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM, socket.IPPROTO_UDP) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST,1) s.bind(('',20031)) while 1: (rfd,wfd,efd) = select.select([s] ,[] ,[]) if s in rfd: # I have a message (string, address) = s.recvfrom(100) print 'RECEIVED:-',string, address if string == 'scan\n': # I've been requested by a scan to identify myself print 'replying to scan from ',address s.sendto('IAM '+ myname +'\n',address) questioning server code:- import socket import select remotedict = {} broadcast_attempts = 3 # I assume UDP broadcasts can get dropped like anything else in UDP reply_attempts = 3 # three re-trys on recieving a broadcast ack_flag = 1 # I have recieved an acknowledgement ... shut up myname = socket.getfqdn(socket.gethostname()) s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM, socket.IPPROTO_UDP) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST,1) s.bind(('',20031)) while 1: if broadcast_attempts: # I need to broadcast broadcast_attempts = broadcast_attempts - 1 print 'sending scan' s.sendto('scan\n', ('', 20031)) (rfd,wfd,efd) = select.select([s] ,[] ,[] , 5) if s in rfd: # I have a message (string, address) = s.recvfrom(100) print 'RECEIVED:-',string, address if string == 'scan\n': # I've been requested by a scan to identify myself print 'replying to scan from ',address if ack_flag and reply_attempts: print 'sending myname ', myname reply_attempts = reply_attempts -1 s.sendto('IAM '+ myname +'\n',address) if not reply_attempts: ack_flag = None if string[:4] == 'IAM ': # I've received an answer print 'got a reply from ' ,address remotedict[address[0]] = string[4:-1] if rfd == [] and wfd == [] and efd ==[]: print 'breaking' break print remotedict Now I just have to work out how to switch between these two chunks of code when a server stops being a wallflower and want's to get interested in who it can talk to. Someone will now tell me what fun this all is :-) From ageron at HOHOHOHOvideotron.ca Thu Jun 26 14:02:33 2003 From: ageron at HOHOHOHOvideotron.ca (Aurélien Géron) Date: Thu, 26 Jun 2003 20:02:33 +0200 Subject: Python executables? References: <3EFAFB13.1090506@removeme.free.fr> Message-ID: Catalin wrote: > > How can I make executables with python? > > I found some utilities that claim they can do something like that like > > Installer and py2exe but they actualy pack the code in a huge arhive! > > This solves the problem of giving python programs to users who don't > > have python but doesn't solve the problem of the source "secrecy" > > (copyright). > > And the programs also run much slower and become extremely big compared > > to a normal C++ program for example. I made a test and a 2 programs > > doing the same thing where 400 KB with C Builder (static linked) and > > 2.80 MB with python+installer in an arhive packed with upx and 6.9 MB > > with py2exe(unpacked). And the speed difference was huge. > > So can a python program become a "real" executable(I am refering both to > > windows and unix platforms)? > > If this is imposible with python is it possible with jpython? Bruno wrote: > Here you expose 3 different problems : > > 1/ source "secrecy" (copyright) : > It's the wrong problem. *Any* binary code can be subject to > reverse-engineering. There are even tools to do this quite easily for > Java. The right way to protect your property is via copyright and licence. IMHO, Catalin has a good point here. I'm no legal expert, but I believe that copyrights and licences are not quite enough to protect your code. They just mean that if someone uses your code without your authorisation, you *could* theoretically sue them, but : 1- Would it be worth it to go and hire a lawyer and everything? 2- How would you prove it (or even know about it) if they just stole pieces of your code? Or even algorithms? 3- Moreover, you may never know who hacked your code. Look at all the games and excellent software cracked everyday: do you know who dunnit? Who would you sue? So why not simply compile your code and make it *harder* (although not impossible) to decypher: it'll stop most of the potential hackers. It's like the lock on your door: however weak it is, it'll stop most burglars because they won't bother fighting it at all: they'll just go and look for an unlocked house! Well... unless everyone knows there's a treasure inside it, that is. In which case there's not much you can do against determined hackers except to make the task difficult for them. I agree with Bruno about Java decompilers, though : I used them many times and I am still amazed at the quality of the decompilation process. In one instance it even helped me recover my own code when all I had left was the compiled result! The recovered code was neatly indented and perhaps clearer than the original code! But there are also free "obfuscators" that make your compiled bytecode (a lot) harder to decompile. Python bytecode has some pretty good decompilers too. But I don't know about any decent C decompiler. If anyone does, though, I'd be greatly interested. > 2/ Size of "packed" programs : > Realize that the pack must include the whole Python interpreter and > librairies. BTW, I personnaly never used such tools, but I think I > remember that some of them allow you to specify which parts you really need. Yes, some do. > 3/ 'Slowness' : > I don't believe that 'packing' the program makes it slower. > > Are you sure your Python code is really Pythonic ? There are tips and > tricks in how to 'optimize' Python code, and it can be very different > from low-level (C/C++ etc) languages techniques. You may want to have a > look at : > http://manatee.mojam.com/~skip/python/fastpython.html > > Now if you really need smallest possible footprint and blazing-fast > execution speed (which are antagonist needs anyway), and your program is > about low-level stuff, you may not have choosen the right tool !-) > > Bruno > I don't see small footprint and fast execution speed as antagonist at all, quite the contrary. In fact, assembly code produces the fastest and smallest programs. But Bruno is right, IMHO, about choosing the right tool: if you need a 50k program calculating Pi to the 5000th decimal in 0.1 seconds... python is definitely *not* the way to go. Aur?lien From frobozz_electric at hotmail.com Tue Jun 3 13:32:48 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 3 Jun 2003 17:32:48 GMT Subject: Variable Modifications in a class References: Message-ID: "Mehta, Anish" wrote in message news:mailman.1054658001.11458.python-list at python.org... > c = b The problem is with this line. c = b makes c an alias for b, so that when you change the value of c's attributes, you are changing the values for b's attributes. So, when you later say > c.a = 30 > c.b = 40 This is *roughly* equivalent to the following: b.a = c.a = 30 b.b = c.b = 40 You see, earlier, when you created b and c with: b = ab() c = ab() you bind two seperate instances of the class ab (which aliases class AB, in your example). But, when you later *re-bind* c to b, there are no longer referrers to two seperate instances, c and b are now bound to the same instance. To see this, put: print c is b after b = ab() c = ab() then put it after c = b an notice the results. From jiwon at softwise.co.kr Fri Jun 13 01:07:42 2003 From: jiwon at softwise.co.kr (Jiwon Seo) Date: 12 Jun 2003 22:07:42 -0700 Subject: exceptions within user-defined functions? References: Message-ID: e y suzuki wrote in message news:... > i'm trying to put together a try/except clause within a function. the > clause will specifically except the ValueError and NameError exceptions. > the clause can be put together fine, but i'm having a bit of trouble > making the NameError exception be caught when the clause is included in > a user-defined function. > > try/except clause directly at the python interpreter appears fine for > both NameError and ValueError: > >>> try: > ... val=int('eep') > ... print val > ... except (NameError,ValueError),msg: > ... print msg > ... > invalid literal for int(): eep > >>> try: > ... val=int(t) > ... print val > ... except (NameError,ValueError),msg: > ... print msg > ... > name 't' is not defined > > i now place the try/except clause in a function: > >>> def str2no(x): > ... try: > ... val=int(x) > ... print val > ... except (NameError,ValueError),msg: > ... print msg > ... > > it appears to work fine for the ValueError, but although the traceback > for string t as input acknowledges that the error is a NameError, the > error isn't caught (even though it is excepted in the function above): > >>> str2no('eep') > invalid literal for int(): eep > >>> str2no(t) > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 't' is not defined > > i've also tried defining the str2no function without the ValueError > exception to isolate the NameError, to no avail. similar unsuccessful > result when excepting the parent error, StandardError, in lieu of both > ValueError and NameError (ValueError is caught fine). > > what am i doing wrong? please advise. > > thanks in advance, > -eys Yes, you don't seem to understand when python evaluate variables. Python uses applicative-order evaluation, which means python evaluates argument first and then applies them. So, your function "str2no" never sees 't' directly, but will see evaluated value. (because python tries to evaluate before applying t to your function) But, since 't' is not defined, it cannot be evaluated. Thus python interpreter gives you Traceback "before" actaully calling your function. try: str2no(t) except (NameError),msg: print msg if you do like above in the interpreter, it will print msg. However, alternative evaluation model would be normal-order evaluation, in which case, variables will not be evaluated until it is actually used. If python used normal-order evaluation, you'd have got what you wanted. From grante at visi.com Thu Jun 5 23:01:36 2003 From: grante at visi.com (Grant Edwards) Date: 06 Jun 2003 03:01:36 GMT Subject: LANGUAGE QUESTION??? References: <8dcf2300.0306040159.118c24e8@posting.google.com> Message-ID: In article , phil hunt wrote: > A hammer is the best tool by far, we should use it for everything, > and throw away all our screwdrivers. Ah, but the effects of a hammer when combined with a screwdriver far surpasses the sum of the individual effects. Just remember never to hammer a screwdriver into a CRT. -- Grant Edwards grante Yow! What PROGRAM are at they watching? visi.com From skip at pobox.com Wed Jun 11 18:03:02 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 11 Jun 2003 17:03:02 -0500 Subject: Octets calculation? In-Reply-To: <3EE79F73.E08C2554@alcyone.com> References: <65eFa.634621$Si4.577158@rwcrnsc51.ops.asp.att.net> <3EE79F73.E08C2554@alcyone.com> Message-ID: <16103.42774.489230.271536@montanaro.dyndns.org> >> In the real world, nobody ever uses it to mean anything other than 8 >> bits. Erik> That's simply not true. Take embedded systems, for examples, Erik> where it's not at all uncommon for a byte to be 16 or 32 bits. It's not uncommon for a machine word to be 16 or 32 bits, but it's rare these days for a byte to be anything other than 8 bits. Skip From db3l at fitlinxx.com Thu Jun 5 17:40:09 2003 From: db3l at fitlinxx.com (David Bolen) Date: 05 Jun 2003 17:40:09 -0400 Subject: PythonD: 4Suite or Twisted? References: <3eddd372$0$16609$9b622d9e@news.freenet.de> <%RlDa.239$R44.10990@nnrp1.ozemail.com.au> <3mmDa.18175$8g5.301248@news2.e.nsc.no> <3EDE1F04.30539A1A@engcorp.com> Message-ID: Moshe Zadka writes: > As far as I know, Perspective Broker is not slated to ever do UDP. > Unreliable transports are really bad for remote-object protocols which > are based on calling methods. I believe it is fairly easy, however, > to transport Jelly over UDP, if all you need is "unreliable high-level > messaging". I guess to me a method invocation for a remote-object protocol is perfect for a simple datagram request/response scenario (providing the payload is small enough for a datagram) and is often what we use for some of our internal stuff. A simple timeout error that can be handled by the upper level application can work fine. There's nothing wrong with using an unreliable transport for remote-object protocols if it fits the problem domain. In many cases, the reliability of the stream protocol can actually get in the way by imposing unnecessary timeouts and underlying retry mechanisms that the higher level request structure doesn't need. Not to mention that managing state on a common server for a lot of stream connections (even if the streams themselves are largely idle) can become a scaling problem. But I'm also fine if there's no real intention to let the PB work in such an environment, as that's a perfectly good design choice. > You're right, but it's not the Twisted tide you're swimming against. > Most of the time, UDP is the wrong solution, period. When it is, > for example for media-streaming, it needs to be treated differently. > There is no sense of writing reliable transports on top of UDP when > TCP exists. "Most of the time" is a broad statement - one that I'm probably in agreement with. But there are large classes of applications where TCP just isn't necessarily the best protocol, and those applications can still benefit from higher level authentication, remote invocation, etc... For example, when you have a large mesh of communicating nodes sending short bursts of traffic to each other (as is typical in network management or distributed processing applications). Constantly setting up and tearing down TCP sessions (with their overhead) is costly, and maintaining the mesh of connections is expensive in system and network resources. Having been a core backbone person when HTTP first came on the scene, the choice of new TCP session per request was devastating to traffic patterns and utilization, to which HTTP 1.1 (shared session) was a crucially needed improvement. Anyway, using UDP datagrams (even with a rudimentary retry mechanism when necessary - and for announcement only services it may not even be necessary if a miss is not critical and will be covered by a later transmission) can have a lot going for it in terms of scaleability and performance in some situations. Should it be misused by games trying to flood backbones by building a retry mechanism without some sort of exponential fallback? Definitely not. But in the right circumstance a stateless UDP server can be a really good paradigm. There's a spectrum between completely unreliable (raw UDP) and the overhead imposed by TCP (particularly in setup/teardown) for its reliability. Sometimes TCP is just too "heavy" and a UDP base is more appropriate. Hmm, this probably slipped into more of a TCP/UDP protocol issue than Twisted specific one. I appreciate the feedback on Twisted though. I'll look into the Jelly over UDP question. -- David From martin at v.loewis.de Sat Jun 28 14:24:19 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 28 Jun 2003 20:24:19 +0200 Subject: Have I broken my installation? References: <2verfvseu4k82h66g3l2co8mhnc2pe334p@4ax.com> <01hrfv8e7j4c7qi2gtcitlfurd749cg7su@4ax.com> <9qmrfv0270kvqa6cr8t4r4i1dve04nhbug@4ax.com> Message-ID: Matt Mower writes: > |>>> import xml > |>>> print xml > | > |>>> import xml.dom > |>>> print xml.dom > | > |>>> import xml.dom.minidom > |>>> print xml.dom.minidom > | And you said you have PyXML installed? This sounds unlikely: minidom would come from site-packages/_xmlplus if you had. Regards, Martin From babith_cj at yahoo.co.in Thu Jun 12 13:06:55 2003 From: babith_cj at yahoo.co.in (=?iso-8859-1?q?Babith=20C.J?=) Date: Thu, 12 Jun 2003 18:06:55 +0100 (BST) Subject: unsubscribe please Message-ID: <20030612170655.62314.qmail@web8203.mail.in.yahoo.com> ________________________________________________________________________ Missed your favourite TV serial last night? Try the new, Yahoo! TV. visit http://in.tv.yahoo.com From mickel at csc.fi Thu Jun 26 05:45:48 2003 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Thu, 26 Jun 2003 12:45:48 +0300 (EEST) Subject: Standard ways to get union, intersection, difference of lists? In-Reply-To: Message-ID: Thanks Gerrit, Eric and Paul, the sets module is exactly what I need! I'm still running Python 2.2.2 though, so I will need to upgrade. /Mickel -- Mickel Gr?nroos, application specialist, linguistics, Research support, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237 CSC is the Finnish IT center for science, www.csc.fi From martin at v.loewis.de Wed Jun 11 17:21:00 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 11 Jun 2003 23:21:00 +0200 Subject: UTF-16 encoding line breaks? References: <3ee72262$1@mail.hmgcc.gov.uk> <3ee7885a_6@corp.newsgroups.com> Message-ID: Chris Reedy writes: > >>> testfile = codecs.open('testfile.txt', mode='wb', encoding='utf16') > >>> testfile.write('abc\r\ndef\r\n') That's an error: you should write Unicode objects to a file opened by codecs.open. So use testfile.write(u'abc\r\ndef\r\n') instead. > UnicodeError: UTF-16 decoding error: truncated data Yes, .readline does not work on a UTF-16 stream. In Python 2.3, you get NotImplementedError: .readline() is not implemented for UTF-16 Contributions are welcome. Regards, Martin From tweedgeezer at hotmail.com Tue Jun 10 17:02:33 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 10 Jun 2003 14:02:33 -0700 Subject: Revised PEP 318 - Function/Method Decorator Syntax References: <20030610082514442-0400@braeburn.themorgue.org> <6qwufu12ee.fsf@salmakis.intevation.de> Message-ID: <698f09f8.0306101302.688b7e52@posting.google.com> Bernhard Herzog wrote in message news:<6qwufu12ee.fsf at salmakis.intevation.de>... > *compiled*? > > Surely you mean "when the def-statement is executed." ... > > In either case, the modified function is bound to the function > > name at compile time. > > Again, I think you mean "when the def-statement is executed." No, he probably means "compile time." Python is compiled to bytecode separate from being execute, the the def statement is executed at compile time. Jeremy From paul at boddie.net Fri Jun 6 10:36:56 2003 From: paul at boddie.net (Paul Boddie) Date: 6 Jun 2003 07:36:56 -0700 Subject: Updating SQL table problems with python References: <3eddac41$0$31519$5a62ac22@freenews.iinet.net.au> Message-ID: <23891c90.0306060636.5c9a2eb2@posting.google.com> kuntzagk at sulawesi.bioinf.mdc-berlin.de wrote in message news:... > [Some SQL with '%s' in the middle of it, used in conjunction with string substitution.] > Did you get a python syntax error or a SQL syntax error? > If the latter, check if your title contains a quote charakter. > Got bitten by this myself. Please: * Do as Andy Todd suggested and use statement parameters. * Do not mess around with quoting your values and dropping them directly into SQL statements. Otherwise: * Your application may fail when it gets characters you didn't think about and which your database system's SQL parser reacts badly to. * You may be exposing security-related defects because of quoting issues you hadn't considered. I recommend taking a couple of minutes looking at the DB-API and reading about "paramstyle" and cursor objects. This will save you a lot of time and needlessly wasted effort later on. http://www.python.org/peps/pep-0249.html Paul From johnroth at ameritech.net Fri Jun 20 19:09:11 2003 From: johnroth at ameritech.net (John Roth) Date: Fri, 20 Jun 2003 19:09:11 -0400 Subject: Runtime Warning 1010 vs 1011 Message-ID: I just recompiled an extension module, and got a warning message telling me that python was at 1011, and the extension was at 1010. I'm at level 2.2.2, but the include library only has one include with the latest date: the one with the 2.2.2 #defines. What have I done wrong, and do I need to fix it? PS - I know it recompiled, because the 2.1 version of the extension throws an exception. I'm on Windows 98SE. John Roth From maney at pobox.com Sun Jun 1 21:53:29 2003 From: maney at pobox.com (Martin Maney) Date: Mon, 2 Jun 2003 01:53:29 +0000 (UTC) Subject: Replace for Goto References: <3ed5f1ce$0$26721$ba620e4c@reader1.news.skynet.be> Message-ID: Aahz wrote: > try: > for ORlist in includes: > try: > for filter in ORlist: > for field in curr_fields: > for item in record[field]: > if item.lower().find(filter) >= 0: > raise Found > else: > raise NotFound > except Found: > continue > except NotFound: > continue > else: > result.append(record) Speaking as one who has indented deeply when it felt appropriate, and actually used a triply-indirect pointer (not nested structures, just a few points where the code reached all the way to ***whatsit... and it did work and seemed perfectly reasonable at the time it was written)... That's scary. Or was it intended as the single example for a long afternoon demonstrating the effects of refactoring on code readability? :-) -- Here's my message to the record industry and its allies: I'm not a thief. I'm a customer. When you treat me like a thief, I won't be your customer. -- Dan Gillmor From gh at ghaering.de Sun Jun 29 18:51:35 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 30 Jun 2003 00:51:35 +0200 Subject: import/from import question In-Reply-To: References: Message-ID: Artur M. Piwko wrote: > Is there a way to detect if module was imported by 'from import ' > or by 'import '? Provided that the information about imported modules is 'sys.modules', that's not possible. -- Gerhard From peter at engcorp.com Sat Jun 7 21:00:44 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 07 Jun 2003 21:00:44 -0400 Subject: program path References: Message-ID: <3EE28ABC.7D6DB511@engcorp.com> kpop wrote: > > how do i get the path of the python script thats running from within > python. Do you mean the path of any Python module that is imported, or just the main script. For the latter, use sys.argv[0]. -Peter From roy at panix.com Wed Jun 11 13:09:11 2003 From: roy at panix.com (Roy Smith) Date: 11 Jun 2003 13:09:11 -0400 Subject: PEP-317 References: <1055255402.3ee5eb6ae09ee@mcherm.com> <1055312155.157424@yasure> <2259b0e2.0306110902.7d7f456d@posting.google.com> Message-ID: Michele Simionato wrote: > In addition to that, there could be an automatic code converter, making > old programs compatible with Python 3000. Any comments about that ? Given the dynamic nature of Python, I suspect that would be extremely difficult to implement. From skip at pobox.com Tue Jun 3 15:40:28 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 3 Jun 2003 14:40:28 -0500 Subject: Proposed extension to file constructor In-Reply-To: <20030603182813.GB1366@taral.net> References: <20030603182813.GB1366@taral.net> Message-ID: <16092.63916.83822.950537@montanaro.dyndns.org> taral> I needed to extend popen functionality, so I modified the file taral> constructor to optionally take a file descriptor. It was, in my taral> opinion, the minimum way to do it while preserving isinstance(x, taral> file). Where are you getting file descriptors? What's wrong with using os.fdopen to wrap a file descriptor in a file object? fdopen(...) fdopen(fd [, mode='r' [, bufsize]]) -> file_object Return an open file object connected to a file descriptor. Skip From manuelbastioniNOSPAM at tin.it Sat Jun 14 03:10:14 2003 From: manuelbastioniNOSPAM at tin.it (Manuel) Date: Sat, 14 Jun 2003 07:10:14 GMT Subject: getFoo1() vs. class.foo1 References: Message-ID: Thanks! I love python: without set and get boring instructions, the class is more simple and readable. :-) Ciao, Manuel From com-nospam at ccraig.org Tue Jun 3 10:14:57 2003 From: com-nospam at ccraig.org (Christopher A. Craig) Date: 03 Jun 2003 10:14:57 -0400 Subject: a = b = 1 just syntactic sugar? References: <3EDC51DE.6040502@nospam.com> Message-ID: Kendear writes: > if Python supports 1 < a < 10 > then maybe it is also just syntactic sugar. > Other language might take it as (1 < a) < 10 > which is just the boolean 0 or 1 less than 10 > which is always true. > > >>> a = -1 > >>> 1 < a < 10 > 0 > >>> (1 < a) < 10 > 1 > > so in Python, we can't just add parenthesis > to multiple = and can't add parenthesis > arbitrarily to multiple <, >, ==, etc. Sure you can. It just totally changes the meaning. 1 < a < 10 is the same as 1 "The mistakes made by Congress wouldn't be so bad if the next Congress didn't keep trying to correct them." Cullen Hightower From achrist at easystreet.com Fri Jun 13 05:05:15 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Fri, 13 Jun 2003 02:05:15 -0700 Subject: Saving Files Under Windows Message-ID: <3EE993CB.F2CE7D39@easystreet.com> I'm using python (with wxPython, PySQLite, etc) under Windows, and I think that by staying with old versions of Windows (NT, 98), I may not be doing what new versions like. Are there new rules under Windows 2000 or XP that restrict in which folders users can or should be saving their data? Do the python libs or the python win32api give me any function that I can call to find out where I should be creating output files for users? I guess I can check for C:\Documents and Settings\" and create data files there if I find it, but is there any more reasonable way to know where data should go? Is there any way to find an output folder where all users should have read and write privileges so that shared data can go there? Of course, I'd like to run on Win95, 98, NT, 2k, XP, and be aa good citizen on all. Any pythonically canonical or vice versa solutions to this one? Al From ulope at gmx.de Sun Jun 1 12:15:07 2003 From: ulope at gmx.de (Ulrich Petri) Date: Sun, 1 Jun 2003 18:15:07 +0200 Subject: Zope with Apache on shared hosting account References: <62e69c0c.0305310449.762b9e00@posting.google.com> Message-ID: "HW" schrieb im Newsbeitrag news:62e69c0c.0305310449.762b9e00 at posting.google.com... > Hi, > > I am trying to install zope on my account on a shared web server (ie > no root access). Is this possible? I find lots of how-to's for > Zope/Apache, PCGI, RewriteRules, etc, but everyone seems to assume you > have root privleges, can recompile Apache, etc. > Hi, if you have access to "your" part in httpd.conf it may work using ProxyPass for example. Ciao Ulrich From ffiorese at franco.homelinux.org Mon Jun 9 17:11:26 2003 From: ffiorese at franco.homelinux.org (Franco Fiorese) Date: Mon, 09 Jun 2003 21:11:26 GMT Subject: Where is bobo? In-Reply-To: References: Message-ID: <2K6Fa.109703$g92.2546078@news2.tin.it> Franco Fiorese wrote: > Hi all, > do you know where is possible to find the latest original package of > bobo (Python ORB)? > The link (http://www.digicool.com/releases/bobo/) referenced by several > pages on the web is broken... > > Thanks > Franco Fiorese > Thank you for your suggestions. I am trying Pyro (I don't need a complete app. server like Zope), it seems very nice and interesting (although I have some problems running the basic example in a terminal, no X window, console... well I need to read all the docs ;-) ) FF From snag at jool.po Wed Jun 18 19:20:15 2003 From: snag at jool.po (kpop) Date: Thu, 19 Jun 2003 00:20:15 +0100 Subject: Windows Program? References: Message-ID: yes you can there are differant toolkits for doing it. one already comes with python called tkinter if you read the python documentation theres a sample of one in the libary reference. in fact the IDLE program that comes with python is written in it. I never wrote a gui program myself but alot of people on here seem to like wxpython and pyqt, which are addons you can download. "David B." wrote in message news:vf1roa984ou832 at corp.supernews.com... > Hello. I'm new to python and I was wondering... can you make windows-like > programs? (Like with the gray background and the input boxes?) > > David > > From gh at ghaering.de Sat Jun 21 12:15:47 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 21 Jun 2003 18:15:47 +0200 Subject: dynamic creating of class In-Reply-To: References: Message-ID: <3EF484B3.1090906@ghaering.de> Salvatore wrote: > Jaros?aw Zabie??o wrote: > >> Is there a possibility for Python to dynamic binding of class? I can >> do it in PHP but I do not know how to make the same in Python. Look at >> the following example: > > > I had the same problem and I don't remember who gave me the solution. > The idea is to use 'eval' > > class A: > def __init__(self): > self.class_name = 'A' > > class B: > def __init__(self): > self.class_name = 'B' > > > choosed_class = 'A' > choosed_class += '()' > instance_of_choosed_class = eval(choosed_class) > > Thanks to the one who gave me the solution :-) While this works, hee's a better solution: chosen_class = A instance_of_chosen_class = chosen_class() Classes are just yet another type of object :) -- Gerhard From rmunn at pobox.com Wed Jun 4 11:45:17 2003 From: rmunn at pobox.com (Robin Munn) Date: Wed, 04 Jun 2003 15:45:17 GMT Subject: a = b = 1 just syntactic sugar? References: <38ec68a6.0306031913.3600bc16@posting.google.com> <3EDD6610.3CABE86A@engcorp.com> Message-ID: Robin Munn wrote: >=== Begin Python transcript === >>>> a = b = [] >>>> a > [] >>>> b > [] >>>> id(a) > 135714444 >>>> id(b) > 135714444 >>>> a is b > 1 >>>> a = [] >>>> b = [] >>>> id(a) > 135714732 >>>> id(b) > 135714508 >>>> a is b > 0 >==== End Python transcript ==== This got me curious. I know that in the "1>> def foo(): ... print "Side effect!" ... return 5 ... >>> a = b = foo() Side effect! >>> a 5 >>> b 5 ==== End Python transcript ==== It seems the RHS is only evaluated once in chained assignment, at least as of Python 2.2.2. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From MK at foo.com Fri Jun 27 04:35:57 2003 From: MK at foo.com (MK) Date: Fri, 27 Jun 2003 10:35:57 +0200 Subject: Exposing object model in Python? References: Message-ID: "MK" wrote [...] Thanks for your input. Apologies for not being clear enough. I'm writing a classical desktop application, using wxPython and some other libraries. I'm interested to expose its object model a la Microsoft's VBA. That is, I want to allow my users to tinker with the app, i.e. write their own macros in Python in a miniature IDE, within the app. I'd also like to ship the program as a standalone app, using py2exe. From kendear at nospam.com Fri Jun 20 00:50:57 2003 From: kendear at nospam.com (Kendear) Date: Fri, 20 Jun 2003 04:50:57 GMT Subject: thinkings on shallow copy References: <3EF1849E.6060103@nospam.com> <3EF225AA.1000909@nospam.com> <87k7bhh6yj.fsf@pobox.com> Message-ID: <3EF292B0.2080807@nospam.com> John J. Lee wrote: > Kendear writes: > [...] > >>>>I wonder if it is actually to insert *the same object references* >>>>into the new compound object... >>> >>>Sort of. Better: "inserts references to the same objects". >>>(Saying that the references are the same suggests, erroneously, >>>that changing one reference would change the other: >> >>hm, why would it suggest that? if two pointers are the >>same, why would changing one pointer change the other? > > > If two references are *the same* (ie. occupy the same location in > memory), then of course changing one will change the other. If they > merely have the same value, then you'd be right. Steven and me both > interpret your use of the phrase 'the same object references' to mean > the former. hm, insert *the same object references* means, if the source list's first item is 0x0123CDEF which is used as a pointer to memory location 0x0123CDEF, then insert (set) the same value, 0x0123CDEF to the target list's first item... (say, 0x0123CDEF to 0x123FFFF contains another list structure in memory). so, insert *the same object references* and "inserts references to the same objects" is the same thing isn't it? both set the list's first item to 0x0123CDEF unless, you treat "reference" not as the number "0x0123CDEF" but mean different thing or a higher level thing? is reference an object too in python? From webmaster at stratastuff.com Mon Jun 16 03:43:02 2003 From: webmaster at stratastuff.com (Chris White) Date: Mon, 16 Jun 2003 07:43:02 GMT Subject: DNS/MX Lookup? Message-ID: Well, I tried the python-dns module that exists out there, but it's not working so for. It would be nice if there was a socket function to pull up info about mx servers for a domain name. If anyone knows a working with (yes, here it comes) windoze operating system that simply uses the default nameserver or lets me set it for that matter (the later would be more prefered, as it would make it more cross platform compatible IMHO). Also, if anyone knows some good easy to understand (snicker) RFC's for DNS Querying (or some page that breaks it down) that would be great as well. Thanks to all Sincerely, Chris White From warlock at eskimo.com Sun Jun 8 15:33:04 2003 From: warlock at eskimo.com (Jim Richardson) Date: Sun, 8 Jun 2003 12:33:04 -0700 Subject: ANN: Self-guided instruction docs for Python References: <2259b0e2.0306070505.79f61d78@posting.google.com> Message-ID: On 7 Jun 2003 06:05:22 -0700, Michele Simionato wrote: > Dave Kuhlman wrote in message news:... >> I've been at work developing several classes for Python. >> >> The first (Python 101) is an introductory course in Python >> programming. The second (Python 201, you probably guessed) >> discusses several slightly advanced topics which have Python >> solutions. >> >> As preparation for these training courses I've written several >> training documents. When I started, they were intended as an >> outline or syllabus for the course. As time went on, they grew as >> I filled in more notes and details. >> >> Now, I believe, these training documents are usable stand-alone. >> In part I'm announcing this in the hope that these documents can >> be used for self-guided learning. >> >> You can find these documents at: >> >> http://www.rexx.com/~dkuhlman/#training >> >> It's still a "work in progress", but I believe there is plenty >> there now to make it useful. >> >> If you have a need for Python training, please contact me. >> >> If you have suggestions for these documents, please let me know. >> >> - Dave > > It seems like you did a lot of work! > You should ask Guido to put a link to your documents in the official > home-page, that would largely increase their visibility to Python newcomers. > > Cheers, > > Michele Yeah! these pages are great. I have been playing with python for a couple of years, off and on, and there are still things I don't "get" mostly 'cause I am a hardware sort of guy :) But that site is really helpful. (self, what the heck is it for! thanks to all the folks who have tried to explain it to me, but I think I am just thick wrt to this. ) -- Jim Richardson http://www.eskimo.com/~warlock Linux, because eventually, you grow up enough to be trusted with a fork() From mertz at gnosis.cx Thu Jun 5 16:13:32 2003 From: mertz at gnosis.cx (David Mertz) Date: Thu, 05 Jun 2003 16:13:32 -0400 Subject: Twisted Panglossia References: <3eddd372$0$16609$9b622d9e@news.freenet.de> <%RlDa.239$R44.10990@nnrp1.ozemail.com.au> <3mmDa.18175$8g5.301248@news2.e.nsc.no> <3EDE1F04.30539A1A@engcorp.com> Message-ID: |A search for "Pollyannaishness" on Google returns 3 results. Merriam Webster |offers no definition. Care to elucidate this obfuscation? =) Pollyanna 1. A person regarded as being foolishly or blindly optimistic.[ After the heroine of the novel Pollyanna , by Eleanor Hodgman Porter (1868-1920), American writer] -------------------- The American Heritage (r) Concise Dictionary of the English Language, Third Edition. I tend towards polysyllabic--sometimes even polyglottal--neologistic agglutinations. I don't think Sophocles warned me about that though. |I vaguely remember Larry Wall mentioning something about hubris being |a virtue... Yeah... I repeat Wall's tripartite virtues in the preface to my book (btw. I got a sample copy, and Amazon shows it as finally saleable). But there's a fine line between virtues and vices. Yours, David... -- 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 xpm4senn001 at sneakemail.com Sun Jun 22 21:26:29 2003 From: xpm4senn001 at sneakemail.com (John Fitzsimons) Date: Mon, 23 Jun 2003 11:26:29 +1000 Subject: "Newbie" questions - "unique" sorting ? References: <8da5fvsnidpjtblgfj4484spso2t9e6r95@4ax.com> Message-ID: On Sat, 21 Jun 2003 02:13:48 -0700, "Cousin Stanley" wrote: < snip > >So, I re-wrote the program >using a dictionary based mechanism >and all dups now seem to be gone >from the output file ... >Usage is ... > python word_list.py file_in.txt file_out.txt >Download ... >http://fastq.com/~sckitching/Python/word_list.zip < snip > When I tried that on my unsorted original file all I got was : C:\Python>python word_list.py file_in.txt file_out.txt word_list.py Indexing Words .... Then nothing. I waited a long time but still nothing. I then used the first word_list file to sort the original into order. That worked perfectly, as before, to give a sorted result. I then inputted this with the latest word_list.py file and got my word_target.txt . Unfortunately I still had duplicate strings eg : Any any Any any Any any Any any ANY any ANY any Any ANY any :-( I have uploaded my original file to : http://members.optushome.com.au/jfweb/jfin.txt As you can see it is text from the other newsgroup. My "original" plan was to : (A) Sort all strings into different lines. (B) Sort the result into "unique" lines. (C) "Grep" (B) for all lines starting http or ftp or www. Perhaps my thinking was wrong ? Perhaps (A), (C), (B) would make things much easier ? Then the unique line sort would have a great deal less to process and thereby be much easier/faster ? The problem is that I don't have the (C) python program/script yet unless someone here wants to help me with that too. Anyone able to do that please ? I feel that you have already spent sufficient time trying to help with (A) and (B) so don't expect that you would have time for (C). Is the above input file and/or comments a help ? Any constructive feedback from anyone will be appreciated. Regards, John. From alanmk at hotmail.com Sat Jun 21 10:54:50 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sat, 21 Jun 2003 15:54:50 +0100 Subject: XML References: Message-ID: <3EF471BA.EE4F056@hotmail.com> Alan Kennedy wrote: >>Of course the point remains that XML is hugely resource inefficient for >>many problems. But maybe in 5 years we'll have so many terahertz and >>gigabytes and megabits-per-sec that we won't care. Roman Suzi wrote: > Well, when XML was entering the arena, it promised to _lessen_ > the burden on telecommunications... Where is that claim now? I've been "following" XML since seeing Jon Bosak lecture on the subject in May 1997. I've been subscribed, periodically, to xml-dev and xsl-list, and I don't think I've ever heard, read or seen anyone seriously claim that XML would lessen the bandwidth used for communicating information. Is that what you meant? And the same argument could be made about HTML: it is just as resource inefficient as XML, perhaps more so. So why is HTML the most widely used document format in human history? If any claims have been made about communications, then I think they would be more likely to be made in relation to how much easier it would be to *process* XML, compared something like EDI, for example. > And one more point: processing of XML is much less > reliable than that of ASCII or even simple Python literals. I have to disagree with that statement. I don't think that a character encoding can be compared to XML: for example, XML can be stored in ascii. "Processing" ascii is easy, but extracting semantics from an ascii byte stream is harder than extracting semantics from XML, i.e. deciding on your tokens, lexing them, writing a grammar, translating that grammar to running code that builds data structures, etc, etc. Processing simple strings like "2+(2*2)" is easy: what about "I would like a deep pan 12-inch pizza with bacon and banana, two portions of garlic bread and 2 litres of sparkling mineral water delivered to my house please". And can you point me to code/programs/utilities to parse python literals in Java, VB, lisp, smalltalk, javascript, ocaml, etc, etc? Character encoded python literals don't travel as well as XML, as of today anyway. And processing XML is completely reliable, as long as your XML tools library is compliant with standards. Non-compliant tools don't last long, because people stop using them. Now, it is definitely the case that there is a lot of "XML" out there that isn't really XML at all: it's XML structures with broken HTML embedded inside. For example, have you tried to process any RSS feeds lately (it's excruciatingly painful)? But that's more of a social issue (people not being strict with their RSS parsing) than a technical issue. If they stuck by the strict rules of XML, their processing would be very easy, but they would lose 50% or more of the information sources that are syntactically broken. As an aside, I wouldn't bother processing not well-formed RSS. If the publisher can't be bothered to check for compliance of their published documents with a simple standard like XML, then they probably haven't put much effort into assuring the quality of their information either. But that's a social decision for me, not a technical one: try: parse(RSS) except XMLIsNotWellFormedError: if not wantToSpend3MonthsWritingAParserForTheMorassThatIsRSS(): bin(RSS) markOriginatingFeedAsRubbish() > The reliablity is what worries me more. It's too easy to get into some > trap (I remember talks here or in XML-SIG when it was discussed > what is better None or "" for representing namespace). But the latter is a minor, python-specific, concern, and one that was satisfactorily resolved relatively quickly, by the excellent PyXML people (thanks Martin von L et al :-). Once that empty namespace gets serialised into an XML byte stream, and then further processed in another language, the semantic travels seamlessly to other languages. XML travels generally much more reliably, across the wide range of available platforms, than any other non-trivial data/document representation. > So far all arguments pro-XML in this thread are like "XML is good > because X, M and L are already here" (be it SGML, javascript, Java, > developers expertise or whatever). But I wonder if there are pure > technical merits of XML itself apart > from it being involved. Well, I suppose where you and I differ is that I believe that something being easy for ordinary people to understand and work with *is* a technical merit. I think that if we are to progress further, you would have to define what you mean by "technical merit". > XML is not well-based scientifically (like RDBMS) Can you give an example of something comparable to XML that is "well-based scientifically"? I don't understand what you mean. > XML for ? is like CSV for a RDBMS > > However, I have no idea what the question stands for... RDBMS is a very broad term. Try comparing something like SQLLite or MS Access on a LAN with a group of large multi-processor, multi-machine, data-replicating, distributed (across time zones) transaction processing Sybase servers, for example. XML database technology has a long way to go before it challenges RDBMS as a reliable, fast and powerful storage mechanism for information. But there are products, projects and languages out there. Compared to your statement above, perhaps statements like these could be made o XML is to a DOM as CSV is to an array o XML is to Apache Xindice as CSV is to a MySQL server. o XML is to an XML-based content server as CSV is to an RDBMS + a raft of content->relational table mappings. o Xpath/XQuery/XPointer is to an XML repository as SQL is to an RDBMS For me, the most important aspect of XML is as a social phenomenon, not a technical one. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From peter at engcorp.com Mon Jun 2 09:51:34 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 02 Jun 2003 09:51:34 -0400 Subject: CGI question: safe passwords possible? References: <7xwug82ag0.fsf@ruckus.brouhaha.com> <3EDB4CC2.B34F910C@engcorp.com> <7xhe784n6u.fsf@ruckus.brouhaha.com> Message-ID: <3EDB5666.A97908C2@engcorp.com> Paul Rubin wrote: > > Peter Hansen writes: > > Also note: you won't be able to have your users change their passwords > > securely with any such approach. For that, I believe SSL is going to > > be the only secure option, to avoid ever sending a password to the server > > in the clear. (Or generate passwords on the server side and email to the > > user, though that has obvious other problems...) > > You could use the old password as a key to encrypt the new password. > Of course that's not too clever if the reason for changing the password > is that the old one is compromised... Ah, a nice solution, I would say. If the password is actually compromised, requiring the user to contact the adminstrator to "reset" their password, or asking the server to generate a new password which is sent via email, would be reasonably acceptable approaches. -Peter From peter at engcorp.com Sun Jun 22 12:14:26 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 22 Jun 2003 12:14:26 -0400 Subject: xrange References: Message-ID: <3EF5D5E2.DF5D9FCB@engcorp.com> Bryan wrote: > > in 2.3, what is the best way to write this: > for i in xrange(100): print 'Hello' > > i used timeit and it seems that repeat is about 10% faster. Is such a small performance difference more important to you than backwards compatibility? I would choose "for i in xrange()" still, merely because of the number of people still using Python 2.2 and before, but I'm not one who cares much about trivial optimizations... (I realize you might be using 2.3-only features, but I don't think that automatically means you should abandon readability, by dumping a well-known idiom with a merely possibly-to-become-idiomatic form.) -Peter From gerrit at nl.linux.org Wed Jun 18 18:04:39 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 19 Jun 2003 00:04:39 +0200 Subject: feature request: mul In-Reply-To: References: <2259b0e2.0306110833.24b998cd@posting.google.com> Message-ID: <20030618220439.GA5958@nl.linux.org> Jacek Generowicz wrote: > mis6 at pitt.edu (Michele Simionato) writes: > > import operator > > multi_and=lambda it: reduce(operator.mul,it) > > if multi_and(condition): > > dosomething() > > > > but frankly it is too ugly for my taste. Having > > 'sum' and 'mul' the use cases for 'reduce' would > > drop, which I think is a good thing. > You don't like abstraction ? One could also use: sum(map(bool, it)) or sum(map(abs, it)). I have two use cases in my program. One is with a (200-elem) list of booleans (pygame.keys.get_pressed()). One is with coordinates for a direction, [-1 - 1, -1 - 1]. Because of this thread, I encountered this bug and fixed it :) yours, Gerrit. -- 137. If a man wish to separate from a woman who has borne him children, or from his wife who has borne him children: then he shall give that wife her dowry, and a part of the usufruct of field, garden, and property, so that she can rear her children. When she has brought up her children, a portion of all that is given to the children, equal as that of one son, shall be given to her. She may then marry the man of her heart. -- 1780 BC, 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 fredrik at pythonware.com Mon Jun 30 08:49:48 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Jun 2003 14:49:48 +0200 Subject: Placing entry widgets on a canvas in Tkinter References: Message-ID: Mickel Gr?nroos wrote: > I'm trying to put an Tkinter.Entry of fixed size onto a specific location > on a canvas using the place manager. The idea is that one can double-click > a rectangle object on a canvas to get an entry field of the same size > as the rectangle placed exactly over the rectangle thus creating > the effect that the rectangle has entered "input mode". When clicking > return in the entry field, the value is fed back to a text object within > the rectangle object on the canvas. > Well, this works fine and well until the canvas is scrolled of one reason > or another. When that happens, the entry naturally does not follow the > canvas. Is there a way to lock a widget which is "placed" onto a canvas > to the canvas so that it follows the canvas as it scrolls or is rescaled? try this: canvas.create_window(x, y, window=widget, anchor=NW) (also make sure to always use canvas.canvasx(screenx) and canvas.canvasy(screeny) to convert between screen coordinates and canvas coordinates in your event handlers) an alternative solution is to implement text editing for text items; see http://effbot.org/guides/editing-canvas-text-items.htm for a discussion, and some code. From dave at nullcube.com Thu Jun 5 22:26:55 2003 From: dave at nullcube.com (Dave Harrison) Date: Fri, 6 Jun 2003 12:26:55 +1000 Subject: Singleton class: what is the purpose? In-Reply-To: References: <20030605111536.GA3436@nl.linux.org> Message-ID: <20030606022655.GA1683@dave@alana.ucc.usyd.edu.au> All design patterns have a tendency to link together, they jigsaw together pretty well. What works with what really depends on context and the problem being solved though. The borg is alot of labels (to use Aldo's term) which are all attached to the same __dict__ Flyweight is in a borg in some senses, and has two important elements. Intrinsic state and extrinsic state. Intrinsic state is the state within the object, where that state is common irrespective of which class is handling that particular object. This is the similarity with the borg pattern. Extrinsic state is the state in which the object exists in the object that is handling it. Clarification time. This means that the object itself, retains a common state. Whether that is because you have a borg, or you have a singleton, is - to some extent - irrelevant. The point is the object keeps its own state. However that does not impact on where that object fits _into_ other object. The below link gives the example of a circle object which works nicely as a simple explanation. The circle itself has a radius which is independant of who is handling it. The values _intrinsic_ to the circle are independant of _where_ the object is. If that circle is in the top left corner of one window object, and the bottom right of another, that does not affect the circles _intrinsic_ state. Those positions are its _extrinsic_ state within each of those objects. http://selab.korea.ac.kr/selab/courses/GoF-patterns/flyweight.htm Hope that helps. Dave Gordon Scott (gscott2112 at adelphia.net): > Is there any difference between the Borg and the Flyweight? Sound like the > same thing. > > Gordo > > "Aldo Cortesi" wrote in message > news:mailman.1054814890.6876.python-list at python.org... > > Thus spake Gerrit Holl (gerrit at nl.linux.org): > > > > > What is a singleton class? What is the purpose of a > > > singleton class? > > > > > > On the web, I have found that a singleton class allows > > > only one instance. Is that correct? > > > > Yep, that's right - the Singleton pattern is used to make > > sure that only one instance of a given class exists. > > > > > > > If so, it should be easily implementable with: > > > > > > 20 >>> class Singleton(object): > > > 20 ... instances = [] > > > 20 ... def __init__(self): > > > 20 ... if len(self.__class__.instances) == 0: > > > 20 ... self.__class__.instances.append(self) > > > 20 ... else: > > > 20 ... raise Exception("No way jose!") > > > > Almost, but this is really only half an implementation of > > the Singleton pattern. A real implementation has to do two > > things: > > - Ensure that only one instance exists > > - Make that instance available in some global way > > > > See here for some discussion of various implementation > > strategies: > > > > http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52558 > > > > > > > But what is the purpose of a Singleton class? > > > > There are lots of circumstances in which the Singleton > > pattern comes in handy. For instance, you may have a program > > that should have only one connection to a database, or a > > system where only one print spooler should exist. Or, > > perhaps you want to share a single instance of a commonly > > used, but expensive to create, object between the various > > parts of your application. For a more in-depth discussion of > > the use (and abuse) of the Singleton Pattern see the > > excellent c2 wiki: > > > > http://c2.com/cgi/wiki?SingletonPattern > > > > > > You should also note that the Singleton pattern has recently > > fallen out of vogue with the Python in-crowd. If you're hip, > > and in-the-know, you're supposed to advocate the Borg > > pattern. The name is a pune or play on words - whereas the > > Singleton pattern means that There Can Only Be One (i.e. > > only one instance can exist), the Borg pattern means that > > You Will Be Assimilated (i.e. many instances can exist, but > > all have the same state). The skeleton for a Borg-ised class > > looks like this: > > > > class Borg: > > __shared_state = {} > > def __init__(self): > > self.__dict__ = self.__shared_state > > > > As you can see, a single __dict__ is shared between all > > instances. In practice, this achieves much the same purpose > > as the Singleton pattern - object identity may differ from > > instance to instance, but since state is shared, all > > instances act exactly the same. > > > > > > Finally, many people forget that Python has something very > > much like the Singleton concept built in - modules. Python > > ensures that code in module scope is only executed once > > (unless you force a reload), no matter how many times a > > module is imported.... > > > > > > > > > > Cheers, > > > > > > > > Aldo > > > > > > > > > > -- > > Aldo Cortesi > > aldo at nullcube.com > > http://www.nullcube.com > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From staschuk at telusplanet.net Mon Jun 16 23:06:55 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 16 Jun 2003 21:06:55 -0600 Subject: does lack of type declarations make Python unsafe? In-Reply-To: <114xq48ewelrf.1xyyacwlxdk1p.dlg@40tude.net>; from imbaczek@poczta.onet.pl on Sun, Jun 15, 2003 at 11:45:55PM +0200 References: <3064b51d.0306151228.22c595e0@posting.google.com> <114xq48ewelrf.1xyyacwlxdk1p.dlg@40tude.net> Message-ID: <20030616210655.B3458@tibia.amotlpaa.bogus> Quoth Marek "Baczek" Baczy?ski: [...] > Your argument is good in theory, but IME such things are extremly rare to > happen in real life. Searching for a lost colon also takes a lot of time > *and* tends to happen more often. Searching for a lost colon does take a lot of time, and a lot of people don't appreciate that. A friend of a friend of mine lost his colon a couple years ago -- usual story, went out for a night on the town, woke up in a bathtub full of ice, colon missing -- and he's *still* looking for it. -- Steven Taschuk staschuk at telusplanet.net "Its force is immeasurable. Even Computer cannot determine it." -- _Space: 1999_ episode "Black Sun" From jtauber at jtauber.com Thu Jun 19 03:36:05 2003 From: jtauber at jtauber.com (James Tauber) Date: Thu, 19 Jun 2003 15:36:05 +0800 Subject: Feature Structures in Python (Part II) Message-ID: <20030619073605.0D2BD35EF0@www.fastmail.fm> This is part II. Note that it hasn't be changed to use clear() instead of having the del_features() function yet. Again, suggestions for improvement appreciated. James ### ### FEATURE STRUCTURES IN PYTHON (Part II) ### ### James Tauber - http://jtauber.com/ ### Updated: 2003-06-19 # # This is the second part of a guide to implementing feature structures # in Python. # # In the previous part, we saw how to use dictionaries for feature # structures and how to implement reentrancy. In this part we'll look # at subsumption. # # Previously, we defined the following: class feature(str): pass def del_features(feature_structure): for f in feature_structure.keys(): del feature_structure[f] ## ## SUBSUMPTION # # We will define subsumption recursively, to cover nested feature # structures. In particular, F1 will be said to subsume F2 iff, for # every feature in F1, the same feature exists in F2 and the value of # the feature in F1 subsumes the value in F2. Furthermore, an atomic # value will only subsume another atomic if they are equal. # # NOTE: I'll postpone the question of whether None should subsume # everything. # # Let's unpack the definition. # # The definition depends on whether the two objects being compared are # dictionaries or not. Let's initially cover the non-dictionary case. def _subsume_1(value1, value2): return value1 == value2 assert _subsume_1("np", "np") assert not _subsume_1("np", "vp") # # Now let's define the corresponding function for two # feature-structures with atomic values: def _subsume_2(structure1, structure2): for feat in structure1: # iterate over features in first if feat in structure2 and \ _subsume_1(structure1[feat], structure2[feat]): pass # if compatible, continue along else: return 0 # found an incompatibility return 1 # got through with no problems assert _subsume_2({}, {}) fs1 = { "NUMBER": "sg", "PERSON": 3 } fs2 = { "NUMBER": "pl", "PERSON" : 3 } fs3 = { "NUMBER" : "sg" } fs4 = { "PERSON": 3 } assert not _subsume_2(fs1, fs2) assert not _subsume_2(fs1, fs3) assert not _subsume_2(fs1, fs4) assert not _subsume_2(fs2, fs1) assert not _subsume_2(fs2, fs3) assert not _subsume_2(fs2, fs4) assert _subsume_2(fs3, fs1) assert not _subsume_2(fs3, fs2) assert not _subsume_2(fs3, fs4) assert _subsume_2(fs4, fs1) assert _subsume_2(fs4, fs2) assert not _subsume_2(fs4, fs3) # # Now we are in a position to properly define our subsume function: def subsume(object1, object2): if type(object1) == type(object2) == dict: for feat in object1: if feat in object2 and \ subsume(object1[feat], object2[feat]): pass else: return 0 return 1 else: return object1 == object2 # # Let's repeat the same tests with the next function. assert subsume("np", "np") assert not subsume("np", "vp") assert subsume({}, {}) assert not subsume(fs1, fs2) assert not subsume(fs1, fs3) assert not subsume(fs1, fs4) assert not subsume(fs2, fs1) assert not subsume(fs2, fs3) assert not subsume(fs2, fs4) assert subsume(fs3, fs1) assert not subsume(fs3, fs2) assert not subsume(fs3, fs4) assert subsume(fs4, fs1) assert subsume(fs4, fs2) assert not subsume(fs4, fs3) # # And now some new ones: assert not subsume(1, fs1) assert not subsume(fs1, 1) fs5 = { "NUMBER": "sg", "GENDER": "masc" } assert not subsume(fs1, fs5) assert not subsume(fs5, fs1) fs6 = { "CAT": "np", "AGR": { "NUMBER": "sg", "PERSON": 3 } } fs7 = { "CAT": "np" } fs8 = { "AGR": { "NUMBER": "sg" } } fs9 = { "AGR": { "PERSON" : 3 } } assert not subsume(fs6, fs7) assert not subsume(fs6, fs8) assert not subsume(fs6, fs9) assert subsume(fs7, fs6) assert not subsume(fs7, fs8) assert not subsume(fs7, fs9) assert subsume(fs8, fs6) assert not subsume(fs8, fs7) assert not subsume(fs8, fs9) assert subsume(fs9, fs6) assert not subsume(fs9, fs7) assert not subsume(fs9, fs8) fs10 = { "AGR": { "PERSON" : 1 } } assert not subsume(fs9, fs10) assert not subsume(fs10, fs9) assert not subsume(fs10, fs6) ### CONTINUED IN Part III (unification) -- James Tauber http://jtauber.com/ From jdhunter at ace.bsd.uchicago.edu Thu Jun 5 14:34:46 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 05 Jun 2003 13:34:46 -0500 Subject: Module for quasi-random sequences? In-Reply-To: <1BLDa.10298$KF1.144776@amstwist00> ("carljohan.rehn@chello.se"'s message of "Thu, 05 Jun 2003 20:11:05 +0200") References: <1BLDa.10298$KF1.144776@amstwist00> Message-ID: >>>>> "carljohan" == carljohan rehn at chello se writes: carljohan> Does anyone know if there exists a python module for carljohan> generating quasi-random sequences (Sobol, Halton, carljohan> Niedereiter, etc)? GSL provides Sobol and Niederreiter Quasi-random number generator algorithms ======================================== The following quasi-random sequence algorithms are available, - Generator: gsl_qrng_niederreiter_2 This generator uses the algorithm described in Bratley, Fox, Niederreiter, `ACM Trans. Model. Comp. Sim.' 2, 195 (1992). It is valid up to 12 dimensions. - Generator: gsl_qrng_sobol This generator uses the Sobol sequence described in Antonov, Saleev, `USSR Comput. Maths. Math. Phys.' 19, 252 (1980). It is valid up to 40 dimensions. and there is a pygsl wrapper for GSL. However, I don't believe the current pygsl (as of v0.1) code wraps these functions specifically, but if you know how to write python extensions, you can wrap it yourself or extend pygsl. I just wrapped the GSL Levy distribution generating function yesterday to fill a Numeric array, and it wasn't hard. I could send you some example code if you like. When I get the time, I want to extend this code to fill Numeric arrays with most/all of the available GSL random number generators, because I work with arrays a lot and don't like the performance hit of having to repeatedly call the pygsl functions in a python loop. John Hunter From michaeljwhitmore at netscape.net Mon Jun 23 09:56:38 2003 From: michaeljwhitmore at netscape.net (Michael J Whitmore) Date: 23 Jun 2003 06:56:38 -0700 Subject: Newbie on importing References: <71650A6F73F1D411BE8000805F65E3CB3B33A9@SRV-03> Message-ID: <68a42404.0306230556.21523c60@posting.google.com> Thanks everyone, I appreciate the feedback... From jubafre at brturbo.com Tue Jun 3 10:28:41 2003 From: jubafre at brturbo.com (jubafre at brturbo.com) Date: Tue, 3 Jun 2003 11:28:41 -0300 (BRT) Subject: Tkinter text Message-ID: <13910268.1054650521536.JavaMail.nobody@webmail1> i have a text componnent, i and i have to get a start and a end positions to the selected(means: select a part of a text with the mouse) text in the text componnent?? Juliano Freitas From sebastien.hugues at swissinfo.org Tue Jun 17 09:09:17 2003 From: sebastien.hugues at swissinfo.org (Sebastien Hugues) Date: Tue, 17 Jun 2003 15:09:17 +0200 Subject: Debug version of Python 2.2 on win32 platform ? Message-ID: <3EEF12FD.9020905@swissinfo.org> Hi Does anyone know where i could find a binary version of Python 2.2 with all debug symbols enabled for win32 ? I tried to build it from scratch, but i cannot set up the wise installation due to a wrong version of wise. Thanks in advance Regards Sebastien From exarkun at intarweb.us Fri Jun 6 02:13:27 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 6 Jun 2003 02:13:27 -0400 Subject: trouble embedding python In-Reply-To: <20030605211532.12139.00000114@mb-m04.aol.com> References: <20030605211532.12139.00000114@mb-m04.aol.com> Message-ID: <20030606061327.GA17460@meson.dyndns.org> On Fri, Jun 06, 2003 at 01:15:32AM +0000, TheDustbustr wrote: > [snip] > > > *** BEGIN main() *** > ... > Script_LoadScript(script, "pobj"); > result=PyDict_GetItemString(script.pDict, "Human.str"); This isn't right. You need to get "Human" separately from "str". PyObject* human = PyObject_GetAttrString(script.pDict, "Human"); if (human == NULL) { ... } PyObject* str = PyObject_GetAttrString(human, "str"); if (str == NULL) { ... } ... > [snip] Stepping back a bit: consider not embedding at all, though. It is more effort for less result than writing extension modules. http://www.twistedmatrix.com/users/glyph/rant/extendit.html is a reasonable summary of the differences between the two strategies, and why you might select one over the other. Stepping back even more: consider why you would use any language other than Python at all. Python should be sufficient for anything except interoperating with native libraries, which do require some wrapping. If you're using C++ for performance, consider optimizing -after- you've written a fair part of your project, rather than before. Premature optimization leads to inflexible software, and closes down avenues for later optimization when the problems may be better understood. Hope this helps, Jp From pifpafpuf at gmx.de Wed Jun 25 13:41:52 2003 From: pifpafpuf at gmx.de (Harald Kirsch) Date: 25 Jun 2003 10:41:52 -0700 Subject: jython type coercion to interface type Message-ID: <16990fa4.0306250941.55973aba@posting.google.com> How would I call a java constructor which takes a java.lang.CharSequence as argument. Say, the java class goes like this class X { public X(CharSequence s) { ... } } In the jython interpreter I tried along the lines of x = X("bla") and got "1st arg can't be coerced to java.lang.CharSequence". Then x = X(CharSequence("bla")) and got "can't instantiate interface (java.lang.CharSequence)" Is there a way to typecast String to CharSequence or, mor generally, a type to a supertype or interface? Harald Kirsch From altis at semi-retired.com Thu Jun 5 12:53:38 2003 From: altis at semi-retired.com (Kevin Altis) Date: Thu, 5 Jun 2003 09:53:38 -0700 Subject: ANN: free mailing list hosting now available for Python User Groups Message-ID: Barry Warsaw has created a mailman hosting site for Python User Groups. The hosting is free and all administration is handled through the mailman web interface. The instructions for getting your list created have been added to the User Groups page: http://www.python.org/UserGroups.html#usergroups If you already have a Python User Group, but don't have a mailing list or would like to move your existing group to mailman, this is a simple way to make the switch. This is also a great opportunity to start a Python User Group in your area. BTW, we're looking for a volunteer to lead the Python user groups effort. We need some web pages to help people get started creating a group, the benefits, etc. If you're interested in leading this effort or have past experience in organizing user groups and would like to help, please email me directly. Local Python advocacy and support is important to promoting Python. A big thanks to Barry for taking care of the mailing list obstacle. ka --- Kevin Altis altis at semi-retired.com http://altis.pycs.net/ http://www.pythoncard.org/ From staschuk at telusplanet.net Mon Jun 2 02:46:45 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 2 Jun 2003 00:46:45 -0600 Subject: iterator.next() confusion In-Reply-To: <20030529174251.GA68946@doublegemini.com>; from cce@clarkevans.com on Thu, May 29, 2003 at 05:42:51PM +0000 References: <20030529174251.GA68946@doublegemini.com> Message-ID: <20030602004645.A8933@tibia.amotlpaa.bogus> Quoth Clark C. Evans: > Hello all. The iterator PEP doesn't seem to say if the next() method > of the iterator could be cached during a loop, for example: [...] > Code like the above seems to work with most iterables, however, > it will get into an endless loop with the following iterator: > > class evilIterator: [...iterator for which calling self.next rebinds self.next...] This kind of iterator actually fails in for loops if it is made new-style. > Which is incorrect use of the iterator PEP? [...] For new-style objects only type(it).next is used; whether it is shadowed by an instance attribute doesn't matter. So my feeling is that using an instance-specific .next is not kosher, even though it works for old-style iterators. (Note that the PEP speaks only of defining .next in the class.) It is possible to write an evil new-style iterator, though: class NewEvilIterator(object): def __iter__(self): return self def next(self): NewEvilIterator.next = NewEvilIterator.next_stop return 1 def next_stop(self): raise StopIteration() This works, sort of. Certainly a for loop looks up the .next class attribute anew at each iteration. Of course, as a real technique this is useless; you can't have multiple independent instances of such a class, even if their lifetimes don't overlap. I can't think of a way to write a usable new-style iterator class which breaks under caching of .next. -- Steven Taschuk staschuk at telusplanet.net Receive them ignorant; dispatch them confused. (Weschler's Teaching Motto) From peter at engcorp.com Mon Jun 23 12:28:22 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 23 Jun 2003 12:28:22 -0400 Subject: non blocking named pipes References: <3ef72290$0$20050$fb624d75@newsspool.solnet.ch> Message-ID: <3EF72AA6.6912C0A3@engcorp.com> Yves Serrano wrote: > > I have a problem with named pipes.... > I searched in the web, but don't found any working solution.... > > My Problem is that I have a pipe (/temp/pipe) where sometimes some data > ist written into, but not very often. > I try to write a python script that opens the pipe and gets the data if > its there. I no data is there the script > should not block, it should immediately exit without data. > > How to do that? > > I'm using python 2.2 on linux There may be a better way, but the select.select() function is probably capable of doing what you need. Just give it timeout parameter of 0 to avoid blocking. mypipe = open-my-pipe(/temp/pipe) dr, dw, de = select([mypipe], [], [], 0) if dr == [mypipe]: # read from mypipe here... -Peter From m at moshez.org Tue Jun 10 01:58:32 2003 From: m at moshez.org (Moshe Zadka) Date: 10 Jun 2003 05:58:32 -0000 Subject: Hardware take on software testing. In-Reply-To: <3EE4F2F0.2EC4FBA5@engcorp.com> References: <3EE4F2F0.2EC4FBA5@engcorp.com>, <2ae25c6b.0306060450.78e988f9@posting.google.com> <3EE0CF2B.57F474E4@engcorp.com> <2ae25c6b.0306061721.148300a@posting.google.com> <3EE14F0A.3D1E1887@engcorp.com> <2259b0e2.0306091158.701ed82a@posting.google.com> Message-ID: <20030610055832.24762.qmail@green.zadka.com> On Mon, 09 Jun 2003, Peter Hansen wrote: > We find we achieve 100% code coverage on code that is purely test-driven, > and we _do_ expect no bugs. > though from time > to time we find them. Make any sense? I should have said "you should > expect no bugs", and didn't mean to imply you will never have them. One area where you easily find lots and lots of bugs, even when you have a good testing suite, is when porting software. Frequently, that's irrelevant -- if you're developing an in-house solution which has to run on, say, Debian Woody, and you're running tests on Debian Woody, then everything is fine. Where I saw this problem was in Twisted. Now, I do realize Twisted has *far* from enough tests. But even the tests that do exist do not keep us "bug free" as far as they go. For example, suppose I write some code, put in a test, and it works. I happily commit. Now it turns out that in Python 2.3, this test spits pending deprecation warnings. No problems, I fix this, and test with both 2.2 and 2.3. Now, the problem is that the test doesn't run if the machine needs a proxy to connect to the web. OK, I hack around it. Now I run it again, and it seems that my code had a race condition: to stop it from hanging the test suite, I put in a time limit, but the limit was too short. So, I increase the limit. Now I commit, and someone running the unit tests with the qtreactor has problems. Having no qtreactor-able set up, I cannot even be sure how to fix it. So on, and on, ad neasuem. Now, I'm not saying that tests do not help -- I am just saying that writing tests in portable ways, even if the code they test is itself portable, is highly non-trivial I predict the XP response to it: "define the platforms you want, and then have the running-tests command automatically run on all those platforms". Unfortunately, again real life intervenes. If every commit had to run the test suite 10 times on five different machines, little real work would be done. -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From gerrit at nl.linux.org Thu Jun 5 15:12:09 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 5 Jun 2003 21:12:09 +0200 Subject: (no subject) In-Reply-To: References: Message-ID: <20030605191209.GB4816@nl.linux.org> Leeds, Mark schreef op donderdag 5 juni om 20:56:34 +0000: > i'm a python beginner but I have three books and i couldn't find an > answer to the following question. > > i have a date, say as a string 26Nov2002 and i want to convert it to a > string 20021126. > > it's probably possible to write a function to do this by creating > a table of months to numbers but I was hoping that > there was some kind of python function i could use instead ? time.strptime does what you want. http://www.python.org/dev/doc/devel/lib/module-time.html#l2h-1676 yours, Gerrit. -- 11. If the owner do not bring witnesses to identify the lost article, he is an evil-doer, he has traduced, and shall be put to death. -- 1780 BC, 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 g2h5dqi002 at sneakemail.com Mon Jun 16 22:34:17 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 17 Jun 2003 14:34:17 +1200 Subject: Python articles In-Reply-To: <3eecd89a$0$49116$e4fe514c@news.xs4all.nl> References: <3eecd89a$0$49116$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > No trouble here with Mozilla 1.3.1, and Konqueror. > > I did have to accept an invalid SSL certificate though... I accepted the certificates and then got error number -8173 attempting to establish an encrypted connection. (Mozilla 1.3b) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From tjreedy at udel.edu Sun Jun 8 15:30:10 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 8 Jun 2003 15:30:10 -0400 Subject: a = b = 1 just syntactic sugar? References: <2259b0e2.0306080415.52a8ba8@posting.google.com> Message-ID: "Michele Simionato" wrote in message news:2259b0e2.0306080415.52a8ba8 at posting.google.com... > "Terry Reedy" wrote in message news:...> > > > So if we are to make special syntactic rules for lambda, I would like > > to make them less powerful by restricting the expression body to > > lambda-less expressions > > Cool! Unfortunately, this cannot be done because it would break existing > code I was suggesting this as a possibility for Python 3, which *will* break existing code by removing deprecated features. How much and when is still up in the air. >(most of it in Python obfuscated code contests ;-). That was my intention ;-) > Anyway, it is a nice idea and I like it! At least one of the PyDev regulars (forget who) has suggested, I believe seriously, that lambda be one of the things deprecated (in the last of 2.x series) and then removed in 3.0. The above is an in-between suggestion. Terry J. Reedy From p-abel at t-online.de Wed Jun 11 04:37:16 2003 From: p-abel at t-online.de (Peter Abel) Date: 11 Jun 2003 01:37:16 -0700 Subject: Scrollable Tkinter widget not threadsafe? Message-ID: <13a533e8.0306110037.6611eefa@posting.google.com> Hi all, Im developping an controlling application on an embedded linux. It gets its input from multiple sensors and other applications via a data-interface. The ouput goes to a data-interfaces, from where it is displayed on a monitor. At the moment Im developping under W2k and Python 2.2.2. I simulate the sensors by Tkinter-widgets (Scales, Radiobuttons). The output is directed to the same Tkinter-window to output-widgets (Listboxes, Labels). The Testsuite under W2k consists of 3 parts: 1) The controlling application, which runs in a thread 2) The Tkinter-window, which runs in a thread too 3) A main-program, which glues 1) and 2) togather. All works fine. Now the number of output-widgets is growing, and it became necessary that the Tkinter-window would be scrollable. With some effort I made it work with the help of Fredrik Lundh's example **Autohiding Scrollbars** at http://effbot.org/zone/tkinter-autoscrollbar.htm. But I couldn't make it work with threads. Either it is not possible or I made some mistake when calling the thread. The following code snippet represents the kernel of my problem. It works, when with_threads is False but not when True. Any help would be appriciated. import Tkinter,thread,time #==================================== class FrameScollTest (Tkinter.Frame): #==================================== """ A class to Test scrolling of widgets with several child-widgets """ #----------------------------------------------------------------- def __init__ (self, master = None, **packOptions): #----------------------------------------------------------------- Tkinter.Frame.__init__ (self, master) self.canvas = Tkinter.Canvas (self,width=80,height=50,bg='white',relief='flat') self.vscroll = Tkinter.Scrollbar (self,orient='vertical',command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.vscroll.set) self.container = Tkinter.Frame (self.canvas) self.label_1 = Tkinter.Label (self.container, { 'bg' : 'green', 'relief' : 'ridge', 'text' : 'GREEN 1' }) self.label_2 = Tkinter.Label (self.container, { 'bg' : 'white', 'relief' : 'ridge', 'text' : 'WHITE 2' }) self.label_3 = Tkinter.Label (self.container, { 'bg' : 'red', 'relief' : 'ridge', 'text' : 'RED 3' }) self.label_4 = Tkinter.Label (self.container, { 'bg' : 'blue', 'relief' : 'ridge', 'text' : 'BLUE 4' }) self.label_5 = Tkinter.Label (self.container, { 'bg' : 'yellow', 'relief' : 'ridge', 'text' : 'YELLOW 5' }) #=============================== # GRIDDING #=============================== self.canvas.grid(row=0,column=0,sticky='nesw') self.vscroll.grid (row=0, column=1, sticky='ns') self.container.grid({ 'in' : self.canvas, 'column' : '0', 'row' : '0', 'sticky' : 'nesw' }) self.label_1.grid({ 'in' : self.container, 'column' : '0', 'row' : '0', 'sticky' : 'nesw' }) self.label_2.grid({ 'in' : self.container, 'column' : '0', 'row' : '1', 'sticky' : 'nesw' }) self.label_3.grid({ 'in' : self.container, 'column' : '0', 'row' : '2', 'sticky' : 'nesw' }) self.label_4.grid({ 'in' : self.container, 'column' : '0', 'row' : '3', 'sticky' : 'nesw' }) self.label_5.grid({ 'in' : self.container, 'column' : '0', 'row' : '4', 'sticky' : 'nesw' }) # The widget itself self.rowconfigure (0, {'weight' : 1, 'minsize' : 10}) # -- self.columnconfigure (0, {'weight' : 1}) self.columnconfigure (1, {'weight' : 0}) # The canvas self.canvas.rowconfigure(0, weight=1) #-- self.canvas.columnconfigure(0, weight=0) # The container self.container.rowconfigure (0, {'weight' : 0, 'minsize' : 80}) self.container.rowconfigure (1, {'weight' : 0, 'minsize' : 80}) self.container.rowconfigure (2, {'weight' : 0, 'minsize' : 80}) self.container.rowconfigure (3, {'weight' : 0, 'minsize' : 80}) self.container.rowconfigure (4, {'weight' : 0, 'minsize' : 80}) #-- self.container.columnconfigure (0, {'weight' : 0, 'minsize' : 80}) # Make canvas scrollable self.canvas.create_window(0, 0, anchor='nw', window=self.container) self.container.update_idletasks() self.canvas.config(scrollregion=self.canvas.bbox("all")) #--------------------- def show_widget(): #--------------------- global root, activated activated=True print 'in show_widget' root.mainloop() print 'root.mainloop ready ...' activated=False #========================================= if __name__ == '__main__': global root, activated activated = False with_threads = False root=Tkinter.Tk() FrameScollTest (root).pack(fill='both',expand=True) if with_threads: # 1) With thread thread.start_new_thread(show_widget,()) # Give the thread a little time to install time.sleep(2.0) while activated: pass print 'ready with thread ...' else: # 2) Without thread root.mainloop () print 'ready without thread ...' Regards Peter From skip at pobox.com Thu Jun 5 23:33:30 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 5 Jun 2003 22:33:30 -0500 Subject: Persistent sets Message-ID: <16096.2954.202393.226411@montanaro.dyndns.org> Related to the trigraph thread, I thought it would be nice if the Set output by the three-character n-gram generator was persistent because it takes awhile to generate. I was pleasantly surprised to see how easy it is: import sets import shelve class PersistentSet(sets.Set): def __init__(self, file, iterable=None): self._data = shelve.open(file) if iterable is not None: self._update(iterable) I haven't tried it for anything other than the little generator, and while obviously slower to generate than if I had used a regular set, it saves a lot of startup time when you have a large mostly read-only set. >>> s = psets.PersistentSet("trigraphs") >>> "abc" in s True >>> "xzz" in s False >>> "aaa" in s False The above trigraph set contains 8106 elements and was generated from /usr/share/dict/words, which on my current machine contains 234937 words. Skip From marcus.bergmann at isst.fhg.de Tue Jun 17 08:54:30 2003 From: marcus.bergmann at isst.fhg.de (Marcus Bergmann) Date: Tue, 17 Jun 2003 14:54:30 +0200 Subject: insert thousands separators (solved) References: <3EE9E548.9010701@isst.fhg.de> Message-ID: <3EEF0F86.6050108@isst.fhg.de> Problem is solved. I took the following code (from Bengt Richter): def commafy(self,val): sign, val, rest = '-'[:val<0], str(abs(val)), [] while val: val, rest = val[:-3], ([val[-3:]] + rest) return sign + '.'.join(rest) Thank to all :-) Regards, Marcus Marcus Bergmann wrote: > Hi, > > how can I insert thousands separators into an integer or a string, e.g. > 1000000 to 1.000.000? > > Thanks and cheers, > Marcus From skip at pobox.com Fri Jun 20 12:07:41 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 20 Jun 2003 11:07:41 -0500 Subject: Using OS time In-Reply-To: <200306201645.16587.tireseas@onetel.com> References: <20030620152602.22899.77521.Mailman@mail.python.org> <200306201645.16587.tireseas@onetel.com> Message-ID: <16115.12621.163636.630622@montanaro.dyndns.org> Andy> The problem: Andy> I am writing a rather simple guessing game (a random number is Andy> generated, user has to guess the number). I am wanting to Andy> introduce a time-limit on the game-play so that the user has - Andy> e.g. 60 seconds - within which to guess the correct number Andy> otherwise they lose. How about signal.alarm()? alarm(...) alarm(seconds) Arrange for SIGALRM to arrive after the given number of seconds. You will obviously have to have a signal handler set up to recover from the signal. You'll have to experiment to see if the signal will terminate the call to raw_input() (or whatever you're using to gather user input). Skip From simonb at webone.com.au Fri Jun 6 16:35:45 2003 From: simonb at webone.com.au (Simon Burton) Date: Sat, 07 Jun 2003 06:35:45 +1000 Subject: Singleton class: what is the purpose? References: <20030605111536.GA3436@nl.linux.org> Message-ID: On Fri, 06 Jun 2003 01:49:42 +0000, Gordon Scott wrote: > Is there any difference between the Borg and the Flyweight? Sound like the > same thing. > > Gordo > My take: A Flyweight would be an instance shared, where there are many flyweights. If there is only one flyweight then it's a singleton. ints (and the other immutables) are flyweights in python. Simon Burton. From fperez528 at yahoo.com Thu Jun 12 18:39:21 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Thu, 12 Jun 2003 16:39:21 -0600 Subject: Glue code References: <2996386.1055452530@dbforums.com> Message-ID: DB_RobertP wrote: > > What systems do people use to easily make C/C++ code visible to Python? > I'm currently checking out Swig, but I've heard others mentioned. If > anyone has any experience with these systems, could you recommend one to > look into? Also, any other general pointers when trying to extend C/C++ > code to python sctipts would be greatly appreciated. > Thanks! > Robert > > -- > Posted via http://dbforums.com I'm a big weave.inline fan (http://scipy.org). I'm attaching here some example code which can get you off the ground. But inline is meant for short snippets, if you want to wrap a large library and freely mix C++ and python into your object structure, boost.python is the way to go. Here's an excellent overview I just read today: http://www.cuj.com/documents/s=8188/cuj0307abrahams/ Best, f. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: weave_examples.py URL: From peter at engcorp.com Sun Jun 8 14:10:10 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 08 Jun 2003 14:10:10 -0400 Subject: program path References: <3EE28ABC.7D6DB511@engcorp.com> <3EE2AD6E.933C6ED7@engcorp.com> <3EE36B46.343D8774@engcorp.com> Message-ID: <3EE37C02.3E43BBB@engcorp.com> Gerhard H?ring wrote: > > Peter Hansen wrote: > > Can anyone with access to a WinNT/XP machine that can invoke > > scripts without explicitly specifying "python.exe" in the > > command line add to this? > > #v+ > C:\>copy con: tmp\x.py > import sys > print sys.argv[0] > ^Z > 1 file(s) copied. > > C:\>tmp\x.py > C:\tmp\x.py > > C:\>ver > > Microsoft Windows XP [Version 5.1.2600] > #v- Thanks Gerhard, but could you please try running it via a directory available only via PATH? Explicitly specifying the directory should always lead to sys.argv[0] containing the "as invoked" name, but we're not sure what would happen if it's found via the PATH. -Peter From martin at v.loewis.de Thu Jun 19 04:41:16 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 19 Jun 2003 10:41:16 +0200 Subject: Installing Python on Solaris 9 References: <2c1dda69.0306190001.53837879@posting.google.com> Message-ID: solarisboy007 at yahoo.com (Solaris Boy) writes: > I set the environment variables and compiled the stuff. > > Python was installed in /usr/local/Python-2.2.3/python. Can you report how exactly you have 'installed' python? In particular, did this involve invoking 'make install'? It appears that you did not install Python, but merely built it. If you had installed it, the python executable would end up in a 'bin' directory. > Also How do I quit out of python Ctrl-D, as with any other Unix program. Regards, Martin From just at xs4all.nl Fri Jun 20 17:55:00 2003 From: just at xs4all.nl (Just) Date: Fri, 20 Jun 2003 23:55:00 +0200 Subject: os.listdir() References: Message-ID: In article , "manuel" wrote: > > It's written in C, in Modules/posixmodule.c. os.py >imports it. > > Thanks. > > Exist another method to read the files > in a directory? I want write a script for Blender, > and because the OS module isn't builtin, and I've need > only this function, I want write a very simple > python class to read only the files in a dir. > > It's possible? If you can't "import os" in Blender, something is wrong... Just From dsavitsk at ecpsoftware.com Mon Jun 2 01:45:32 2003 From: dsavitsk at ecpsoftware.com (dsavitsk) Date: Mon, 02 Jun 2003 05:45:32 GMT Subject: dictionary issue (and maybe PEP ... depending on the answer) Message-ID: <0wBCa.651$ig1.627675@newssrv26.news.prodigy.com> (Python 2.2.1 on FreeBSD 4.7 being used via mod_python 3) I have a dictionary at the top of a module that looks like this _months = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'} never mind, for now, that there are proably better ways to do what the dict obviously does. anyhow, I get a list of the months by doing this >>> [_months[i] for i in _months.keys()] The issue is, this consistently returns the months in order. I don't see any obvious reason that it does, but I can't get it to fail. So,I am wondering if there is a reason, or is it serendipity. Assuming that there is not a good reason, the PEP idea is adding a sorted_keys() method to dictionaries which would just return the keys in the same order they would be in by doing this. >>> l = d.keys() >>> l.sort() The advantage is that using dictionary keys in list comprehensions would be easier, but other than that it is not too big a deal. Thanks, Doug From g2h5dqi002 at sneakemail.com Thu Jun 12 02:34:08 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Thu, 12 Jun 2003 18:34:08 +1200 Subject: Octets calculation? In-Reply-To: References: <65eFa.634621$Si4.577158@rwcrnsc51.ops.asp.att.net> <0modevgetee4eh0pg2k7s4qhacq7s6bbkm@4ax.com> Message-ID: William Yeo wrote: > Ah yes, and remember Honeywell in the glorious 70's whose systems used > 36 bits arranged as 6 6-bit bytes or 4 9-bit bytes depending on whether > you're in batch or timesharing mode. But were these actually called "bytes"? That's the crucial thing here. I can remember such units being referred to as "characters" or some such, but not "bytes". -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From justinjohnson at fastmail.fm Sun Jun 29 10:24:25 2003 From: justinjohnson at fastmail.fm (Justin Johnson) Date: Sun, 29 Jun 2003 08:24:25 -0600 Subject: struct.pack and perl's 'B' code for bitstrings In-Reply-To: <20030628084946.GA78521@hishome.net> References: <20030627201935.3669537E73@www.fastmail.fm> <20030628084946.GA78521@hishome.net> Message-ID: <20030629142425.86F7C38292@www.fastmail.fm> Yes, I meant 'featureful'. Thank you for your advice. This helpful for me. Part of the problem is I haven't done much with byte/bit manipulation, so when I don't have the capabilities I'm used to I have a hard time being inovative. :-( Thanks much. -Justin On Sat, 28 Jun 2003 04:49:46 -0400, "Oren Tirosh" said: > On Fri, Jun 27, 2003 at 02:19:35PM -0600, Justin Johnson wrote: > > Is there anything equivalent to perl's pack code B, which allows you to > > specify bits to pack? For example, in perl, pack('B8', '00000010') will > > return 8 bits exactly as the bit string appears. I don't see any similar > > codes in struct.pack. In general struct.pack is not as robust as perl's > > pack function. > > Are you using the word 'robust' to mean 'featureful'? > > > Is there a better version of struct somewhere, or how are > > people overcoming some of these problems? > > I've heard of some alternative version of struct. I've never checked if > they have bitstring options. When I need something like this I just use > the int or long constructor with radix 2: > > >>> struct.pack('B', int('00000010', 2)) > '\x02' > > >>> struct.pack('>H', int('0001001000011000', 2)) > '\x12\x18' > > Oren > From staschuk at telusplanet.net Wed Jun 18 12:52:54 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 18 Jun 2003 10:52:54 -0600 Subject: does lack of type declarations make Python unsafe? In-Reply-To: <87ptlbml4b.fsf@pobox.com>; from jjl@pobox.com on Wed, Jun 18, 2003 at 05:00:20PM +0100 References: <3064b51d.0306151228.22c595e0@posting.google.com> <1055736914.49032@yasure> <3EEDEDBE.BCB56D6E@engcorp.com> <873ci7o7c0.fsf@pobox.com> <87ptlbml4b.fsf@pobox.com> Message-ID: <20030618105254.I637@tibia.amotlpaa.bogus> Quoth John J. Lee: > Steven Taschuk writes: [...] > > But I find it greatly eases > > debugging and one-off data munging tasks. > > That's what I was referring to, and I assume David too. If any > function or class is more than say 5 lines, I use emacs. [...] Hm... then I think I'm missing something. When debugging, all the substantial code is written elsewhere; I just import it and fiddle. When data munging, I load the data into memory and fiddle. Each fiddle is almost invariably a single line of code, so errors are not big setbacks. > [...] It's still > convenient, but can be replaced quite easily with a good IDE, I think. I'm not sure how an IDE would help with interactive data-munging, unless it provides an environment very similar to the one which the interactive prompt provides. -- Steven Taschuk o- @ staschuk at telusplanet.net 7O ) " ( From mhammond at skippinet.com.au Thu Jun 12 10:15:02 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 12 Jun 2003 14:15:02 GMT Subject: pythonCOM with Flash In-Reply-To: References: Message-ID: Bradley Schatz wrote: > Hi, > > I am attempting to use Flash as a UI for a python program. I have > successfully prototyped this using VB/Flash, and am not trying to convert it > over to work with python. > > My problem is this, when I run the following code (attached below) nothing > happens. > > I assume that the Flash activex component needs to be placed in some > container to be seen, as I am not seeing any window come up when I run this. > > Could anyone suggest how to embed this into a container? Look at the Pythonwin OCS demos, under the pywin\demos directory. wxPython also has some ActiveX container support, but I have never used it. Mark. From peter at engcorp.com Thu Jun 19 08:46:41 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 19 Jun 2003 08:46:41 -0400 Subject: Binary adresse for localhost References: <3ef18bc1$0$14312$7a628cd7@news.club-internet.fr> Message-ID: <3EF1B0B1.A5181869@engcorp.com> Benoit BESSE wrote: > > for "224.4.0.1" the binary adresse is 0xe0040001L. Actually, that's a hexadecimal value, not a binary one. The difference is that binary refers to base 2, while hexadecimal (hex==6, dec==10) refers to base 16. Each pair of digits, in this form, represents 8 binary bits, for a total of 32 (aka a "long word"). > What is the corresponding convertion for 127.0.0.1. Python's hex() method is helpful here: hex(127) == 7f the same way that hex(224) is e0. -Peter From adalke at mindspring.com Fri Jun 13 12:27:44 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 13 Jun 2003 10:27:44 -0600 Subject: Type hierarchy References: Message-ID: Gerrit Holl: > But wouldn't a type hierarchy be very useful for other types as > well? For example, checking whether something is a number, currently > needs isinstance(o, int) or isinstance(o, long), or float... although > ints and longs are going to be the same. Would it be wise to let those > have common base types? I haven't needed that discrimination ... at least not that I can remember. I have done some type-based dispatching, which was either very specific (as for serialization of different data types) or special cased only one type, as in def read_it(file): if isinstance(file, string): file = open(file) .... The basestring type is useful because I want to handle byte strings and unicode strings equivalently in many cases. But numbers as you mention? No. > For example: Suppose I have this: class Headers: .... def __getitem__(self, i): if isinstance(i, int): return self._headers_list[i] return self._headers_dict[i] def __setitem((self, k, v): self._headers_list.append(v) self._headers_dict[k] = v def __iter__(self): return iter(self._headers_list) def keys(self): return self._headers_dict.keys() ... This is a specialized dict-like / list-like with mixed mutability. (dict is more mutable, but list isn't immutable because elements can be changed from underneath it.) So this wouldn't be one of your types, but could be used by code which overly asserts type checking. Which would be sad. Except *possibly* for the existance of a "number" type, I don't think this suggestion gives any useful power or flexibility to Python, while encouraging ex-statically-typed-language programmers to do unneeded and detrimental type checks. Andrew dalke at dalkescientific.com From bokr at oz.net Sun Jun 1 04:37:02 2003 From: bokr at oz.net (Bengt Richter) Date: 1 Jun 2003 08:37:02 GMT Subject: Tkinter.Canvas.create_line.coords References: Message-ID: On Sun, 1 Jun 2003 09:53:20 +0200 (CEST), Arnd Baecker wrote: >Hi, > >I have a question concerning modifying a line created >within a Canvas: > >It boils down to that (for `plot` being a Canvas) > self.plot.coords(self.line,10,0,10,10,80,100,100,200) >works, whereas > liste=[10,0,10,10,80,100,100,200] > self.plot.coords(self.line,liste) I would try prefixing a '*' on the theory that the function is defined like foo below: self.plot.coords(self.line, *liste) Notice: >>> def foo(first, *rest): print first,rest ... >>> foo(1,2,3,4) 1 (2, 3, 4) >>> r = [2,3,4] >>> foo(1,r) 1 ([2, 3, 4],) Note what happened in the preceding: the entire r simply became the first and only arg in the args tuple, which has length 1 instead of 3. >>> foo(1,*r) 1 (2, 3, 4) Compare this result to the original. We have unpacked r into the arg sequence, so the r elements show up as if they had been passed as separate args. >raises the error: > self.tk.splitlist( > TclError: bad screen distance "[10," >((Maybe the example below more clearly demonstrates what I mean here.)) > >Actually, help(Tkinter.Canvas.coords) gives > coords(self, *args) unbound Tkinter.Canvas method looks like foo above. [...] If the above works, we can go on to the next problem, which someone else will have to get into if it's going to happen tonight ;-) Regards, Bengt Richter From drmental at yahoo.com Sat Jun 21 11:32:42 2003 From: drmental at yahoo.com (Thunder Perfect Mind) Date: 21 Jun 2003 08:32:42 -0700 Subject: Problems retreiving double from database References: Message-ID: That explains it.... Thank you so much dr//\//\ From marks.pryorSHRUB at CHENEYverizon.net Fri Jun 27 01:11:04 2003 From: marks.pryorSHRUB at CHENEYverizon.net (Mark S Pryor) Date: Fri, 27 Jun 2003 05:11:04 GMT Subject: win32ui screen capture References: Message-ID: Hi, wrote in message news:o43nfvsc8r4q934p709l1g3thtoube37qn at 4ax.com... > i, > I have trying to code a small console app that will > allow a user to select a window and then create a > screen capture of the window. I haven't been able to > figure out how to do the screen capture part. The > code is as follows, the commented out lines at the end > are things I have tried, but don't work. Whenever I > try to create a compatibe Bitmap or DC it comes back > with an error as > win32ui: CreateCompatibleDC failed > or > AttributeError: CreateCompatibleDC > Any help would be greatly appreciated. > > import win32gui > import win32ui > > numWindows = 0 > windows = [] > winDict = {} > windowsText=[] > inc = 0 > > def _MyCallback( hwnd, extra ): > extra.append(hwnd) > > > win32gui.EnumWindows(_MyCallback, windows) > for i in windows: > if win32gui.IsWindowVisible(i): > if win32gui.IsWindowVisible: > windowsText.append(i) > winDict[numWindows] = i > numWindows +=1 > > > > > print "Please select a window to capture" > for window in windowsText: > windowText = win32gui.GetWindowText(window) > print inc, windowText > inc += 1 > > selection = input() > > print win32gui.GetWindowText(winDict[selection]) > myDC = win32ui.CreateDCFromHandle(winDict[selection]) > win32gui.SetForegroundWindow(winDict[selection]) > win_sz = win32gui.GetClientRect(winDict[selection]) > myBitMap = win32ui.CreateBitmap() > #myMemDC = win32ui.CreateCompatibleDC(myDC) > #myBitMap.BitBlt((0,0),(win_sz[2],win_sz[3],myDC,(0,0),0)) > #myBitMap.CreateCompatibleBitMap(myDC,win_sz[2], win_sz[3]) > #myBitMap.CreateCompatibleDC(myDC) > > > Thanks, > Rob You may be able to make this work ... eventually. However, circulating in the Python community you will find the C file _grabscreen.c with all the same API calls you are trying to use in standard C. see this post http://groups.google.com/groups?selm=mailman.1011217637.9447.python-list%40p ython.org It explains how to compile the module _grabscreen.pyd with MS Visual C. I was able to get a screen shot script in 10 minutes after I read this post. If you don't have a grabscreen module already, see this ZIP file for the relevant files. Use the file ImageGrab1.py to make a screen capture of the desktop and save the results as PNG. (for ActivePython 2.2 only) http://mysite.verizon.net/res1ur2j/GrabScreen.zip you will need PIL from http://www.pythonware.com/products/pil/ hth, Mark Pryor From gerrit at nl.linux.org Wed Jun 4 05:18:29 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 4 Jun 2003 11:18:29 +0200 Subject: Possible PEP: Improve classmethod/staticmethod syntax In-Reply-To: <1ieDa.35049$DV.60225@rwcrnsc52.ops.asp.att.net> References: <20030603164521903-0400@braeburn.themorgue.org> <1ieDa.35049$DV.60225@rwcrnsc52.ops.asp.att.net> Message-ID: <20030604091829.GB2636@nl.linux.org> Hi, Bryan schreef op woensdag 4 juni om 06:11:23 +0000: > ok, i understand what you mean now. but, in a way, it seems that we are > playing symantec games here. from a programmers prespective, it looks and > feels like a keyword. > > style 1: > def myMethod(args) [staticmethod]: > blah, blah, blah > > style 2: > def staticmethod myMethod(args): > blah, blah, blah style 3: def myMethod(args)(staticmethod): blah, blah, blah style 4: def staticmethod(myMethod(args)): blah, blah, blah BTW, what would happen if a modifier is applied that doesn't return a callable (like def foo(args)(str):)? Would it raise an exception or bind a string to 'foo', ignoring the contents of the 'def' declaration? > but i have to vote -1 on style one, +1 on style 2, +0 keeping it the way it style 1: -1 style 2: +0 style 3: +1 style 4: +0 for me yours, Gerrit. -- 149. If this woman does not wish to remain in her husband's house, then he shall compensate her for the dowry that she brought with her from her father's house, and she may go. -- 1780 BC, 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 tim.one at comcast.net Sat Jun 21 23:00:51 2003 From: tim.one at comcast.net (Tim Peters) Date: Sat, 21 Jun 2003 23:00:51 -0400 Subject: random function with strings In-Reply-To: <3ef51a51$0$8029$79c14f64@nan-newsreader-01.noos.net> Message-ID: [messageboardfan1 at yahoo.com] > I have a function that goes through a directory and I would like to > remove randomly one of the files contained in that directory. I > checked out the random() function in the documentation but it only > deals with integers. random.choice(seq) returns an element from the its sequence argument. > here's what my function looks like: > > with os.path.walk > def delete_backups(arg, dirname, names): > /*here I need a function that select a file randomly and, let's > call it "name", then I do this:*/ > os.remove(os.path.join(dirname, name)) > > any suggestions? Do random.choice(names) to pick a name at random. Note that this will fail if names is empty, and won't do what you hope for if the name returned happens to be the name of a contained directory. From missive at frontiernet.net Fri Jun 20 16:21:29 2003 From: missive at frontiernet.net (Lee Harr) Date: Fri, 20 Jun 2003 20:21:29 GMT Subject: Newbie on importing References: Message-ID: > That example is still less than clear... > >>import sys >> >>Imports the module named 'sys'. > > Which get me access to what in 'sys'? > >>from sys import * >> >>Imports all names from sys (including names referring to functions). > > Likewise, what additional thing are available when doing this? > Is 'import sys' a subset of 'from sys import *'? > > $python Python 2.2.3 (#1, Jun 9 2003, 18:01:50) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> dir() ['__builtins__', '__doc__', '__name__'] >>> import sys >>> dir() ['__builtins__', '__doc__', '__name__', 'sys'] >>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',\ '__stdin__', '__stdout__', '_getframe', 'argv', 'builtin_module_names',\ 'byteorder', 'copyright', 'displayhook', 'exc_info', 'exc_type',\ 'excepthook', 'exec_prefix', 'executable', 'exit', 'getdefaultencoding',\ 'getdlopenflags', 'getrecursionlimit', 'getrefcount', 'hexversion',\ 'maxint', 'maxunicode', 'modules', 'path', 'platform', 'prefix',\ 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags', 'setprofile',\ 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version',\ 'version_info', 'warnoptions'] >>> $python Python 2.2.3 (#1, Jun 9 2003, 18:01:50) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> dir() ['__builtins__', '__doc__', '__name__'] >>> from sys import * >>> dir() ['__builtins__', '__doc__', '__name__', 'argv', 'builtin_module_names',\ 'byteorder', 'copyright', 'displayhook', 'exc_info', 'exc_type',\ 'excepthook', 'exec_prefix', 'executable', 'exit', 'getdefaultencoding',\ 'getdlopenflags', 'getrecursionlimit', 'getrefcount', 'hexversion',\ 'maxint', 'maxunicode', 'modules', 'path', 'platform', 'prefix', 'ps1',\ 'ps2', 'setcheckinterval', 'setdlopenflags', 'setprofile',\ 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',\ 'version', 'version_info', 'warnoptions'] >>> From aahz at pythoncraft.com Thu Jun 12 12:59:57 2003 From: aahz at pythoncraft.com (Aahz) Date: 12 Jun 2003 12:59:57 -0400 Subject: why 'lambda' and 'reduce'? References: Message-ID: In article , Manuel Garcia wrote: > >If anyone ever asks for what good are 'lambda' and 'reduce', show them >this... Betcha Guido would call it one of the best arguments for rippin' 'em out. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From mwh at python.net Fri Jun 13 07:47:15 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 13 Jun 2003 11:47:15 GMT Subject: Rudeness with names (was Re: interpreted) References: <3EE5BF67.2040201@ghaering.de> <7h3d6hjmpbw.fsf@pc150.maths.bris.ac.uk> Message-ID: <7h37k7qkxtp.fsf@pc150.maths.bris.ac.uk> "Fredrik Lundh" writes: > Michael Hudson wrote: > > > You know Yahoo! Groups used to be eGroups? You know who was the > > brains behind eGroups (and medusa and asyncore and calldll...)? > > Scott Hassan wrote Medusa? Wasn't Sam Rushing at eGroups? Perhaps I should have researched that post... Cheers, M. -- The above comment may be extremely inflamatory. For your protection, it has been rot13'd twice. -- the signature of "JWhitlock" on slashdot From db3l at fitlinxx.com Wed Jun 4 13:53:10 2003 From: db3l at fitlinxx.com (David Bolen) Date: 04 Jun 2003 13:53:10 -0400 Subject: PythonD: 4Suite or Twisted? References: <3eddd372$0$16609$9b622d9e@news.freenet.de> <%RlDa.239$R44.10990@nnrp1.ozemail.com.au> <3mmDa.18175$8g5.301248@news2.e.nsc.no> <3EDE1F04.30539A1A@engcorp.com> Message-ID: Peter Hansen writes: > (...) The core internet components, for example, are quite robust > already, and you will rarely see messages about rewriting/refactoring > those pieces. Just one small comment, since I generally don't see it mentioned in postings about Twisted - the underlying protocol support for internet components appear robust in terms of TCP support, but we found that UDP support was much weaker when we last looked at Twisted (not too long ago). To the extent that WAN applications for existing popular protocols are virtually all TCP based, this isn't much of an issue (and probably explains the state of affairs), but if you're thinking of using Twisted for in-house development, it's at least something to be aware of and to check that it has the functionality you need. For example in our case, we use UDP-based systems probably in equal amounts to TCP based systems for in house code. Note that this is far from a knock on Twisted, which is certainly an attractive framework in its own right. But references to its support for network processing generally don't mention the different level of support at the protocol layer. -- David From staschuk at telusplanet.net Thu Jun 26 08:50:15 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 26 Jun 2003 06:50:15 -0600 Subject: Reading a binary file In-Reply-To: <3EFABDE0.7090205@semafor.ch>; from mas@semafor.ch on Thu, Jun 26, 2003 at 11:33:20AM +0200 References: <3EFAA842.1070505@semafor.ch> <20030626083305.GF17335@frobozz> <3EFABDE0.7090205@semafor.ch> Message-ID: <20030626065015.A329@tibia.amotlpaa.bogus> Quoth Sorin Marti: [...] > That is not exactly what I meant. I've found a solution (a is the binary > data): > > b = binascii.hexlify(a) > > For example it gives me C8 which is a HEX-Value. How to change this one > into a decimal? (The decimal should be 130, right?) 200, actually; hex C = 12, so hex C8 = 12*16 + 8 = 200. Each byte represents a number in the range [0..255]. Those numbers may be obtained with the ord function, as Andrew noted: >>> bytes = file('foo.py', 'rb').read(10) >>> bytes 'def inplac' >>> map(ord, bytes) [100, 101, 102, 32, 105, 110, 112, 108, 97, 99] These are numbers, so you can, e.g., do arithmetic with them. They are neither hex numbers nor decimal numbers; 'hex' and 'decimal' describe notations by which numbers may be represented, not numbers themselves. So, when you ask for the hex value, it seems you want a string containing characters which represent the number in hexadecimal notation. The hex function does that, again as Andrew noted: >>> numbers = map(ord, bytes) >>> [hex(num)[2:] for num in numbers] ['64', '65', '66', '20', '69', '6e', '70', '6c', '61', '63'] (I've cut out the leading '0x' which this function produces.) As you've discovered, binascii.hexlify does this all in one step -- turns a string containing bytes into a string containing hexadecimal digits representing the bytes: >>> import binascii >>> binascii.hexlify(bytes) '64656620696e706c6163' If, for some reason, you wanted to obtain numbers from such a string, you could do it this way, for example: >>> def hex2numbers(s): ... numbers = [] ... for i in range(0, len(s), 2): ... numbers.append(int(s[i:i+2], 16)) ... return numbers ... >>> hex2numbers(binascii.hexlify(bytes)) [100, 101, 102, 32, 105, 110, 112, 108, 97, 99] -- Steven Taschuk staschuk at telusplanet.net "I tried to be pleasant and accommodating, but my head began to hurt from his banality." -- _Seven_ (1996) From fredrik at pythonware.com Sat Jun 28 17:45:00 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 28 Jun 2003 23:45:00 +0200 Subject: (Numeric) should -7 % 5 = -2 ? References: <87k7b6cf3d.fsf_-_@schedar.com> Message-ID: Stan Heckman wrote: > Is the following behavior expected, or have I broken my Numeric > installation somehow? > > $ python > >>> import Numeric > >>> Numeric.__version__ > '23.0' > >>> -7 % 5 > 3 > >>> Numeric.array(-7) % 5 > -2 > >>> Numeric.remainder(-7, 5) > -2 looks like Numeric implements C semantics, which is different from how Python does it. From mis6 at pitt.edu Wed Jun 11 10:46:10 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 11 Jun 2003 07:46:10 -0700 Subject: PEP 318 - Function Modifier Syntax References: <20030609081617512-0400@braeburn.themorgue.org> <2259b0e2.0306100802.c805a50@posting.google.com> Message-ID: <2259b0e2.0306110646.50ea8242@posting.google.com> Robin Becker wrote in message news:... > In article <2259b0e2.0306100802.c805a50 at posting.google.com>, Michele > Simionato writes > .... > > in this scheme you're notationally overriding the __metaclass__ for the > class, is there a default __metadef__ concept to go along with the > methods? > > is > > class A: > __metadef__ = traced > > ...... > > could make all of A's methods 'traced'. > Esplicit is better than implicit and I would prefer to write an explicit metaclass like that: >>> from types import FunctionType >>> class Traced(type): def __init__(cls,name,bases,dic): for name,func in dic.iteritems(): if isinstance(func,FunctionType): setattr(cls,name,traced(func)) Notice that typically one does NOT want to trace all functions, but only a given subset. The explicit metaclass gives much more control. For instance I could modify it to trace only special methods, or only staticmethods, or any combination I wish. Michele From dwblas at yahoo.com Thu Jun 5 15:49:05 2003 From: dwblas at yahoo.com (DavidW Blaschke) Date: Thu, 5 Jun 2003 12:49:05 -0700 (PDT) Subject: data base Message-ID: <20030605194905.12276.qmail@web21606.mail.yahoo.com> I prefer metakit over SQLLite. As I understand it, SQLLite is an interface to gdbm. Metakit is a step up but is still easy to use. But it is personal preference, of course. Search for database on freshmeat and you'll probably find several options. D.W. > --- In python-list at yahoogroups.com, "Alex" > wrote: > > Hi All, > > > > I'm newbie > > > > What is the cross-platform/free data base that I > can use in my > project? > > > > The data base not need of server db such as SQL > server/Oracle/mySql, > but > > like a MS Access. > > > > > > Thank you, > > Alex - Italy > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From andersjm at dancontrol.dk Mon Jun 2 04:19:34 2003 From: andersjm at dancontrol.dk (Anders J. Munch) Date: Mon, 2 Jun 2003 10:19:34 +0200 Subject: Defensive programming References: Message-ID: <3edb089e$0$76130$edfadb0f@dread11.news.tele.dk> "Tim Peters" wrote: > Sure. All dict implementations (hash tables) have O(N**2) worst-case > behavior, over a sequence of N inserts and/or lookups, provoked by a > sufficiently nasty set of N keys. A hash table with balanced binary tree collision resolution has O(N logN) worst case. Not that I see any way of using that for Python dicts. - Anders From alanmk at hotmail.com Fri Jun 13 09:37:00 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 13 Jun 2003 14:37:00 +0100 Subject: OnFileOpent(self, event): References: <3EE9B807.491924C6@hotmail.com> <3EE9BF83.3421667C@engcorp.com> Message-ID: <3EE9D37C.C19FA8EB@hotmail.com> Alan: >> This is a family newsgroup after all, isn't it? Don't we get high-school >> kids and younger around here? Peter: > It was probably a high-school kid asking the question! :-) In any case, > would it make you feel better to know that the vast majority of people > who would be offended by that are the adults, Oh no! You're right, I've turned into a grumpy 'dult! When did that happen? :-) > not the kids who have > grown up hearing the phrase in every TV show and movie they've ever > watched? ;-) Hopefully, here in c.l.p, we can help the youngsters to find more eloquent and elegant ways to say and express what they're thinking :-)& cheers, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From mis6 at pitt.edu Sun Jun 8 12:24:44 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 8 Jun 2003 09:24:44 -0700 Subject: solving the metaclass conflict References: <2259b0e2.0306070629.7f5fcad7@posting.google.com> <25b5433d.0306071443.63b27df6@posting.google.com> Message-ID: <2259b0e2.0306080824.13c15a91@posting.google.com> pje at telecommunity.com (Phillip J. Eby) wrote in message news:<25b5433d.0306071443.63b27df6 at posting.google.com>... > mis6 at pitt.edu (Michele Simionato) wrote in message news:<2259b0e2.0306070629.7f5fcad7 at posting.google.com>... > > I have just posted a recipe on the online Cookbook that could be of interest > > for metaclasses users. > > > > ---------------------------------------------------------------------------- > > > > Description: > > > > Any serious user of metaclasses has been bitten at least once by the > > infamous metaclass/metatype conflict. Here I give a general recipe > > to solve the problem, as well as some theory and some examples. > > > > --> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204197 > > I think I have fixed the meta-metaclass conflict and the other issue with unneeded metaclasses, without adding additional lines. Here is the last version of my class factory: # noconflict.py def memoize(f): """This closure remembers all f invocations""" argskw,result = [],[] def _(*args,**kw): akw=args,kw try: # returns a previously stored result return result[argskw.index(akw)] except ValueError: # there is no previously stored result argskw.append(akw) # update argskw result.append(f(*args,**kw)) # update result return result[-1] # return the new result _.argskw=argskw #makes the argskw list accessible outside _.result=result #makes the result list accessible outside return _ def clsfactory(*metas,**options): """Class factory avoiding metatype conflicts. The invocation syntax is clsfactory(M1,M2,..,priority=1)(name,bases,dic). If the base classes have metaclasses conflicting within themselves or with the given metaclasses, it automatically generates a compatible metaclass and instantiate it. If priority is True, the given metaclasses have priority over the bases' metaclasses""" priority=options.get('priority',False) # default, no priority trivial=lambda m: sum([issubclass(M,m) for M in metas],m is type) # hackish!! m is trivial if it is 'type' or, in the case explicit # metaclasses are given, if it is a superclass of at least one of them def generatemetaclass(bases,metas,priority): metabases=tuple([mb for mb in map(type,bases) if not trivial(mb)]) metabases=(metabases+metas, metas+metabases)[priority] metaname="_"+''.join([m.__name__ for m in metabases]) if not metabases: # trivial metabase return type elif len(metabases)==1: # single metabase return metabases[0] else: # multiple metabases return clsfactory()(metaname,metabases,{}) generatemetaclass=memoize(generatemetaclass) return lambda n,b,d: generatemetaclass(b,metas,priority)(n,b,d) Notice that I am not going to change the Cookbook recipe yet, since I haven't tested very well this new version. However, it seems to be working better than the previous one: # solving the meta-metaclass conflict class MM1(type): pass class MM2(type): pass class M1(type): __metaclass__=MM1 class M2(type): __metaclass__=MM2 class A: __metaclass__=M1 class B: __metaclass__=M2 class C(A,B): __metaclass__=clsfactory() print C,type(C),type(type(C)) #=> # skipping unneeded metaclasses class M(type): pass class M1(M): pass class B: __metaclass__=M class C(B): __metaclass__=clsfactory(M1) print C,type(C),type(type(C)) #=> If somebody found a case where the new version fails due to some bug (which is quite possible ;-), please let me know. Notice that (on purpose) I am not checking against David's example class A(type): pass class B(A): pass class C(type): pass M = _generatemetaclass((),(B,A,C),0) print M #-> since in my view only bases classes should be checked. In other words, I am assuming the user is not perverse and s/he is passing non mutually redundant metaclasses (whereas the metaclasses corresponding to the base classes can be redundant). I could improve this later. Michele From eppstein at ics.uci.edu Thu Jun 19 03:02:11 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 19 Jun 2003 00:02:11 -0700 Subject: Algorithm help per favore References: <2ec1bc1c.0306180746.159679d6@posting.google.com> <3EF0AAFB.DDA5F555@engcorp.com> <3v3Ia.109349$pR3.2389728@news1.tin.it> Message-ID: In article , anton at vredegoor.doge.nl (Anton Vredegoor) wrote: > Nice idea, there seems to be no problem with L an empty list, but > there would be a problem with L a tuple. However that can be > corrected: > > [x for x,y in zip(L,L[1:]+L[:-1]) if x!=y] or list(L[:1]) Still buggy, it drops the last item whenever it's equal to the first and the list has two unequal items. >>> L=[3,1,4,1,5,9,3] >>> [x for x,y in zip(L,L[1:]+L[:-1]) if x!=y] or list(L[:1]) [3, 1, 4, 1, 5, 9] -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From belred1 at yahoo.com Tue Jun 24 22:34:03 2003 From: belred1 at yahoo.com (Bryan) Date: Wed, 25 Jun 2003 02:34:03 GMT Subject: "Newbie" questions - "unique" sorting ? References: <8da5fvsnidpjtblgfj4484spso2t9e6r95@4ax.com> <3ef80342$0$13176$edfadb0f@dread15.news.tele.dk> <3ef816ff$0$13210$edfadb0f@dread15.news.tele.dk> Message-ID: > totally skipping the word count should speed it up - and i believe that > the approach of dict_words[this_word]=dict_words.get(this_word,0) btw. > is a bit faster than doing has_key() or the least of doing: > > if this_word not in dict_words.keys() : > > which aught to be extremely slow on a large dictionary (creating and > dropping lists of thousands + doing a O(n) search over it). And that may > very well be the culprit of the slow run you see.... > > > > > else : > > > > dict_words[ this_word ] += 1 > > > > this is how i check if a key is in a dictionary: if this_word not in dict_words: i believe this doesn't do an O(n) search over it. it's supposed to constant time for every lookup by way of a hash lookup. bryan From robin at jessikat.fsnet.co.uk Sat Jun 7 07:29:28 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 7 Jun 2003 12:29:28 +0100 Subject: finding origin of names Message-ID: Is it possible to determine where a particular name is defined? As an example #a.py v=1 #b.py from a import v >>> import a, b >>> a.v is b.v 1 >>> dir(a) ['__builtins__', '__doc__', '__file__', '__name__', 'v'] >>> dir(b) ['__builtins__', '__doc__', '__file__', '__name__', 'v'] >>> do I have to inspect the code to determine that module a defines v? -- Robin Becker From pythonidae_olivaceous at hotmail.comREMOVE Sun Jun 8 22:04:36 2003 From: pythonidae_olivaceous at hotmail.comREMOVE (Ben Minton) Date: Mon, 9 Jun 2003 02:04:36 +0000 (UTC) Subject: Simple Script to Combine/Seperate Lines of Text Message-ID: Hi All Was wondering how to write a simple script that performs the following task: -------------------------------------------------- airncjrlfojqmxirnxplvmndrhqndj ... e (length n) combined with qpmgktincirzpwncjftewnchdtecru ... f (length n) equals motnciqaxhfyeklpgmchqicngiehfc ... a (length n) and then motnciqaxhfyeklpgmchqicngiehfc ... a (length n) subtract qpmgktincirzpwncjftewnchdtecru ... f (length n) equals airncjrlfojqmxirnxplvmndrhqndj ... e (length n) -------------------------------------------------- uses plain text alphabetic characters only, where initial string of characters is any integer n, upto 1000. I can write this in a flow diagram but don't understand strings enough to do this. Thanks, Ben, Australia From gmduncan at netspace.net.au Thu Jun 19 06:01:39 2003 From: gmduncan at netspace.net.au (Gary Duncan) Date: Thu, 19 Jun 2003 20:01:39 +1000 Subject: Alternatives to Python ? Message-ID: <3EF18A03.3050706@netspace.net.au> There's been occasional not-unfavourable comments in this news-group about the pros-and-cons of other so-called "high-level-languages" like Ruby, and Haskell , and others too. I can't afford to buy more than one such book from the list of HLLs; so what would you suggest ? - Gary (currently reading "Don Qixote - for Dummies" - hilarious ) From gus.tabares at verizon.net Mon Jun 16 19:29:48 2003 From: gus.tabares at verizon.net (Gus Tabares) Date: Mon, 16 Jun 2003 19:29:48 -0400 Subject: Possible bug in setting Windows file permissions? (os.chmod() not working properly?) In-Reply-To: <5ab0af73.0306161517.43dbb96b@posting.google.com> Message-ID: Matt, I do believe os.O_RDWR is specifically for the open() function. Check out the bottom of this page: http://www.python.org/doc/current/lib/os-fd-ops.html HTH, Gus -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org]On Behalf Of Matt Shomphe Sent: Monday, June 16, 2003 7:18 PM To: python-list at python.org Subject: Possible bug in setting Windows file permissions? (os.chmod() not working properly?) I noticed an error when trying to change the file permissions for a file on a Windows (2K) machine. I'm using David Beazley's excellent "Python Essential Reference, 2nd. Ed." as a reference. According to the book (p. 186 for those following along at home), it should be used thusly: import os os.chmod('myReadOnlyFile.txt', os.O_RDWR) Where for os.O_RDWR, you could have any of the modes specified on p. 184. In other words, all the same bitwise-or modes for opening a file. What happens with the above code is: nothing at all. However, the following code *will* work to change a file to be accessible: import os os.chmod('myReadOnlyFile.txt', 33206) So, either I am using the os.chmod() function incorrectly, or there is something wrong elsewhere. Any hints on what's to be done? M@ -- http://mail.python.org/mailman/listinfo/python-list From staschuk at telusplanet.net Wed Jun 11 14:06:56 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 11 Jun 2003 12:06:56 -0600 Subject: Newbie: changing an attribute of objects in a list In-Reply-To: ; from bsimuyandi@africonnect.com on Wed, Jun 11, 2003 at 04:06:01PM +0100 References: Message-ID: <20030611120656.F1157@tibia.amotlpaa.bogus> Quoth Ben Simuyandi: > OK, I've read a bit and I've now changed the code. If anyone would like to > give feedback (better ways of doing it, where am I going wrong) that would > be appreciated: [...] It would be nice to see an example list of objects and the desired result for that list. Without that, here's one possible, simple-minded and completely untested notion: # separate items into groups by x.order d = {} for x in items: d.setdefault(x.order, []).append(x) # resolve conflicts orders = d.keys() orders.sort() for order in orders: # sort descending by age assert len(d[order]) > 0 decorated = [(x.age, -i, x) for x in enumerate(d[order])] decorated.sort() decorated.reverse() sorted = [x for _, _, x in decorated] del decorated # Replace the list d[order] with its oldest element. # Put the remaining elements, in reverse order of age, into # d[order+1], d[order+2], etc. # If one of those is found already to have elements, # just dump all the remaining elements in that list; the # loop over the orders will then pick up at that point. # (Note how this makes it okay to be mutating the dict and # iterating over an independent list of the original keys.) del d[order] for i, x in enumerate(sorted): if order+i not in d: d[order+i] = x else: d[order+i].extend(sorted[i:]) break # assign .order attributes for order, x in d.iteritems(): x.order = order This uses enumerate(), a new built-in in Python 2.3; in 2.2 you can write it yourself, like this: from __future__ import generators def enumerate(items): i = 0 for x in items: yield i, x i = i + 1 -- Steven Taschuk staschuk at telusplanet.net "I tried to be pleasant and accommodating, but my head began to hurt from his banality." -- _Seven_ (1996) From donn at u.washington.edu Tue Jun 17 12:52:24 2003 From: donn at u.washington.edu (Donn Cave) Date: Tue, 17 Jun 2003 09:52:24 -0700 Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> <3EECED65.ACF1A6B7@engcorp.com> <4017400e.0306162016.b0f8c6c@posting.google.com> Message-ID: In article <4017400e.0306162016.b0f8c6c at posting.google.com>, marshall at spamhole.com (marshall) wrote: ... > Most of the code I come across in strong typed languages makes heavy > use of type coercion. So how does typing help if you are just going > to coerce everything? It's unfortunate, but then most of the code in existence today was written for languages that are pretty old now and aren't necessarily the best example of anything. You're right about coercion, in my opinion but also in the opinion of people who have created some more rigorous static typing languages. Of the ones I know about, Haskell and Objective CAML are the most interesting. Haskell being the more interesting language and ocaml the more interesting compiler (cf. F# if you're a .NET fan.) Haskell is maybe too interesting, it even types the execution model if that makes sense (and won't right away.) Donn Cave, donn at u.washington.edu From sismex01 at hebmex.com Thu Jun 5 12:42:07 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 5 Jun 2003 11:42:07 -0500 Subject: Sort() Message-ID: > From: Turhan Ozen [mailto:txo at cs.nott.ac.uk] > Sent: Thursday, June 05, 2003 11:32 AM > > I created a class and modified the default _comp_ function. > I can sort an array of instances of this class. But I don't > want to change the original array. Instead, I want to keep > the positions after sorting in an attribute of the instances. > > Instead of [a1,a2,a3] becoming [a2,a1,a3], I would like the > order remain same but > > a1.rank=2 > a2.rank=1 > a3.rank=3 > > How can I do this? Does this functionality already exist? If > not could you please give me advice on how to implement it? > I have read the HOWTO on sorting, there is an example of sorting > classes there. Is there any other place where I can find more > examples of using Python functions? > > Thanks, > Turhan. > Hmmm... you could simulate it with: ## First we have... L = [ ... original list ... ] ## Now, we create a sorted version of the list: SL = L[:] SL.sort() ## We now create a dictionary keyed by item, relating to it's index: D = dict( zip(SL, range(len(SL))) ) ## And now, we transfer the index position as an attribute to ## the items on the original list: for item in L: item.rank = D[item] HTH! -gca Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From mcfletch at rogers.com Thu Jun 26 13:27:23 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 26 Jun 2003 13:27:23 -0400 Subject: Standard ways to get union, intersection, difference of lists? In-Reply-To: References: Message-ID: <3EFB2CFB.5060505@rogers.com> I've back-ported sets to 2.2.2. It was a matter of implementing a few functions from itertools (which is a Python module IIRC). Here's the majority of the backporting code: ### Backport to 2.2 by Mike Fletcher from __future__ import generators def ifilter(predicate, iterable): if predicate is None: def predicate(x): return x for x in iterable: if predicate(x): yield x def ifilterfalse(predicate, iterable): if predicate is None: def predicate(x): return x for x in iterable: if not predicate(x): yield x ### End backport There's some more for getting the tests to run under 2.2.2, but that's not actually necessary to use the module. Enjoy, Mike John Hunter wrote: >>>>>>"Steve" == Steve Holden writes: >>>>>> >>>>>> > > Steve> Not necessarily: I believe you can just pick up the sets > Steve> module from CVS and run it under 2.2+. > >I just tried import sets from the 2.3b1 distribution under python 2.2, >but it failed with an ImportError trying to load itertools. I believe >itertools is a C module, so perhaps it is not so straightforward to >use sets from 2.2? > >John Hunter > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From p-abel at t-online.de Thu Jun 26 17:52:50 2003 From: p-abel at t-online.de (Peter Abel) Date: 26 Jun 2003 14:52:50 -0700 Subject: Reading a binary file References: <3EFAF999.2F77CACF@engcorp.com> Message-ID: <13a533e8.0306261352.1e1ab44d@posting.google.com> Sorin Marti wrote in message news:... > Peter Hansen wrote: > > Sorin Marti wrote: > > > >>I am quite new to python and very new to this list. > >> > >>I've got following problem. I have a binary file which contains > >>information I should read. I can open the file with > > > > [snip] > > > > It would really be best if you could describe in more detail > > what you are trying to do with this data. Bytes are bytes, > > and things like hex and binary are just different _representations_ > > of bytes, so whether you want binary, hex, decimal, or something > > else depends entirely on the use to which you will put the info. > > > > Hi Peter, > > Ok I'll try to give more details. I have a Siemens SPS. With an SPS you > can controll machines such as pumps or motors or anything else. To > controll you have to set Variables. If you want to see which state these > variables have you can get a file via ftp where these values are stored. > This is what I have done. Now I have a file (called cpu1db2.dat) and > this file has a length of 16 bytes. > > Byte Number/Length Type Hex-Value > ---------------------------------------------------------------- > Byte 1: Boolean: 01 (which is true, 00 would be false) > Byte 2: Byte: 11 (This data type is called byte) > Byte 3: Char: 50 (Which should be a "P") > Byte 4,5: Word 00 00 > Byte 6,7: Integer 22 04 > Byte 8,9,10,11: DoubleWord D2 00 00 BB > Byte 12,13,14,15,16: Real BB 42 C8 00 00 > > As some others described the struct module should do the right work: >>> import struct ### This should be your data to read from a file into a string x. >>> x='\x01\x11P\x00\x00\x22\x04\xd2\x00\x00\xbb\xbb\x42\xc8\x00\x00' ### The format to decode your data except the Real. ### The **>** is necessary because your data come little-endian. >>> decode_fmt='>BBcHHI' >>> (Boolean,Byte,Char,Word,Integer,DoubleWord)=struct.unpack(decode_fmt,x[:-5]) >>> format=""" ... Boolean : %02X ... Byte : %02X ... Char : %s ... Word : %04X ... Integer : %04X ... DoubleWord: %04X""" >>> print format%(Boolean,Byte,Char,Word,Integer,DoubleWord) Boolean : 01 Byte : 11 Char : P Word : 0000 Integer : 2204 DoubleWord: D20000BB > So I have written a python class which makes a connection to the > ftp-server (on the SPS) and gets the file. > Then there is a function where you can call a value with a startbyte and > an endbyte. You also have to specify the type. That means you can call > getValue('REAL',12,16) and you should get back 100 because if you have I guess your Real is a 4-Byte Realvalue and you meant: '42 C8 00 00' what is the value of your binary representation. > the binary value of 'BB 42 C8 00 00' is 01000010110010000000000000000000 > , first digit is the Sign (which is + or - ), next 8 digits are the > exponent, in this case 10000101 = 133dec. Now you take away 127 from 133 > then you get six, thats the exponent. The rest > (110010000000000000000000) has a hex value of C80000 this is 13107200 > decimal. Now you have to multiply 13107200 with 2^6 and 2^-23 and you > get (tataaaaaa!): 100! > I'm not quite sure if I understand the format your're describing above. I dealed some time ago with IEEE and some AMD FPU-Format but you seem to me to describe a format where the exponent goes over Bytelimits. A function could be somewhat as the following: >>> def str2real(s): ... sign = ord(s[0])&0x80 and -1 or 1 ... expo = ((ord(s[0])&0x7f)<<1) + (ord(s[1])>>7) - 127 ... mantissa = ((ord(s[1])<<16)|0x80) + (ord(s[2])<<8) + ord(s[3]) ... print 'sign=%d, expo=%d, mantissa=%06X'%(sign,expo,mantissa) ... return sign*2**(expo-23)*mantissa ... >>> str2real(x[-4:]) sign=1, expo=6, mantissa=C80080 100.0009765625 Thoug I'm not sure if I hit the goal, cause normally the exponent is in 6 or 7 or 8 Bits 2's complement and then there would be a - 64 or - 128 or - 256 instead of - 127 in the algo. Also a 23 Bit mantissa seems a bit strange to me. Even if so the 24rth Bit is **1** by default, why I put **|0x80**. With an excact description of your Real-Format the solution would be a "Klacks". > The different data types need different calculations, that's why I asked > a few things about changing the representation because I only can do > some things in binary mode or hex mode. > > Cheers > Sorin Marti Regards Peter From tertiusc at netscape.net Wed Jun 11 18:53:13 2003 From: tertiusc at netscape.net (Tertius) Date: Thu, 12 Jun 2003 00:53:13 +0200 Subject: Jython anyone? References: Message-ID: <3EE7B2D9.6030603@netscape.net> If you're serious about Python and serious about Java... you should be serious about Jython. All the info I needed, I found on Jython.org The rest I found on python.org HTH Tertius anthony wrote: > Does anyone have strong feelings one way or another regarding Jython? > I just started playing around with it, but the limited online > discussions and the sort have me wondering if it's worthwhile. Any > thoughts? > > Anthony From fredrik at pythonware.com Thu Jun 26 09:23:18 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Jun 2003 15:23:18 +0200 Subject: filedescriptor out of range in select() References: <3EFABC5E.329613C6@alcyone.com> Message-ID: Paolo Invernizzi wrote: > > > the number of files supported by an actual system doesn't necessarily > > have to match the value of a include-file constant on the build machine... > > Umm... > > Python was installed via FreeBSD port system, so was built on this > machine... but that doesn't necessarily mean that the #define in an include file somewhere automagically picks up the kernel configuration, does it? (a quick googling brings up some posts about FreeBSD machines with FD_SETSIZE=256 and maxuserfiles>1024 etc. dunno if they've made their configuration tools smarter, but in any case, "poll" is the "right way" to deal with large number of file handles (compared to "select", at least -- there are better but platform-specific ways to do things if you want to...)) From martin at v.loewis.de Thu Jun 5 12:49:57 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 05 Jun 2003 18:49:57 +0200 Subject: Characters in Python References: Message-ID: jansun at home.se (Jan Sundstr?m) writes: > And how can one easily change what Python considers to be > default character encoding? There is, but I don't recommend using it. > I couldn't find anything about that in the tutorial. You'll find the easy way in the FAQ. However, Python 2.3 will solve this problem in a better way. Regards, Martin From terry at wayforward.net Fri Jun 6 18:22:27 2003 From: terry at wayforward.net (Terence Way) Date: Fri, 06 Jun 2003 18:22:27 -0400 Subject: Add methods to a class dynamically References: <64fb4467.0306060628.2c51bf09@posting.google.com> Message-ID: On Fri, 06 Jun 2003 11:28:54 -0400, Hoang Do wrote: I think it works :-) replace print %s with print '%s' the global name 'a' it's looking for is the a in 'print a' Cheers! > I am having trouble invoking the created method. The function addition > goes fine but invoking it gives an error. Here is some simple code: From drmental at yahoo.com Fri Jun 20 18:17:59 2003 From: drmental at yahoo.com (Thunder Perfect Mind) Date: 20 Jun 2003 15:17:59 -0700 Subject: Problems retreiving double from database Message-ID: I'm using an Access database where some fields are doubles. I'm using ADO to access this and when I try to retrieve the value in the field it returns the wrong value, instead of say 12.432 which might be the value of the field it returns 12.43200000000000003. Thinking this might be a problem with ADO I tried to use ODBC with the same result..... hmmmm maybe the database is the problem so I downloaded MySQL and connected with ODBC.... again same problem. Anyone know what causes this? and if so how do I fix it? Any help appreciated, dr//\//\ From peter at engcorp.com Sat Jun 7 20:57:55 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 07 Jun 2003 20:57:55 -0400 Subject: Excuting scripts question References: <3EE26F88.C86E88BB@alcyone.com> Message-ID: <3EE28A13.65FD29DD@engcorp.com> Ken wrote: > > > > Hi, I have a few scripts that ran well in Unix environment with: > > > #!/usr/local/bin/python > > > > > > What do I need to change to if I relocate these scripts on a Windows > > > environment? I have installed Python 2.2.3 in C:\Python22 directory. > > > Hi, I tried to run the script on IE (eg: http://192.168.0.2/test1.cgi) but > it doesn't seem to load. (The script seems to load forever... but ordinary > html files work) And 192.168.0.2 is your own machine? Do you have a web server running on it? IE does not actually execute CGI or Python or anything except *client-side* Javascript and Java. If you want to execute CGI, you have to have a web server running, and the web server itself executes the CGI and returns its results to IE in the form of HTML. IE can handle HTML that is loaded from the local filesystem, but consider this to be a special feature, not something that means you can treat your hard drive exactly as you treat a web server. If you want to learn more, try looking at CGIHTTPServer in the standard library, or look into setting up another web server locally, perhaps ... Twisted. :-) -Peter From mwh at python.net Thu Jun 12 08:55:28 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 12 Jun 2003 12:55:28 GMT Subject: Rudeness with names (was Re: interpreted) References: <3EE5BF67.2040201@ghaering.de> Message-ID: <7h3d6hjmpbw.fsf@pc150.maths.bris.ac.uk> Andrew Walkingshaw writes: > In any case, isn't the list archived on python.org and (furthermore) > replicated to a whole bundle of news servers approximately everywhere? > This is the first I've heard of Yahoo being involved - is the list > gatewayed to Yahoo Groups too? Yes, I believe so, but I find the web incarnation of Yahoo! Groups to be impossible to use. You know Yahoo! Groups used to be eGroups? You know who was the brains behind eGroups (and medusa and asyncore and calldll...)? Cheers, M. -- US elections For those of you fearing that the rest of the world might be making fun of the US because of this: Rest assured, we are. -- http://www.advogato.org/person/jameson/diary.html?start=12 From jjl at pobox.com Thu Jun 19 21:16:59 2003 From: jjl at pobox.com (John J. Lee) Date: 20 Jun 2003 02:16:59 +0100 Subject: include files? References: <3ef1c90f$0$49114$e4fe514c@news.xs4all.nl> Message-ID: <87smq5h7jo.fsf@pobox.com> "rgndrp" writes: > hi all, > > I use python for making cgi scripts on a iis/w2k > box and i wanted to know if it is it possible to include files in > python? > like: > or something :) No, that's physically impossible in Python. The laws of nature dictate that using a generic macro processor like m4 on Python code is forbidden. Sorry. More seriously: http://www.google.com/search?q=SSI+IIS But maybe that's not what you mean, who knows... John From grante at visi.com Fri Jun 6 10:50:05 2003 From: grante at visi.com (Grant Edwards) Date: 06 Jun 2003 14:50:05 GMT Subject: Including binary files in a .py file; advice needed References: <3EDEB0A6.202@netspace.net.au> Message-ID: <3ee0aa1d$0$640$a1866201@newsreader.visi.com> In article <3EDEB0A6.202 at netspace.net.au>, Gary Duncan wrote: > Here's what I want to do; distribute a .py file (a GUI app) with > an embedded (binary) .GIF file (a photo of me at 1 yo ;) rather than > distribute both separately. For convenience, mainly. Here's how I did it: LogoString = """R0lGODdhtQByAPcAAAAAAA4DBA4NCxsGBxwaFSkJCyonIDYMDjgqIzg0KkQOEkQZGUY3LkZB NVERFVREOFROP18UGWE9NWJbSmwXHW0rK242Mm9KQG9UR3FpVXoaIH92X4cdJIgxMok7OYlG QI2DapUgJ5UqLpdIQ5uQdKIjK6MtMqM3OaRBQKZqXKd0Y6d+aqiTeKmdf7AlLrJOSraggreq ib0oMr9RTsKEccSjhsW3lMsrNcs1PM1UUc5oX9CHdNCRe9GbgtGlidKwkNK6l9PEntguOdk4 QNlCR9pNTtpXVdthXNtrY9x1at2Acd6Uf96eht+ojeC9m+DHouHRqQLzAAD/AAC/ANgkqP30 [...] 2FU4hRenxTmuXK4nJOn0AsBgy54dea/+717PvABAFYSh97yhWs+4xD8y944vHyQNqIzyn0/9 6lv/+hEPCAA7 """ LogoImage = PhotoImage(data=LogoString) > If in a Unix shell script, I'd uuencode the .GIF and include the > printable-ASCII file in it as a 'here' file. When executed the script > would 'cat' it out to e.g. a /tmp file from the main body of the script, > then uudecode the /tmp file to revert to the original .GIF file. Sounds complicated with temp file and all. -- Grant Edwards grante Yow! A GRAM?? A BRAM... A at GROOM... A BROOM... Oh, visi.com Yeh!! Wash the ROOM!! From exarkun at intarweb.us Thu Jun 5 16:49:38 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 5 Jun 2003 16:49:38 -0400 Subject: Loop over list of pairs In-Reply-To: References: Message-ID: <20030605204938.GA16141@meson.dyndns.org> On Thu, Jun 05, 2003 at 04:25:29PM +0200, Thomas G?ttler wrote: > Hi! > > What is the prefered way of loop over > a list like this? > mylist=[1, "one", 2, "two", 3, "three"] From your subject, I'm guessing you want a loop with two variables which take on the values (1, "one"), then (2, "two"), and finally (3, "three"). If this is the case, this works: i = iter(mylist) for (a, b) in zip(i, i): ... Jp -- "Minerals are inexhaustible and will never be depleted. A stream of investment creates additions to proved reserves, a very large in-ground inventory, constantly renewed as it is extracted... How much was in the ground at the start and how much will be left at the end are unknown and irrelevant." -- Morry Adelman, World Renowned Economist From jeremy at jdyallop.freeserve.co.uk Sat Jun 21 15:02:31 2003 From: jeremy at jdyallop.freeserve.co.uk (Jeremy Yallop) Date: 21 Jun 2003 19:02:31 GMT Subject: a clean way to define dictionary References: <3EEFEBFD.8090003@nospam.com> Message-ID: Alexander Schmolck wrote: > Skip Montanaro writes: >> I don't think it would normally be used that way. Instead, consider you >> have a preexisting dictionary and want a copy: >> >> >>> d1 = {'foo':1, 'bar':'sean'} >> >>> d2 = dict(**d1) >> >>> d2 == d1 >> True >> >> That's a one-liner where the equivalent >> >> d2 = {} >> d2.update(d1) >> >> is a two-liner and likely slower. > > Uhm, > > d2 = d1.copy() ? d2 = dict(d1) Jeremy. From joch at blueyonder.co.uk Mon Jun 2 15:55:31 2003 From: joch at blueyonder.co.uk (John Ochiltree) Date: Mon, 02 Jun 2003 20:55:31 +0100 Subject: Python get's a mention on University Challenge In-Reply-To: <3edbaa7a$0$49106$e4fe514c@news.xs4all.nl> References: <2vNCa.733$Bp6.118@news-binary.blueyonder.co.uk> <3edbaa7a$0$49106$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > John Ochiltree wrote: > >> Hi all, thought you may like to know that the UK TV programme >> 'University Challenge' of 2nd June has just had 'The Python >> Programming Language' as the answer to a question in a round about >> programming languages (the other languages were Pascal and Eiffel). > > > What was the question? > > --Irmen > "What object oriented scripting language was created by Guido Van Rossum at Stichting Mathematisch Centrum?" I think that's right, or more or less. John From http Mon Jun 2 04:17:16 2003 From: http (Paul Rubin) Date: 02 Jun 2003 01:17:16 -0700 Subject: Defensive programming References: <7xptlxq2yz.fsf@ruckus.brouhaha.com> Message-ID: <7xel2csxkj.fsf@ruckus.brouhaha.com> Lulu of the Lotus-Eaters writes: > Well... for Python, I'd rather have a hash with excellent typical case > performance than a typically slower one with more collision resistance. I haven't seen any evidence that adding some countermeasure to the attack would make any significant slowdown. Until there's some evidence I'm not willing to go along with assumptions that there will be a slowdown. > If my normal, non-DoS programs run a bit faster, that's something I > experience every day... If you want your programs to run as fast as they can, then you're using the wrong language. And there are lots of other ways to speed up Python. For example, fixing the hash function is meeting resistance because the interpreter does so many hash lookups. But the interpreter really doesn't need to do so many lookups, and the amount of lookups is part of why Python programs are so slow. Better to fix the interpreter than to worry about shaving another nanosecond out of a hash lookup. From aahz at pythoncraft.com Sun Jun 29 21:10:11 2003 From: aahz at pythoncraft.com (Aahz) Date: 29 Jun 2003 21:10:11 -0400 Subject: (x)range( 40000000000, 40000000001 ) References: <3eff347f$1@buckaroo.cs.rit.edu> Message-ID: In article <3eff347f$1 at buckaroo.cs.rit.edu>, Chris Connett wrote: > >It seems range and xrange don't like longs that can't be sqeezed into ints: > >With Python 2.3b1+: > > >>> xrange( 40000000000, 40000000001 ) >Traceback (most recent call last): > File "", line 1, in ? >OverflowError: long int too large to convert to int > >>> range( 40000000000, 40000000001 ) >Traceback (most recent call last): > File "", line 1, in ? >OverflowError: long int too large to convert to int > >>> The first problem is that range is designed to create a list and the canonical usage for range is range(N); lists cannot currently have more than int elements. xrange() could get away with fixing it, but Guido has decreed that xrange() is a target for deprecation (and will go away in Python 3.0), so he won't allow any improvements to xrange() in order to encourage people to use alternatives. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Usenet is not a democracy. It is a weird cross between an anarchy and a dictatorship. From g2h5dqi002 at sneakemail.com Mon Jun 9 22:33:24 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 10 Jun 2003 14:33:24 +1200 Subject: Editing a Binary File. In-Reply-To: <924a9f9c.0306090603.5162d697@posting.google.com> References: <924a9f9c.0306082237.222a46cf@posting.google.com> <924a9f9c.0306090603.5162d697@posting.google.com> Message-ID: Paradox wrote: > I just didn't even read the r capabilities cause I thought they were > for readonly access. Yes, the meanings of the + modes are somewhat unintuitive. 'Twould have been better if the mode letters had been designed to be more orthogonal, but we're stuck with them for Historical Reasons. :-( -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bobsmith327 at hotmail.com Sat Jun 7 18:50:18 2003 From: bobsmith327 at hotmail.com (Bob Smith) Date: 7 Jun 2003 15:50:18 -0700 Subject: Tkinter: Do you really need a "root"? Message-ID: Hi. I'm just starting to learn to use the Tkinter module for creating GUIs. I'm using a tutorial that gives a basic starting program of: from Tkinter import * root = Tk() app = Frame(root) root.mainloop() But do I really need root? It seems like the program could simply be: from Tkinter import * app = Frame() app.mainloop() This second program works just as well as the first and seems more intuitive to me. I'm creating an application that is a Frame and I start the application by invoking the application's mainloop() method. The first example seems more obtuse. root seems unnecessary and invoking root's mainloop() instead of app's seems odd to me too (if I want to start app, I should invoke a method of app). So, what's wrong with the second version? Will I run into problems later when I add more widgets and get into more complex GUIs? Thanks, Bob From frobozz_electric at hotmail.com Thu Jun 19 11:29:02 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 19 Jun 2003 15:29:02 GMT Subject: sum(strings) References: Message-ID: "Steve McAllister" wrote in message news:bcsjii$3vf$1 at alto.univ-mlv.fr... > Why does sum reject strings? Is it a matter of efficiency of the > underlying implementation? > http://www.python.org/dev/summary/2003-04-16_2003-04-30.html """ Originally Alex [Martelli, who implemented sum(),] also wanted to special-case the handling of a list of strings so as to prevent having to tell new Python programmers that "".join(list_of_strings) is the best way to concatenate a bunch of strings and that looping over them is really bad (the amount of I/O done in the loop kills performance). But this special-casing was shot down because it seemed rather magical and can still be taught to beginners easily enough ('reduce' tends to require an understanding of functional programming). """ Also see: http://mail.python.org/pipermail/python-dev/2003-April/034854.html and other related python-dev discussions From skip at pobox.com Wed Jun 4 10:03:29 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 4 Jun 2003 09:03:29 -0500 Subject: Possible PEP: Improve classmethod/staticmethod syntax In-Reply-To: References: <20030603164521903-0400@braeburn.themorgue.org> <1ieDa.35049$DV.60225@rwcrnsc52.ops.asp.att.net> Message-ID: <16093.64561.953770.980195@montanaro.dyndns.org> bryan> thanks skip... now i can see the elegance of this solution. bryan> wouldn't this also solve the pre/post conditions that are bryan> currently put in comments with another current solution? That was the general idea. ;-) bryan> but, how would you handle pre/post conditions that are only bryan> supposed to be used in a debug version? Like I said, it was probably full of holes. Skip From rmunn at pobox.com Fri Jun 6 15:03:47 2003 From: rmunn at pobox.com (Robin Munn) Date: Fri, 06 Jun 2003 19:03:47 GMT Subject: Updating SQL table problems with python References: <3eddac41$0$31519$5a62ac22@freenews.iinet.net.au> Message-ID: kuntzagk at sulawesi.bioinf.mdc-berlin.de wrote: > >> As you can tell, im parsing a xml RSS feed and updating items table. Im >> trying to replace >> default value of 'Title' with the title from the RSS feed. >> The update statement is givng me the syntax error >> I cant see whats wrong > > Did you get a python syntax error or a SQL syntax error? > If the latter, check if your title contains a quote charakter. > Got bitten by this myself. I also notice that your SQL statment contains single-quotes. In many databases, that's fine, you can use single- or double-quotes around a string, no problem. If your database system happens to be picky about which style of quote chars you use, that might be it. Note that I have no idea what database system you're using, so I may very well be talking through my hat here. But it's something to try, at least. -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From nav at adams.patriot.net Mon Jun 30 08:02:29 2003 From: nav at adams.patriot.net (Nick Vargish) Date: 30 Jun 2003 08:02:29 -0400 Subject: SOAP client References: Message-ID: ddoc writes: > Doesn't work for me. > Hmm. I haven't run it in a while... that server might just have been a transient. I meant the example more for purposes of illustration, anyway. :^) 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 wavegroom at gmx.net Mon Jun 2 12:24:06 2003 From: wavegroom at gmx.net (wavegroom) Date: Mon, 02 Jun 2003 18:24:06 +0200 Subject: python2.0, _socket module, builtin, compile Message-ID: hi First my config: Athlon 1.8 GHZ latest gentoo-linux and w2k python2.2 and python 2.0.1 I have a problem with python 2.0. I use Blender (2.25) wich has a built in python engine (python2.0). I tried to import the socket module, but I get the error message module _socket not found. I added a python 2.0.1 installation for blender, so that I have all modules. Its so that blender python doesn't have all builtin modules. On windows it works because the built in modules are not static linked to python.exe. On linux the _socket module ins integrated in the python-bin. How can I compile python 2.0.1 under linux, so that i get the built in functions as non static modules, so that i can load _socket.so at runtime. (like in python2.2) I tried a bit to modify some config files from the source, but nothing worked :-( any help would be very welcome :-))) From djc at object-craft.com.au Wed Jun 18 06:44:27 2003 From: djc at object-craft.com.au (Dave Cole) Date: 18 Jun 2003 20:44:27 +1000 Subject: ANNOUNCE: JOTWeb 1.11, preview of new web application system. References: <20030617162210.GB5896@tummy.com> <1055884182.1169.11.camel@emilio> Message-ID: > I didn't like that, at least as far as the documentation indicates > to me, Albatross web pages have this context that has to be set up > and maintained for each of the pages. There's a fairly similar set > of 10 lines of code that need to be set up for each page that you > want to be dynamic. > > For example, in JOTWeb to display a page with the current time in > it, you would have a "code.py" file that contains: > > def currenttime(): > import time > return(time.strftime('%H:%M:%S')) > > And call that from an HTML file using: > > The current time is: > > As a comparison, it seems to be that this code in Albatross would be > a python module containing: > > #!/usr/bin/python > import os > from albatross import SimpleContext > > ctx = SimpleContext('.') > templ = ctx.load_template('time.html') > > import time > ctx.locals.currenttime = time.strftime('%H:%M:%S') > > templ.to_html(ctx) > > print 'Content-Type: text/html' > print > ctx.flush_content() > > Then the HTML of: > > The current time is: > > It just seems like you have to cut and paste a lot of code in > Albatross for every page you want to display. But it's not just cut > and paste, because you have to customize some parts of it (while > leaving other parts alone). JOTWeb tends to do a lot of that sort > of stuff for you behind the scenes so that you don't have to think > about them. Or you could use one of the application classes to reduce the code needed for each page. Assuming you have more than one page in the application. >From where I sit it looks like JOTWeb makes more of the application plumbing implicit than Albatross. That is a good thing when the plumbing fits the problem you are trying to solve. When it comes down to it, the number of lines in a trivial application is not why you use toolkits and frameworks. You use a framework to help construct a complex application. - Dave - - app.py - - - - - - - - - - - - - - - - - - - - - - - - - - - - #!/usr/bin/python import albatross from albatross.cgiapp import Request if __name__ == '__main__': app = albatross.ModularApp(base_url='app.py', module_path='.', template_path='.', start_page='start', secret='not telling') app.run(Request()) - - start.py - - - - - - - - - - - - - - - - - - - - - - - - - - - import time def page_display(ctx): ctx.locals.now = time.time() ctx.run_template('time.html') - - time.html - - - - - - - - - - - - - - - - - - - - - - - - - - - The current time is: -- http://www.object-craft.com.au From cpbotha at i_triple_e.org Fri Jun 27 10:40:00 2003 From: cpbotha at i_triple_e.org (Charl P. Botha) Date: Fri, 27 Jun 2003 14:40:00 +0000 (UTC) Subject: OFF TOPIC: What did Guido say? References: <20030625002727.20904.qmail@web11402.mail.yahoo.com> <3EF95F29.8050609@riks.nl> <6BYKa.333824$3n5.216510@news2.central.cox.net> Message-ID: In article <6BYKa.333824$3n5.216510 at news2.central.cox.net>, Steve Holden wrote: > "Anders Hammarquist" wrote in message >> and that would really be: >> >> Hej, det h?r ?r Linus Torvalds och jag uttalar Linux Linux. > So Linus speaks Swedish even though he's a Finn? IIRC, Linus is one of the ethnic Swedes that make up 5% of the Finnish population. -- charl p. botha http://cpbotha.net/ http://visualisation.tudelft.nl/ From http Sun Jun 22 13:25:15 2003 From: http (Paul Rubin) Date: 22 Jun 2003 10:25:15 -0700 Subject: Remove duplicate letters in a word References: Message-ID: <7x4r2iowhw.fsf@ruckus.brouhaha.com> Eliran Gonen writes: > I'm stuck here: > > for i in range(len(key)): > for j in range(len(key)): > if key[i] == key[j] : > key[j] = "" > > Hope you can help me, You can't change the contents of a string in Python. You have to make a new string: temp = [] for c in key: if c not in key2: temp.append(c) key = str(temp) From ebolonev at mail.ru Sun Jun 29 18:54:24 2003 From: ebolonev at mail.ru (Egor Bolonev) Date: Mon, 30 Jun 2003 09:54:24 +1100 Subject: strings Message-ID: Hi All! I have a 'Pink Floyd/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00' and I want a 'Pink Floyd' How can I manage it? This one isn't work. author=f.read(30).replace('\0',' ').rstrip() #from mp3 tag -- Egor [ru eo en] From fraqutal at gmx.de Thu Jun 19 12:11:00 2003 From: fraqutal at gmx.de (Luther Blisset) Date: 19 Jun 2003 09:11:00 -0700 Subject: error loading files containing nullbytes w/ urllib? Message-ID: When I try to load a file from a server which contains nullbytes, I get back a corrupted file where all null bytes are converted to spaces. When I save the image with a webbrowser I get a normal .jpg with a length of 4.545 bytes. When I do that... import urllib pic = urllib.urlopen('http://news.bbc.co.uk/olmedia/195000/images/_198996_george_bush_junior_150.jpg') img = pic.read() pic.close() f = open('gwb.jpg','w') f.write(img) f.close() ... I get a file with a size of 4565 bytes and all null bytes are converted to spaces. What am I doing wrong??? regards, frq. From rnd at onego.ru Tue Jun 24 11:19:28 2003 From: rnd at onego.ru (Roman Suzi) Date: Tue, 24 Jun 2003 19:19:28 +0400 (MSD) Subject: Booleans and comparison results Message-ID: Just a thought. Why cmp() returns -1,0,1 while comparison results are False and True? Isn't it logical step to add Less, Equal and More? >>> cmp(1,2) Less >>> cmp(1,-1) More >>> cmp(1,1) Equal if cmp(foo, bar) is Less: ... hmmm... Sadly, I know GvR is not going to add new keyword: if cmp(foo, bar) are Equal: ... ;-) Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From tecnic at codidoc.com Wed Jun 18 06:21:35 2003 From: tecnic at codidoc.com (Oscar Rambla) Date: Wed, 18 Jun 2003 03:21:35 -0700 Subject: How to recognize a generator function? Message-ID: <200306180321.35471.tecnic@codidoc.com> Hi, I'm not been able to find a solution to the following: How to recognize if a function is a generator function before calling it? (Alternatives to having to inspect code for a yield or wrapping it into a class). Note: I refer to the function, not to the generator itself. Thank you in advance. -Oscar From nosp at m.needed Thu Jun 19 12:14:01 2003 From: nosp at m.needed (Steve McAllister) Date: Thu, 19 Jun 2003 18:14:01 +0200 Subject: sum(strings) In-Reply-To: References: Message-ID: > Python is not Perl! If you need to build the sum over a sequence of > strings containing numbers > then you need to convert them to numbers. I am talking about sum(['x', 'y']) -> 'xy'. Since strings can be added, they should be sumable too. No? :-) From jdhunter at ace.bsd.uchicago.edu Wed Jun 25 22:27:52 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 25 Jun 2003 21:27:52 -0500 Subject: problem with % operator on format string In-Reply-To: <20030626020423.GB12627@bobas.nowytarg.pl> (vald@valis.amber.eu.org's message of "Thu, 26 Jun 2003 04:04:23 +0200") References: <20030626020423.GB12627@bobas.nowytarg.pl> Message-ID: >>>>> "vald" == vald writes: vald> query = "select date(xxx, '\%d') from yyy where xxx like vald> '%s%s\%'" % (year, month) vald> so it should produce something like that (year=2003, vald> month=06) vald> select date(xxx, '%d') from yy where xxx like '200306%' To make a literal %, use %%. You are looking for query = "select date(xxx, '%%d') from yy where xxx like '%d%02d%%'" % (2003, 6) The %02d says to pad the second integer with zeros up to length 2. Check out http://www.python.org/doc/current/lib/typesseq-strings.html for the details. John Hunter From staschuk at telusplanet.net Tue Jun 10 11:26:02 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 10 Jun 2003 09:26:02 -0600 Subject: Access "slot" field dynamically? In-Reply-To: ; from no_replies@fake_email_address.invalid on Tue, Jun 10, 2003 at 01:49:12PM +0000 References: Message-ID: <20030610092602.H374@tibia.amotlpaa.bogus> Quoth Robert Oschler: [...] > In the block belonging to "printSomeFields()", how do I access the field > (slot) by grabbing the field name from the fldlist list of strings? > > print instance_of_hasslot.fl What you need is print getattr(instance_of_hasslot, fl) Btw, I don't think __slots__ is something you should use for your run-of-the-mill classes. It's intended for memory optimization for classes with lots and lots and lots of instances, afaik (contrary to some of the documentation, which suggests a bug-prevention role). -- Steven Taschuk staschuk at telusplanet.net "Telekinesis would be worth patenting." -- James Gleick From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Tue Jun 17 01:50:21 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Tue, 17 Jun 2003 09:50:21 +0400 Subject: You know you're a Pythonista when.. In-Reply-To: <4h2tevsoatvr7ahac0qtdmk6v826uf47e9@4ax.com> References: <16102.10640.855883.967908@montanaro.dyndns.org> <20030610190206.54459.qmail@web11407.mail.yahoo.com> <4h2tevsoatvr7ahac0qtdmk6v826uf47e9@4ax.com> Message-ID: Tim Roberts wrote: > anton muhin wrote: > > >>Tim Roberts wrote: >> >> >>>In Unix, this option little more than an exercise, because most of the >>>shells are so functional. However, there is a very functional and quite >>>useful Python shell for Windows called PyDOS that adds some very useful >>>things, as well as allowing direct Python statements. It's especially >>>useful on Windows 98, since it adds path completion and other niceties that >>>are built-in to Win2K. >> >>Could you provide an URL? I googled for it, but I was able to find DOS >>version of Python only :( > > > Memory fault. It is called "pdos.py". Find it here: > > http://hammer.prohosting.com/~pyguy/ > > I do not think it is being actively developed, but it's useful as-is, and > is easily extended. Thanks a lot. anton. From shalehperry at attbi.com Sat Jun 14 14:21:45 2003 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sat, 14 Jun 2003 11:21:45 -0700 Subject: comprehending comprehensions In-Reply-To: References: Message-ID: <200306141121.45474.shalehperry@attbi.com> On Saturday 14 June 2003 10:52, Roy Smith wrote: > Why are list comprehensions called what they are? I find the name very > confusing. Is this some standard computer science term? Is it stolen > from some other language? it came from the functional programing world via ML (or was it Haskell). That's what they called it. looking up comprehension in a dictionary (.com) I find : 3. Logic. The sum of meanings and corresponding implications inherent in a term. which I suspect is the meaning used here. From alanmk at hotmail.com Tue Jun 24 05:50:43 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 24 Jun 2003 10:50:43 +0100 Subject: minidom toxml() not emitting attribute namespace qualifier References: <3EF71DBB.321885B4@hotmail.com> Message-ID: <3EF81EF3.4E519EE6@hotmail.com> Alan Kennedy wrote: > That's a bug in minidom. > > I reported it back in November 2002, but I wasn't precise enough about > version numbers, so it went unaddressed. https://sourceforge.net/tracker/?func=detail&atid=106473&aid=637355&group_id=6473 I've checked further, and this is now my understanding. The bug report I made above related to the standard minidom that comes with the base installation of python, which does indeed have the bug. The bug was fixed by the pyxml maintainers, a long time ago, but only in the minidom that comes with pyxml. Obviously, the two minidom implementations are out-of-synch. If you install pyxml, you won't see this problem. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From mwilson at the-wire.com Fri Jun 20 09:08:26 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 20 Jun 2003 09:08:26 -0400 Subject: sum(strings) References: Message-ID: In article , "Greg Ewing (using news.cis.dfn.de)" wrote: >Raymond Hettinger wrote: >> Because there is just one right way to do it: >> >> "".join([str1, str2, str3, ...]) > >Hmmm... maybe this ought to be the "right" >way to do summing as well: > > total = 0.join([17, 42, 88]) Interesting point arose the other day.. using '+' to concatenate strings is wrong, because concatenation isn't commutative. Not that it would necessarily affect my thinking if I were designing a computer language, but it is a sensible point. It might trip up a naive optimizer. Regards. Mel. From tchur at optushome.com.au Mon Jun 2 07:35:07 2003 From: tchur at optushome.com.au (Tim Churches) Date: Mon, 2 Jun 2003 21:35:07 +1000 Subject: How to make slicing and other methods interact? Message-ID: <002601c328fb$07cbe090$a300a8c0@emilio> What is the general pattern for making methods interact? For example, I define a class with overridden __str__ and __getslice__ methods. If I print an instance of the class, the __str__ method is used. But if I print a slice of the instance, only the __getslice__ method is called, but not __str__. ################################### class test(object): def __init__(self,iterable): self._data = iterable def __str__(self): xlate = {1:'one',2:'two',3:'three',4:'four',5:'five'} ret = ['['] for x in self._data: ret.append(xlate[x]) ret.append(']') return '\n'.join(ret) def __getslice__(self,low,high): return self._data[low:high] t = test([1,2,3,4,5]) print t print print t[1:3] ################################### Produces this output: [ one two three four five ] [2, 3] When what I really want is: [ one two three four five ] [ two three ] Is there a general way of achieving this - so that slicing (or indexing) semantics propagate to other methods? Tim C From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sun Jun 8 20:37:11 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 09 Jun 2003 02:37:11 +0200 Subject: Strange problem with notebook computer In-Reply-To: References: Message-ID: <3ee3d6b6$0$49107$e4fe514c@news.xs4all.nl> Homer Ellison wrote: > Is there a possibility that somehow Python or the > code I'm writing in Python is causing my notebook computer to overheat? > I can't imagine why this would be, but I can't figure out what else > might be causing the problem. Any ideas? This all sounds very unlikely to be Python's fault... the only thing that I can imagine is that 1) your computer's cooling is broken (bios/fan troubles?), and; 2) the particular python program you're running has a loop that eats up 100% cpu time, which causes your machine to overheat. Try using top (linux) or task manager (windows) to find out if so, and what is eating 100% cpu? --Irmen From max at alcyone.com Mon Jun 23 06:26:37 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 23 Jun 2003 03:26:37 -0700 Subject: XML References: <3EF471BA.EE4F056@hotmail.com> <23891c90.0306230142.83612c8@posting.google.com> Message-ID: <3EF6D5DD.15420D8F@alcyone.com> Paul Boddie wrote: > Indeed. The assertion that "7-bit plain text ASCII" is even a > meaningful format is highly dubious, at least when it comes to > understanding the information presented in that format. 7-bit ASCII is pretty clear, it's just ASCII (which only defines the lower 7 bits). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Gods are born and die, but the atom endures. \__/ Alexander Chase From jarausch at skynet.be Wed Jun 11 17:13:15 2003 From: jarausch at skynet.be (Helmut Jarausch) Date: Wed, 11 Jun 2003 23:13:15 +0200 Subject: simple text filter In-Reply-To: References: Message-ID: <3EE79B6B.40506@skynet.be> boutrosp at hotmail.com wrote: > I need some help on a simple text filter. The problem I am having is > when the file comes to the end it stays in the while loop and does not > exit. I cannot figure this out. I would use a for loop with the > readlines() but my datasets can range from 5 to 80 MB of text data. > Here is the code I am using. Please help. > > import sys, re > > p1 = re.compile('ADT100') > p2 = re.compile('AUDIT') > p3 = re.compile('HARDWARE') > p4 = re.compile('PACKAGES') > p5 = re.compile('NODE') > p6 = re.compile('DROP') > p7 = re.compile('GRID') > p8 = re.compile('ATAP') > > f=open('adt100_0489.rpt.txt', 'r') > junky = 1 > done = False > while not done : > junky = f.readline() > if p1.search(junky) : > continue > elif p2.search(junky) : > continue > elif p3.search(junky) : > continue > elif p4.search(junky) : > continue > elif p5.search(junky) : > continue > elif p6.search(junky) : > continue > elif p7.search(junky) : > continue > elif p8.search(junky) : > continue > elif junky == None : replace this with elif junky == '' : since readline returns an empty string on EOF > done = True > else : > print junky > > f.close() -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From max at alcyone.com Tue Jun 3 23:23:30 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 03 Jun 2003 20:23:30 -0700 Subject: Python get's a mention on University Challenge References: <2vNCa.733$Bp6.118@news-binary.blueyonder.co.uk> <3edbaa7a$0$49106$e4fe514c@news.xs4all.nl> Message-ID: <3EDD6632.AF37CDB2@alcyone.com> "Greg Ewing (using news.cis.dfn.de)" wrote: > Should be simple enough: > > def pray(text): > open("/dev/god", "w").write(text) > > (Implementation of the /dev/god kernel module left as > an exercise for the reader.) God doesn't like being overwritten as another poster pointed out, and additionally God doesn't particularly like the conditions under which connections to him are closed left unspecified ... :-). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ My reputation grows with every failure. \__/ George Bernard Shaw From m at moshez.org Wed Jun 11 07:40:50 2003 From: m at moshez.org (Moshe Zadka) Date: 11 Jun 2003 11:40:50 -0000 Subject: Properties using metaclasses (was: Function/Method Decorator Syntax) In-Reply-To: <20030611110300.GA3350@nl.linux.org> References: <20030611110300.GA3350@nl.linux.org>, <20030610082514442-0400@braeburn.themorgue.org> <20030610142845.4540.qmail@green.zadka.com> <20030611013918.GA2113@frobozz> <20030611085935.GG2113@frobozz> Message-ID: <20030611114050.25523.qmail@green.zadka.com> On Wed, 11 Jun 2003, Gerrit Holl wrote: > Just a question: Why would this be evil? Because people expect class x(EvilProperty): pass to be a *class* (albeit, new style), and not a *property*. For example, doing X() would not give you an instance of X. -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From bignose-hates-spam at and-zip-does-too.com.au Sun Jun 29 18:30:28 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 30 Jun 2003 08:20:28 +0950 Subject: shebang strange thing... References: <3EF3A07B.A683F94F@alcyone.com> <3EF7A121.7B4C3775@alcyone.com> <3EF933AA.C16ADFE5@alcyone.com> Message-ID: On Sun, 29 Jun 2003 11:05:44 GMT, Van Gale wrote: > Ben Finney wrote: >> I maintain that the CR and LF were needlessly preserved as separate >> operations, with no benefit. > > I disagree. IIRC there were plenty of printers where the carriage > return operation took a disproportionately long time, so therefore > backspacing was the prefered method for overstriking, but at the same > time that meant line feeds were a big performance win for smart > applications. Fair enough then; the operations were kept separate for a reason justifiable at the time. Sadly, now we have to live with the legacy of the resulting confusion, long after those benefits are obsolete. -- \ "Here is a test to see if your mission on earth is finished. If | `\ you are alive, it isn't." -- Francis Bacon | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From shlomme at gmx.net Sun Jun 1 13:24:31 2003 From: shlomme at gmx.net (Torsten Marek) Date: Sun, 01 Jun 2003 19:24:31 +0200 Subject: PyModule for ID3 v2.2+ In-Reply-To: References: <2147483647.1054415157@[192.168.0.3]> <3EDA120F.ADEBBDAA@hotmail.com> <20030601111005.M1276@localhost.localdomain> Message-ID: Alexander Winston schrieb: > On Sun, 2003-06-01 at 10:10, Jack Diederich wrote: > >>Most people still use id3v1 which just used fixed length fields. > > > By the way, if you all are looking to implement a standard that does not > have the same fixed length field limitations and does not suck, check > out APEv2. They are quite similar to Vorbis comments, which are > _definitely_ a tagging/commenting format that doesn't suck. But of > course, you can't have Vorbis comments in your MP3, so APEv2 is > definitely your best bet. > Vorbis tags are easy to read (not at least to good support in libvorbisfile), but it is (to my knowledge) more difficult to write them because every time you change the comment, you have to re-write the file (at least vorbiscomment from the official xiph.org does this), which does not happen with ID3v2 tags and additional padding in the header. The flac developers prevented this with putting a vorbis comment into the metadata, which can have some padding. I do not know APEv2 by now (but I will soon, after your hint, thanks), but do programs support it? Just another information: vorbis comments contain UTF-8 text, but Winamp 3.0 seems to screw it up, at least in the version my girlfriend has installed. greetings Torsten From ss3canon at earthlink.net Thu Jun 26 23:15:56 2003 From: ss3canon at earthlink.net (Mike) Date: Fri, 27 Jun 2003 03:15:56 GMT Subject: List of lists References: Message-ID: Ok, I'm doin an exercise and I need to expand on test.py. I'm pretty much done with the exercise except I need to print out the questions and answers that are in the function. here is the snippet: def get_questions(): return [["What color is the daytime sky on a clear day?","blue"],\ ["What is the answer to life, the universe and everything?","42"],\ ["What is a three letter word for mouse trap?","cat"]] How do I get the lists from this? oh here is the whole program; ## This program runs a test of knowledge true = 1 false = 0 # First get the test questions # Later this will be modified to use file io. def get_questions(): # notice how the data is stored as a list of lists return [["What color is the daytime sky on a clear day?","blue"],\ ["What is the answer to life, the universe and everything?","42"],\ ["What is a three letter word for mouse trap?","cat"]] # This will test a single question # it takes a single question in # it returns true if the user typed the correct answer, otherwise false def check_question(question_and_answer): #extract the question and the answer from the list question = question_and_answer[0] answer = question_and_answer[1] # give the question to the user given_answer = raw_input(question) # compare the user's answer to the testers answer if answer == given_answer: print "Correct" return true else: print "Incorrect, correct was:",answer return false # This will run through all the questions def run_test(questions): if len(questions) == 0: print "No questions were given." # the return exits the function return index = 0 right = 0 while index < len(questions): #Check the question if check_question(questions[index]): right = right + 1 #go to the next question index = index + 1 #notice the order of the computation, first multiply, then divide print "You got ",right*100/len(questions),"% right out of",len(questions) #now lets run the questions run_test(get_questions()) ## This program runs a test of knowledge true = 1 false = 0 # First get the test questions # Later this will be modified to use file io. def get_questions(): # notice how the data is stored as a list of lists return [["What color is the daytime sky on a clear day?","blue"],\ ["What is the answer to life, the universe and everything?","42"],\ ["What is a three letter word for mouse trap?","cat"]] # This will test a single question # it takes a single question in # it returns true if the user typed the correct answer, otherwise false def check_question(question_and_answer): #extract the question and the answer from the list question = question_and_answer[0] answer = question_and_answer[1] # give the question to the user given_answer = raw_input(question) # compare the user's answer to the testers answer if answer == given_answer: print "Correct" return true else: print "Incorrect, correct was:",answer return false # This will run through all the questions def run_test(questions): if len(questions) == 0: print "No questions were given." # the return exits the function return index = 0 right = 0 while index < len(questions): #Check the question if check_question(questions[index]): right = right + 1 #go to the next question index = index + 1 #notice the order of the computation, first multiply, then divide print "You got ",right*100/len(questions),"% right out of",len(questions) #now lets run the questions run_test(get_questions()) From kdahlhaus at yahoo.com Wed Jun 4 14:02:18 2003 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 4 Jun 2003 11:02:18 -0700 Subject: PIL and py2exe Issues Message-ID: <283adf56.0306041002.4b2d456f@posting.google.com> Anyone come across the problem of PIL not being able to identify image files once it's compiled with py2exe? Do I need to manually add some plugins to the setup or something? Traceback (most recent call last): File "", line 65, in ? File "", line 31, in __init__ File "PictureList.pyc", line 42, in __init__ File "PictureInfo.pyc", line 23, in __init__ File "Image.pyc", line 1571, in open IOError: cannot identify image file Versions: Python 2.2.2 (#37) PIL 1.1.4 Thanks From no at spam.invalid Wed Jun 18 19:55:33 2003 From: no at spam.invalid (Russell E. Owen) Date: Wed, 18 Jun 2003 16:55:33 -0700 Subject: best idiom for wide try/except net? Message-ID: I have an application that has to be as robust as possible but also loads some user-written modules. it is useful in a few places to catch almost any exception and report a detailed traceback, then go on. So far I've been doing this: try # code that might have bugs except StandardError: sys.stderr.write(...) traceback.print_exc(file=sys.stderr) since catching "Exception" also catches SystemExit, which sounded like a bit much. (I'd rather also not catch KeyboardInterrupt, but I can live with that). However, some standard libraries, such as socket, use exceptions which are a subclass of Exception, but not a subclass of StandardError. I'm wondering if this typical/normal/acceptable for standard libraries or is something to be fixed? The only workaround I've thought of is this, which looks a bit ugly to me (it seems a shame to have to explicitly catch stuff I don't want): try: # code that might have bugs except (SystemExit, KeyboardInterrupt): # exceptions I do not want to catch throw except: # all other exceptions sys.stderr.write(...) traceback.print_exc(file=sys.stderr) Any suggestions? -- Russell From sholden at holdenweb.com Fri Jun 27 10:45:50 2003 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 27 Jun 2003 14:45:50 GMT Subject: filedescriptor out of range in select() References: <3EFABC5E.329613C6@alcyone.com> Message-ID: "Paolo Invernizzi" wrote in message news:mailman.1056716925.10216.python-list at python.org... > Fredrik Lundh wrote: > > > but I'm pretty sure asyncore supports the "poll" interface. try changing > > the asyncore.loop call in Dibbler.py to: > > > > asyncore.loop(map=context._map, use_poll=1) > > > > and see what happens. > > Here we are again.... > Too many open files... with poll too... > > --- > Paolo > > SpamBayes POP3 Proxy Beta1, version 0.1 (May 2003), > using SpamBayes POP3 Proxy Web Interface Alpha2, version 0.02 > and engine SpamBayes Beta1, version 0.1 (May 2003). > > Loading database... Done. > SMTP Listener on port 2525 is proxying 127.0.0.1:25 > Listener on port 8110 is proxying kpnqwest.it:110 > User interface url is http://localhost:8880/ > error: uncaptured python exception, closing channel > <__main__.BayesProxyListener listening :8110 at 0x83c9f6c> > (socket.error:(24, 'Too many open files') [...] > Traceback (most recent call last): > File "/usr/local/bin/pop3proxy.py", line 731, in ? > run() > File "/usr/local/bin/pop3proxy.py", line 725, in run > main(state.servers, state.proxyPorts, state.uiPort, state.launchUI) > File "/usr/local/bin/pop3proxy.py", line 664, in main > Dibbler.run(launchBrowser=launchUI) > File "/usr/local/lib/python2.2/site-packages/spambayes/Dibbler.py", > line 528, in run > asyncore.loop(map=context._map,use_poll=1) > File "/usr/local/lib/python2.2/asyncore.py", line 206, in loop > poll_fun (timeout, map) > File "/usr/local/lib/python2.2/asyncore.py", line 190, in poll3 > obj.handle_error() > File "/usr/local/lib/python2.2/site-packages/spambayes/Dibbler.py", > line 205, in handle_error > asynchat.async_chat.handle_error(self) > File "/usr/local/lib/python2.2/asyncore.py", line 427, in handle_error > self.close() > File "/usr/local/bin/pop3proxy.py", line 368, in close > if not self.isClosed: > File "/usr/local/lib/python2.2/asyncore.py", line 372, in __getattr__ > return getattr (self.socket, attr) > AttributeError: '_socket.socket' object has no attribute 'isClosed' > I suspect that the "too many open files" is simply a symptom of a deeper problem, in that your sockets aren't being correctly closed due to a programming error. The asyncore framework will happily continue to run even if errors occur in the event-handling routines, cneatly demonstrating the dangers of an unlimited "try:/except:". There's a clear implication here that a BayesProxy instance isn't running its __init__() method, because if it *were* running it the isClosed attribute would be defined. Are you perchance subclassing Bayesproxy and overriding its __init__() rather than extending it? If so then try adding BayesProxy.__init__(self, clientSocket, serverName, serverPort) or equivalent to your subclass' __init__(). regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From doug at notAvalidEmail.com Fri Jun 6 18:49:52 2003 From: doug at notAvalidEmail.com (Doug) Date: Fri, 06 Jun 2003 22:49:52 GMT Subject: server, not client, modules needed. Message-ID: Hi, i know that there is an smtpd module in the standard library and a few web server modules out there but i was wondering if there were any other server modules (ftp,ircd,pop3, etc) on the net. i've been searching and have come up empty handed, ones using threads or asyncore would be great. TIA From jjl at pobox.com Fri Jun 20 07:59:49 2003 From: jjl at pobox.com (John J. Lee) Date: 20 Jun 2003 12:59:49 +0100 Subject: Need help optimizing first script References: Message-ID: <87smq5558q.fsf@pobox.com> bokr at oz.net (Bengt Richter) writes: > On 19 Jun 2003 06:03:22 -0700, popup391 at yahoo.com (Frederic Lafleche) wrote: [...] > No one seems to have mentioned strftime yet ;-) [...] Um, except the original poster, and me. John From misterxx at uni-koblenz.de Wed Jun 18 03:35:26 2003 From: misterxx at uni-koblenz.de (Oleg Seifert) Date: Wed, 18 Jun 2003 09:35:26 +0200 Subject: recv Message-ID: <3EF0163E.4010204@uni-koblenz.de> Hallo Leute, habe eine kleine Frage: Ich soll mit Python eine Netzwerkanfrage senden und eine Antwort ausgeben. Daf?r habe ich folgenden Skript geschrieben: ------------------------------------- from socket import * def read(): print s.recv(1024) s = socket(AF_INET, SOCK_STREAM) s.connect(("localhost", 99)) s.send("loadGraph(\"g.g\");\n") read() s.close() ------------------------------------- Die Anfrage wird gesendet und die Antwort kommt auch an, aber von dem Antwort erscheint immer nur eine Zeile. Die Antworte sind auch unterschiedlich, sie k?nnen verschiedene Zeilenanzahl haben. Wie kann ich unabh?ngig von einer Antwortstruktur, ganze Antwort ausgeben ? danke im Voraus. mfg, Oleg From CousinStanley at hotmail.com Fri Jun 20 15:51:31 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Fri, 20 Jun 2003 12:51:31 -0700 Subject: XML References: Message-ID: Roman ... My opinion of XML is that instead of stuff that looks like this .... Y I'd rather have a Cobol record layout ... -- Cousin Stanley Human Being Phoenix, Arizona From hankhu at 263.net Thu Jun 26 23:40:27 2003 From: hankhu at 263.net (Hank Hu) Date: Fri, 27 Jun 2003 11:40:27 +0800 Subject: How to upload a file with httplib? Message-ID: Hi all, I'm writing a prototype with python and need upload a zip file to a web server. Any idea? Hank Hu From andrew-pythonlist at puzzling.org Tue Jun 10 09:49:23 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 10 Jun 2003 23:49:23 +1000 Subject: Revised PEP 318 - Function/Method Decorator Syntax In-Reply-To: <20030610082514442-0400@braeburn.themorgue.org> References: <20030610082514442-0400@braeburn.themorgue.org> Message-ID: <20030610134923.GE16327@frobozz> On Tue, Jun 10, 2003 at 12:25:13PM +0000, Kevin Smith wrote: [...] > The proposed syntax is general enough that it could be used > on class definitions as well as shown below. > > class foo(object) as classmodifier: > class definition here > > However, there are no obvious parallels for use with other > descriptors such as property(). Note that you can already do tricky stuff with properties if you really want to define one all at once: class EvilProperty(type): def __new__(cls, name, bases, d): return property(d.get('get'), d.get('set'), d.get('del'), d['__doc__']) class C(object): class x: """An evil test property""" __metaclass__ = EvilProperty def get(self): print 'Getting' return 1 def set(self, value): print 'Setting to', value c = C() print c.x c.x = 5 print C.x.__doc__ This has the advantage that you can define your property in a single block, and you don't have to look too far ahead in the nested class to see the crucial "__metaclass__ = EvilProperty" line. It does kinda feel like yet-another-gratuitous-use-of-metaclasses, though ;) -Andrew. From staschuk at telusplanet.net Tue Jun 3 12:18:05 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 3 Jun 2003 10:18:05 -0600 Subject: a = b = 1 just syntactic sugar? In-Reply-To: <3EDC51DE.6040502@nospam.com>; from kendear@nospam.com on Tue, Jun 03, 2003 at 07:44:35AM +0000 References: <3EDC51DE.6040502@nospam.com> Message-ID: <20030603101805.A341@tibia.amotlpaa.bogus> Quoth Kendear: [...] > I think if a language supports a = b = 1 > then that means "b = 1" returns a value > of 1, which can be assigned to any variable. > But it seems like it is only a syntactic sugar > in Python? Right. Note also that the assignments happen left to right; try d = {} i = 0 i = d[i] = 4 print d (Though obviously it's not good style to exploit this detail in real code.) The relevant part of the Language Reference is > if Python supports 1 < a < 10 > then maybe it is also just syntactic sugar. Right. It's the same as 1 < a and a < 10 except that the middle expression is evaluated only once. See > Other language might take it as (1 < a) < 10 > which is just the boolean 0 or 1 less than 10 > which is always true. ... which is one reason Python is better than such languages. The test 1 < a < 10 does in Python is actually useful, and in keeping with the mathematical notation. -- Steven Taschuk 7\ 7'Z {&~ . staschuk at telusplanet.net Y r --/hG- (__/ )_ 1^1` From jjl at pobox.com Thu Jun 19 08:04:26 2003 From: jjl at pobox.com (John J. Lee) Date: 19 Jun 2003 13:04:26 +0100 Subject: parsing complex web pages References: <873ci7x80p.fsf@pobox.com> Message-ID: <87r85qqnn9.fsf@pobox.com> John Hunter writes: > >>>>> "John" == John J Lee writes: > > John> If it works well for you, why not stick with it? [...] > It did cause me to wonder though, whether some good python html->text > converters which render the html as text (ie, preserve visual layout), > were lurking out their beneath my radar screen. If they exist, it's unlikely they'll do as good a job as lynx (in general, not talking about Yahoo in particular), because there is so much awful HTML out there. lynx has been around a long time. John From nosp at m.needed Wed Jun 25 08:35:17 2003 From: nosp at m.needed (Steve McAllister) Date: Wed, 25 Jun 2003 14:35:17 +0200 Subject: Newbie: "compiling" scrips (?) In-Reply-To: References: Message-ID: > You don't need to compile into the machine language of every > platform you target. Instead the "compilation" process > generates bytecodes for a fictitious virtual computer. [...] > Both Java and Perl work in a similar way I would add the nuance that unlike Java, no explicit compilation phase has to be performed, which, in combination with lightweight syntax and library ergonomy, saves a lot of time, undermine anything. For instance, when you go into quick-and-dirty checks, no sticks will be put in your wheels because you forgot to throw IOException, because a method throws more than the superclass's, etc. From cybersamurai at mac.com Fri Jun 13 12:56:27 2003 From: cybersamurai at mac.com (Luiz Siqueira) Date: Fri, 13 Jun 2003 13:56:27 -0300 Subject: html on Python Message-ID: <3804745.1055523387787.JavaMail.cybersamurai@mac.com> I need some html browser or some package to work with html for my project, I try Grail but it have a lot of deprecated code. Thanks about help me. From andrew-usenet at lexical.org.uk Mon Jun 2 11:08:52 2003 From: andrew-usenet at lexical.org.uk (Andrew Walkingshaw) Date: 2 Jun 2003 15:08:52 GMT Subject: A Python application server? References: Message-ID: In article , Duncan Smith wrote: > Hello, > I'm trying to put together a (basic) design for an online > examination system. The system already exists, but is based on Java > technologies. I have (probably prematurely) assured the author that the > system could have been developed in Python. This is based in faith rather > than reason, as I have never had cause to consider such a thing before > (although I can now envisage that I might need to develop a simple > application server within the next year or so). In terms of prior art, I and a fellow student, as holiday employees, wrote an exam server in Python (mod_python/apache, postgres backend), conformant to the QTI Lite spec (http://www.imsproject.org/ - basically multiple-choice visual/audio/textual questions), in about three months: we didn't have strong authentication or any sort of eavesdropping protection, though (we were doing everything via unencrypted HTTP). This was meant to be released as BSD license software at some point, but it never appeared. :( This makes me believe more experienced programmers could put together a rather better system in the same sort of timeframe. Is there any reason (type of question, etc) why you can't aim for a web-browser based solution on the client side, using SSL authentication or similar to counter MITM/eavesdropping/impersionation attacks? - Andrew -- Andrew Walkingshaw | andrew-usenet at lexical.org.uk From gh at ghaering.de Fri Jun 13 09:56:29 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 13 Jun 2003 15:56:29 +0200 Subject: user authentication interface in python In-Reply-To: <3cf72d52.0306130501.6acb9984@posting.google.com> References: <3cf72d52.0306130501.6acb9984@posting.google.com> Message-ID: <3EE9D80D.4030504@ghaering.de> scn wrote: > hello. does anyone have a high-level example of how to implement > 'secure' user authentication interface for web users in python. > > i am in the process of designing a simple web application that > requires user authentication and i remembered that php typically held > system authentication information in a separate file and included this > file in the main interface script. What's the advantage of this approach? The only pro I see is that if you misconfigure your webserver so the .php file is rendered as-is without processing through PHP the user won't see the password. > is there a similar convention or methodology in python for > accomplishing the same idea? [...] Sure, you can a) import a module from elsewhere or b) open the file using file("/path/to/file") and read it I still don't see why you'd want to store user information like this. FWIW, I typically do authentication either using Apache directly or store login and password in a PostgreSQL database. From hsart at gmx.de Fri Jun 27 06:27:42 2003 From: hsart at gmx.de (H.S. Art) Date: Fri, 27 Jun 2003 12:27:42 +0200 Subject: output Message-ID: <3EFC1C1E.6020504@gmx.de> Hi folks, I have a sript that runs very well. I do my output to the python shell with the print command. That works well, too. print 'Error occured ' + str(i+1) No I want to have my output into a textctrl frame in a window. I start my script by pushing a button in my window. It starts fine but I can't see any output. For test purposes I added the following code to the event handler of the button: self.textCtrl1.WriteText('TEST\n') This produces output to my text ctrl window. So I replaced all 'print' commands in my script with 'self.textCtrl1.WriteText ...' Unfortunately it still doesn't work. I don't get any output from my script. I always get an error saying self is unknown. That's why I replaced it with the name of the file of the window and so on and so on. Nothing worked. Can you help me telling me how I have to write my code to get an output? Thank you very much. Henry From adalke at mindspring.com Wed Jun 4 17:33:24 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 4 Jun 2003 15:33:24 -0600 Subject: Tk vs wxPython ? References: Message-ID: Aur?lien G?ron: > - the documentation is half Tk and half python which makes it confusing Well, I find the wxPython documentation pretty confusing myself. The Qt documentation is much easier to use. For example, suppose I'm looking at the wxListBar documention to find out how to select an item programmatically. It's not on that page - I need to look at the list of base classes, guess that it's in wxControlWithItems and look at that documentation. Qt's docs include a list of all methods available from a given widget. I also like Qt's cross references to code, inclusion of how the widgets look, and that the HTML docs for a widget are in a URL ending with the same name (I have Konqueror set up so that "qt:XYZ" expands to "/path/to/qt/docs/qtXYZ.html", so I can quickly pull up the docs for the widget.) Or, for example, see the "wxGrid classes overview" which has sections with content "Yet to be written." > So I looked for a better way and behold: I found wxPython. In comparison, > it truly ROCKS ! I've only dabbled in Qt and wxPython, but so far I've found Qt easier to use. The API also seems a bit more stable - I've known people who used wxWindows a couple years ago, and things like the table widget kept changing enough that they decided to write their own interface layer to that widget. That may have stabilized since then. > I'm sure beginners would come to love Python even faster if they could truly > create their first GUI in minutes. I'm voting for wxPython to replace Tk in > the future Python distribution. > > Any comments on this ? Anyone else want to vote ? I also found Qt's Designer easier to use than Boa Constructor or the XML-based one which comes with wxPython. In no small part because Qt includes a nice tutorial describing how to write a simple application. With Boa Constructor, I couldn't figure out how to say "put a spacer between these two objects". I gave up and just wrote the code myself, using an empty text widget, but even then my layout doesn't work correctly on resizes, and I don't yet know why. Then again, I don't use Tkinter, so changing to another default GUI doesn't really affect me. Andrew dalke at dalkescientific.com From alanmk at hotmail.com Fri Jun 13 07:39:51 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 13 Jun 2003 12:39:51 +0100 Subject: OnFileOpent(self, event): References: Message-ID: <3EE9B807.491924C6@hotmail.com> MK wrote: > Hi group, > I just picked up Python two days ago and it's ....... true Call me a prude, but I don't believe that there's any need for that kind of "descriptive language" in c.l.p. This is a family newsgroup after all, isn't it? Don't we get high-school kids and younger around here? :-( -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From staschuk at telusplanet.net Mon Jun 2 17:44:13 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 02 Jun 2003 21:44:13 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 2) Message-ID: QOTW: "There is a certain charm to seeing someone happily advocate a triangular wheel because it has one less bump per revolution than a square wheel does." -- Chuck Swiger "It took me years to realise how deep and important the divide is between wanting an SDK and wanting to know the underlying protocol." -- Tim Bray Discussion: Bengt Richter works out (with a few revisions, and variants from other posters) how to make a switch-case work-alike by abusing exceptions. Carl Banks demonstrates an introspective technique for "declaring" local variables. A draft essay explaining descriptors, by Raymond Hettinger. Announcements: Python 2.2.3: A bug fix release for the Python 2.2 code line. Voting for the 2003 Active Awards for open-source programmers starts June 3. EmPy 3.0: a system for embedding Python expressions and statements in template text. gdmodule 0.41: A Python wrapper for the GD graphics module. McMillan Installer 5b5_3: A utility for distributing Python applications; this is a bug fix release. managesieve 0.2: A MANGAGESIEVE client library for remotely managing Sieve scripts, including an interactive 'sieveshell'. msnp.py 0.3: A pure-Python implementation of the MSN instant messaging protocol. PyGDChart Alpha 2: A Python interface to the GDChart graphing library. PyOSG 0.4.0: Python bindings for the OpenSceneGraph real-time visualisation library. yawPyCrypto 0.02: A more full-featured PyCrypto wrapper. ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From a.schmolck at gmx.net Mon Jun 23 11:06:14 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 23 Jun 2003 16:06:14 +0100 Subject: Getting a list of an object's methods? References: <2259b0e2.0306230447.52460ace@posting.google.com> Message-ID: mis6 at pitt.edu (Michele Simionato) writes: > The problem with .mro() is that it is a method of the metaclass > 'type': > > >>> dir(type) > ['__base__', '__bases__', '__basicsize__', '__call__', '__class__', > '__cmp__', '__delattr__', '__dict__', '__dictoffset__', '__doc__', > '__flags__', '__getattribute__', '__hash__', '__init__', > '__itemsize__', '__module__', '__mro__', '__name__', '__new__', > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', > '__subclasses__', '__weakrefoffset__', 'mro'] > > IIRC, Tim Peters wrote in this newsgroup some months ago that 'dir' > was > designed in such a way to not report metaclass methods. The idea was > that the typical user doesn't want too much information. Therefore > 'dir' > is not meant to be exaustive: > > >>> help(dir) > 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: > > Nevertheless, one may disagree with this attitude, and I think that if > enough users protest enough, we may get a more powerful 'dir' in the > future. The desirable semantics for `dir` are not relevant here. If 'mro' is a "member" of `int`, then ``inspect.getmembers(int)`` should return it, regardless of whatever `dir` does, because that's what its documentation says: Definition: inspect.getmembers(object, predicate=None) Docstring: Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate. Now I have no idea what the hell a "member" is supposed to be (inspect's docu won't tell you and the only sense in which it occurs in the language ref is that of set membership (i.e. qualfiying __contains__)), so my guess is that it's just some ad hoc synonym for attribute (not that I remember stumbling across a clear definition of attribute anywhere, either). "Member" better have *some* reasonably well-defined meaning, because unlike `dir` which is supposed to just give a "convinient" overview of an objects content in interactive session, AFAICT `inspect.getmembers` is meant to be used for programming. I somehow prefer my programs to have well-defined meanings. So if no-one enlightens me, I shall file a bug report. 'as From dradul at yahoo.com Mon Jun 9 14:26:17 2003 From: dradul at yahoo.com (Alejandro Lopez-Valencia) Date: Mon, 09 Jun 2003 13:26:17 -0500 Subject: Size of Cygwin's distribution References: Message-ID: On Mon, 09 Jun 2003 11:56:06 -0400, Jason Tishler wrote: > >On Mon, Jun 09, 2003 at 10:20:36AM -0500, Alejandro Lopez-Valencia wrote: >> Yet, I do have a little complain: size. Why is so big? There is a lot > Jason, >OK, submit a patch to remedy the above and I will consider it. Note >that I am just tar-ing up the "make install" and doc trees. Hmmm... To cygwin's bug tracker/mailing list? Or to you directly? >Maybe it's time to split the monolithic package into multiple packages? >However, an important goal to keep in mind is minimizing the "cost" for >me to generate these packages. Any solution must be script-able and fit >into my packaging infrastructure. Sure, I think what I have in mind can be integrated within your build script. I'll give it a spin. Cheers Alejo From polux2001 at wanadoo.fr Sun Jun 1 03:01:33 2003 From: polux2001 at wanadoo.fr (polux) Date: Sun, 01 Jun 2003 09:01:33 +0200 Subject: tkinter text display on linux Message-ID: I've noticed that the tkinter text display in canvas is much more faster on windows than on linux....do you have the same problem ? Is there a way to fix it ? thanks From Dick.Zantow at lexisnexis.com Mon Jun 16 13:31:16 2003 From: Dick.Zantow at lexisnexis.com (rzed) Date: Mon, 16 Jun 2003 13:31:16 -0400 Subject: Loop from 'aaaa' to 'tttt' ? References: Message-ID: Lars Schaps wrote: > Hello. > > In my program in need a loop from 'aaaa' over > 'aaac', 'aaag', 'aaat', 'aaca' to 'tttt'. > (Possible characters 'a', 'c', 'g' and 't') > > One idea i had is to take a number n with the base of > 4 and use > > t= string.translate( '0123', 'acgt') > string.translate( n, t) > > But i don't know how to convert from base10 to base4. > > Has anyone a idea? > I'm not sure if this is at like what you had in mind, but: ltrs = 'acgt' for a in ltrs: for c in ltrs: for g in ltrs: for t in ltrs: print '%s%s%s%s' % (a,c,g,t) -- rzed From martin at v.loewis.de Sun Jun 8 02:39:59 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 08 Jun 2003 08:39:59 +0200 Subject: Characters in Python References: <23891c90.0306060626.24e6646d@posting.google.com> Message-ID: jansun at home.se (Jan Sundstr?m) writes: > By the way, where do I find what strings are acceptable names for > encodings? http://www.python.org/dev/doc/devel/lib/node126.html Regards, Martin From gmuller at worldonline.nl Tue Jun 3 15:06:28 2003 From: gmuller at worldonline.nl (GerritM) Date: Tue, 3 Jun 2003 21:06:28 +0200 Subject: reading files in folder References: Message-ID: > Here are links that demonstrate os.path.walk. Note > the use of isfile to distinguish between files and > directories. > > http://www.faqts.com/knowledge_base/viewphtml/aid/3380/fid/481 the first link misses one dot, the working link is: http://www.faqts.com/knowledge_base/view.phtml/aid/3380/fid/481 regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From timr at probo.com Sat Jun 14 23:38:58 2003 From: timr at probo.com (Tim Roberts) Date: Sat, 14 Jun 2003 20:38:58 -0700 Subject: You know you're a Pythonista when.. References: <16102.10640.855883.967908@montanaro.dyndns.org> <20030610190206.54459.qmail@web11407.mail.yahoo.com> Message-ID: Skip Montanaro wrote: > >Me too from time to time. Someone else mentioned using Python as their >login shell. Just for the hell of it I created an account named "skippy" on >my laptop with the same privileges as my normal "skip" account but with >Python instead of Bash as my login shell: In Unix, this option little more than an exercise, because most of the shells are so functional. However, there is a very functional and quite useful Python shell for Windows called PyDOS that adds some very useful things, as well as allowing direct Python statements. It's especially useful on Windows 98, since it adds path completion and other niceties that are built-in to Win2K. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From alanmk at hotmail.com Thu Jun 12 14:20:13 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 12 Jun 2003 19:20:13 +0100 Subject: Sockets and threads References: <3EE6FEE7.8CFF39B5@hotmail.com> Message-ID: <3EE8C45D.DDF6780B@hotmail.com> Byron Morgan wrote: >>> If I monitor a socket connection or even jsust listen to a >>> socket in a thread, Python's cpu usage expands to use all >>> available processor time. > Here are two code samples - sample 1 runs very politely, using > minmal cpu. Sample 2 causes the cpu usage meter to max out to 100% > unless there is a sleep cycle in main(), in which case cpu usage > looks very much like sample 1 (but I need for my apps to do stuff, > not spend the day sleeping). > # tnet1.py > while not msvcrt.kbhit(): > txt = session.read_until('\n',.5) > #seems to make no difference whether a timeout value is used or not. > if txt.strip() is not '': > print txt.strip() I think that this is one problem. My understanding is that msvcrt.kbhit() is a non-blocking call, meaning that there will no pause whether or not a key has been hit. This while loop will cycle continually until a key is pressed. And if the code that is running inside the loop does not pause for any reason, then this will consume all of the CPU cycles. But, inside your function, you do a "Telnet().read_until()", which is actually blocking waiting for particular input, i.e. the "\n". This means that the ".read_until" function won't return until it has read a "\n" from the input stream, or until 0.5 seconds have elapsed. Which means that most often, the keyboard will only be checked every 0.5 seconds. Which is fairly light load for a modern machine ;-) Which is why this while loop *seems* to behave properly. > #tnet2.py > def main(): > while not msvcrt.kbhit(): > pass > #sleep(5) > #uncomment sleep statement and cpu usage returns to normal. > session.close() And the same while loop again, but this time without a blocking call inside it to prevent it from chewing up all of the CPU cycles. If you uncomment your sleep(5), you will find that it runs continually, waking up every five seconds, checking once if the keyboard was hit and then going back to sleep or exiting. One keyboard check every five seconds is a pretty light load, so you wouldn't notice it on your cpu meter. But it won't respond to your input while it is inside that sleep call. If you want to check two different sources of information in this way, you have to make a trade-off between how many CPU cycles you want to consume and how responsive you want your application to be. Make your while loop pause for a configurable amount of time, and pause that amount. These loops often have a format like this: timeout = 0.100 # 100 milliseconds while 1: # Do a non-blocking check of source 1 checkSource1() # Do a non-blocking check of source 2 checkSource2() # And be nice to the cpu sleep(timeout) On platforms like *nix, there are ways of checking multiple sources at a time, through a select, but you need to be able to wrap everything as a file descriptor. This kind of activity should only be required in a single-threaded situation. The reason for having multiple threads is that threads can operate independently, meaning that some can block while others continue executing, i.e. do multiple things at once, without you having to explicitly manage them. BTW, another thing I notice (in "tnet2.py") is that you're checking "msvcrt.kbhit()" in two threads at a time. This is threading on thin ice, since input sources like keyboards can generally not be shared between two threads simultaneously consuming the input. However, if you don't actually read any characters from the keyboard, it should be OK. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From stan at stanheckman.com Sat Jun 28 13:00:06 2003 From: stan at stanheckman.com (Stan Heckman) Date: 28 Jun 2003 13:00:06 -0400 Subject: (Numeric) should -7 % 5 = -2 ? Message-ID: <87k7b6cf3d.fsf_-_@schedar.com> Is the following behavior expected, or have I broken my Numeric installation somehow? $python Python 2.2.2 (#1, Mar 21 2003, 23:01:54) [GCC 3.2.3 20030316 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Numeric >>> Numeric.__version__ '23.0' >>> -7 % 5 3 >>> Numeric.array(-7) % 5 -2 >>> Numeric.remainder(-7, 5) -2 -- Stan From bdeck at lycos.co.uk Wed Jun 4 10:27:57 2003 From: bdeck at lycos.co.uk (deckerben) Date: Wed, 4 Jun 2003 16:27:57 +0200 Subject: PythonD: 4Suite or Twisted? References: <3eddd372$0$16609$9b622d9e@news.freenet.de> <3EDDF17B.F7B930E@engcorp.com> Message-ID: <3ede00c9$0$16597$9b622d9e@news.freenet.de> "Peter Hansen" wrote in message news:3EDDF17B.F7B930E at engcorp.com... > deckerben wrote: > By the way, do you really mean DOS, as in MS-DOS or PC-DOS or something > *without* Windows running on top, or do you just mean in a DOS window > of one of Microsoft's operating systems? > > If the former, how do you plan to get Python running? Once you do, are > you sure either of the above will work on it? They might require modules > that are not available to you on DOS. But Python DOES run under DOS, especially well under DJGPP. Have you seen our project at htpp://members.lycos.co.uk/bdeck ?? There is also a downloadable pre-alpha 4suite there for DOS (v12) ciao, Ben From aleax at aleax.it Tue Jun 17 04:15:27 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 17 Jun 2003 08:15:27 GMT Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> <3eece571$0$49110$e4fe514c@news.xs4all.nl> <3BfHa.95965$pR3.2057696@news1.tin.it> Message-ID: Bengt Richter wrote: ... >>def isStringLike(s): >> try: s+'' > Nit: succeeding with this test could be expensive if s is e.g., a 100MB > file image (I think this has come up before in a discussion of such Yes. The solution I suggested then (and keep in my sleeve for possible future needs, but have never needed yet -- see below) was try: s[:0]+'' > I like the concept of testing for comptible behavior, but I would want to > feel sure that there could be no unexpected side effects from testing any > candidate args. You cannot "feel sure" in any language that allows "virtual methods": whenever you call a potentially-virtual method you _might_ be hitting a weird override that has crazy side effects. To achieve polymorphism, you give up on the yearning to "feel sure" and trust the client to NOT do such crazy things. Testing candidate args is not any different from using any (potentially virtual) operation whatsoever on the args, i.e., no different from any other application whatsoever of polymorphism. > I wonder if > try: s and s[0]+'' or s+'' > would serve as well, and protect against the big-s hit. Or is > there a sensible string-like thing that doesn't support logical > tests and indexing but does support adding '' ? I prefer the more concise suggestion above, which requires slicing instead of indexing and logical tests. However, the issues are similar. In particular, both of these tests classify mmap.mmap instances as "string-like", while my preferred s+'' doesn't -- i.e., an mmap instance isn't "directly" string-like, but its slices and items are (indeed, said slices and items ARE strings!-). So, in my sleeve next to the slicing possibility is a small reminder to specialcase mmap if I ever do end up needing that... and, the very need to specialcase is in turn a reminder that the workarounds are not entirely pleasant. Alex From mis6 at pitt.edu Sun Jun 8 08:15:10 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 8 Jun 2003 05:15:10 -0700 Subject: a = b = 1 just syntactic sugar? References: Message-ID: <2259b0e2.0306080415.52a8ba8@posting.google.com> "Terry Reedy" wrote in message news:...> > So if we are to make special syntactic rules for lambda, I would like > to make them less powerful by restricting the expression body to > lambda-less expressions Cool! Unfortunately, this cannot be done because it would break existing code (most of it in Python obfuscated code contests ;-). Anyway, it is a nice idea and I like it! Michele From bignose-hates-spam at and-zip-does-too.com.au Wed Jun 18 00:29:43 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Wed, 18 Jun 2003 04:29:43 GMT Subject: Python Cannot be Killed References: Message-ID: On Wed, 18 Jun 2003 13:57:36 +1000, Delaney, Timothy C (Timothy) wrote: > There is a growing view (not necessarily correct - IANAL) that the GPL > is actually an explicit waiver of copyright due to the requirement to > distribute the source when the binary is distributed. Your use of the word "explicit waiver of copyright" is provably false, since "explicit" means "clearly stated; plain in language", and there is no language in the GPL that clearly states a waiver of copyright. You may mean "implicit", which is the exact opposite ("fairly to be understood, though not expressed in words"), but there has been no ruling on the GPL to date (because anyone found to be in breach of its terms has decided not to challenge it in court), so we can't know anything about what a court may find implicit in the license. So we are left with a putative "growing view", which has only the status of rumour; and you don't state whether it is a growing view among copyright lawyers, or among casual observers, or even how many people hold this view. Thanks for the FUD, but no thanks. -- \ "Giving every man a vote has no more made men wise and free | `\ than Christianity has made them good." -- Henry L. Mencken | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From gerrit at nl.linux.org Wed Jun 11 11:55:55 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 11 Jun 2003 17:55:55 +0200 Subject: FW: [Python-Dev] Re: PEP-317 Message-ID: <20030611155555.GA5264@nl.linux.org> Hi, Guido officially rejected PEP-317. :( ----- Forwarded message from Guido van Rossum ----- Date: Wed, 11 Jun 2003 15:10:22 +0200 Subject: [Python-Dev] Re: PEP-317 From: Guido van Rossum To: Michael Chermside Cc: guido at python.org, staschuk at telusplanet.net, python-dev at python.org X-BeenThere: python-dev at python.org Sender: Gerrit Holl Old-Date: Wed, 11 Jun 2003 09:13:29 -0400 > If the PEP winds up being officially rejected, I propose that it > grow a "rejection reasons" section explaing why, and that this section > also describe the above plan as the "plausible alternative" to PEP 317 > for eventual migration to new-style exceptions. I strongly recommend doing that. I hereby officially reject PEP 317. --Guido van Rossum (home page: http://www.python.org/~guido/) _______________________________________________ Python-Dev mailing list Python-Dev at python.org http://mail.python.org/mailman/listinfo/python-dev ----- End forwarded message ----- yours, Gerrit. -- 132. If the "finger is pointed" at a man's wife about another man, but she is not caught sleeping with the other man, she shall jump into the river for her husband. -- 1780 BC, 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 sismex01 at hebmex.com Wed Jun 4 10:08:14 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 4 Jun 2003 09:08:14 -0500 Subject: Possible PEP: Improve classmethod/staticmethod syntax Message-ID: > From: Skip Montanaro [mailto:skip at pobox.com] > Sent: Wednesday, June 04, 2003 9:03 AM > > bryan> thanks skip... now i can see the elegance of this solution. > bryan> wouldn't this also solve the pre/post conditions that are > bryan> currently put in comments with another current solution? > > That was the general idea. ;-) > > bryan> but, how would you handle pre/post conditions that are only > bryan> supposed to be used in a debug version? > > Like I said, it was probably full of holes. > > Skip > Since decorators are in a dictionary, in what order should they be applied? I though item extraction from a dictionary was, basically, unordered. The idea of keeping them in a list (syntax #1) was that it's easy to see the order they're going to be applied to the original function. -gca Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From smulloni at bracknell.smullyan.org Sat Jun 14 23:20:43 2003 From: smulloni at bracknell.smullyan.org (Jacob Smullyan) Date: 14 Jun 2003 23:20:43 -0400 Subject: Zip imports on python 2.2? References: Message-ID: In article , Alex Martelli wrote: > > > Beni Cherniavsky wrote: > >> I have a university shell account with 10MB quota (most of it filled >> by mail). At last they've installed python 2.2 (they forgot curses, >> sockets and some other nice modules but never mind ;). Now I'm >> installing some modules, notably docutils, under my home directory and >> it takes even more of my quota... >> >> Is there some pure-python way to use zip imports in Python 2.2 so I >> can save space by compressing the installed modules? > > You might kludge something up by using your site.py (or the like) to > substitute a customized __import__ wrapping the normal built-in one -- > your customized __import__ might look into the relevant zipfiles' > directories, extract the needed modules into some /tmp subdirectory > suitably created and inserted in your sys.path, then delegate to the > real-builtin __import__. There are cleaner ways but you may not need > generality enough -- perhaps this kludge, perfected experimentally > for your specific and rather peculiar needs, might suffice. To save yourself some coding, you could use the vfs importer in SkunkWeb. To use it you need the vfs package available at http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/skunkweb/skunkweb/pylibs/vfs/ or in the skunkweb tarball (actually, sourceforge's viewcvs seems to be borked at the moment) and Gordon MacMillan's iu.py, which is available at ../iu.py relative to the above, among other places. Then you need to do something along these lines: import vfs.importer # install the import hook vfs.importer.install() # create a virtual filesystem that is backed with a zip file. # if you have multiple archives, you could create a MultiFS # and mount various other fses at mount points on it. vfs.VFSRegistry['foo']=vfs.ZipFS('/home/me/myzip.zip') import sys sys.path.append('vfs:///path/to/my/libs') # you should now be able to use the import hook import MyZippyModule I haven't tested this particular example, but I doubt that it contains more than two or three fundamental errors! You can also import from various other sources, of course, by means of this hook. Cheers, Jacob Smullyan From mertz at gnosis.cx Tue Jun 10 13:12:58 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Tue, 10 Jun 2003 13:12:58 -0400 Subject: Rudeness with names References: <2259b0e2.0306100912.8946854@posting.google.com> Message-ID: |> >> [Aahz didn't like me calling anonymous posters "anonymous cowards"] |> >>- anonymous posters |> >>- top-posting |> >>- broken quoting |I have seen Gerhard using "anonymous cowards" before and liked |the joke. I didn't imagine it could be taken seriously as an offence. I didn't think the "anonymous coward" was meant in a bad way. But I -do- think it kinda misses the nature of the medium. On /. (and similar webboards, but that's the one where the term comes from), you actually -can- write posts with no return address or identifying info. Usenet is just different: EVERY poster has a From: field in their header. So the idea of an AC is misguided. The closest it comes is when posters mangle their addresses in a (misguided) effort to stop spammers from harvesting it. Those posters are closer to being AC than are those who just have somewhat unusual netnames. I know how Aahz feels, FWIW. I can hardly count the number of times discussants (mostly on other groups) have slighted my dear old dad Mr. Lotus, and my sweet mother Ms. Eaters. 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 jkraska at san.rr.com Thu Jun 19 23:31:31 2003 From: jkraska at san.rr.com (Courageous) Date: Fri, 20 Jun 2003 03:31:31 GMT Subject: Definition of Aspect Oriented Programming References: <8csIa.133$rN.2282@news-server.bigpond.net.au> Message-ID: <1pv4fvsv2bvmglio3l5be4e9qakim3or4t@4ax.com> >> What is aspect oriented programming? Dynamic retrofit of classes to support functionality not anticipated by their designer. C// From martin at v.loewis.de Wed Jun 4 00:30:25 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 04 Jun 2003 06:30:25 +0200 Subject: nntplib body question References: <879Da.1139848$uT2.175876@news.easynews.com> Message-ID: "Peter Melchart" writes: > is there any way to load only the first x lines of a post body via nntplib? > with read callbacks or something similar? To my knowledge, the NNTP protocol does not support such a query. So regardless of what the API is, you always have to fetch the entire body, and throw away all lines you don't want. Now, keeping only the first x lines of a string is certainly possible in Python. Regards, Martin From h_schneider at marketmix.com Mon Jun 23 02:25:44 2003 From: h_schneider at marketmix.com (Harald Schneider) Date: Mon, 23 Jun 2003 08:25:44 +0200 Subject: Python 2.2.3 test_re.py fails with coredump on FreeBSD 5.0, fails also on FreeBSD4.8 References: <2251d03c.0306211009.2596e9fd@posting.google.com> Message-ID: import pre as re is a practical workaround for most appliacations on the FreeBSD platform. --Harald "PieterB" schrieb im Newsbeitrag news:2251d03c.0306211009.2596e9fd at posting.google.com... > Ok, > > I had a little look at testing Python 2.2.3 under FreeBSD and > 5.0. When I use './configure ; make ; make test' Lib/test/test_re.py > gives a Signal 10 (coredump) on FreeBSD5. The test coredumps because > of the following test from Lib/test/test_re.py: > > > if verbose: > print 'Test engine limitations' > > # Try nasty case that overflows the straightforward recursive > # implementation of repeated groups. > try: > verify(re.match('(x)*', 50000*'x').span() == (0, 50000)) > except RuntimeError, v: > print v > > > On FreeBSD 4.8 this test also fails, but doesn't core dump: > %python2.2.3 test_re.py > Running tests on re.search and re.match > Running tests on re.sub > Running tests on symbolic references > Running tests on re.subn > Running tests on re.split > Running tests on re.findall > Running tests on re.match > Running tests on re.escape > Pickling a RegexObject instance > Test engine limitations > maximum recursion limit exceeded > Running re_tests test suite > === Failed incorrectly ('(?u)\\w', u'\xc4', 0, 'found', u'\xc4') > > Can anybody, give me a clue: > a) if this is caused by a FreeBSD5.0 issue, or by Python. > Can somebody test this on FreeBSD 5.1 or FreeBSD5-CVS? > b) how can I fix the coredump on FreeBSD 5.0? > c) what should be done to fix the test on FreeBSD 4.8? > > Can this related to the FreeBSD python/zope/zwiki stability problems > for FreeBSD. (see http://zwiki.org/GeneralDiscussion200306). Zwiki > makes heavy use of regular expressions. > > I also made some patches to make regrtest.py aware of freebsd4/freebsd5. > I've put them online at: http://www.gewis.nl/~pieterb/python/bugs-2.2.3/ > > Thanks in advance, > > PieterB > > -- > http://zwiki.org/PieterB From gh at ghaering.de Tue Jun 3 08:58:36 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 03 Jun 2003 14:58:36 +0200 Subject: Bi-directional communication with external programs? In-Reply-To: References: Message-ID: <3EDC9B7C.5010404@ghaering.de> Norbert Nemec wrote: > Hi there, > > can anybody help me on this: I want to communicate bidirectionally with a > gnuplot session I spawned from python. [...] Shouldn't http://gnuplot-py.sourceforge.net/ make this unnecessary? -- Gerhard From anton at vredegoor.doge.nl Sat Jun 28 04:44:17 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 28 Jun 2003 10:44:17 +0200 Subject: "Newbie" questions - "unique" sorting ? References: <8da5fvsnidpjtblgfj4484spso2t9e6r95@4ax.com> Message-ID: "Cousin Stanley" wrote: > Edited version of screensaver.py .... > > http://fastq.com/~sckitching/Python/scr_av.py > >I'm sure you will hate it, >but it's much easier for me to read .... On the contrary, I am very glad someone reads my code and make changes to it, for better or worse! The more "eyeball" inspection code gets, the more chances it has into evolving into something better, even if sometimes newer versions of the code are worse than earlier versions. It works like a genetic algorithm improving ones code snippets :-) The other thing is that while using Python it seems to be common to read ones previous code and discover that code from only a few months ago would be done very differently now. For example my screensaver module imports a "sequencer.py" file that could now be rewritten in probably a fourth of the number of lines, because someone on c.l.py here made a comment on a newer version of it that was already half the number of lines of "sequencer.py". Also the "Transformer" class in the screensaver needlessly recomputes a lot of things at every call that could be done during initialization, later versions of this class are doing this better. My personal observation is that *everything* I write in Python is a candidate for improvement in only a few months time because of my changing perspectives on the matter. For another perspective on the "lulu" code for example, try this : trans = [string.lower(chr(i)) for i in range(256)] for i in range(256): if not trans[i] in string.letters: trans[i] = ' ' trans = ''.join(trans) I think this is both a line or so shorter than the original code and is probably also a bit clearer. Because IMO everything written in Python is improved sooner or later -according to how many people look at it- I expect *this* code fragment to be updated once again soon. This peculiar aspect of Python (and probably other high level languages) is probably caused by the fact that Python code comes closer to ones thoughts than other code, and -at least for me- thoughts are the most volatile elements in the world. So better get used to it (if your experience is anything like mine of course) and don't let yourself be distracted by the code-reusers, unit-testers, and static typers that are still trying to get a grip on this elusive aspect of Python coding. Anton From maxm at mxm.dk Wed Jun 4 18:29:32 2003 From: maxm at mxm.dk (Max M) Date: Thu, 05 Jun 2003 00:29:32 +0200 Subject: Not getting all keys in FieldStorage (Multipart form data) In-Reply-To: <3EDDF63D.88366C54@hotmail.com> References: <3EDDDF00.3070104@mxm.dk> <3EDDF63D.88366C54@hotmail.com> Message-ID: Alan Kennedy wrote: > The CGI "spec" specifies two different mechanisms for providing access to the > two different types of query data. URI query data, after the "?", should be made > available in the "QUERY_STRING" environment variable, whereas POSTed or PUT form > data should be made available on standard input. There is no specification of > what to do when both forms of data are specified, and therefore no guidance on > what the cgi.py module should do. > > http://hoohoo.ncsa.uiuc.edu/cgi/env.html > > Best to follow the simple rules stated than try to interpret situations outside > the explicitly stated rules. I would also suspect it to have different behaviours with different enctypes. The IIS at least acts a bit differently when you try and upload files with enctype="multipart/form-data". You need to read the form as binary data, and once you have done that you can no longer get the QUERY_STRING. It simply dissapears. It would also be a bit of luck if an undefined situation was implemented the same way in all browsers and webservers. -- hilsen/regards Max M Rasmussen, Denmark http://www.futureport.dk/ Fremtiden, videnskab, skeptiscisme og transhumanisme From yserrano at cdr.ethz.ch Mon Jun 23 11:53:52 2003 From: yserrano at cdr.ethz.ch (Yves Serrano) Date: Mon, 23 Jun 2003 17:53:52 +0200 Subject: non blocking named pipes Message-ID: <3ef72290$0$20050$fb624d75@newsspool.solnet.ch> hi I have a problem with named pipes.... I searched in the web, but don't found any working solution.... My Problem is that I have a pipe (/temp/pipe) where sometimes some data ist written into, but not very often. I try to write a python script that opens the pipe and gets the data if its there. I no data is there the script should not block, it should immediately exit without data. How to do that? I'm using python 2.2 on linux regards yves From rajarshi at presidency.com Tue Jun 10 11:18:46 2003 From: rajarshi at presidency.com (Rajarshi Guha) Date: Tue, 10 Jun 2003 11:18:46 -0400 Subject: isFloat: Without Exception-Handling References: <%82i9.1366$bh1.943@fe03> Message-ID: On Wed, 18 Sep 2002 12:47:40 -0400, Steve Holden wrote: > "Rajarshi Guha" wrote in message > news:pan.2002.09.18.11.40.50.766802.29524 at presidency.com... >> On Wed, 18 Sep 2002 11:41:47 -0400, Thomas Guettler wrote: >> >> > Hi! >> > >> > Is there a way to write the following method without using >> > exceptions? >> > >> > def isFloat(string): >> > is_float=1 >> > try: >> > float(string) >> > except: >> > is_float=0 >> > return is_float >> > >> > print isFloat("asdf") # --> 0 >> > print isFloat("0.1") # --> 1 >> >> >> def isFloat(string): >> if type(string) == type(1.0): >> return 1 >> else >> return 0 >> >> This should do what you want without exceptions > > I doubt that VERY much. Please test your code before submitting, or > ensure you note it wasn't tested ... > >>>> def isFloat(s): > ... if type(s) == type(1.0): > ... return 1 > ... else: > ... return 0 > ... >>>> isFloat("banana") > 0 >>>> isFloat("1.2") > 0 If its called as isFloat(1.2) it works. (My idea was that it would called with a variable and not a literl) From Henk Mon Jun 23 04:18:04 2003 From: Henk (Henk) Date: Mon, 23 Jun 2003 08:18:04 GMT Subject: Newbie: using the parser from PyExpat/sgmlop Message-ID: <3ef6b6f4.1558250671@news.skynet.be> Hi, I want to use the XML parser from PyExpat and/or sgmlop. I have installed PyXML 0.8.2. I want to parse an XML file into a DOM-tree, like the DOM-tree in Document() from minidom.py. This may be a stupid question, but as I am a newbie: can anyone help me out how I can force Python to use the parser from PyExpat or sgmlop? Thanks, Henk From janezgd at email.si Sun Jun 22 04:09:36 2003 From: janezgd at email.si (Miki) Date: 22 Jun 2003 01:09:36 -0700 Subject: Zlib dictionary References: Message-ID: Thank you, but this is not what I had in mind. I'm new to Python and I forgot that there are also dictionaryes in Python. What I had in mind was the dictionary that Zlib builds during the compression. I would like to build a dictionary like this and then compress some other texts with this dictionary as the starting dictionary. This is confusing... :) Janez "Byron Morgan" wrote in message news:... > I haven't used Zlib, but it looks as though it is at least somewhat > possible. > > >>> import zlib > >>> data = {'Name':'Spam','Pet':'ex-Parrot'} > >>> dataz = zlib.compress(repr(data)) > >>> eval(zlib.decompress(dataz))['Name'] > 'Spam' > >>> > > Byron Morgan > > "Miki" wrote in message > news:d75d795f.0306210032.238abe54 at posting.google.com... > > Hi > > > > Is it possible, with the Zlib library in Python, to compress some text > > data with a dictionary built on some other text? Is it possible to > > somehow access the dictionary after the compression and reuse it in > > another compression? > > > > Thanky you, > > > > Janez From husalwan at sci.kun.nl Thu Jun 5 11:16:22 2003 From: husalwan at sci.kun.nl (Husam) Date: Thu, 05 Jun 2003 17:16:22 +0200 Subject: Newbie: How do you enable python scripts in apache server? Message-ID: <3EDF5EC6.6050704@sci.kun.nl> Hi, I have apache server running on redhat 9 and wants to run python scripts with it. I made a test script test.py and chmod to 777. The script sits in the root directory of the www-site. The script is this: #!/usr/bin/python print "Content-Type: text/plain\n\n" print "Hello, Python!" Although the script executes properly in konsole terminal, the problem is when I try to execute this script in netscape like this: http://localhost/test.py the script is showing as plain text. Can anybody points me to the right direction? Thanks in advance From theller at python.net Wed Jun 4 02:44:04 2003 From: theller at python.net (Thomas Heller) Date: 04 Jun 2003 08:44:04 +0200 Subject: calldll References: <3EDD42A6.3D45B60E@engcorp.com> Message-ID: <4r36xryj.fsf@python.net> Peter Hansen writes: > Vincent L wrote: > > > > I'm searching for the python binary module "calldll.pyd" for python > > 2.3 (for Win32 platform)? (and the file npstruct.pyd) > > > > Where I can find this file? > > I believe the best answer might be "use ctypes instead". > > You probably found this: http://www.nightmare.com/software.html > from which you can infer that calldll is not supported any more. > (I'm not sure that's the case... and of course the source is > available so you could presumably make it run under Python 2.3 > yourself.) > > On the other hand, http://starship.python.net/crew/theller/ctypes/ > is the place to go for something that appears to be supported, > although depending on your needs it may not be quite mature enough > yet. It has been described as "experimental" in the past, although > that label seems to have been removed from the web page... I don't label it experimental anymore. It's a solid module in the sense that it works and has been from the beginning. Thomas From sismex01 at hebmex.com Fri Jun 6 09:50:09 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 6 Jun 2003 08:50:09 -0500 Subject: LANGUAGE QUESTION??? Message-ID: > From: Bowen [mailto:ten.sardna at newoB.com] > Sent: Thursday, June 05, 2003 8:17 PM > > phil hunt wrote: > > On Wed, 4 Jun 2003 13:17:46 -0400, Reginald Blue > wrote: > > > >>Pupppy Wizzard wrote: > >> > >>>Hi. I am an old school programmer looking to modernize my > skill set. I > >>>want to focus on one new language. Should I choose: > >>> > >>>VB > >>>VB.net > >>>C# > >>>C++ > >>>Python > >>>Smalltalk > >>>J# > >>>JScript.net > >>>or Java? > >> > >>(Yes, I know this is a troll, but I just wanted to get this in): > >> > >>Hi. I'm an old school woodworker looking to modernize my > skill set. I want > >>to focus on one new tool. Should I choose: > >> > >>Hammer > >>Screwdriver (phillips) > >>Screwdriver (flat head) > >>Chisel > >>Rasp > >>File > >>Saw > >>Socket Wrench > >>Monkey Wrench > >>or Box Wrench? > > > > > > A hammer. > > > > A hammer is the best tool by far, we should use it for everything, > > and throw away all our screwdrivers. > > Ah, you can hammer in screws... albeit not very well. > But you can't screw in nails. :-) -gca -- Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From gerrit at nl.linux.org Tue Jun 24 06:03:33 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 24 Jun 2003 12:03:33 +0200 Subject: d.keys() and d.values() Message-ID: <20030624100333.GA2595@nl.linux.org> Hi, is it guaranteed that dict(zip(d.keys(), d.values())) == d? In words, do .keys() and .values() always have the same order? Is it safe to rely on this? yours, Gerrit. -- 279. If any one by a male or female slave, and a third party claim it, the seller is liable for the claim. -- 1780 BC, 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 mickel at csc.fi Thu Jun 26 04:12:41 2003 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Thu, 26 Jun 2003 11:12:41 +0300 (EEST) Subject: Standard ways to get union, intersection, difference of lists? Message-ID: Hi! Are there any standard list methods for getting the intersection and difference of two lists? (The union is easy ("list1.extend(list2)"), unless you want it to contain unique values.) Here is what I would like to have: list1 = [1,2,3] list2 = [3,4] list3 = list1.intersection(list2) (list3 is now [3]) list3 = list1.difference(list2) (list3 is now [1,2]) list3 = list2.difference(list1) (list3 is now [4]) I realize I could quite easily implement this myself, but I was hoping for a built-in solution. Cheers, /Mickel -- Mickel Gr?nroos, application specialist, linguistics, Research support, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237 CSC is the Finnish IT center for science, www.csc.fi From tweedgeezer at hotmail.com Wed Jun 25 22:20:15 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 25 Jun 2003 19:20:15 -0700 Subject: sets.filter? References: Message-ID: <698f09f8.0306251820.46a4ee93@posting.google.com> Gerrit Holl wrote in message news:... > would it be a good idea to add a .filter() method to a set object, > which behaves like the builtin filter() but resulting in a set? > I often see myself doing sets.Set(filter(f, someset))... Would this > be a good addition to sets.Set? Yes, it'd be a great idea. filter/map/reduce should've been methods on sequences from the beginning. Jeremy From peter at engcorp.com Mon Jun 16 22:16:37 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 16 Jun 2003 22:16:37 -0400 Subject: long-term release schedule? References: Message-ID: <3EEE7A05.DEB78BD8@engcorp.com> "Greg Ewing (using news.cis.dfn.de)" wrote: > > Delaney, Timothy C (Timothy) wrote: > >>From: Peter Hansen [mailto:peter at engcorp.com] > >> > >>>would have to have a nuclear war. > > > > He's assuming that everyone would die in such a war. He's forgetting that > > the vault dwellers, ghouls, super mutants and deathclaws will still > > be around ... > > Unfortunately, all the computers in the world will have > been wiped out by EMP, so there'll be nothing left for ^^^ Evil Microsoft Power? (Yes, I know... :-) From srart at operaxtrashitheremail.com Fri Jun 20 03:59:10 2003 From: srart at operaxtrashitheremail.com (Ryan) Date: Fri, 20 Jun 2003 02:59:10 -0500 Subject: Run a linux program through python References: Message-ID: A couple of ways, you can just use: os.system("YOUR OTHER PROGRAM %s"%(AND_ARGUMENTS) or os.execv(path_to_program, (arguments))#this replaces your program you started or os.spawnv(mode, path_to_other_program, args)# mode will probly be P_NOWAIT or P_WAIT, no_wait if it will work fine no matter how many times you have it running, wait if you are worried about some kind of collision (sound same file may be used more than once, sockets, etc) On Fri, 20 Jun 2003 09:29:37 +0200, Gunnar Staff wrote: > I would like ti run a linux program through a python script. Do enyone > know the syntax for running a OS program from python? > > Assume I'll run > $ convert fromfile tofile > > Gunnar > -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From tim at remove_if_not_spam.digitig.cix.co.uk Wed Jun 25 12:39:14 2003 From: tim at remove_if_not_spam.digitig.cix.co.uk (Tim Rowe) Date: Wed, 25 Jun 2003 17:39:14 +0100 Subject: editing text file References: <3ef9c81d$0$28231$79c14f64@nan-newsreader-02.noos.net> Message-ID: On Wed, 25 Jun 2003 18:05:53 +0200, ataraxia2500 wrote: > is there a function that can search for specific words in a text file (kind >of like grep) and change them? >say in my text file there's a line such as: >[myvalue]=X > >and my function would search the line [myvalue] and replace X by Y. > >any suggestions? > >thanx in advance Use a for line in file.readlines() loop and the re module for your matching. Though, to be honest, if that's all you want to do then Python is probably an overkill; there's probably a port of sed for your platform, whatever platform it is, and I reckon that would be the appropriate level of tool. From donald.welch.nospam at hp.com Fri Jun 6 13:48:46 2003 From: donald.welch.nospam at hp.com (djw) Date: Fri, 06 Jun 2003 10:48:46 -0700 Subject: Directory & File Monitoring References: <6f8cb8c9.0306060731.21813c29@posting.google.com> Message-ID: <3ee0d822@usenet01.boi.hp.com> Steve wrote: > Hi; > > I would like to write a python script for windows 2000 that will log > who/what touches a particular file in a particular directory. > > Is this possible with python alone or do I need to access some Windows > api( and which one?)? > > Any clues would be appreciated > > Steve Maybe this would work? http://sysinternals.com/ntw2k/source/filemon.shtml Don From vivek at cs.unipune.ernet.in Thu Jun 26 00:50:06 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Thu, 26 Jun 2003 10:20:06 +0530 Subject: problem with % operator on format string In-Reply-To: <20030626020423.GB12627@bobas.nowytarg.pl>; from vald@valis.amber.eu.org on Thu, Jun 26, 2003 at 04:04:23AM +0200 References: <20030626020423.GB12627@bobas.nowytarg.pl> Message-ID: <20030626102006.A27960@cs.unipune.ernet.in> On Thu, Jun 26, 2003 at 04:04:23AM +0200, vald at valis.amber.eu.org wrote: > > hello, > i just subscribed to this list, so first i'd like to greet all of you :) > i've recently discovered this great language and now i'm coding alot in > it. today i ran into some problem with % operator on strings. > > i have some database query, which i want to format nicely. it looks like: > > query = "select date(xxx, '\%d') from yyy where xxx > like '%s%s\%'" % (year, month) > > so it should produce something like that (year=2003, month=06) > > select date(xxx, '%d') from yy where xxx like '200306%' > > arguments, even if i (as you see) use an escape character '\' before %d. use '%%d' instead of '\%d' regrads Vivek Kumar From sismex01 at hebmex.com Fri Jun 27 10:56:32 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 27 Jun 2003 09:56:32 -0500 Subject: How to memoize functions? Message-ID: > From: Chris Reedy [mailto:creedy at mitretek.org] > Sent: Viernes, 27 de Junio de 2003 09:19 a.m. > > That's true. Unfortunately, that misses the other half of the > problem (which, admittedly, I didn't mention) which is that I > would also like to be able to collect the results of the function, > which could be complex data structures, as well as the arguments > (which could be other instances of the same complex structures). > > Chris > So how do you wish to memoize, if you wish for the results (which are gonna get cached) to be collected? Is this a long running process? If it's not, then I'd say to cache the results which take more than X seconds to calculate and forget about having the results collected. Or, use a shelf instead of a dictionary. -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From edvard+web at majakari.net Mon Jun 23 06:40:00 2003 From: edvard+web at majakari.net (Edvard Majakari) Date: 23 Jun 2003 13:40:00 +0300 Subject: When is unit-testing bad? [was: Re: does lack of type...] References: <3EEE1210.3004AB45@engcorp.com> <3EEDDA77.E9246F25@engcorp.com> <3064b51d.0306151228.22c595e0@posting.google.com> <3EECED65.ACF1A6B7@engcorp.com> <3EEE7D4C.DA0B3512@engcorp.com> <878ys06tcv.fsf_-_@pobox.com> Message-ID: <87of0pno5s.fsf@titan.staselog.com> I'm rather interested in (and fond of) unit testing as well as TDD, so I though to share my opinions. I once discussed TDD with my friend in here, and the common agreement seemed to be that TDD is not a silver bullet - often there are types of computational modules that are very hard to unit test, eg. think of graphical user interfaces or complex systems, where forking or threading is concerned. I tried to think of quick rule when to write unit tests for a module or not, and I only came up with this: if the whole module works like a set of functions (may be only one f, of course) where 1. Input is easily representable as native language data structures or combination of those 2. Output is easily representable as native language data structures or combination of those 3. Relationship between those two is deterministic Then I thought that if number of all (obvious) test cases is very large, it may not be worth it to write unit tests for all of them if the functions/methods concerned are simple enough. For example, a software that reads XML and converts certain some XML snippets to Python data structures may contain very large number of combinations considering all possible valid XML files, but it may be still worth the trouble to write unit tests for at least most typical situations. You can always add more tests later. I think one of the best things in writing unit tests is how it helps to avoid doing same mistakes twice. When you encounter a bug, you add appropriate test case to your test suite and fix it until all tests pass again. By running unit tests before every release you can be sure that all known bugs have been corrected (assuming every accepted bug results in new written test case). Some people seem to have lukewarm attitude towards unit testing and TDD. No, TDD is not a silver bullet and neither unit testing nor TDD - or both combined - can guarantee a 100% bug-free software product, but it sure helps a lot and is a nice method in addition to many others in an attempt to design, implement and maintain high-quality software products. Just my 2 cents, -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! One day, when he was naughty, Mr Bunnsy looked over the hedge into Farmer Fred's field and it was full of fresh green lettuces. Mr Bunnsy, however, was not full of lettuces. This did not seem fair. --Mr Bunnsy has an adventure From usenet_spam at janc.invalid Sun Jun 1 19:31:26 2003 From: usenet_spam at janc.invalid (JanC) Date: Sun, 01 Jun 2003 23:31:26 GMT Subject: Seeking wisdom on URI path parameters. References: <3ED3C89E.EDD9CEF1@hotmail.com> <3ED8AF6D.B33E3414@hotmail.com> Message-ID: Alan Kennedy schreef: >> Maybe the OP should ask the "pros" at www-talk at w3.org >> > > Maybe I'll do that one of these days. I think it is a question worth > asking and answering. If you want to be sure, I think that's the best you can do. :-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From chppxf1 at NOSPAM_yahoo.com.au Sun Jun 29 05:01:07 2003 From: chppxf1 at NOSPAM_yahoo.com.au (Charles Handy) Date: Sun, 29 Jun 2003 17:01:07 +0800 Subject: Fast CGI Vs Java Application Servers Message-ID: How does FastCGI compare against java Apps running in java app servers like TomCat, Sun One, WebLogic and WebSphere? Is there a business case for switching from CGI to Java? Performance? Productivity? Features? Object orientation? Code Reuse? Any opinions? From sismex01 at hebmex.com Fri Jun 6 09:58:06 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 6 Jun 2003 08:58:06 -0500 Subject: Possible PEP: Improve classmethod/staticmethod syntax Message-ID: > From: Duncan Booth [mailto:duncan at NOSPAMrcp.co.uk] > Sent: Friday, June 06, 2003 4:46 AM > > "Sean Ross" wrote in > news:9HRDa.4706$IR1.570080 at news20.bellglobal.com: > > > # version with sugar > > def foo() as static, > > synchronized, > > contract(pre,post): > > ...do stuff... > > I don't think this quite works as stated. > Python lets you break a line inside a parenthesised > expression or with a continuation character, so it > seems to me that this proposal would require one of > the following: > > def foo() as (static, > synchronized, > contract(pre,post)): > pass > > or: > > def foo() as static, \ > synchronized, \ > contract(pre,post): > pass > since it's a tuple, any of the forms is valid. Has anyone patched the compiler source to do this yet? Seems like a minor change to the grammar, but I don't have the source onhand, nor can I download it. :-( -gca -- Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From bdesth.nospam at removeme.free.fr Thu Jun 26 09:54:27 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Thu, 26 Jun 2003 13:54:27 +0000 Subject: Python executables? References: Message-ID: <3EFAFB13.1090506@removeme.free.fr> Catalin wrote: > How can I make executables with python? > I found some utilities that claim they can do something like that like > Installer and py2exe but they actualy pack the code in a huge arhive! > This solves the problem of giving python programs to users who don't > have python but doesn't solve the problem of the source "secrecy" > (copyright). > And the programs also run much slower and become extremely big compared > to a normal C++ program for example. I made a test and a 2 programs > doing the same thing where 400 KB with C Builder (static linked) and > 2.80 MB with python+installer in an arhive packed with upx and 6.9 MB > with py2exe(unpacked). And the speed difference was huge. > So can a python program become a "real" executable(I am refering both to > windows and unix platforms)? > If this is imposible with python is it possible with jpython? > Here you expose 3 different problems : 1/ source "secrecy" (copyright) : It's the wrong problem. *Any* binary code can be subject to reverse-engineering. There are even tools to do this quite easily for Java. The right way to protect your property is via copyright and licence. 2/ Size of "packed" programs : Realize that the pack must include the whole Python interpreter and librairies. BTW, I personnaly never used such tools, but I think I remember that some of them allow you to specify which parts you really need. 3/ 'Slowness' : I don't believe that 'packing' the program makes it slower. Are you sure your Python code is really Pythonic ? There are tips and tricks in how to 'optimize' Python code, and it can be very different from low-level (C/C++ etc) languages techniques. You may want to have a look at : http://manatee.mojam.com/~skip/python/fastpython.html Now if you really need smallest possible footprint and blazing-fast execution speed (which are antagonist needs anyway), and your program is about low-level stuff, you may not have choosen the right tool !-) Bruno From anton at vredegoor.doge.nl Wed Jun 18 11:28:14 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 18 Jun 2003 17:28:14 +0200 Subject: Loop from 'aaaa' to 'tttt' ? References: Message-ID: Steven Taschuk wrote: >> ... 7, 8, 9, 00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, etc. > >A very small modification to the normal base-representation >algorithm does this: > > def antoniandigits(val, base=10): > val = abs(val) > digits = [] > while True: > q, r = divmod(val, base) > digits.append(r) > if not q: > break > val = q - 1 # no "- 1" normally > digits.reverse() > return digits > >Conversely, > > def antonianvalue(string, base=10): > digits = list(string) > value = 0 > for digit in digits: > value = value*base > value = value + ord(digits) - ord('0') + 1 # no "+ 1" normally > return value - 1 # no "- 1" normally Thanks a lot! I've already refactored it further into two reciprocal functions: val <==> tuple: def antoniandigits(val, base=10): tup = () while val > -1: tup = (val % base,) + tup val = val/base-1 return tup def antonianvalue(tup, base=10): return reduce(lambda x,y: x*base+y+1,tup,0)-1 >How about "Antonine" instead of "Antonian"? Tough choice :-( Should I follow my heart and sail after Cleopatra, resulting in an Antonine wall and having to use roman numerals for ages, or stay with Octavia and have a loveless life, which however would make it possible to have Antonians now and which would open up possibilities for a great magic Celtic Empire? Anton From puccio_13 at yahoo.it Sat Jun 21 20:21:45 2003 From: puccio_13 at yahoo.it (Alessio Pace) Date: Sun, 22 Jun 2003 02:21:45 +0200 Subject: embedded db in python app? References: Message-ID: drs wrote: > "Alessio Pace" wrote in message > news:qRVIa.34337$Fr5.730650 at tornado.fastwebnet.it... >> Hi, I wrote a python application which needs to persistently store 2 >> *big* hash maps at the end of its execution and retrieve them when it >> starts again. Up to now I just used pickle to serialize 2 objects that >> "encapsulate" those hash maps (and nothing else). I wonder if using an >> embedded db (but which one??) to store those two hash maps would be >> faster both in storing and in retrieval. > > > if pickle as a concept is working, but it is just too slow, try cPickle > before changing the strategy too much. If, however, that is not a good Fortunately the layers of my app were quite separated so changing how to use the persistency of that datas required not so long time :-) I tried BerkeleyDB as suggested by one post above, I am quite happy with it, it seems to be faster than Pickle in de-serializing but slower in serializing. Because my app is more speed tolerant in serialization I am almost convinced to use a db instead of pickle... > strategy, then look in to ZODB. Similar in concept to bsddb (I guess) but > way cooler for python apps. ...so maybe I will give a try to ZODB as well. > > http://www.amk.ca/zodb/ > > -d Thanks. -- bye Alessio Pace From belred1 at yahoo.com Sun Jun 22 12:26:59 2003 From: belred1 at yahoo.com (Bryan) Date: Sun, 22 Jun 2003 16:26:59 GMT Subject: xrange References: <3EF5D5E2.DF5D9FCB@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3EF5D5E2.DF5D9FCB at engcorp.com... > Bryan wrote: > > > > in 2.3, what is the best way to write this: > > for i in xrange(100): print 'Hello' > > > > i used timeit and it seems that repeat is about 10% faster. > > Is such a small performance difference more important to you than > backwards compatibility? > > I would choose "for i in xrange()" still, merely because of the > number of people still using Python 2.2 and before, but I'm not > one who cares much about trivial optimizations... > > (I realize you might be using 2.3-only features, but I don't think > that automatically means you should abandon readability, by dumping > a well-known idiom with a merely possibly-to-become-idiomatic form.) > > -Peter i was trying to think in general terms, not just a simple 100 iterations. of course for backwards compatibility xrange wins there. to me both xrange and repeat are similarly readable. i guess i got a bit confused because python now has two obviously correct way of doing something, and for the rest of my python life i have to always decide which one to use. From ofnap at nus.edu.sg Sun Jun 29 08:42:06 2003 From: ofnap at nus.edu.sg (Ajith Prasad) Date: 29 Jun 2003 05:42:06 -0700 Subject: AN ENROLMENT PROJECTION PROBLEM Message-ID: <37ee60c8.0306290442.60be2b57@posting.google.com> I would appreciate advice on how best to formulate the following problem in Python. I have originally posted the problem to the J Programming forum and received a one-line formulation ((#s) (|.s)&(+/@:*)\ I)! I was wondering what the equivalent Python formulation would be. The Problem: The enrolment E(n) of an institution at the beginning of year n is the sum of the intake for year n, I(n), and the survivors from the intakes of previous r years. Thus, if s(1) is the 1-year intake survival rate, s(2) is the 2-year survival rate, etc, we have: E(n)= I(n)+I(n-1)*s(1)+ I(n-2)*s(2)+...+I(n-r)*s(r) E(n+1)= I(n+1)+I(n)*s(1)+I(n-1)*s(2)+... +I(n-r-1)*s(r) . . . E(n+k)= I(n+k)+I(n+k-1)*s(1)+I(n+k-2)*s(2)+...+I(n+k-r)*s(r) Given: (a) the actual intakes for the current and previous r years, I(n), I(n-1),I(n-2),..,I(n-r), and the planned intakes for the next n+k years: I(n+1), I(n+2),..., I(n+k), we have the intake vector I = (I(n-r), I(n-r-1),...,I(n),I(n+1),..., I(n+k)); and (b) the survival rate vector, s = (1,s(1), s(2),...,s(r)) Find: The k*1 enrolment projection column vector, E = (E(n+1),E(n+2),...,E(n+k)) in terms of a k*(r+1) matrix P (derived from I) and the (r+1)*1 column vector, s. I = P*s Is there a compact Python representation of the relevant matrix P where: P = [I(n+1) I(n) I(n-1).. . I(n-r) I(n+2) I(n+1) I(n)... I(n-r-1) . . I(n+k) I(n+k-1) I(n+k-2)... I(n+k-r)] Alternatively, a non-matrix formulation of the problem would be acceptable. Thanks in advance for any suggestions on how to proceeed. From rnd at onego.ru Sat Jun 21 13:22:49 2003 From: rnd at onego.ru (Roman Suzi) Date: Sat, 21 Jun 2003 21:22:49 +0400 (MSD) Subject: XML In-Reply-To: <3EF471BA.EE4F056@hotmail.com> Message-ID: On Sat, 21 Jun 2003, Alan Kennedy wrote: >Alan Kennedy wrote: > >>>Of course the point remains that XML is hugely resource inefficient for >>>many problems. But maybe in 5 years we'll have so many terahertz and >>>gigabytes and megabits-per-sec that we won't care. > >Roman Suzi wrote: > >> Well, when XML was entering the arena, it promised to _lessen_ >> the burden on telecommunications... Where is that claim now? > >I've been "following" XML since seeing Jon Bosak lecture on the subject in May >1997. I've been subscribed, periodically, to xml-dev and xsl-list, and I don't >think I've ever heard, read or seen anyone seriously claim that XML would lessen >the bandwidth used for communicating information. Is that what you meant? Yes. Because XML could be received once (as a recordset) and then processed locally, with further subqueries etc. >And the same argument could be made about HTML: it is just as resource >inefficient as XML, perhaps more so. So why is HTML the most widely used >document format in human history? Because Microsoft made Outlook Express use HTML for letters by default (and Netscape too). Oh, yes: spammers like HTML a lot. I do not have figures ready, but 95 percent emails addressed to me which use HTML are spams. >If any claims have been made about communications, then I think they would be >more likely to be made in relation to how much easier it would be to *process* >XML, compared something like EDI, for example. Yes, I believe BASIC interpreter is much easier than Ada's one... >> And one more point: processing of XML is much less >> reliable than that of ASCII or even simple Python literals. > >I have to disagree with that statement. I don't think that a character encoding >can be compared to XML: for example, XML can be stored in ascii. "Processing" >ascii is easy, but extracting semantics from an ascii byte stream is harder than >extracting semantics from XML, i.e. deciding on your tokens, lexing them, >writing a grammar, translating that grammar to running code that builds data >structures, etc, etc. Processing simple strings like "2+(2*2)" is easy: what >about "I would like a deep pan 12-inch pizza with bacon and banana, two portions >of garlic bread and 2 litres of sparkling mineral water delivered to my house >please". He we came to the whole point of having XML. If ASCII text can be compared with string or list of strings, then XML is like a dict (probably, with subdicts). But still I can't imagine that having structured the above sentence will help to make an order to robotized pizza delivery! I will always fear that my garlic bread will swim in a mineral water. XML is pure formal language and its applications are sometimes overdesigned. For example, the above mentioned 2+(2*2) could be as simple as >>> 2+(2*2) 6 or very complex, requiring put everything into XML and applying XSLT to it to get the answer. BTW, I have almost the same pessimism toward OOrientation. Some time ago I came across a program (I shall not name it here because it's quite a useful program and I do not want to scare it's author) which was very object oriented. I needed to make changes to it because I wanted one of it's functions to be dumbed down and be faster. I managed to do it dropping many classes. Some time ago I needed another version to output some parameter interesting to me. Luckily, the program runs only once per file, so after tracing class structure to understand where can I return needed value, I just added a global variable which I fill at one location and output in the other location! And now I want to have a dumbed down version of another function of the program: oh no... I better rewrite it in simple structural/modular way: it will be much shorter, much easier to "refacture". Again, is it me who refuses to see how wonderful and intuitive OO technology was to make my life happier? Or is it misuse of technology? Another example is about Linux. Slackware had simple and strightforward init script(s). Now, Look at RedHat initscripts. No wonder it takes so much time to boot RedHat Linux... And if I needed to have, say, some network added in Slackware, I put ifconfig into place where I needed it. In RedHat I am at loss and I put it to rc.local (which get executed last). I know why all that fancy was needed (to allow separation of services and easier automated add/remove), but what they did is IMHO overkill... So, in my opinion, XML is far from KISS principle. >And can you point me to code/programs/utilities to parse python literals in >Java, VB, lisp, smalltalk, javascript, ocaml, etc, etc? Character encoded python >literals don't travel as well as XML, as of today anyway. > >And processing XML is completely reliable, as long as your XML tools library is >compliant with standards. >Non-compliant tools don't last long, because people >stop using them. > >Now, it is definitely the case that there is a lot of "XML" out there that isn't >really XML at all: it's XML structures with broken HTML embedded inside. This means they are using broken tools to generate such XML... XML is fragile. Much more fragile than ASCII text. Yes, XML serves more complex tasks, but does it really need to be so unreliable? >> The reliablity is what worries me more. It's too easy to get into some >> trap (I remember talks here or in XML-SIG when it was discussed >> what is better None or "" for representing namespace). > >But the latter is a minor, python-specific, concern, and one that was >satisfactorily resolved relatively quickly, by the excellent PyXML people >(thanks Martin von L et al :-). Once that empty namespace gets serialised into >an XML byte stream, and then further processed in another language, the semantic >travels seamlessly to other languages. XML travels generally much more reliably, >across the wide range of available platforms, than any other non-trivial >data/document representation. It may travel, but I do not think this helps. If robotized pizza delivery doesn't have a recipe for sparkling mineral water, it will give ParsingError. Because you thought it has it and in reality it doesn't. So what is the advantage to have flexible transport if target isn't that flexible (semantically, of course)? If my browser do not understand blink, what it is supposed to do instead? Drop the whole text? Do not blink it? Give a warning? Segmentation fault? >> So far all arguments pro-XML in this thread are like "XML is good >> because X, M and L are already here" (be it SGML, javascript, Java, >> developers expertise or whatever). But I wonder if there are pure >> technical merits of XML itself apart >> from it being involved. > >Well, I suppose where you and I differ is that I believe that something being >easy for ordinary people to understand and work with *is* a technical merit. Hmmm... XML document is a tree with marked nodes and ordered vertices. But is XML a best markup format for representing a tree in a plain text? Yes, we are all accustomed to it so we think it's its technical merit. >I think that if we are to progress further, you would have to define what you >mean by "technical merit". Technical merits could be different: 1- simplicity of processing 2- easiness for "ordinary people to understand and work with" 3- flexibility and power of expression >> XML is not well-based scientifically (like RDBMS) > >Can you give an example of something comparable to XML that is "well-based >scientifically"? I don't understand what you mean. Relational databases are based on well-defined set theory. Contemporary digital computers and circuitry are based on mathematical logic. Programming languages - lambda calculus, Turing machines - also well known objects. Regular expressions correspond to grammars and to finite automata (also criss-cross researched things). But what about XML? Where can I find an algebra of XML? Or a "truth table" of XSLT? The same problem I have with OOP. What well-established math theory is behind OOP? Gurus' opinions? Maybe XML and OOP aren't science at all but special kind of literature. The first one soap opera and the second... science fiction. >> XML for ? is like CSV for a RDBMS >> >> However, I have no idea what the question stands for... > >RDBMS is a very broad term. Try comparing something like SQLLite or MS Access on >a LAN with a group of large multi-processor, multi-machine, data-replicating, >distributed (across time zones) transaction processing Sybase servers, for >example. > >XML database technology has a long way to go before it challenges RDBMS as a >reliable, fast and powerful storage mechanism for information. But there are >products, projects and languages out there. Compared to your statement above, >perhaps statements like these could be made > > o XML is to a DOM as CSV is to an array > o XML is to Apache Xindice as CSV is to a MySQL server. > o XML is to an XML-based content server as CSV is to an RDBMS + a raft of >content->relational table mappings. > o Xpath/XQuery/XPointer is to an XML repository as SQL is to an RDBMS > >For me, the most important aspect of XML is as a social phenomenon, not a >technical one. That is why I wrote the initial message: because I want to understand the society of XMLists and learn. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From jepler at unpythonic.net Mon Jun 2 10:59:02 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 2 Jun 2003 09:59:02 -0500 Subject: Detect hung apps spawned from python In-Reply-To: <3edb494b$0$12997$afc38c87@news.easynet.co.uk> References: <3edb494b$0$12997$afc38c87@news.easynet.co.uk> Message-ID: <20030602145902.GB32639@unpythonic.net> On Mon, Jun 02, 2003 at 01:55:39PM +0100, David Stubbs wrote: > Hi, > > I have a python app that builds a list of all subdirectories from the > current directory, and then in turn runs a 'test.py' script from within each > of these directories. I currently do this using os.system(). Is there any > easy way of detecting apps that crashed, and terminating them if so? Ideally > being able to set a time-out to wait for the application to finish would be > good. > > I think I could do it using CreateProcess, but, well, it just seems like > overkill and that there'll be a much simpler method somewhere. As far as I know, you'll have to use the Windows-specific APIs if you want to do something like "kill this process if it takes longer than 30 seconds". On Unix, you would use fork+exec and os.kill(), but as far as I know these don't translate to the Windows world. Jeff From max-resume at alcyone.com Mon Jun 23 20:53:53 2003 From: max-resume at alcyone.com (Erik Max Francis) Date: Mon, 23 Jun 2003 17:53:53 -0700 Subject: shebang strange thing... References: <3EF3A07B.A683F94F@alcyone.com> Message-ID: <3EF7A121.7B4C3775@alcyone.com> Dan Bishop wrote: > But how many people use \r at the end of filenames? Or are even aware > that they can? > > Even if it isn't a bug, it's a feature that causes more harm than > good. It's simply an end-of-line issue. The "bug" here is that DOS chose to use CR LF as the end-of-line terminator. (Mac gets even fewer points, since it chose to do deliberately do smoething even more different.) This has nothing to do with Unix, it's an inherent difference between platforms. The platforms are not the same; if you pretend like they are then you'll continually run into problems. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I go out with actresses because I'm not apt to marry one. \__/ Henry Kissinger From alanh at unc.edu Sat Jun 7 19:11:29 2003 From: alanh at unc.edu (Alan Hoyle) Date: 7 Jun 2003 23:11:29 GMT Subject: Kerberos authentication for IMAP? Message-ID: I recently discovered IMAP Spam Begone, a python client script which accesses IMAP mailboxes, downloads mails, runs them through a local spam filter, and moves them to a Remote spam folder if appropriate. http://www.rogerbinns.com/isbg/ The authentication method it uses is standard username/password, and my local IMAP server doesn't support SSL. However, it does support Kerberos 4. I was wondering if it would be possible to modify the script so that it could use my Kerberos tokens instead. I glanced at the documentation for the python IMAP client library: http://www.python.org/doc/current/lib/imap4-objects.html and that seems to indicate that the authenticate function won't work. | authenticate(func) | Authenticate command -- requires response processing. This is | currently unimplemented, and raises an exception. However, glancing at the actual source code in my python subdirectory (/usr/lib/python2.2/imaplib.py), and found the following code snippet: def authenticate(self, mechanism, authobject): """Authenticate command - requires response processing. 'mechanism' specifies which authentication mechanism is to be used - it must appear in .capabilities in the form AUTH=. 'authobject' must be a callable object: data = authobject(response) It will be called to process server continuation responses. It should return data that will be encoded and sent to server. It should return None if the client abort response '*' should be sent instead. """ mech = mechanism.upper() cap = 'AUTH=%s' % mech if not cap in self.capabilities: raise self.error("Server doesn't allow %s authentication." % mech) self.literal = _Authenticator(authobject).process typ, dat = self._simple_command('AUTHENTICATE', mech) if typ != 'OK': raise self.error(dat[-1]) self.state = 'AUTH' return typ, dat Which seems a bit more promising than the how can I set this up to use my Kerberos tokens or TGT? I don't want it to generate entirely new tokens on its own..... -alan -- Alan Hoyle - alanh at unc.edu - http://www.alanhoyle.com/ "I don't want the world, I just want your half." -TMBG Get Horizontal, Play Ultimate. From kendear at nospam.com Tue Jun 3 03:44:35 2003 From: kendear at nospam.com (Kendear) Date: Tue, 03 Jun 2003 07:44:35 GMT Subject: a = b = 1 just syntactic sugar? Message-ID: <3EDC51DE.6040502@nospam.com> I don't like the fact that you can say in Python a = b = 1 but you can't say a = (b = 1) which is perfectly fine in C or Perl. In those cases, "=" is just an operator with associativity from right to left... so adding parenthesis is not a problem. But in Python, it would give an error. >>> a = b = 1 >>> a = (b = 1) SyntaxError: invalid syntax I think if a language supports a = b = 1 then that means "b = 1" returns a value of 1, which can be assigned to any variable. But it seems like it is only a syntactic sugar in Python? if Python supports 1 < a < 10 then maybe it is also just syntactic sugar. Other language might take it as (1 < a) < 10 which is just the boolean 0 or 1 less than 10 which is always true. >>> a = -1 >>> 1 < a < 10 0 >>> (1 < a) < 10 1 so in Python, we can't just add parenthesis to multiple = and can't add parenthesis arbitrarily to multiple <, >, ==, etc. From thanks200 at hotmail.com Mon Jun 16 00:02:24 2003 From: thanks200 at hotmail.com (Tom Hanks) Date: 15 Jun 2003 21:02:24 -0700 Subject: Python class __init__(mandatory arguments?) References: Message-ID: <6152d0a0.0306152002.4d5a37b0@posting.google.com> Lee John Moore wrote in message news:... > Just for confirmation really: When I create a custom class, is > it *really* true that def __init__() arguments can only ever be > optional? Eg: Mr Moore, No. In my experience __init__ arguments without default values (or using the *args, **kwargs idiom) are required and not optional, exactly like all other functions. > > class MyClass: > param1 = None > param2 = None > def __init__(self, param1, param2): > param1 = self.param1 > param2 = self.param2 > > myinstance1 = MyClass() > myinstance2 = MyClass("Hello", "World") > [snip] > > I'm really unhappy that myinstance1 is allowed. ;-) I would be unhappy too. :-( Luckily running your code under 2.2.1 I get a traceback :-) Traceback (most recent call last): ... TypeError: __init__() takes exactly 3 arguments (1 given) I hope this info leaves you less confused than when you started... Tom. From noreply at babiesonline.com Thu Jun 26 10:44:12 2003 From: noreply at babiesonline.com (noreply) Date: Thu, 26 Jun 2003 10:44:12 -0400 Subject: Application Message-ID: <200306261444.h5QEiCd01770@ns1.netlinkrg.com> I'm sorry, but you have sent a message to a Babies Online address that does not accept incoming mail. If you have an inquiry, please direct your browser to our Frequently Asked Questions page at http://www.babiesonline.com/faq If you wish to unsubscribe from one of our mailings, please direct your browser to http://www.babiesonline.com/forms/newsletters/unsubscribe.asp Best Regards, Babies Online.com http://www.babiesonline.com From rbsharp at gmx.de Tue Jun 17 11:49:30 2003 From: rbsharp at gmx.de (Richard Sharp) Date: Tue, 17 Jun 2003 17:49:30 +0200 Subject: HL7 servers in Python? References: Message-ID: Hello, I'll keep this general since not everyone is interested. 1. Whilst receiving the messages I don't do any parseing at all. Breaking down HL7 is really for all practical purposes trivial. It is a collection of separators, one for fields and one for components and so on. So you can get the data out of a HL7-Message basically using split. I don't parse the data until I can process it and that is done in a separate process. This has always proved to be a good thing, because I can stop the processing and correct something without worrying about data loss. What does vary is the packaging of the data, but the basic pattern is some start character (usually chr(11)), data consisting of records separated usually with chr(13) and then an end character (chr(28)) and a stop character (chr(13)). But this can vary from system to system. What constitutes an ACK or a NAK is also quite different at times 2. I am (was) stuck with Python 1.5.2 because I have to link Python against a static unify database library and bind in some external C-Routines. This was not quite trivial and I had to play about with SWIG for a while, but now its routine. I mostly confused my self with Python 2.2 and had to understand the build process. At the end my interpreter still crashed, and I despaired, but the reason was a bug relating to shared memory segments in the database library. But it is still an issue updating ca 25 to 30 Installations with 2 MB of Python, many of which still only have a modem. By the way, an earlier version of Twisted blocked SCO Machines. After a while nobody could log in any more. I installed the newer version and the problem went away. 3. I use Twisted to serve a variety of transport needs. Basically the Information I send or receive is Ascii data, only I and the receiver really know what is in there. What we do have to agree on how the data is to be transported. Whether over sockets, per FTP or a mounted NFS-directory. If the means of transport is not available, then I need to be able to keep retrying until I succeed. I need to be able to serve several sources and several destinations, each of which can be individually configured. I could be receiving data over NFS and sending using sockets. For Sockets I "hang" them in to the select loop. I differentiate according to direction. Incoming data is handled by calling the TCPListen method of the application und outgoing data by creating an instance of tcp.Client. With tcp.Client I had some difficulties handling connections that come and go. If the connection was dropped I had to delete the Client and recreate it and then reestablish the connection FTP and NFS are dealt with by quite simply creating a Job Manager that is repeatedly called using reactor.callLater(5,). The Job Manager maintains a queue of objects where it repeatedly calls generic methods, like put and get. There may be better ways of doing things, but it worked and has been working for some time now. Richard Sharp On Mon, 16 Jun 2003 17:05:46 +0000, Moshe Zadka wrote: > On Mon, 16 Jun 2003, "Richard Sharp" wrote: > >> I have one Pathology Unit that does work for two hospitals and >> communicates with two hospital systems. With Twisted I basically >> subclass protocol.Factory and implement the necessary submethods. > > You probably also needed to subclass protocol.Protocol to actually parse > HL7, right? > >> It is a little daunting at first and there was at the time (about 2 >> years ago) when no usable documentation worth speaking of was >> available. I am also stuck at the moment with Twisted 0.18.0, because >> it runs with Python 1.5.2, and I had trouble getting Python >= 2.0 >> running on the all the Unixes I had to get it running on. In the >> meantime, I think I've got that under control. > > Ugh. Current Twisted (1.0.5) needs Python 2.2. Python is pretty > portable, I've managed to build it (back when I needed to) on pretty > wierd unices. Sometimes you want to install gcc because the compiler > that comes with the system is damaged :( > > If you are having serious problems building Python, you're better off > asking here (giving all the details about your platform) than using > Twisted 0.18 (which was not a horribly good version, IIRC -- I kinda > liked 0.15.5 I think). > >> If you're interested in looking at the programms I will have to ask the >> company I developed the software for, but the complete program is only >> ca. 800 Lines and covers 4 Low Level Protocols. > > If you get permission to put them up, that would be even better :) As a > Twisted developer, I keep hoping that people will implement Protocols > for Twisted as the standard way of having Python support a network > protocol (rather than, say, asyncore) but except for ldaptor, I don't > think there have been many 3rd party protocols. From Dan.Pop at cern.ch Wed Jun 4 13:10:20 2003 From: Dan.Pop at cern.ch (Dan Pop) Date: 4 Jun 2003 17:10:20 GMT Subject: [OT] Re: LANGUAGE QUESTION??? References: Message-ID: In ruse at webmail.co.za (goose) writes: >PupppyWizzard at glay.org (Pupppy Wizzard) wrote in message news:<8dcf2300.0306040159.118c24e8 at posting.google.com>... > > > >woodworking ??????? You see, he's obviously not earning his life as a professional programmer, so this might be a clue about his real profession... Dan :-) -- Dan Pop DESY Zeuthen, RZ group Email: Dan.Pop at ifh.de From ben at transversal.com Fri Jun 6 09:09:20 2003 From: ben at transversal.com (ben at transversal.com) Date: 6 Jun 2003 06:09:20 -0700 Subject: sandboxing python code References: Message-ID: Moshe Zadka wrote in message news:... > On 3 Jun 2003, ben at transversal.com (ben at transversal.com) wrote: > > > I've recently (6 months or so) been converted to Python, and so have > > become an avid reader of this newgroup. One thing that has been brought up > > occasionally by other people, but never has really been answered > > satisfactorily is the problem of running untrusted code. > > How is the answer "you can't" not satisfactory? > > I'll note that even in Java, where a lot of energies and quite a lot > programming hours has been spent on this kind of stuff, it would be hard > to accomplish. IIRC, Java's sandboxing had quite a few bugs itself, and > moreover has limited protection against allocating too much memory (you > can tell the JVM not to let the process allocate over a certain amount, > but not, AFAIK, by sandbox) and against CPU-intensive DoS attacks -- and > that's the best technology. > > My suggestion is to try to find a way where you can handle the overhead > for separating the tasks into separate processes, and then use your OS's > sandboxing capabilities. This easily lets you take care of such things > as CPU and memory limitations, and with more advanced operating systems > (like FreeBSD's jails, NSA's SELinux and chroot()) you can achieve more > control. As an extreme measure, you may consider something like > User-Mode-Linux, which gives you (relatively) cheap virtualization of > the operating system. > > Of course, you can still use the fact that it is Python on both sides > of the fence by using remote-object protocols to communicate -- such > as Pyro or Twisted's Perspective Broker. > > Just like in real life -- if you don't trust someone, don't invite them > into your house and try to keep an eye on them, it's just too hard. Communicate > with them by phone, so that their opportunity to harm you is limited. Of > course, they may shout into your phone, or try to overload your stack > by sending you malformed objects. But it is is much easier to defend against > these kind of attacks. > > Yes, Java and Flash are treated as "code you can run untrusted", but this > is just wrong. It's fairly easy, for example, to crash most browsers with > these, which is a fairly efficient DoS attack :) Thanks for all the replies. I will have to have a think about it. At the moment I am experimenting using twisted to both control the lifetime of sub processes and to communicate with them. This way I can use chroot and resource.setrlimit to hopefully isolate the bogus code Thanks again Ben --- From jjl at pobox.com Sun Jun 15 15:39:48 2003 From: jjl at pobox.com (John J. Lee) Date: 15 Jun 2003 20:39:48 +0100 Subject: You know you're a Pythonista when.. References: <87el1whkhc.fsf@pobox.com> Message-ID: <87fzmbqge3.fsf@pobox.com> "Edward K. Ream" writes: > > I don't understand. Could you elaborate? For example, could you [...] > My old way was pretty stupid: I would develop Leo using Leo to edit Leo's > sources, LeoPy.leo. Then I would _exit_ the copy of Leo that was editing > LeoPy.leo. So if there were any problems that prevented Leo from running I > would have to correct those problems either using a backup copy of Leo or > using Idle. Not only that, but LeoPy.leo is a big file, and it would take > 15-20 seconds to reload it. [...] I see. Been there, sort of. (spent ages slowly being driven nuts by PyQt, which took 40 seconds or so to start a tiny script on a slow laptop of a few years ago -- until I recompiled my kernel, when everything X windows-related sped up by a factor of five, for reasons I don't understand) > window open that is running Python in -i mode, and I would have to close the [...] Hey, I didn't know about -i mode. I've been using Python three years, maybe I should read the manpage... :-) John From member31018 at dbforums.com Thu Jun 12 17:15:30 2003 From: member31018 at dbforums.com (DB_RobertP) Date: Thu, 12 Jun 2003 21:15:30 +0000 Subject: Glue code Message-ID: <2996386.1055452530@dbforums.com> What systems do people use to easily make C/C++ code visible to Python? I'm currently checking out Swig, but I've heard others mentioned. If anyone has any experience with these systems, could you recommend one to look into? Also, any other general pointers when trying to extend C/C++ code to python sctipts would be greatly appreciated. Thanks! Robert -- Posted via http://dbforums.com From paddy3118 at netscape.net Sat Jun 7 10:24:09 2003 From: paddy3118 at netscape.net (Paddy McCarthy) Date: 7 Jun 2003 07:24:09 -0700 Subject: Hardware take on software testing. References: <2ae25c6b.0306060450.78e988f9@posting.google.com> <3EE0CF2B.57F474E4@engcorp.com> <2ae25c6b.0306061721.148300a@posting.google.com> <3EE14F0A.3D1E1887@engcorp.com> Message-ID: <2ae25c6b.0306070624.141e4b42@posting.google.com> First i'd like to state that I too like the ideas mentioned in XP and TDD. If the HW design ideas are outside current software methodologies then I'd like to debate whether adding them would be benificial. my comments are interspersed in Peters mail below... Peter Hansen wrote in message news:<3EE14F0A.3D1E1887 at engcorp.com>... > Paddy McCarthy wrote: > > > > Peter Hansen wrote in message news:<3EE0CF2B.57F474E4 at engcorp.com>... > > > ... a new approach to design, testing, and coding, called Test-Driven > > > Development (TDD). > > > > On TDD when do you know you are done? > > Oh, *good* question! > > > In the Hardware development process we graph the number of bugs found > > over time and end up with an S curve, we also set coverage targets > > (100 percent statement coverage for executable statements is the > > norm), and rather like the TDD approach of software, some teams have > > dedicated Verification engineers who derive a verification spec from > > the design spec and write tests for the design to satisfy this, > > (independantly). > > With TDD, only one > test at a time is even written, let alone passed by writing new code. > You would "never" write two tests at the same time since you wouldn't > necessarily know whether you needed the second test until you had > written the first. If I remember correctly, XP advocates a very close working relationship with the customer with quick customers feedback on program development. > > > If TDD uses no random directed generation, then don't you tend to test > > strictly the assumed behaviour? > > Bob Martin wrote "The act of writing a unit test is more an act of > design than of verification. It is also more an act of documentation > than of verification. The act of writing a unit test closes a remarkable > number of feedback loops, the least of which is the one pertaining to > verification of function." I was trying to learn more about how these tests are written. Writing tests is better than not writting them, but I was trying to show a possibly different way of writing tests, to the way that the program will be implimented, hopefully complimentary, and allowing you (sometimes, with the right set of random variables/constraints), to explore more of those corner cases. You might think of a random directed tests as generating a spray of test values for your program, with the constraints controlling the width of the spray, and direction of the hose. We can find hard to get at bugs with this technique in HW design, that's why I'd also like it added to the software arsenal. > > Let me go back to the "graph the number of bugs" thing you mention above. > If you are working in a world where that concept holds much meaning, > you might have to change gears to picture this: with XP and TDD, you > generally expect to have *no* bugs to graph. > > Now fast-forward to months later, when you have literally hundreds of > little tests, each one having driven the development of a few lines of > code. You have effectively 100% code coverage. In fact, you probably > have tests which overlap, but that's a good thing here. Now you make > a tiny mistake, which traditionally would not be noticed until "test > time", way down at the end of the project when the QA/verification people > get their hands on your code. Instead of being noticed, perhaps, > months later just before shipping, you immediately fail one or two > tests (or a whole pile) and fix the problem. Yep, if the traditional way is to have verification/QA right at the end then I don't advocate that either. But I DO believe in some quantifiable metric. Some may well state that 'what does 100% statement coverage actually mean?', But it is an easy metric to compute and very few would advocate that 90% code coverage by tests is better than 100%. It could be that your suite of current tests may well cause both clauses of all if statements to be excercised, but how do you know what possible combinations of variables used in the if clause have actually contributed to each choice? Your tests could test functionality but still you may have a variable in an if statement that is never exercised so that its changes affect the outcome: something like 'if a or b==c:' when a is always false for some reason. Coverage tools give you this kind of metric and allow you to test the quality of the code produced, not just in terms of 'does it function correctly when tested', but helps to answer 'how well do the tests exercise the given code'. You say in the next statement that the methodology TDD ensures no extraneous code. I say *measure it*. > Or, in spite of the fact that you actually *drove the development of > the code with the tests*, and that therefore there is really no code > that doesn't need to be there to pass the tests, you manage to let > a bug get through. Maybe it was more of an error in interpretation > of the functional requirements. In other words, almost certainly one > of your tests is actually wrong. Alternatively, the tests are all fine > but you're in the unfortunate (but fortunately rare when you do it this > way) position of having an actual, real _bug_ in spite of all those tests. > > What do you do? Add it to the bug database and see the graph go up? > No, you don't even *have* a bug database! There are no bugs to go in it, > except this one. What's the best next step? Write a test! In your scenario, I would graph test 'checkins' over time, assuming tests are checked-in to some version control system when they 'work'. > > The new test fails in the presence of the bug, and now you modify the > code to pass the test (and to keep passing all those other tests) and > check in the change. Problem solved. No bug, no bug database, no graph. > > Maybe this sounds goofy or unrealistic to some who haven't tried it. > Personally I thought it was novel enough to warrant an experiment when > I first encountered it, but it didn't take long before I was convinced > that this approach was fundamentally different and more powerful than > the previous approaches I'd tried over twenty plus years of coding. > It may not feel right to some people, but since it's pretty darn easy > to read up on the approach and experiment for a few hours or days to > get a feel for it, "don't knock it if you haven't tried it". :-) I don't doubt that XP and TDD can be an advance on previous methods, I'm just wary of the lack of metrics. And I'm unsure of how you alleviate the problem of only testing how one person or close team think it should work. In HW design some teams have separate Verification and Design groups and/or create two implimentations in different languages and compare their results. If you'r writing the test and writing the code, you can be blind to common errors. Is TDD enough? > > To answer the original question of "how do you know when you're done?" > I would say that TDD itself doesn't really say, but in XP you have > what are called "acceptance tests", which are similar to the unit tests > in that they are a fully automated suite of tests that verify the > high level functionality of the entire program. When your code > passes all the units tests you have written to drive it's development, > *and* all the acceptance tests, then you're done. (That's another one > of the "things of beauty" in XP: the tests aggressively control scope > since you don't have to build anything for which you don't have a test.) OK, how do you guage the quality of those acceptance tests + TDD + generated program? Graphs of TDD checkins and acceptance test checkins over time, as well as in-depth coverage metrics might allow you to at least compare one development effort with the next one and evolve a useful set of 'numbers' that attempt to abstract what a good design project looks like. With Xp but without the stats, makes it harder to encapsulate and disseminate good project management principals. I'd like to see people describe how to measure SW bug rates and coverage (statement and branch etc), using specific tools, then say 'don't ship until the bug rate is below X when measured using Y; and the Coverage metric is S when measured using tool T with options A, B and C). A dumb follower of rules might still cock things up, but quantifiable goals like that would help the non-dumb. > -Peter Donald 'Paddy' McCarthy. From gh at ghaering.de Fri Jun 6 08:39:06 2003 From: gh at ghaering.de (=?ISO-8859-15?Q?Gerhard_H=E4ring?=) Date: Fri, 06 Jun 2003 14:39:06 +0200 Subject: Why it doesn't go ???? In-Reply-To: References: Message-ID: <3EE08B6A.7020401@ghaering.de> Panther wrote: > import os > fd = os.popen('python ping.py 192.168.1.4', 'r') > if fd.readline() == 'None': > print "I'don't ping ip" ping.py? Which ping.py are you talking about? Or do you want to invoke the system command 'ping' instead? If you want to invoke the system command, this would look like: fd = os.popen('ping 192.168.1.4', 'r') No python and no .py. Also it's hard for me to believe this program will actually print a line called 'None'. To invoke the system 'ping', here's a suggestion: import commands output = commands.getoutput("ping -c 1 192.168.1.4") Linux ping has a -c parameter for how often to ping. Similarly -n on Windows. Linux ping will ping until killed by default. HTH, -- Gerhard From belred1 at yahoo.com Wed Jun 4 01:55:36 2003 From: belred1 at yahoo.com (Bryan) Date: Wed, 04 Jun 2003 05:55:36 GMT Subject: Possible PEP: Improve classmethod/staticmethod syntax References: <20030603164521903-0400@braeburn.themorgue.org> <1ieDa.35049$DV.60225@rwcrnsc52.ops.asp.att.net> Message-ID: "Skip Montanaro" wrote in message news:mailman.1054700708.6942.python-list at python.org... > > bryan> these two "styles" appear to be the same, except the second one > bryan> seems to be more natural and simpler and obvious to me. > > Perhaps, but style two limits you to a single "keyword" after the def, and > from a parser standpoint suggests that "staticmethod" should be an actual > keyword. You also have to consider the other modifiers which might > reasonably be applied to a function and how they will be implemented. For > pre- and post-conditions, something like > > def foo_pre(...) [contract]: > > > def foo_post(...) [contract]: > > > def foo(...) [pre=foo_pre, post=foo_post]: > > > or > > def foo_pre(...) {'contract': True}: > > > def foo_post(...) {'contract': True}: > > > def foo(...) {'pre': foo_pre, 'post': foo_post}: > > > might be sufficient to allow foo_pre and foo_post to be compiled in such a > way that when they run they actually see foo's locals as their locals and > allow foo to be compiled in a way that calls the pre-condition function upon > entry and the post-condition function just before return (after the return > value has been computed, but before the return is executed). (FYI, the > above is just right off the top of my sleep-starved brain. I'm sure it's > full of holes.) > > Combining that with static methods or class methods and you find the same > mechanism can be easily extended: > > def foo(...) {'staticmethod': True, 'pre': foo_pre, 'post': foo_post}: > > > so now foo() is a static method with both pre- and post-condition contracts > which are executed at the appropriate times. > > and-tim's-your-uncle-ly, yr's, > > Skip > thanks skip... now i can see the elegance of this solution. wouldn't this also solve the pre/post conditions that are currently put in comments with another current solution? but, how would you handle pre/post conditions that are only supposed to be used in a debug version? bryan From max at cNOvSisiPonAtecMh.com Wed Jun 11 13:24:04 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Wed, 11 Jun 2003 17:24:04 GMT Subject: Go buy _Text Processing in Python_ References: <84fc4588.0306110058.1c019f66@posting.google.com> Message-ID: David made the whole thing available on-line: http://gnosis.cx/TPiP/ unfortunately the formatting is crap. I bought the book from amazon but I would love to have a PDF version for those other times. -- ======================================== 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] "Anand Pillai" wrote in message news:84fc4588.0306110058.1c019f66 at posting.google.com... > Hi David > > Is an online version available for this book ? I remember that > you had put up sample chapters of the book sometime back on your > website. > > I would like to buy a copy, but just asking... > > Thanks > > Anand Pillai > > mertz at gnosis.cx (David Mertz) wrote in message news:... > > "Max Khesin" wrote previously: > > |btw, your book is supposed to be on its way from Amazon. I hope it > > |comes fast... > > > > Thanks Max. Which reminds me to announce that it is out: > > > > +++ > > > > After way too long, my occassionally plugged book, _Text Processing in > > Python_ is actually printed and being sold in stores. I think it looks > > quite nice, decent paper, binding, and I am pleased by the typography > > now that I've seen the real thing etc. (I did the composition, but > > somehow the bound volume is still a step past my laser printer pages). > > My Amazon rank fell from 1.5 millionth to 100 thousandth already... a > > runaway seller :-). > > > > FWIW. I am supposed to get 50 author's copies of the text (but my > > publisher has seemed to drag their feet greatly on little details like > > paying me--and delivering these copies). When I get them, beyond a few > > for friends and family, I'll sell the rest to the Pythonistas here (I > > should be able to do a credit card via textbookx.com, where I have an > > account; or send them to anyone who wants to pay me directly by > > check). I'll announce details when I wrestle the copies out of AW. > > > > 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 zathras at thwackety.com Fri Jun 13 17:43:45 2003 From: zathras at thwackety.com (Michael Sparks) Date: Fri, 13 Jun 2003 22:43:45 +0100 Subject: Type hierarchy In-Reply-To: References: Message-ID: <200306132243.45270.zathras@thwackety.com> On Friday 13 June 2003 21:05, Pedro Werneck wrote: > > needs isinstance(o, int) or isinstance(o, long), or float... although > > Maybe I'm wrong, but can't you use isinstance(o, (int, long, float)), for > instance ? > > And the benefits of such changes would be greater than the effort to do it > ? It strikes me that OP wants to be able to get at things in the middle of his type hierarchy: isinstance(o,numeric)) isinstance(p,mutable) isinstance(q,collection) However, as you note, these can all be done right now however: >>> numeric=(int,long,float,complex) >>> mutable=(dict,list) >>> collection=(tuple,dict,list) >>> o, p, q = 1j, "hello", (1,2,3) >>> isinstance(o,numeric) True >>> isinstance(p,mutable) False >>> isinstance(q,collection) True What this _doesn't_ allow however is for someone to either subclass from in the middle of the hierarchy, or to modify the definitions of (say) numeric to allow this: >>> class foo(numeric): pass >>> foo = mySpecialNumber(1,2,3) >>> isinstance(foo, numeric) Because numeric is immutable. However, if you're willing to accept a slight obfuscation in order to gain the ability to add extra things inside the hierarchy you can do this: >>> numeric=[int,long,float,complex] >>> mutable=[dict,list] >>> collection=[tuple,dict,list] >>> o, p, q = 1j, "hello", (1,2,3) >>> isinstance(o,tuple(numeric)) True >>> isinstance(p,tuple(mutable)) False >>> isinstance(q,tuple(collection)) True You could argue "fix the hierarchy", but the problem AFAICT is this: a hierarchy forms a taxonomy - but who's taxonomy do you want? Do you want a fixed one formed by inheritance through abstract classes, or do you want a more flexible approach? OP's taxonomy would map like this: basestring = [string, unicode] immutable = basestring + [tuple] mutable = [list, array] sequence = immutable+mutable mapping = [dict] intclasses = [int, bool] number = intclasses+ [long, float, complex] internal = [code, frame, traceback] Despite these problems, if I was faced with this hierarchy I could change it if I disagreed with it - and I do: >>> # eg >>> immutable = basestring + [tuple,int,long,float,complex] ie have a flat type system makes it simpler for a user to override the hierarchy in a way that make sense for their application. After all Russ Salsbury disagreed, and preferred: Sequence = [tuple,list] Mapping = [dict] Collection = Sequence+Dict Which is a just as valid hierarchy. The nice thing also is it makes any hierarchy orthoganal with any other. (This is one reason I've never been particularly convinced of the idea of defining a single *static* hierarchy - multiple or single inheritance style or otherwise) If you combined this with an appropriate metaclass type approach (or similar), you could even update these "central" hierarchies as classes are constructed using "class" statements :-) This approach has problems of its own of course. Changing basestring doesn't update sequence, etc. This could be solved by having a form of dynamic union of subsets - akin to an SQL view added to the sets - an idea I quite like TBH. (You could of course just have a separate class that does the same thing :-) Just my tuppence worth :-) Michael. From suresh_vsamy at rediffmail.com Wed Jun 25 01:43:33 2003 From: suresh_vsamy at rediffmail.com (Suresh Kumar) Date: 25 Jun 2003 05:43:33 -0000 Subject: Problem in storing tkinter canvas as PNG file using ImageGrab.grab Message-ID: <20030625054333.4153.qmail@webmail25.rediffmail.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From martin at v.loewis.de Wed Jun 11 14:33:43 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 11 Jun 2003 20:33:43 +0200 Subject: UTF-16 encoding line breaks? References: <3ee72262$1@mail.hmgcc.gov.uk> Message-ID: "Richard" writes: > I have a script which uses the .encode('UTF-16') function to encode a string > into UTF-16. However I am having difficulties in putting line breaks into > that string. \n is what I normally use but does not appear to become valid > UTF-16 once encoded. Can you demonstrate that? It works fine for me. Regards, Martin From aahz at pythoncraft.com Wed Jun 11 17:38:52 2003 From: aahz at pythoncraft.com (Aahz) Date: 11 Jun 2003 17:38:52 -0400 Subject: __past__ (Was: Re: PEP-317) References: <1055255402.3ee5eb6ae09ee@mcherm.com> <1055312155.157424@yasure> Message-ID: In article , Gerrit Holl wrote: > >How about a __past__ pseudo-module? > >from __past__ import string_exceptions # for those to lazy to update their code >from __past__ import access >from __past__ import implicit_instatiation ># etc. This has been suggested before and Guido has emphatically rejected it. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From t_therkelsen at hotmail.com Fri Jun 20 18:32:13 2003 From: t_therkelsen at hotmail.com (Troels Therkelsen) Date: 20 Jun 2003 22:32:13 GMT Subject: Problems retreiving double from database References: Message-ID: In article , Thunder Perfect Mind wrote: > I'm using an Access database where some fields are doubles. I'm using > ADO to access this and when I try to retrieve the value in the field > it returns the wrong value, instead of say 12.432 which might be the > value of the field it returns 12.43200000000000003. Thinking this > might be a problem with ADO I tried to use ODBC with the same > result..... hmmmm maybe the database is the problem so I downloaded > MySQL and connected with ODBC.... again same problem. > > Anyone know what causes this? and if so how do I fix it? > > Any help appreciated, > > dr//\//\ The problem isn't directly related to Python, but how floating-point numbers are represented using a limited number of bits. Please read this page: http://www.python.org/doc/current/tut/node14.html Regards, Troels Therkelsen From mike at bindkey.com Tue Jun 17 22:11:39 2003 From: mike at bindkey.com (Mike Rovner) Date: Tue, 17 Jun 2003 19:11:39 -0700 Subject: pack and unpack problems References: <20030618014303.0DCCB269AC@www.fastmail.fm> Message-ID: "Justin Johnson" wrote in message > exceptions.ValueError: unpack tuple of wrong size > > struct.calcsize('xxLxx8c') returns 18, which is the amount of bytes in > "data", at least I think so. Hm, make yourself sure: assert len(data)==struct.calcsize('xxLxx8c') Mike PS. Better use '!xxLxx8c' cause N is network order 4-byte long PPS. xxNxxH8 = 1+1+4+1+1+8 = 16, so check alignment! From jjl at pobox.com Mon Jun 9 18:50:06 2003 From: jjl at pobox.com (John J. Lee) Date: 09 Jun 2003 23:50:06 +0100 Subject: Why is error message value "disappearing"? References: Message-ID: <87k7bu7tnl.fsf@pobox.com> "Robert Oschler" writes: [...] > It's as if errMsg is being passed by value and the assignment that occurs > inside errtest() doesn't "stick". I thought Python was pass by reference? > > What am I doing wrong? [...] http://www.python.org/doc/FAQ.html#4.35 http://www.python.org/doc/FAQ.html#4.89 John From theller at python.net Tue Jun 17 07:35:21 2003 From: theller at python.net (Thomas Heller) Date: Tue, 17 Jun 2003 13:35:21 +0200 Subject: Python 2.2.2 win32 build References: Message-ID: Sebastien Hugues writes: > Hi, > > I built Python 2.2.2 dll and exe under win32 using Visual Studio and now > i wonder how i could make a distribution from my build. The official > distribution > uses Wise, but i didn't see and config file for Wise in the package... > > Any ideas ? It's PCBuild\python20.wse. Thomas From erased*remove_this* at xs4all.nl Fri Jun 20 07:38:24 2003 From: erased*remove_this* at xs4all.nl (rgndrp) Date: 20 Jun 2003 11:38:24 GMT Subject: include files? References: <3ef1c90f$0$49114$e4fe514c@news.xs4all.nl> <3ef2d8fc$0$49114$e4fe514c@news.xs4all.nl> Message-ID: <3ef2f22f$0$49107$e4fe514c@news.xs4all.nl> it would if i'd get it to work :) now it returns this cgi error: ---------------8<-------------------------- The specified cgi application misbehaved by not returning a complete set of HTTP headers. The headers it did return are: File "e:\_cgi\test.cgi", line 1 include applic.py ^ SyntaxError: invalid syntax --------------->8-------------------------- the only line in applic.py is: myvar=5 hmpf! Thomas G?ttler wrote: > rgndrp wrote: > > > Bengt Richter wrote: > > > >> On 19 Jun 2003 14:30:39 GMT, "rgndrp" > >> wrote: > >> > >> >hi all, > >> > > >> >I use python for making cgi scripts on a iis/w2k > >> >box and i wanted to know if it is it possible to include files in > >> >python? > >> >like: > >> >or something :) > >> > > >> It depends on you context. If you are in a Python source context, > >> execfile has a similar effect to #include. Chances are there are > >> better ways to solve your problem though. > >> > >> Regards, > >> Bengt Richter > > > > what im trying to do is have a file in which i define some > > global variables and functions such as fonts and background colors > > and debug/database functions. i used to do this is asp with include > > files. any other suggestions, anyone? :) > > Does this help you? > > main.py: > include variables > if variables.myvar==5: > print "OK" > > variables.py: > myvar=5 > > thomas From jepler at unpythonic.net Mon Jun 16 15:52:51 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 16 Jun 2003 14:52:51 -0500 Subject: Diamond inheritance with str In-Reply-To: References: Message-ID: <20030616195248.GA923@unpythonic.net> I don't understand why it fixes the problem, but if you write this instead, it works: >>> class A(str): pass ... >>> class B(A): pass ... >>> class C(A): pass ... >>> class D(B, C): pass ... The original case fails just like your message described: >>> class B1(str): pass ... >>> class C1(str): pass ... >>> class D1(B1, B2): pass ... Traceback (most recent call last): File "", line 1, in ? TypeError: multiple bases have instance lay-out conflict This is in Python 2.2.2. Jeff From david24 at iland.net Wed Jun 18 18:57:42 2003 From: david24 at iland.net (David B.) Date: Wed, 18 Jun 2003 17:57:42 -0500 Subject: Windows Program? Message-ID: Hello. I'm new to python and I was wondering... can you make windows-like programs? (Like with the gray background and the input boxes?) David From m at moshez.org Wed Jun 4 23:51:55 2003 From: m at moshez.org (Moshe Zadka) Date: 5 Jun 2003 03:51:55 -0000 Subject: 123.3 + 0.1 is 123.3999999999 ? In-Reply-To: <3EDEA84A.389C1AC5@alcyone.com> References: <3EDEA84A.389C1AC5@alcyone.com>, <3EC3BCCD.3090605@nospam.com> <895e4ce2.0306021736.13c657a5@posting.google.com> <3EDC1074.CA05EC23@alcyone.com> Message-ID: <20030605035155.16099.qmail@green.zadka.com> On Wed, 04 Jun 2003, Erik Max Francis wrote: > There are all sorts of alternative definitions of the reals which have > differing properties than the reals we've all come to know and love. > They usually fall under the general category of "non-standard analysis." In non-standard analysis, 0.9999..... has *no* meaning if you just translate the usual definition of limit from the real numbers. This shouldn't be surprising, as limits are not a first-order property. In general, since being a least upper bound is not first-order property, there are no least upper bounds in non-standard analysis. And again, not surprising -- it is easy to prove that any ordered field with least upper bounds is the standard reals. Only when we become myopic enough for first-order sentences only, can the non-standard reals simulate the reals. (Oh, of course, if you translate the definition of limits blindly *enough*, that is to allow the sequence to range over the non-standard integers too, then 0.999....=1 again. Although the *name* 0.99999... is misleading, since it looks like it only ranges over the standard integers). -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jun 25 16:54:35 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 25 Jun 2003 22:54:35 +0200 Subject: Staying Connected to a POP3/SMTP Server In-Reply-To: <5a8e622e.0306251107.1d5e3202@posting.google.com> References: <5a8e622e.0306251107.1d5e3202@posting.google.com> Message-ID: <3efa0c0b$0$49107$e4fe514c@news.xs4all.nl> Amos Joshua wrote: > Would any Bad Things happen if I stayed connected to a POP3 and an > SMTP server for say, an hour, while checking for new emails say, every > ten seconds, and sending some at small intervals like that too? If it is your own mail server, I think not. If it is the mail server of your ISP, I think they won't be happy. Checking for mail that often is a substantial load on the machine, compared to 'normal use'. I'm not sure, but the POP3 server may erminate the connection if you keep it open for minutes...? As a safeguard for people hogging server resources... --Irmen From dave at boost-consulting.com Wed Jun 18 10:25:54 2003 From: dave at boost-consulting.com (David Abrahams) Date: Wed, 18 Jun 2003 10:25:54 -0400 Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> <3EECED65.ACF1A6B7@engcorp.com> <3EEE3036.1080105@removeme.free.fr> Message-ID: Alex Martelli writes: > But this has little to do with the need of 'type declarations'. I > suspect that a statically typed language would also be better off > without them, relying on type inferencing instead, a la Haskell (and > Haskell's typeclasses to keep the inferencing as wide as feasible), > for example. But I have no research to back this up;-). I don't have any first-hand experience, but the experience of friends of mine who have used Haskell is that it can be exceedingly difficult to locate the source of a type error when it does occur, since the inference engine may propagate the "wrong" type back much further than the source of the error. Furthermore, if you do everything by inference you lose the explanatory power of type declarations. -- Dave Abrahams Boost Consulting www.boost-consulting.com From sholden at holdenweb.com Thu Jun 26 21:21:20 2003 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 27 Jun 2003 01:21:20 GMT Subject: shebang strange thing... References: <3EF3A07B.A683F94F@alcyone.com> <3EF7A121.7B4C3775@alcyone.com> <3EF933AA.C16ADFE5@alcyone.com> Message-ID: "Ben Finney" wrote in message news:slrnbfn2eb.rbb.bignose-hates-spam at iris.polar.local... > On 26 Jun 2003 12:25:55 -0700, - wrote: > > I think the terminology is not taken from typewriters, but from some > > old printers where you needed both characters to start a new line. > > > > CR moved the print head to the beginning of the line > > CR stands for "carriage return". If you're talking about a print head > moving across the paper, you're no longer talking about a carriage > "returning", so the terminology obviously didn't come from electric > printers. > > Carriage Return is a direct reference to the paper carriage on a manual > typewriter. These predate electric printing machines, and thus the > terminology was borrowed when teletypes needed control codes to control > their print head. > > On such typewriters, the "line feed" function was also separate; once > the carriage was returned to the start of the line, one could cause > the paper to feed up a line at a time to introduce more vertical space; > this didn't affect the position of the paper carriage, so was > conceptually a separate operation. > > So, it was teletypes that needlessly preserved the CR and LF as separate > control operations, due to the typewriter-based thinking of their > designers. If they'd been combined into the one operation, we would > have all the same functionality but none of the confusion over line > ending controls. > Although in actual fact the KSR33 teletype did need a fifth of a second to guarantee that the print head would have returned to the left margin from column 72 haracters was a "feature". Sometimes you would (all right, *I* would) depress the two keys in the wrong order, and the result was that you would see a single character printed in the middle of the new line during the "flyback" period. mobile-mine-of-useless-information-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From painlord2k at yahoo.it Fri Jun 20 04:29:56 2003 From: painlord2k at yahoo.it (Mirco Romanato) Date: Fri, 20 Jun 2003 08:29:56 GMT Subject: Tiger Hash Function in Python References: Message-ID: <8CzIa.104097$Ny5.3014903@twister2.libero.it> "Aahz" ha scritto nel messaggio news:bct5oh$6k4$1 at panix1.panix.com... > In article , > Mirco Romanato wrote: > >I'm thinkering with Python to build an utility (more specs at the end > >of the post) and I need to utilize the Tiger Hash function. > >I have not MSVC and run a Win box with the last Cygwin and Python > >2.2.3. > >There is any module that compile automagically with Cygwin, or a > >module that don't need to be compiled, only installed? > Why not write a Tiger hash module yourself? I'm a newby to Python, and I want use Python because it don't need to compile and other things in order to have a working program. It is over 10 years I don't program anything, apart my VCR :-( But you are right, probably I will follow yours if I find no alternative. What I dare is, what if I use Python to compute Tiger hash for big files: e.g tiger of 1024 bytes chunks of a 650 - 1 GB files (650k-1M function call for a file). The function efficiency compared to C how will compare? Mirco From stephane.richard at verizon.net Mon Jun 23 08:26:00 2003 From: stephane.richard at verizon.net (Stephane Richard) Date: Mon, 23 Jun 2003 12:26:00 GMT Subject: XML References: <3EF471BA.EE4F056@hotmail.com> <23891c90.0306230142.83612c8@posting.google.com> Message-ID: As they say in the industry. The Majority (here the most widely used) sometimes means that all the fools are on the same side...hehehe.. For data Sharing, XML seems to be the way to go, no two ways about it, and it's why Oracle and SQL Server offer, directly in their SQL statements the ability to select as XML directly. To me, although it may be to many tags at times, I use XML for configuration purposes, instead of an INI file for example. reason being that INI files do have a size limit and I hate dealign with such limits :-).....also I've created engines that build dynamic forms from the contents of XML documents (to define and configure data screens for multiple phase dialogs or instrumentation in the case of an musical editor librarian). which can easily break the 64Kb limit offered by ini files. and since each tree section can hold very different GUI design elements for the same part of a data entry screen. XML proves ideal in describing each part and under which condition each part should occur in a very human readable format, at least I liek to think so :-). -- St?phane Richard Senior Software and Technology Supervisor http://www.totalweb-inc.com For all your hosting and related needs "Ben Finney" wrote in message news:slrnbfdp5t.qk.bignose-hates-spam at rose.localdomain.fake... > On 23 Jun 2003 02:42:49 -0700, Paul Boddie wrote: > > it is fair to say that claiming the suitability of [ASCII plain text] > > because "there are a lot of parsers which use it" is analogous to > > telling a Japanese person that they only need to know the Latin > > alphabet to be able to understand most Western languages. > > Good thing nobody's tried to claim that then. I raised the issue of > ASCII plain text to refute the claim that HTML was the "most widely used > document format". I make no necessarily related claim about > suitability. > > In fact, I raised awareness of the "most widely used document format" > issue to show that just because something is widely used, doesn't > necessarily mean it's suitable in all the place it's used. > > Plain text ASCII is great as far as it goes, but for structured data, > a threshold is usually reached where something more complex is needed. > When it is, XML -- encoded as plain ASCII, or some other standard text > encoding -- is a prime choice, in my book. > > > There are some pretty solid reasons for choosing XML to represent > > data. > > I agree with most of them, and am in favour of choosing XML when > interchangeable, structured data is needed. > > (I'm always tempted to leave out the "interchangeable" -- isn't data > essentially useless unless it can be interchanged? -- but then I recall > proprietary formats that enforce vendor lock-in by deliberately > obstructing interchangeability, and realise it still needs to be made > explicit.) > > -- > \ "One seldom discovers a true believer that is worth knowing." | > `\ -- Henry L. Mencken | > _o__) | > http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From sheila at spamcop.net Sat Jun 7 01:02:34 2003 From: sheila at spamcop.net (Sheila King) Date: Fri, 06 Jun 2003 22:02:34 -0700 Subject: Anyone using Python to access PHPbb's MySQL database on a web server? References: Message-ID: On Fri, 06 Jun 2003 13:50:08 GMT, "Robert Oschler" wrote in comp.lang.python in article : > "Sheila King" wrote in message > news:bbln6k.1i0.1 at kserver.org... > > On Wed, 04 Jun 2003 02:01:08 GMT, "Robert Oschler" > > wrote in comp.lang.python in > > article : > > > > > I want to run Python programs locally on my Win2k box to read/write the > > > PHPbb.MySQL database(s). I have Python 2.2.x with the venerable WingIDE > > > debugger running on my Win2k box. Has anyone done any Python > programming > > > like this? If so, I'd be very interested in what you had to do to get > it > > > working, especially in the area of any available python > libraries/modules to > > > help with the MySQL access. > > > > You really do need to check with your host as to whether they allow IP > > addresses outside of their local network to even access the MySQL server. > > > > I get quite a number of support incidents at the Service Desk where I > work, > > where clients just assume that because they have Telnet/SSH and FTP > access, > > that they can also connect to their MySQL databases remotely. > > > > We do not permit this, excepting that they order a special ODBC > connection. > > > > Like I said, check first to see whether it is even permitted by your host. > > > > -- > > Sheila King > > http://www.thinkspot.net/sheila/ > > http://www.k12groups.org/ > > Sheila, > > Good info, thanks. It looks like I may have to do some PHP work to create > an interface to the MySQL database, if my ISP says "no" to remote access. > > thx > In that case, you might find that phpMyAdmin will fit the bill quite nicely. Saves you from re-inventing the wheel. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From gradha at titanium.sabren.com Mon Jun 16 17:07:40 2003 From: gradha at titanium.sabren.com (Grzegorz Adam Hankiewicz) Date: Mon, 16 Jun 2003 23:07:40 +0200 Subject: Html: replacing tags In-Reply-To: References: <2972888.1055030986@dbforums.com> Message-ID: <20030616210740.GA28574@pedos.es> On 2003-06-13, Lee Harr wrote: > I needed to do something very similar recently. I was making > a mirror of a website for burning on to a cdrom, so all links > needed to be made relative instead of absolute. > > It seems like this may be a very common thing to do (replacing > tags). If someone makes a general solution, it might be nice if > this functionality were in the standard library. > > My solution was to get a list of the tags and then just > line.replace(old_tag, new_tag) through the file. > > Problem is it tends to find things that should not be replaced. I wrote that not long ago for work and packaged it inside a small class which allows link extraction and link modification. You can get it from http://gradha.sdf-eu.org/efaber.en.html. -- Please don't send me private copies of your public answers. Thanks. From op73418 at mail.telepac.pt Thu Jun 19 10:02:08 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Thu, 19 Jun 2003 15:02:08 +0100 Subject: How to recognize a generator function? References: Message-ID: On Wed, 18 Jun 2003 16:33:37 -0700, Oscar Rambla wrote: [Text snipped] >Gon?alo wrote: >>And then again, why are you interested in such a difference? Seems >>like the typical YAGNI. > >Could you spell it, please? You aint gonna need it. > >Oscar Rambla >CODI > With my best regards, G. Rodrigues From staschuk at telusplanet.net Fri Jun 27 10:15:23 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Fri, 27 Jun 2003 08:15:23 -0600 Subject: GC time debug... In-Reply-To: <20030626064759.GD11302@c1.neotonic.com>; from jeske@neotonic.com on Wed, Jun 25, 2003 at 11:47:59PM -0700 References: <20030626064759.GD11302@c1.neotonic.com> Message-ID: <20030627081523.A5072@tibia.amotlpaa.bogus> Quoth David Jeske: > In debugging Python GC actions, it's really useful to know the amount > of time Python spends doing the GC cycle (i.e. the pause time). I made > a quick hack to do this, and I've attached the patch. [...] > I'd like to see something like this added to gc module. What you should do, then, is submit it on SourceForge: (I think you'll have to register to submit a patch.) -- Steven Taschuk staschuk at telusplanet.net "[T]rue greatness is when your name is like ampere, watt, and fourier -- when it's spelled with a lower case letter." -- R.W. Hamming From mis6 at pitt.edu Tue Jun 24 13:18:49 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 24 Jun 2003 10:18:49 -0700 Subject: Getting a list of an object's methods? References: <2259b0e2.0306230447.52460ace@posting.google.com> Message-ID: <2259b0e2.0306240918.1eb58afe@posting.google.com> Alexander Schmolck wrote in message news:... > Now I have no idea what the hell a "member" is supposed to be (inspect's docu > won't tell you and the only sense in which it occurs in the language ref is > that of set membership (i.e. qualfiying __contains__)), so my guess is that > it's just some ad hoc synonym for attribute (not that I remember stumbling > across a clear definition of attribute anywhere, either). > > "Member" better have *some* reasonably well-defined meaning, because unlike > `dir` which is supposed to just give a "convinient" overview of an objects > content in interactive session, AFAICT `inspect.getmembers` is meant to be > used for programming. I somehow prefer my programs to have well-defined > meanings. > > So if no-one enlightens me, I shall file a bug report. > > > 'as Do you mean a documentation bug report? I do agree with you that a non-ambiguous definition of "member" should be given in the language reference. At the present it seems that metaclass methods are not considered "members" of the instance class: if this is the case, it should be documented. On the other hand, if this is not the case, then inspect.getmember is buggy. Michele From llafba at gmx.net Thu Jun 26 15:31:30 2003 From: llafba at gmx.net (Tom) Date: Thu, 26 Jun 2003 21:31:30 +0200 Subject: boa constructor - run script/output References: <3EFAE800.6080406@gmx.net> Message-ID: <3EFB4A12.1010504@gmx.net> Thanks for your answer. 1.) yes, I had to put my whole script into a function. Didn't know that first. I wanted to run the whole script, but I think it works now. 2.) I also think that the examples of wxPython are really great. Sometimes it is just hard to understand the code if you are a newbie. :-) I worked on this all day and think that I did it now!:-) Thanks for your help. Tom delphiro wrote: >problem 1) > >It sounds like you need to import your script > >import your_script_name > >and attach an event to the function that you want to call >from within your script > >for example; > >yourscript.py contains function 'DoThis()' > >in gui class: > >import yourscript.py > >some event > >def OnButtonMyButtonDown(self,event): > yourscript.DoThis() > >2) > >You will have to edit your script in a way that it >knows where to send it's output. This means you will >have to pass a widget (like wxTextCtrl) to your script >and output the messages to that widget. > >The best way to actualy learn wxPython for me was to study the >examples. They realy make things clear for almost any widget! > >Hope this helps, >Rob > > > From yweng at cs.uoregon.edu Tue Jun 10 03:00:14 2003 From: yweng at cs.uoregon.edu (Yan Weng) Date: Tue, 10 Jun 2003 00:00:14 -0700 Subject: Provide an option: static typing + type inference ? Message-ID: In theory, dynamic typing = static typing + type inference. ML implemented the later one. Can we provide something similar in Python? I knew this topic was discussed two years ago in type SIG. Is there any new achivement in this area recently? -- Yan Weng yweng at cs.uoregon.edu http://www.cs.uoregon.edu From PupppyWizzard at glay.org Wed Jun 4 05:59:01 2003 From: PupppyWizzard at glay.org (Pupppy Wizzard) Date: 4 Jun 2003 02:59:01 -0700 Subject: LANGUAGE QUESTION??? Message-ID: <8dcf2300.0306040159.118c24e8@posting.google.com> Hi. I am an old school programmer looking to modernize my skill set. I want to focus on one new language. Should I choose: VB VB.net C# C++ Python Smalltalk J# JScript.net or Java? From mis6 at pitt.edu Wed Jun 4 10:12:31 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 4 Jun 2003 07:12:31 -0700 Subject: How to replace the metaclasses of all the classes imported References: Message-ID: <2259b0e2.0306040612.1605d37@posting.google.com> janeaustine50 at hotmail.com (Jane Austine) wrote in message news:... > > Let me explain more about what I want: > > Let's assume there are a dozen of modules in my program. > ############################## > #main.py > > import alpha > > class A: > .... > > class B: > .... > > def main(...): > .... > temp=alpha.C() > .... > > if __name__=='__main__': > main(...) > > ############################## > #alpha.py > > import beta > > class C: > .... > > def ... > > ############################## > #beta.py > > class D: > .... > > def ... > > ---------------------------------- > What I'd like to do with metaclasses is, for example, log all > method calls with minimum code change. Two ideas: 1. The poor man solution: if all classes are old style classes, as it seems from your example, simply add on top of each module the line __metaclass__=LoggerMetaclass (you can also do that automatically, if there are too many modules). If this is too much a change of the source code, or if you have new style classes, then 2. The rich man solution: redefine the __import__ function by using an improved version of import_with_metaclass. I suggest to look at Demo/imputil/knee.py in the Python source distribution for hints on how to do it. Note for David Mertz: we should fix the import_with_metaclass function to make it safe under meta-type conflicts. I hadn't time to look at it yet :-( Michele From a.schmolck at gmx.net Sun Jun 22 19:55:30 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 23 Jun 2003 00:55:30 +0100 Subject: Getting a list of an object's methods? References: Message-ID: Jeremy Yallop writes: > Alexander Schmolck wrote: > >>>> import inspect, operator > >>>> inspect.getmembers(foo, operator.isCallable) > > Unfortunately, this isn't any better than the original idea of using > dir(), I think it is, see below. > since inspect.getmembers is implemented using dir(). True. > As the OP noted, dir() isn't reliable. True. The premises are right, but they don't entail the conclusion. `dir`s behavior is not guaranteed to be stable, but `inspect.getmembers`'s obviously is [1]. Since `inspect.getmembers` is part of python itself, it can freely use any behavior guaranteed for *a particular python version* and the fact that it uses `dir` thus becomes and implementation detail that needs to be of no concern to anyone except the inspect module's official maintainer -- if `dir` changes, he or she will need to update `inspect.getmembers`. However: > For example, 'mro' isn't in int's dir(), although it is (the name of) a > method of type and in type's __dict__. Indeed, so this looks like a bug to that should be filed (unless `mro` somehow doesn't qualify as a 'member' -- I can't see why, but this is something I leave to the wizards). If these omissions turn out to be important of the OP's desired application, then he'll indeed need to consider a further alternative (maybe based upon the union of `inspect.getmembers` and the `__dict__.keys()`, where the latter are available). Anyway, this example highlights a problem I'm getting increasingly concerned about, namely the erosion of python's metaprogramming capabilities. I don't think "What methods does this object have?" is a question that only a python wizard should be able to ask and receive a well-defined answer. 'as Footnotes: [1] Otherwise the inspect module would be bascially useless. From alanmk at hotmail.com Mon Jun 9 07:03:34 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 09 Jun 2003 12:03:34 +0100 Subject: Recall last result References: <3ee4577d$0$25096$91cee783@newsreader01.highway.telekom.at> <3EE45AED.8A20FD8E@hotmail.com> <3EE45F0A.750D7AB3@alcyone.com> Message-ID: <3EE46986.53EFF8EC@hotmail.com> Erik Max Francis wrote: > This is indeed true, but note that it is only the case in the > interactive interpreter. It is not the case in a general script; it > wasn't clear which the original poster meant. I didn't say that it would work in the general case, all I said was "try this". Original Poster wrote: > I call a function producing a large solution > for a combinatorial problem. The computation takes quite some time. > I forgot to assign the result to a variable. > The list is displayed on screen? ... > History recall does not help me, since that would reproduce my input, > but I need the output. The latter statement strongly indicates to me that the OP is running an interactive shell, which is why I suggested a solution that would work in the interactive shell. Just in case he wasn't, then perhaps you can enlighten us on how to solve the problem in the general case? -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From cbrown at metservice.com Fri Jun 13 01:19:29 2003 From: cbrown at metservice.com (Colin Brown) Date: Fri, 13 Jun 2003 17:19:29 +1200 Subject: CPU utilization References: Message-ID: <3ee95cd2$1@news.iconz.co.nz> Eric Jensen wrote in message news:bc7m2n$6jp4$1 at acs2.byu.edu... > I am writing a diagnostics program and would like to get the CPU > utilization for the system. Does anyone know simple way to do this? ... With the emphasis on simple & for Win32 you may like to look at wrapping a call to pslist.exe from pstools (www.sysinternals.com). Colin Brown From ngps at netmemetic.com Thu Jun 12 20:56:43 2003 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 13 Jun 2003 00:56:43 GMT Subject: Python Coredump on FreeBSD References: Message-ID: According to Andrew MacIntyre : > Ok, so you're using threads... Also see here: http://www.zettai.net/Members/george/python213FreeBSDPlone.blog/view -- Ng Pheng Siong http://firewall.rulemaker.net -+- Manage Your Firewall Rulebase Changes http://www.post1.com/home/ngps -+- Open Source Python Crypto & SSL From usenet at soraia.com Wed Jun 4 23:53:05 2003 From: usenet at soraia.com (Joe Francia) Date: Thu, 05 Jun 2003 03:53:05 GMT Subject: Including binary files in a .py file; advice needed In-Reply-To: <3EDEB0A6.202@netspace.net.au> References: <3EDEB0A6.202@netspace.net.au> Message-ID: <3EDEBED2.80605@soraia.com> Gary Duncan wrote: > > Here's what I want to do; distribute a .py file (a GUI app) with > an embedded (binary) .GIF file (a photo of me at 1 yo ;) rather than > distribute both separately. For convenience, mainly. > > > If in a Unix shell script, I'd uuencode the .GIF and include the > printable-ASCII file in it as a 'here' file. When executed the script > would 'cat' it out to e.g. a /tmp file from the main body of the script, > then uudecode the /tmp file to revert to the original .GIF file. > > I imagine in Python, one could place the uuencoded file (lines) > as a triple-quoted string, then uudecode it the .py program. > You can use the uu module, though I'd suggest the base64 instead, as it can decode a string directly (uu requires a file-like object), and tends to produce somewhat smaller strings. ############ #careful not to include a leading newline in b64 string ENCODED_GIF = \ '''R0lGODlhcwCKAPf/AJNtWolhToNdS7OEbGxLPbOMcraimHRTQ6iclkc4NntTQ725tnFiXFlJRb2o m5x5ZUEuKod5dpt1YotkUqZzXVtCN6t9Zb2Se5ptWpiJiKyKdJOIer6bhMbGxlM2LoV0bToqJ3NL blah blah etc... ''' import base64 out_gif = file('/home/scaba/littleman.gif', 'wb') out_gif.write(base64.decodestring(ENCODED_GIF)) out_gif.close() ############# jf From peter at engcorp.com Mon Jun 2 09:10:26 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 02 Jun 2003 09:10:26 -0400 Subject: CGI question: safe passwords possible? References: <7xwug82ag0.fsf@ruckus.brouhaha.com> Message-ID: <3EDB4CC2.B34F910C@engcorp.com> Paul Rubin wrote: > > Don't do it that way, since the hashed value sent to the server is > re-useable. Try something more like: > >
> > > From ed at membled.com Thu Jun 5 13:57:36 2003 From: ed at membled.com (Ed Avis) Date: 05 Jun 2003 18:57:36 +0100 Subject: a = b = 1 just syntactic sugar? References: Message-ID: Michael Chermside writes: >> table = {'setcolour': lambda x: b = x, >> 'invertcolour': lambda x: b = inverted[b], >>However it is not possible to write it as above because anonymous >>functions don't allow assignment, or at least, not with =. > table = {'setcolour': lambda setgs, x: setattr(setgs, 'b', x), > 'invertcolour': lambda setgs, x: setattr(setgs, 'b', inverted[b]), >Of course, you can argue that using setattr is simply another way of >doing assignment (but with a function, so it can be done in a lamda) >-- which would be true. Yes. Or even, instead of having a new class each time it might be worthwhile to define a 'holder': class Holder(object): def set(v): self.v = v def get(): return self.v bh = Holder() table = {'setcolour': lambda x: bh.set(x), ...} So inside the parallel universe of lambda expressions, a.set(b) is what you say instead of a = b. It seems a bit perverse that setattr is allowed in lambda expressions but assignment is not; that you can call setdefault to update a dictionary, but not simply set the dictionary's elements; that you can do sys.stdout.write but not print; that you can call a function which asserts but not call assert. If lambda accepted statements as well as expressions - or if a statement could be used as an expression, as in C - then these warts would not arise. -- Ed Avis From bignose-hates-spam at and-zip-does-too.com.au Thu Jun 26 22:53:14 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 27 Jun 2003 12:43:14 +0950 Subject: stupid question about os.listdir References: Message-ID: On Fri, 27 Jun 2003 03:06:04 GMT, Jason Kratz wrote: > Ben Finney wrote: >> Please reduce the problem to a simple script > > Ben...I tried the above in a new script file (with print os.listdir) > and it works as I thought my other should. Which means i'm doing > something wrong when passing the path in to my function but I'm not > sure what. ugh. Congratulations! You've learned an immensely valuable debugging technique: Reduce the problem behaviour to the *minimum necessary code* to reproduce the problem; otherwise, you're searhing in code that, it turns out, has absolutely no bearing on the problem. (This leads, in turn, to the principle that writing less code in the first place leads to fewer bugs -- but that will come naturally as you learn Python :-) -- \ "What if the Hokey Pokey IS what it's all about?" -- Anonymous | `\ | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From joel at memes.com Fri Jun 20 14:42:17 2003 From: joel at memes.com (Joel Boehland) Date: 20 Jun 2003 11:42:17 -0700 Subject: Definition of Aspect Oriented Programming References: <8csIa.133$rN.2282@news-server.bigpond.net.au> <1pv4fvsv2bvmglio3l5be4e9qakim3or4t@4ax.com> Message-ID: <3258dfc2.0306201042.30e7c2ce@posting.google.com> One other aspect-oriented/meta-object programming python toolkit to play around with: http://moppy.sourceforge.net cheers, Joel Boehland From steve.horsley at cwcom.cwplc.com Fri Jun 6 12:34:27 2003 From: steve.horsley at cwcom.cwplc.com (Steve Horsley) Date: 6 Jun 2003 09:34:27 -0700 Subject: Totally Confused: Passing variables to functions References: Message-ID: Chuck wrote in message news:... > > > >>> v = [1,2] > > >>> arg = v > > >>> arg.append(3) > > >>> v > > [1, 2, 3] > > I'm not "getting" variables in Python, then. > > What exactly happens when I say "arg = v"? > > Not "arg is assigned the value [1,2] that v happens to hold"... > > Not "arg now points to v" (can't be, since you can delete v and arg still > exists) > > It seems to say, "arg now points to what v also points to".. is this correct? > Spot on. Exactly. Except some people may prefer to say "refers to" rather than saying "points to". The one list now has two references to it. > And so... > > a = 1 > b = a > > is really saying, "b points to what a points to, which is a 'variable' with > the value of 1, which cannot be changed (immutable)". > > Is this correct? > Yes. In python, even the number 1 is a object - a number sort of object. try: >>> dir(1) and see how many functions the number 1 has! Then try (note the space before the dot): >>> 1 .__hex__ >>> 1 .__hex__() '0x1' But the fact that numbers are objects is something of a diversion here. Let's try this: def foo(arg): # This appends to the list that arg refers to arg.append('three') # make arg refer to something completely different arg = 42 # make a list and a variable 'a' that refers to it a = ['one', 'two'] # make a new variable 'b' and point it at the same # list as that a refers to b = a # call foo, which will append to our list # (and also fiddle with a different list of its own) foo(b) # remove one of the references to our list del a # remove the other reference to our list. # Poof! the list gets garbage collected because no-one has a # reference to it any more. It's gone and forgotten. del b > If so, I *think* I'm starting to "get it"... ;-) > I'm sure you are. Steve From mis6 at pitt.edu Fri Jun 20 13:37:26 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 20 Jun 2003 10:37:26 -0700 Subject: a clean way to define dictionary References: <3EEFEBFD.8090003@nospam.com> <2259b0e2.0306190831.63d42265@posting.google.com> <2259b0e2.0306191332.664300c0@posting.google.com> <2259b0e2.0306200552.6e41358d@posting.google.com> Message-ID: <2259b0e2.0306200937.483de18@posting.google.com> Alexander Schmolck wrote in message news:... > mis6 at pitt.edu (Michele Simionato) writes: > > > Sorry for the typo, of course I meant __setitem__/__getitem__. > > I am saying that a workaround for the change of the constructor signature > > is to subclass dict and to override the constructor. There is > > not a big penalty and you seems to agree (your last sentence). > > Overriding __getitem__ gives a big penalty, that's true, but this has > > nothing to do with the change of the constructor in Python 2.3, right ? > > I do not understand where the source of the confusion is (if any). > > OK, I see now what you mean. I don't agree the penalty for overriding > __getitem__ "has nothing to dow ith change of the constructor" in the context > of deciding whether it would be more desirable to 'enhance' dicts with a new > 'default' option or the syntactic sugar behavior. Still I don't understand your point. Anyway, the access time to DefaultDict objects with Python 2.3b1 is ~40% *faster* than with Python 2.2.0. Michele From dwblas at yahoo.com Mon Jun 9 16:25:48 2003 From: dwblas at yahoo.com (DavidW Blaschke) Date: Mon, 9 Jun 2003 13:25:48 -0700 (PDT) Subject: Error checking in Python Message-ID: <20030609202548.80290.qmail@web21609.mail.yahoo.com> With all due respect to the others who have posted a reply, a very small slowdown is better than having a program abort. You then have to track down the reason, and if this is on a program written some time ago, it may take a while to figure out that someone was passing a string when the function expected an int. Also, it is proper programming etiqiette for a function to ensure that is has the proper type, and when necessary, to do bounds checking as well. That way, you can pass a variable to a function without having to find the source every time, to check and see what kind of a variable it requires. BTW type checking can be done with: if type(1) == type( var ) : type("A") == etc. although, it is easier to simply use: new_ var = int(var) = float(var) = str(var) etc. Always check for "None" or an empty string first, and you have to return some sort of default error indicator if the variable is empty or can not be processed. If you are concerned about slowdowns caused by a loop, then simply code the function with a default that tells it whether it should check. as in: def my_funct( var, check=1 ): if check : ## type and bounds checking on var In general, you should be able to call a function without worrying about any of the consequences. It is the functions job to verify and alter when, and if possible. An old, old saying is to write code that is iron-clad, meaning that it can handle almost anything that is thrown at it. Sissy functions cost much more in the long run. Good question though. It shows that you want to develop good programming habits. D.W. > --- In python-list at yahoogroups.com, BGM > wrote: > > > > Hello all: > > > > I am new to python, coming from a modest C > background. Recently, I > was > > writing some custom module in Python and I was > wondering about one > thing: > > Since the user of the module can pass any argument > they wish, then > it > > seemed like a good idea to check ,say, for type > errors within the > > functions in the module. However, it occurred to > me that if some of > these > > functions are used in in the inner loops of some > program, there > could be a significant > > slow-down. When writing their own modules, what do > the users of the > list > > usually do? Do you leave the responsibility for > type checking to the > user > > of the functions, or do you implement this in the > modules, or some > > combination of these two approaches? > > > > I apologize if there is a simple mechanism that > Python provides that > I > > have perhaps not learned about. (Other than > throwing an exception > during > > runtime) > > > > ------------------- > > BGM. > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From MK at foo.com Fri Jun 27 10:00:40 2003 From: MK at foo.com (MK) Date: Fri, 27 Jun 2003 16:00:40 +0200 Subject: Exposing object model in Python? References: Message-ID: "Steve Holden" wrote > If you can get a look at "Python Programming on Win32" by Mark Hammond and > Andy Robinson that will show you a number of ways to do this, including > writing a COM server in Python and providing Python scripting facilities to > your users. Is COM platform-specific? I believe it is, but I may be wrong. (Anyway I'm sure it's platform specific, no matter what MS says.) If it is platform-specific, then that's not what I need. I'd like to expose my object model on every Python-enabled platform. From bokr at oz.net Thu Jun 5 01:51:57 2003 From: bokr at oz.net (Bengt Richter) Date: 5 Jun 2003 05:51:57 GMT Subject: Including binary files in a .py file; advice needed References: <3EDEB0A6.202@netspace.net.au> Message-ID: On Thu, 05 Jun 2003 12:53:26 +1000, Gary Duncan wrote: > >Here's what I want to do; distribute a .py file (a GUI app) with >an embedded (binary) .GIF file (a photo of me at 1 yo ;) rather than >distribute both separately. For convenience, mainly. > > >If in a Unix shell script, I'd uuencode the .GIF and include the >printable-ASCII file in it as a 'here' file. When executed the script >would 'cat' it out to e.g. a /tmp file from the main body of the script, >then uudecode the /tmp file to revert to the original .GIF file. > >I imagine in Python, one could place the uuencoded file (lines) >as a triple-quoted string, then uudecode it the .py program. > >Anything better ? > I think uuencode can generate triple quotes as data, so I'd try base64. E.g., this should accept a gif file name and generate a python program to stdout that has the gif embedded and which can be executed to extract the gif to a file (you supply name), with optional shell start on it: Not very tested!! ====< mkshowgif >================================================ front = r'''import base64 import os b64gif = """\ ''' back = '''""" def showit(filename, show=False): fgif = file(filename, 'wb') fgif.write(base64.decodestring(b64gif)) fgif.close() if show: os.system('start %s' % filename) # assumes file extension association if __name__=='__main__': import sys args = sys.argv[1:] if args[:1] == ['-show']: show = True; args.pop(0) else: show = False if len(args)!=1: print 'Usage: python %s [-show] gifOutputFile => writes file and' % sys.argv[0] print ' starts it if -show opt' raise SystemExit showit(args[0], show) ''' if __name__== '__main__': import sys, base64 if len(sys.argv) != 2: print 'Usage: python mkshowgif giffile => showgif.py to stdout' raise SystemExit gif = file(sys.argv[1],'rb').read() print front print base64.encodestring(gif) print back ================================================================= I borrowed the python site python gif for a test: [22:51] C:\pywk\clp>python mkshowgif.py pythonHi.gif > showgif.py [22:51] C:\pywk\clp>showgif.py -show showgif.gif This sequence should generate showgif.py (note redirection may require explicit python on some windows platforms, like NT4), and the second command should write showgif.gif and start whatever your windows thinks .gif is associated with. Regards, Bengt Richter From newsgroups.NOSPAM at dfackrell.mailshell.com Thu Jun 5 10:14:58 2003 From: newsgroups.NOSPAM at dfackrell.mailshell.com (Daniel Fackrell) Date: Thu, 5 Jun 2003 08:14:58 -0600 Subject: Changing python process name (or argv[0]) References: <1054739086.3ede0a8ec5f95@mcherm.com> Message-ID: <3edf5063$1_3@hpb10302.boi.hp.com> mike wakerly wrote: > Hi Michael and Skip, > > Thanks for the responses! > > On Wednesday 04 June 2003 08:04 am, Michael Chermside wrote: >> Mike writes: >>> I think the functionality is desirable for some >>> (at least on Unix python), and this simple trick hardly warrants an >>> extra module if it is indeed acceptable in the python world. >> >> Mike, you have it exactly backwards. This simple trick hardly >> warrents inclusion in core Python when it can be implemented >> by an extra module. The fact that it _is_ a simple trick is >> a good reason to keep it as a module. The fact that it might >> not be portable to all operating systems is another good >> reason. Don't be afraid to use modules... that's what they're >> for! > > Aiyee, I was worried about this; it is what my 'acceptable in the > python world' qualifier was for. It may be a simple trick, or it may > be expected functionality (if uncommon). Yes, I am all for using > modules where appropriate; not everybody's hack needs to be part of > python (see Perl..), etc.. I've only just discovered this trick and > couldn't find much discussion on whether or not it is considered a > kludge. > > (An 'Argv_write' module just seemed a bit inelegant to my eyes; > perhaps I underestimate the rarity of its usefulness, but [as in my > original problem], I see few other ways to 'hide python' from > unintelligent interfaces.) > > So, it would seem that rewriting argv[0] is indeed not a necessary > standard feature, since, according to Skip: > >> In addition, the idea was rejected by Guido in the past (I remember >> because I proposed it). I doubt he's changed his mind on the topic >> in the past few years. > > I'll have to do some homework and find that thread; maybe it will > reveal why argv rewriting is good/bad/standard/uncommon. > > Thanks all, > Mike Hrm... maybe I'm just naive on this point, but it seems to me that having python programs show up by name is ps, top, etc. would be a nice benefit, especially where many different python processes might be running simultaneously. I'd even consider that such should be the default. I for one would much rather see ChatServer.py, intermud.py, and python listed by ps (for a chat server, intermud daemon, and interactive python shell, respectively), than python, python, and python. Should this really require finding, downloading, and installing a non-standard module? -- Daniel Fackrell (newsgroups.NOSPAM at dfackrell.mailshell.com) When we attempt the impossible, we can experience true growth. From johnroth at ameritech.net Thu Jun 26 15:34:58 2003 From: johnroth at ameritech.net (John Roth) Date: Thu, 26 Jun 2003 15:34:58 -0400 Subject: Test-Driven Dev. (Kent Beck) Python Chapter Question References: <6e07b825.0306252246.16fa828@posting.google.com> <3EFAF786.76B66629@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3EFAF786.76B66629 at engcorp.com... > "yaipa h." wrote: > > > > In Chapter 20. Cleaning Up After > > > > When adding "tearDown()" to "TestCase" in xUnit, the TestCase method run() > > suddenly takes on a new argument named "result." In the next line result > > is used as "result.testStarted()." Oddly, when TestCase.run() is called by > > "TestCaseTest" it is called without an argument, so of course Python complains. > > If I drop "result" from the argument list and strike the line > > "result.testStarted()" everything works fine. I've looked and > > there seems to be no code download page or errata available. > > > > Anyone had similar problems with this chapter or am I reading over > > something here? > > I think you're right. I looked ahead at page 114 and found what I > think is the first place where run() actually takes a TestResult > object, in a later chapter. > > It looks like this was an early mistake, as it appears even in the first > draft of the book which had this chapter, from March 9 last year. > (See http://groups.yahoo.com/group/testdrivendevelopment/files/ for ref.) I agree, it looks like a misprint. There's nothing in the narrative in Chapter 20 to justify putting in the collecting parameter, while there's a discussion in Chapter 23, including all the changes to the various calls that resulted from adding the parameter. > Yaipa, if you submit this errata report on the testdrivendevelopment > group on Yahoo Groups it would probably be appreciated. > > -Peter John Roth From vze4rx4y at verizon.net Thu Jun 5 13:59:48 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 05 Jun 2003 17:59:48 GMT Subject: Help with dictionary References: <9afd3f36.0306042301.5243a9e8@posting.google.com> Message-ID: [Jim Shady] > I have a dictionary of the sort: > > {(1, (21353, 21418)): 3900, (2, (53006, 53164)): 3800, (0, (19697, > 19763)): 4100} Dictionaries have an arbitrary ordering and so they can't be sorted directly. > I need to re-sort this dictionary with the first element of the tuple > in the keys. A sorted dictionary of the above would be: > > {(0, (19697, 19763)): 4100, (1, (21353, 21418)): 3900, (2, (53006, > 53164)): 3800} Make a copy of the dictionary into a list of items. Then, sort the list: >>> d = {(1, (21353, 21418)): 3900, (2, (53006, 53164)): 3800, (0, (19697, 19763)): 4100} >>> it = d.items() >>> it.sort() >>> it [((0, (19697, 19763)), 4100), ((1, (21353, 21418)), 3900), ((2, (53006, 53164)), 3800)] Raymond Hettinger From webmaster at watchtowerDOTcom.pl Sat Jun 21 23:31:16 2003 From: webmaster at watchtowerDOTcom.pl (=?ISO-8859-2?Q?Jaros=B3aw_Zabie=B3=B3o?=) Date: Sun, 22 Jun 2003 05:31:16 +0200 Subject: mod_python hell in Apache/Windows XP References: <6GTIa.32066$111.24282@news04.bloor.is.net.cable.rogers.com> Message-ID: On Sat, 21 Jun 2003 13:59:21 GMT, "Tim" wrote: >Any advice on the best way to configure for CGI is much appreciated... You must check and add missing lines to your Apache httpd.conf file: LoadModule python_module modules/mod_python.so SetHandler python-program PythonHandler mod_python.cgihandler From guettler at thomas-guettler.de Thu Jun 5 05:12:36 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Thu, 05 Jun 2003 11:12:36 +0200 Subject: How to get the hostname? Message-ID: Hi! Is there a way to get the hostname with python? fd=open("/etc/HOSTNAME") or getting the environment variable $HOST is not nice. thomas From m at moshez.org Sun Jun 1 13:32:29 2003 From: m at moshez.org (Moshe Zadka) Date: 1 Jun 2003 17:32:29 -0000 Subject: medusa http server In-Reply-To: References: , Message-ID: <20030601173229.3640.qmail@green.zadka.com> On 1 Jun 2003, aahz at pythoncraft.com (Aahz) wrote: > >% mktap web --path=/var/www/htdocs --port=80 > >% sudo twisted -f web.tap > > Yes, that's all that's required [about the using-twistedweb.html HOWTO] > That's actually a moderately long document. If you want to emphasize > how quickly a Twisted web server can be deployed, you should create a > separate document called "Fast start: Twisted web server". That would > include a minimal set of install instructions so that people don't need > to read separate pages. Hrm, a good idea. I might actually do that -- "Bringing Up a Twisted Web In Five Minutes" might be a win. > Note that I'm not complaining about the current setup, but you seem to > imply that it ought to be even easier. Yes. I want it to be easy enough that people will say "nah, let's just install Twisted Web" :) -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From dwblas at yahoo.com Thu Jun 5 16:02:13 2003 From: dwblas at yahoo.com (DavidW Blaschke) Date: Thu, 5 Jun 2003 13:02:13 -0700 (PDT) Subject: Iteration through a text file. Message-ID: <20030605200213.90994.qmail@web21603.mail.yahoo.com> You want to write it in a way that you will understand. If you are a newbie then you want to keep it simple. (Nice word newbie, no negative connations, but instead is someone trying to improve). Anyway, I would suggest that you spilt the data up into understandable portions. The following is some code that I think does what you want. It stores all the lines for one server in a list. That list is then processed by a function and the detail is printed. Then, the next server is processed, etc. If you feel more comfortable writing the data for one server to a file and then processing it, do that by all means. Do it in a way that you understand. This could all be done with nested loops, but I donlt think that would work for you. BTW, if at any time I sound like I'm talking down to you please forgive me. It is just the way my own simple mind works. Note the ErrorPrint function. Put that somewhere so you can import it anytime you use try/except. It took a while for me to find out how to do this, so I hope it will save you some grief. If you save this message as a text file, you can delete all of these first comments and run the program as is on a linux system. It will give you an error from ErrorPrint() because it can't find the filename that's on the final line. Then change the filename to whatever yours is and run it again. D.W. #!/usr/bin/python ## Program Name: Print_Stuff.py import sys import string def PrintMain( filename ) : ##----- Read the file try : fp = open( filename, "r" ) data = fp.readlines() fp.close() server_list = [] server_ctr = 0 server_name = "" for eachRec in data : ##--- Eliminate any upper/lower case errors new_rec = string.upper( eachRec ) ##--- Replace newline and end of rec new_rec = string.replace( new_rec, "\n", " " ) new_rec = string.strip( new_rec ) ##--- Note that we only want to find "server" if it is the ## first word, not if it's burried in the text found_server = cmp( new_rec[:7], "SERVER," ) if 0 == found_server : ##--- don't process if this is the first server found if server_ctr : Process_Server( server_name, server_list ) server_ctr += 1 substrs = string.split( new_rec ) server_name = substrs[1] server_list = [] ## blank the list else : server_list.append( new_rec ) ##--- Process the final batch of recs Process_Server( server_name, server_list ) except : print "Could NOT open filename %s" % (filename) ErrorPrint() ## END PrintMain() ##===================================================================== ## Process the recs associated with a server ##===================================================================== def Process_Server( server_name, rec_list ) : ##--- Now, look for system availability ##--- I like to use a field with the look-for sting in it, ## that way it can be easily changed look_for = "SYSTEM AVAILABILITY" len_lf = len(look_for) found = 0 print "\n----> for server %s" % (server_name) for eachRec in rec_list : found_server = cmp( eachRec[:len_lf], look_for ) if 0 == found_server: found = 1 ##--- just print it - you can massage it any way you like substrs = string.split( eachRec ) len_subs = len(substrs) ##--- don't print substrs[0] = "Server" or ## substrs[1] = "Availability" for j in range( 2, len_subs ) : print " %s" % (substrs[j]) print ##--- No "System Availability" found if not found : print " N/A - None\n" ## END Process_Server() ##===================================================================== ## print details of try / except errors ##===================================================================== def ErrorPrint( ) : import Tkinter import traceback et, ev, tb = sys.exc_info() while tb : co = tb.tb_frame.f_code filename = "Filename = " + str(co.co_filename) line_no = "Error Line # = " + str(traceback.tb_lineno(tb)) print filename print line_no tb = tb.tb_next print "et = ", print et print "ev = ", print ev ## END ErrorPrint() #===================================================================== if __name__ == "__main__" : filename = "print_stuff.txt" PrintMain( filename ) __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From staschuk at telusplanet.net Mon Jun 9 19:11:39 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 9 Jun 2003 17:11:39 -0600 Subject: PEP 317: Eliminate Implicit Exception Instantiation In-Reply-To: ; from ed@membled.com on Mon, Jun 09, 2003 at 10:16:26PM +0100 References: Message-ID: <20030609171139.B2699@tibia.amotlpaa.bogus> Quoth Ed Avis: > Steven Taschuk writes: > > > raise_stmt ::= "raise" [expression ["," expression]] > > Why not go further and make it look like a normal function call, that > can take zero one or two arguments? > > raise_stmt ::= "raise" "(" [expression ["," expression]] ")" Two reasons: First, it would increase the backwards incompatibility, which is already quite large. Under such a change, *all* raise statements would need to be revised; under the change proposed, those who have been using the One True Syntax for raising exceptions (i.e., instantiating explicitly) are exempt. Second, I don't object to raise being a statement; in particular, I don't think its being a statement makes any code less clear. Implicit exception instantiation, however, I do believe to be significantly less clear than explicit instantiation. (I also don't have any particular wish to use raise in lambdas. I have followed the timbot's alleged injunction to learn to love the return key.) -- 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 tom1 at launchbird.com Mon Jun 2 19:05:36 2003 From: tom1 at launchbird.com (Tom Hawkins) Date: 2 Jun 2003 16:05:36 -0700 Subject: ANN: Confluence -> Python for Hardware Verification Message-ID: <833030c0.0306021505.43d5cdf6@posting.google.com> Over the weekend we released Confluence 0.4.6: the first version to included the new Python model generator. Confluence is a functional programming language for hardware and logic design. Though its syntax is much simpler than either Verilog or VHDL, it's semantics enables a level of design flexibility beyond the reach of either HDL. Til now, Confluence compiled into Verilog and VHDL for logic synthesis and cycle-accurate C for high-speed simulation and hardware-software co-development. With the addition of the Python model generator, hardware designers can now use the high-level constructs of our favorite language (Python!) to perform functional verification. We were very surprised by Python's simulation performance; Python simulation of our benchmarks was right on par with HDL event-based simulators. Not bad for a "scripting" language! For more info on Confluence: http://www.launchbird.com/ To see Confluence output, including generated Python models visit any of the Confluence projects at: http://www.opencores.org/ Regards, Tom -- Tom Hawkins Launchbird Design Systems, Inc. 952-200-3790 tom1 at launchbird.com http://www.launchbird.com/ From uche at ogbuji.net Mon Jun 9 09:31:35 2003 From: uche at ogbuji.net (Uche Ogbuji) Date: 9 Jun 2003 06:31:35 -0700 Subject: looking for a simple XML api for python References: <3H9za.47086$h42.8645@twister.nyc.rr.com> Message-ID: Van Gale wrote in message news:... > There are at least two other choices: > > ElementTree: http://effbot.org/zone/element-index.htm > > cDomlette: http://4suite.org/index.xhtml > > I believe the 4Suite XPath module works with cDomlette. Yep. http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/domlettes http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/basic-xpath http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/basic-xslt BTW, ElementTree is very nice, and the latest, 1.2alpha1 mentions limited XPath support. --Uche http://uche.ogbuji.net From sholden at holdenweb.com Fri Jun 27 09:15:20 2003 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 27 Jun 2003 13:15:20 GMT Subject: Exposing object model in Python? References: Message-ID: "MK" wrote in message news:bdgvk5$sid7t$1 at ID-174077.news.dfncis.de...> > [...] > > Thanks for your input. Apologies for not being clear enough. > > I'm writing a classical desktop application, using wxPython > and some other libraries. I'm interested to expose its > object model a la Microsoft's VBA. That is, I want to allow > my users to tinker with the app, i.e. write their own macros > in Python in a miniature IDE, within the app. I'd also like to ship > the program as a standalone app, using py2exe. > If you can get a look at "Python Programming on Win32" by Mark Hammond and Andy Robinson that will show you a number of ways to do this, including writing a COM server in Python and providing Python scripting facilities to your users. Unfortunately the techniques used are a little too complicated to describe in a newsgroup posting. with-apologies-to-pierre-de-fermat-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From guy.flowers at Machineworks.com Tue Jun 10 09:27:22 2003 From: guy.flowers at Machineworks.com (Guy) Date: 10 Jun 2003 06:27:22 -0700 Subject: Building Python Message-ID: Hi I'm trying to build python on a sparc "Sun Microsystems Inc. SunOS 5.5.1". I have already built python-2.2.2 on another machine which seems to work well. I've tried both python-2.2.2 and python-2.2.3 on the sparc both come up with the same error. Which can be seen below. In file included from Python/thread_pthread.h:9, from Python/thread.c:113: /usr/include/pthread.h:238: parse error before `destructor' /usr/include/pthread.h:238: parse error before `)' make: *** [Python/thread.o] Error 1 Can any one make any suggestions about a fix. TIA Guy From bokr at oz.net Sun Jun 15 18:18:46 2003 From: bokr at oz.net (Bengt Richter) Date: 15 Jun 2003 22:18:46 GMT Subject: raw strings under windows References: Message-ID: On Sun, 15 Jun 2003 08:12:35 GMT, Alex Martelli wrote: > > >Cecil H. Whitley wrote: > >> Hi, >> When doing the following: >> >> #!/usr/bin/env python >> >> path = r"c:\python23\" >> >> I get a syntax error, unexpected EOL with singlequoted string. It was my >> (mis?) understanding that raw strings did not process escaped characters? > >They don't, in that the backslash remains in the string resulting from >the raw literal, BUT so does the character right after the backslash, That seems like a contradiction to me. I.e., the logic that says to include "...the character right after the backslash, unconditionally." must be noticing (processing) backslashes. >unconditionally. As a result, a raw string literal cannot end with an >odd number of backslashes. If they did otherwise, it would instead be >impossible to include a single quote character in a single-quoted raw So? Those cases would be 99.99% easy to get around with alternative quotes, especially considering that """ and ''' are alternative quotes. >string literal, etc. Raw string literals are designed mainly to ease >the task of entering regular expressions, and for that purpose an odd >number of ending backslashes is never needed, while making inclusion of >quote characters harder _would_ be an issue, so the design choice was >easy to make. ISTM only inclusion of same-as-initial quote characters at the end would be a problem. Otherwise UIAM triple quotes take care of all but sequences with embedded triple quotes, which are pretty unusual, and pretty easy to spell alternatively (e.g. in tokenizer-concatenated pieces, with adjacent string literals separated by optional whitespace). Was the design choice made before triple quotes? Otherwise what is the use case that would cause real difficulty? Of course, now there is a backwards-compatibility constraint, so that r"""xxxx\"""" must mean r'xxxx\"' and not induce a syntax error. > >Of course people who use raw string literals to represent DOS paths might >wish otherwise, but as has been pointed out it's not a big problem in >any case -- not only, as you note: > >> Of course >> path = "c:\\python23\\" >> >> works just fine. I wouldn't mind a raw-string format that really did treat backslashes as ordinary characters. Perhaps upper case R could introduce that. E.g., path = R"c:\python23\" > >but so, almost invariably, does 'c:/python23/' (Microsoft's C runtime >libraries accept / interchangeably with \ as part of file path syntax, >and Python relies on the C runtime libraries and so does likewise). > Another alternative would be a chosen-delimiter raw format, e.g., path = d'|c:\python23\| or path = d'$c:\python23\$ I.e., the first character after d' is the chosen delimiter. Even matching-brackets delimiting could be possible d'[c:\python23\] == d' == d'{c:\python23\} by recognizing [, <, or { delimiters specially. Space as a delimiter would be iffy practice. BTW, I think I would have preferred a chosen-delimiter form with alternate raw and normal designators over triple quoting. If upper case meant raw, D'' or D"" would have been equivalent to most current uses of r' and r" and there would be more flexibility. The d' normal format would treat \ as non-magic in front of the chosen delimiter, and otherwise recognizing standard control character spellings as now. While I'm at it (;-) and last but not least, to be able to paste arbitrary text into a string literal, some other delimiting method is needed. A number exist for other text contexts (e.g., perl sources, MIME format, etc.) so I guess it's a matter of whether the itch is sufficient. Apparently not yet ;-) BTW, has anyone heard of a terminating delimiter in the form of an escape-introduced hash of the preceding text in hex? It would mean computing a running hash for such a string and checking every time a hash-escape was encountered to see if the next characters were a matching hex hash. In a lot of cases the "hash" could probably just be the byte count, but in the extreme an md5 hash could be used. Twice if you want to get weird and hash the first hash to check two successive hashes. That should let you delimit pretty much any unmodified arbitrary text ;-) enough ... ;-) Regards, Bengt Richter From jjl at pobox.com Thu Jun 19 08:29:23 2003 From: jjl at pobox.com (John J. Lee) Date: 19 Jun 2003 13:29:23 +0100 Subject: ftplib question References: <3ef19a1c$1@news.012.net.il> Message-ID: <87isr2qmho.fsf@pobox.com> "Avner Ben" writes: > How do I find the year of a remote file in ftplib? > > retrlines('LIST') seems to include only month day and hour. Forgot to say: if the year is equal to the current year, the time is shown, with no year. Otherwise, the year is shown, with no time. John From stevesusenet at yahoo.com Thu Jun 19 11:20:28 2003 From: stevesusenet at yahoo.com (Steve) Date: 19 Jun 2003 08:20:28 -0700 Subject: Is python good for making database work short? References: <6f8cb8c9.0306181727.9c86095@posting.google.com> Message-ID: <6f8cb8c9.0306190720.13833b52@posting.google.com> Paul McNett

wrote > I as the developer need to use a common dialect of SQL that will work wit > h > whatever backend the user chooses, whether it is Oracle, MSSQL, MySQL, > Gadfly, or whatever. > Thoughts on this? I used INTRODUCTION TO SQL 3RD EDITION by Rick van der Lans ISBN 0-201-59618-0 to learn SQL. Don't let the "INTRODUCTION" fool you, the book is very short and very thorough. Anyway, the book explicitly states it only teahes SQL you can use anywhere. Steve From gh at ghaering.de Mon Jun 16 10:15:46 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 16 Jun 2003 16:15:46 +0200 Subject: does lack of type declarations make Python unsafe? In-Reply-To: <3EEDD203.54F5672B@engcorp.com> References: <3064b51d.0306151228.22c595e0@posting.google.com> <3EECED65.ACF1A6B7@engcorp.com> <3EEDDA04.8000005@netspace.net.au> <3EEDD203.54F5672B@engcorp.com> Message-ID: <3EEDD112.7060702@ghaering.de> Peter Hansen wrote: > To take up Alex' point: passing in the wrong type is probably much > less common than, say, using the wrong value, or mixing up the order > of arguments (and many functions take a bunch of arguments of the > same type, so type-checking doesn't help there!). There is something that helps with confusing the order of arguments: *Only* use named parameters. I've heard of Ada 95 projects that mandate this style for procedure/function calls. -- Gerhard From hwlgw at hotmail.com Sun Jun 22 08:30:19 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 22 Jun 2003 05:30:19 -0700 Subject: python applets inside anyone? Message-ID: The following is from the W3C HTML4.0 specification, but I could not get it to work anyhow (using "myscript.py" containing "print '

12:00

'" instead of the URI in the example). Can you? Why is this "python applet" example there in the HTML 4 spec, is there any browser supporting it (my IE6 doesn't even give the "An animated clock" message or another error message). They should not put Python applet examples in specifications that don't work, this makes Python look bad! HTML 4.0 Sect. 13.3.1 "Rules for rendering objects:" -------------------------------------------------------------- In the following example, we insert an analog clock applet in a document via the OBJECT element. The applet, written in the Python language, requires no additional data or run-time values. The classid attribute specifies the location of the applet:

An animated clock. -------------------------------------------------------------- From darrenteo82 at yahoo.com Tue Jun 17 03:34:15 2003 From: darrenteo82 at yahoo.com (Darren Teo) Date: Tue, 17 Jun 2003 00:34:15 -0700 (PDT) Subject: (no subject) Message-ID: <20030617073415.6384.qmail@web40408.mail.yahoo.com> --------------------------------- Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alanmk at hotmail.com Wed Jun 4 06:04:35 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 04 Jun 2003 11:04:35 +0100 Subject: Help with coroutine-based state machines? References: <3ED622CA.4B01E3C1@hotmail.com> <3ED76105.CB8F3ECF@hotmail.com> <3EDC69DF.A46A97D4@hotmail.com> <3EDD05FA.CDE86800@hotmail.com> Message-ID: <3EDDC433.133B8F11@hotmail.com> Terry Reedy wrote: > After reading your response to my response to your essay, I think we > can combine ideas and converge on the following essentials, with > implementation details left out: [ Excellent model for generators and coroutines elided ] Thanks, Terry, for that excellent summary. I'm really glad that you raised the problems with my original essay, because now I have a much clearer picture of what is happening. Or rather, my picture is almost the same, but my terminology when describing it and using it will be *much* cleaner. This kind of collaborative model development is, to my mind, what Usenet is great for. When I first approached the generators and coroutines concepts, I really needed to find a discussion similar to the one we've just had, to help me clarify my thoughts. And now, thanks to the magic of Usenet archives like Google Groups, etc, our model is preserved for all to see and use. Thanks, Terry, it's been fun :-) And of course, thanks to all the other contributors to this thread. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From a at b.c Wed Jun 4 09:41:24 2003 From: a at b.c (SFBayling) Date: Wed, 4 Jun 2003 13:41:24 +0000 (UTC) Subject: converting decimal to binary References: Message-ID: "Tim Peters" wrote in news:mailman.1053741576.26298.python-list at python.org: > [Michael P. Soulier] >>> I'm trying to find a simple way to convert a decimal number to a >>> binary string representation. I could do this the hard way, but as >>> it's a one-liner in perl, I'm hoping there's an easy way to do this >>> in python. > OTOH, there's curious asymmetry here: > >>>> int('00011000000', 2) > 192 >>>> > > That is, "the other direction" is built in. I was hoping there would be something to continue the existing patterns like; hex(value) oct(value) bin(value) or perhaps print "%d" % value #Decimal print "%x" % value #Hex print "%o" % value #Octal print "%b" % value #Binary I ended up finding the baseconvert module in the CookBook as well and changing it to default to decimal->binary. def baseconvert(number, fromdigits=BASE10, todigits=BASE2): newsgroup-post-testingly yours, sfb. --- (First time back in newsgroups in a while, I can only hope this works properly). From peter at engcorp.com Sat Jun 21 23:16:25 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 21 Jun 2003 23:16:25 -0400 Subject: random function with strings References: <3ef51a51$0$8029$79c14f64@nan-newsreader-01.noos.net> Message-ID: <3EF51F89.22D7E78E@engcorp.com> ataraxia2500 wrote: > > I have a function that goes through a directory and I would like to remove > randomly one of the files contained in that directory. I checked out the > random() function in the documentation but it only deals with integers. Use random.choice() instead. From anton at vredegoor.doge.nl Fri Jun 13 07:41:54 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 13 Jun 2003 13:41:54 +0200 Subject: Bug in v1.5.2 Websucker GUI? References: <7isqqi$8ki@vern.bga.com> Message-ID: "Andrew Dalke" wrote: >I posted your bug report using my login. Thanks, it seems to be registered with "[ 753592 ] websucker bug". Also thanks to you and other posters for their valuable comments. Of course, now that I've posted about it here, there's no visible malfunction in sourceforges page any more. Anton From tim.one at comcast.net Thu Jun 12 21:20:13 2003 From: tim.one at comcast.net (Tim Peters) Date: Thu, 12 Jun 2003 21:20:13 -0400 Subject: Use __del__ methods to improve gc? In-Reply-To: Message-ID: [Edward K. Ream] > My app has unlimited undo. As a result, most "user" data never truly > gets deleted: the undo stack keeps references to all such data alive > "forever". > > I am wondering whether it would be a good idea to put dummy __del__ > methods in the user data classes. Would this help the gc by telling > the gc what not to look at? As others have explained, no, gc scans everything when it's time for it to get scanned . An interesting question may be why you suspect gc *needs* help. For example, is gc taking a lot of time in your app? From sismex01 at hebmex.com Mon Jun 9 12:11:08 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 9 Jun 2003 11:11:08 -0500 Subject: simple, old-style graphic ? Message-ID: > From: Alessandro de Manzano [mailto:demanzano at playstos.com] > Sent: Monday, June 09, 2003 11:07 AM > > Hello, > > I'ld need a little suggestion :-) > > For educational purposes I'ld find a Python module (Windows > platform) to draw simple 2D graphic (even 3D if possible, > but is not a requirement). Like very old Basics, so lines, > points, circles, rectangles, colors, simple text strings, etc. > You can use Tkinter.Canvas, it does this, and plenty more. > > As last resort I thought about some OpenGL module but I would > really prefer something easier and simpler. > Planning on killing any ants with an H bomb this week? :-) > > Have you some idea ? > Tkinter.Canvas is good for you. > > I accept any hints and suggestions :) > Hmmm... Tkinter.Canvas *wink* *wink* *nudge* *nudge* saynomore saynomore. > > Many thanks in advance! > -gca Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From grante at visi.com Fri Jun 13 15:18:15 2003 From: grante at visi.com (Grant Edwards) Date: 13 Jun 2003 19:18:15 GMT Subject: Octets calculation? References: <65eFa.634621$Si4.577158@rwcrnsc51.ops.asp.att.net> <3EE79F73.E08C2554@alcyone.com> <3ee88ede$0$645$a1866201@newsreader.visi.com> Message-ID: <3eea2377$0$1394$a1866201@newsreader.visi.com> In article , Greg Ewing (using news.cis.dfn.de) wrote: > >> It's not rare in the DSP world. TI's line of FP DSPs all had >> 32-bit bytes. Where "byte" is used in the sense of the "C" >> standard as the smallest unite of addressable memory. > > I thought the C standard used the word "char" for that, not > "byte". Both. In the C standard "char" and byte "byte" are equivalent. Using "byte" is more confusing, and if I had written it I would have stuck with "char". But they didn't ask me... ;) > If DSP people really use the word "byte" that way, they're > utterly barking, IMO. It's just too confusing for words. (Or > should I say octet-groups?-) They generally only use it that way when they're dealing with the C standard, and I, for one, do prefer "char". -- Grant Edwards grante Yow! How's it going in at those MODULAR LOVE UNITS?? visi.com From staschuk at telusplanet.net Fri Jun 13 21:24:07 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Fri, 13 Jun 2003 19:24:07 -0600 Subject: Type hierarchy In-Reply-To: <200306132243.45270.zathras@thwackety.com>; from zathras@thwackety.com on Fri, Jun 13, 2003 at 10:43:45PM +0100 References: <200306132243.45270.zathras@thwackety.com> Message-ID: <20030613192407.C2309@tibia.amotlpaa.bogus> Quoth Michael Sparks: [...] > It strikes me that OP wants to be able to get at things in the middle of his > type hierarchy: > isinstance(o,numeric)) > isinstance(p,mutable) > isinstance(q,collection) For numeric and collection, I think this would not be useful. (More on 'mutable' below.) There might be a little bit of shared functionality among such types, but not much. (Certainly int and float would not share an implementation of __mul__, for example.) The only other reason I can think of to do isinstance checks is LBYL. But then why not just check for the existence of __add__ or __getitem__ or whatever it is you need? Inheritance should be for sharing implementation, not interface. It's different for mutable, of course, since there's no signature which will distinguish mutable from immutable (or "amutable", if I may coin a term, meaning "I provide no mutation facilities but do not prevent subclasses from doing so"). I can think of cases in which it would be helpful to know whether an object was mutable -- e.g. copy.deepcopy might be able to optimize if it could tell that a user-defined object was immutable -- but I'm not sure a marker interface (to borrow the Java term) is the way to go. [...] -- 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 skip at pobox.com Tue Jun 24 20:31:36 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 24 Jun 2003 19:31:36 -0500 Subject: OFF TOPIC: What did Guido say? In-Reply-To: <20030625002727.20904.qmail@web11402.mail.yahoo.com> References: <20030625002727.20904.qmail@web11402.mail.yahoo.com> Message-ID: <16120.60776.955362.605668@montanaro.dyndns.org> Carlos> So, what did Guido say in: Carlos> http://www.python.org/~guido/guido.au Carlos> I hear this a thousand times, every day (my co-workers want to Carlos> kill me :) ), and still can't undertand Guido's words. I Carlos> especially pay attention to the funny noise in the end. I seems he's saying something about making the sound of Woody Woodpecker (then makes like Woody), but it sounds like Dutch to me. Skip From op73418 at mail.telepac.pt Wed Jun 18 10:03:05 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 18 Jun 2003 15:03:05 +0100 Subject: How to recognize a generator function? References: Message-ID: On Wed, 18 Jun 2003 03:21:35 -0700, Oscar Rambla wrote: > >Hi, > >I'm not been able to find a solution to the following: > >How to recognize if a function is a generator function before calling it? >(Alternatives to having to inspect code for a yield or wrapping it into a >class). > >Note: I refer to the function, not to the generator itself. > >Thank you in advance. > >-Oscar Let us see... >>> from __future__ import generators >>> def testfunc(): ... return None ... >>> testfunc >>> def testfunc(): ... yield None ... >>> testfunc >>> Hmm, it seems that short of analyzing the source code you cannot... And then again, why are you interested in such a difference? Seems like the typical YAGNI. Hoping-to-be-corrected-ly-yours, G. Rodrigues From nskhcarlso at bellsouth.net Mon Jun 9 16:42:02 2003 From: nskhcarlso at bellsouth.net (Kevin Carlson) Date: Mon, 09 Jun 2003 16:42:02 -0400 Subject: using urllib or httplib to post with ENCTYPE=mulitpart/form-data In-Reply-To: <87of176mhz.fsf@pobox.com> References: <87he751jla.fsf@pobox.com> <87of1cs8jq.fsf@pobox.com> <87of176mhz.fsf@pobox.com> Message-ID: <376Fa.49926$SN1.18232@fe02.atl2.webusenet.com> John J. Lee wrote: > Kevin Carlson writes: > [...] > > No reason why not, but IMHO perverse. :-) > I agree, it is easier to use urllib, but in this case I have to post data in multipart/form-data which means MIME. I can build the proper request and send it using httplib, but haven't been able to figure out how to do this with urllib. If I create the MIME data as 'data', and them post the request using urllib.request(URL, data), it doesn't seem to post the form correctly. If I do the same with httplib it works fine. Am I missing something? Thanks for the help! From ab528 at freenet.carleton.ca Tue Jun 10 04:47:27 2003 From: ab528 at freenet.carleton.ca (Heinz Wiggeshoff) Date: Tue, 10 Jun 2003 04:47:27 -0400 Subject: PLease help with my web site References: Message-ID: wrote in message news:bV8Fa.9753$ly.3447270 at news4.srv.hcvlny.cv.net... > Please help me with my web site www.ratepcmods.com and go there MORONIC SPAMMER From gh at ghaering.de Tue Jun 3 19:03:56 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 04 Jun 2003 01:03:56 +0200 Subject: smtplib and SSL In-Reply-To: References: Message-ID: <3EDD295C.40500@ghaering.de> Michael Prager wrote: > I have looked through Google groups and am not sure if this > question has been answered before (by "Windows Python does not > yet include SSL support.") [...] Install my _socket.pyd binary for Python 2.2.x http://pypgsql.sourceforge.net/misc/python-ssl.html to get SSL support on Windows. -- Gerhard From a.schmolck at gmx.net Fri Jun 6 18:56:52 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 06 Jun 2003 23:56:52 +0100 Subject: Numeric don't compare arrays correctly References: <3EDFBACD.2090802@wanadoo.es> Message-ID: "Mike C. Fletcher" writes: > Alexander Schmolck wrote: > ... > > >``3 < 1 < 4`` (False in python, True in most other languages where it isn't a > >syntax error) > > > OMG! That's horrific! It actually took me 3 or 4 seconds to even come up > with a rationale for why it would be considered true when it so obviously is > trying to say something false. Well, it is only obvious because you (and I) are already used to a rather hackish notation. > Hopefully all those languages with these semantics issue a strong warning > during compilation (1/5 ;) ) that this statement does nothing useful and > should never be used in anything save obfuscated code contests :) . Nope: #include int main() { printf("Is 1 < 1 < 1 true? %d\n", 1 < 1 < 1); return 0; } > gcc -Wall /tmp/ex.c > a.out Is the 1 < 1 < 1 true? 1 > Every once in a while I thank Guido for God's common sense (or vice versa). I tend to agree, but in this case I'm not so sure. After all pythons conformance with the expected "common sense" behavior breaks down nastily for rich comparisons. 'as From pajer at iname.com Mon Jun 9 11:55:06 2003 From: pajer at iname.com (Gary Pajer) Date: Mon, 9 Jun 2003 11:55:06 -0400 Subject: Newbie Question re Python 2.2.2 WIN References: Message-ID: "Ben Minton" wrote in message > thanks sfb ... i thought that might be the case, but wasn't sure. > at the python shell .... with the >>> what is the command to bring run an > python script, say my_first_script.py? I remember being exactly where you are. The intro docs somehow miss this topic. Try this: start the python interpreter from the directory where my_first_script.py lives. Then at the >>> prompt, import my_first_script (without the ".py") See if that does what you want. From staschuk at telusplanet.net Thu Jun 19 15:56:05 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 19 Jun 2003 13:56:05 -0600 Subject: WTF is Fibonnacci In-Reply-To: <7inIa.55233$Io.5225846@newsread2.prod.itd.earthlink.net>; from ss3canon@earthlink.net on Thu, Jun 19, 2003 at 06:29:23PM +0000 References: <7inIa.55233$Io.5225846@newsread2.prod.itd.earthlink.net> Message-ID: <20030619135605.A28346@tibia.amotlpaa.bogus> Quoth Mike: > I'm readin through the Non-Programers Tutorial for Python and I'm on the > examples of section Count to 10. And I can't figure out how the example got > the output, can anyone help break it down for me? I assume you're reading and that you're referring to the Fibonacci sequence example further down the page. Rather than trying to explain that example, let me first ask: are you happy with that page's earlier examples of while loops? If not, what's the first one you're having trouble with? -- Steven Taschuk staschuk at telusplanet.net "I tried to be pleasant and accommodating, but my head began to hurt from his banality." -- _Seven_ (1996) From mcherm at mcherm.com Fri Jun 6 09:24:33 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Fri, 6 Jun 2003 06:24:33 -0700 Subject: a = b = 1 just syntactic sugar? Message-ID: <1054905873.3ee09611900c6@mcherm.com> > >Lambda expressions are syntactic sugar that allow the embedding of > >what would otherwise be a def statement within some other statement > > Not quite, of course, since not everything that can appear in a def > statement can appear in a lambda. No, Terry means precisely what he said. Lambdas can do a SUBSET of what def can do. Specifically, they can't provide a name for the function, and they can't include statements. > [lambda 'designed for side-effect free expressions'] > > >>I would accept this argument, except for the four examples I > >>mentioned above. They are all things which have side effects, and > >>which are not excluded from appearing in lambda expressions. > > > >So what? Many syntactic constructs can be used for more than > >intended or thought about by the designer. > > The point is that the supposed justification for lambda's restrictions > - that it is supposed not to have side effects - bears no relation to > how it really behaves. The extra complexity introduced by having an > arbitrary and semantically meaningless (IMHO) set of rules about what > can be used in lambda and what can't doesn't seem worthwhile. Again, the argument is from the other direction. *IF* you only wanted lambda for side-effect-free functions, then you would have little need (with one exception mentioned below) for statements. The fact that some expressions ALSO have side effects is irrelevent. And that's not the REAL motivation for allowing only expressions... the REAL motivation is the fact that Python makes a clear distinction between statements and expressions. Many statements have places where arbitrary expressions can occur, and Python allows expressions to contain other (arbitrarily complex) expressions, but does NOT have a concept of expressions containing statements. So lambdas (which are expressions) can't contain statements. There isn't even a clean way in which it could be done... unlike (for instance) C and Java where statements are delimited by ";", statements in Python are delimited by whitespace and bracket-balancing. > Why then not allow the same things inside lambda as inside def? At > least as far as keeping the function body on a single line. (1) Because expressions don't contain statements, and there's no obvious (and readable) syntactic way to change that. (2) Because it isn't needed (if you use lambda for simple side-effect-free functions). (3) Because Guido considers "def" *BETTER* than lambda (because it forces the user to come up with a name, and it's multi-line layout is more readable). So he wants to encourage "def" whenever the task being done is even remotely complicated. > >Extending lambda to embed even simple statements within expressions > >is problematical: > > lambda x: assert(x > 0) > lambda x: print 'value:', x > lambda x: y += x # (without any change to scoping rules) > Actually, ONE of those is convincing to me. Even a side-effect-free expression ought to be able to raise exceptions, and "raise" (and also its special-case sibling "assert") is a statement. But if the function is simple enough, then this won't be an issue. If it is really needed, it's trivial to define a function "assert_()" which does what is needed. And if that's too complex, you can fall back on "def". > all things you might reasonably want to use as lambda expressions (for > example an assertion that 'every number in this list is positive'). > > Then again, I am not a Python developer. Perhaps there is some > syntactic ambiguity that would stop the above examples being > parsable. But it seems unlikely, one of the big advantages of Python > is is clean grammar (currently marred only by the strange rules about > lambda-expressions, IMHO). Actually, I think you're missing a fundamental point about the grammer. Unlike many other languages, Python makes a very fundamental distinction between STATEMENTS and EXPRESSIONS. There are a small number of clearly specified statements defined in the Python grammer, each is delimited by whitespace (and bracket-balancing), and there are no rules for making NEW kinds of statements. Expressions are defined recursively (nearly all kinds of expressions can contain other arbitrary expressions) and thus very complicated structures can be built up within an expression. But the distinction is maintained throughout the language... it is not a "strange rule". Hope this helps you make sense of it... -- Michael Chermside From peter at engcorp.com Mon Jun 16 10:19:47 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 16 Jun 2003 10:19:47 -0400 Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> <3EECED65.ACF1A6B7@engcorp.com> <3EEDDA04.8000005@netspace.net.au> Message-ID: <3EEDD203.54F5672B@engcorp.com> Gary Duncan wrote: > > Alex Martelli wrote: > > >>>Calling functions with invalid arguments is one of the commonest > >>>programming errors > >> > >>Debatable. Not true in my experience. (To clarify, in the face of trimmed attributions: I, not Alex, wrote the last sentence above.) > I suspect this assertion relates to juxtaposing args, not so > much the values thereof. Obviously passing bad values to a function > is a crime we have all committed - at least it's one I admit to ;) If we consider that bugs come from either bad data or bad logic, and that bad logic will very likely or inevitably lead to bad data, and that all data eventually is used as an "argument" in some fashion, I'll agree that calling functions with invalid arguments is quite common. :-) To take up Alex' point: passing in the wrong type is probably much less common than, say, using the wrong value, or mixing up the order of arguments (and many functions take a bunch of arguments of the same type, so type-checking doesn't help there!). -Peter From jjl at pobox.com Fri Jun 20 08:11:57 2003 From: jjl at pobox.com (John J. Lee) Date: 20 Jun 2003 13:11:57 +0100 Subject: include files? References: <3ef1c90f$0$49114$e4fe514c@news.xs4all.nl> <3ef2d8fc$0$49114$e4fe514c@news.xs4all.nl> <3ef2f22f$0$49107$e4fe514c@news.xs4all.nl> Message-ID: <87k7bh54oi.fsf@pobox.com> "rgndrp" writes: > Thomas G?ttler wrote: [...] > > Does this help you? > > > > main.py: > > include variables > > if variables.myvar==5: > > print "OK" > > > > variables.py: > > myvar=5 [...] > it would if i'd get it to work :) > now it returns this cgi error: [...] > include applic.py [...] 1. Thomas meant to say 'import', not include. 2. You don't want the '.py' in the import statement. Two files, main.py and variables.py: # -------------START main.py:---------------- import variables if variables.myvar==5: print "OK" # -------------END main.py:---------------- # -------------START variables.py:---------------- myvar=5 # -------------END variables.py---------------- No, you don't need the comments, they're just there to show you where the files begin and end. :-) John From a.schmolck at gmx.net Thu Jun 12 12:02:15 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 12 Jun 2003 17:02:15 +0100 Subject: vector subscripts in Python? References: <3064b51d.0306111512.7701dbbc@posting.google.com> Message-ID: beliavsky at aol.com writes: > Does Python have the equivalent of "vector subscripts" of Fortran 95? > The code below illustrates what I am looking for -- with better syntax. > > def subscript(xx,ii): > # return the elements in xx subscripted by ii > y = [] > for i in ii: y.append(xx[i]) > return y > > ii = [0,2] > xx = [1,4,9] > print subscript(xx,ii) # returns [1, 9]; in F95, "print*,xx(ii)" is > analogous As already pointed out, a list comprehension will do what you want, but since I find this behavior useful quite often I think wrapping it up in a function is worthwhile (note that it allows works for dicts and other iterables). def at(iterable, indices): return [iterable[i] for i in indices] In [5]: at(xx, ii) Out[5]: [1, 9] In [6]: at({'a':1, 'b':2}, ['a','b']) Out[6]: [1, 2] 'as From delphiro at zonnet.nl Fri Jun 20 07:12:37 2003 From: delphiro at zonnet.nl (delphiro) Date: Fri, 20 Jun 2003 13:12:37 +0200 Subject: freeing objects In-Reply-To: <3EF2D852.2050101@irst.itc.it> References: <3EF2D852.2050101@irst.itc.it> Message-ID: <20030620131237.28d838f0.delphiro@zonnet.nl> Hi everyone, I am writing an application where I use Chaco for the excellent graphical output and now I have a question about creating / freeing objects. I use this code to create and assign a chaco-object (a 'vertical') to my dialog: self.plotitem = PlotCanvas( pv1, PlotTitle( 'Soilstress in vertical ..' ), plot_type = 'rangebar', axis_index = x_ax, axis = y_ax ) now the user has the possibility to change the view to another 'vertical' so self.plotitem should be assigned to another PlotCanvas and the old one should disappear. What is the correct way to do this? should I 'free' self.plotitem before assigning a new PlotCanvas to self.plotitem and if so, how do you 'free' objects in Python? Thanks in advance, Rob From mis6 at pitt.edu Fri Jun 6 11:00:21 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 6 Jun 2003 08:00:21 -0700 Subject: Using metaclasses to make super more beatiful References: Message-ID: <2259b0e2.0306060700.428f9c97@posting.google.com> Gerrit Holl wrote in message news:... You may want to google for the thread "help on autosuper" date February 3, 2003. At the time I found that the autosuper metaclass was conflicting with pydoc: # try this under Python 2.2 class autosuper(type): #Guido's metaclass def __init__(cls, name, bases, dic): super(autosuper, cls).__init__(name, bases, dic) setattr(cls,"_%s__super" % name, super(cls)) class C(object): #a simple class __metaclass__=autosuper help(C) # error because super objects have not __name__ For this reason I abandoned the autosuper approach. However, I have checked today with Python 2.3 and now it works! The reason is that now private attributes are no more retrieved by pydoc, therefore the inconsistency is hidden under the hood. However, it is still there and if you do # try this under Python 2.2-2.3 class C(object): pass C.sup=super(C) help(C) you will get Traceback (most recent call last): File "pro.py", line 15, in ? help(C) File "/usr/local/lib/python2.3/site.py", line 293, in __call__ return pydoc.help(*args, **kwds) File "/usr/local/lib/python2.3/pydoc.py", line 1539, in __call__ self.help(request) File "/usr/local/lib/python2.3/pydoc.py", line 1575, in help else: doc(request, 'Help on %s:') File "/usr/local/lib/python2.3/pydoc.py", line 1368, in doc pager(title % desc + '\n\n' + text.document(object, name)) File "/usr/local/lib/python2.3/pydoc.py", line 279, in document if inspect.isclass(object): return self.docclass(*args) File "/usr/local/lib/python2.3/pydoc.py", line 1122, in docclass lambda t: t[1] == 'method') File "/usr/local/lib/python2.3/pydoc.py", line 1057, in spill name, mod, object)) File "/usr/local/lib/python2.3/pydoc.py", line 280, in document if inspect.isroutine(object): return self.docroutine(*args) File "/usr/local/lib/python2.3/pydoc.py", line 1145, in docroutine realname = object.__name__ AttributeError: 'super' object has no attribute '__name__' Another reason to use private attributes ;) There is a simple fix, anyway: class Super(super): def __init__(self,C,S=None): super(Super,self).__init__(C,S) self.__name__="Super(%s)" % C.__name__ To you and to other explorers of the wonders of super, I say "DON'T USE 2.2!". There were many subtle bugs now mostly solved in 2.3 (except the one with pydoc, AFAIK). Cheers, Michele From gh at ghaering.de Tue Jun 17 09:10:13 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 17 Jun 2003 15:10:13 +0200 Subject: Debug version of Python 2.2 on win32 platform ? In-Reply-To: <3EEF12FD.9020905@swissinfo.org> References: <3EEF12FD.9020905@swissinfo.org> Message-ID: <3EEF1335.8080206@ghaering.de> Sebastien Hugues wrote: > Hi > > Does anyone know where i could find a binary version of Python 2.2 with > all debug symbols enabled for win32 ? There used to be a ZIP file with the debug binaries available from ActiveState. Not that there's much point in this download, though. > I tried to build it from > scratch, but i cannot set up the wise installation due to a wrong > version of wise. You don't need to build the WISE installer to copy a few .exe, .dll and .pyd files into the right places, do you? -- Gerhard From mertz at gnosis.cx Mon Jun 16 16:21:15 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Mon, 16 Jun 2003 16:21:15 -0400 Subject: Diamond inheritance with str References: Message-ID: <7ai7+kKkXIwd092yn@gnosis.cx> Patrick Earl wrote previously: |>>> class A(str): pass |... |>>> class B(str): pass |... |>>> class C(A,B): pass |... |Traceback (most recent call last): | File "", line 1, in ? |TypeError: multiple bases have instance lay-out conflict Likewise: >>> class A(tuple): pass ... >>> class B(tuple): pass ... >>> class C(A,B): pass ... Traceback (most recent call last): File "", line 1, in ? TypeError: multiple bases have instance lay-out conflict I imagine that you could do some clever checks in a metaclass (as usual), but it feels to me also like that shouldn't be necessary. -- ---[ 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 martin at v.loewis.de Sun Jun 29 23:40:06 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 30 Jun 2003 05:40:06 +0200 Subject: using extended built-in types References: <6f03c4a5.0306291248.325e5ecc@posting.google.com> Message-ID: rimbalaya at yahoo.com (Rim) writes: > How do I make all future integers use myint instead of int without > explicitely say a = myint(value)? That is not possible. Martin From tdelaney at avaya.com Wed Jun 11 20:24:11 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 12 Jun 2003 10:24:11 +1000 Subject: Why it doesn't go ???? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE6EA054@au3010avexu1.global.avaya.com> > From: Panther [mailto:saspurss at libero.it] > > Because I have an error if I import ping.py. In that case you're going to have very little luck calling it as a string. http://www.catb.org/~esr/faqs/smart-questions.html In particular: http://www.catb.org/~esr/faqs/smart-questions.html#beprecise Tim Delaney From ccurvey at earthlink.net Sat Jun 14 18:14:39 2003 From: ccurvey at earthlink.net (Chris Curvey) Date: Sat, 14 Jun 2003 22:14:39 GMT Subject: sgmllib missing an end tag? Message-ID: I hope this doesn't post twice.... Can anyone see why sgmllib would miss the tag just after "Log in" in the following HTML fragment? I've been looking at this so long that the characters are starting to swim around.... Log in Join From aahz at pythoncraft.com Thu Jun 19 10:31:52 2003 From: aahz at pythoncraft.com (Aahz) Date: 19 Jun 2003 10:31:52 -0400 Subject: Feature Structures in Python (Part I) References: Message-ID: In article , James Tauber wrote: > >This is the first part of a tutorial/cookbook I'm writing up on >implementing feature structures in Python. > >I'd love any feedback (particularly on the Pythonicity of my approach). You should also cover using classes and class instances. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From tim at remove_if_not_spam.digitig.cix.co.uk Fri Jun 27 05:46:49 2003 From: tim at remove_if_not_spam.digitig.cix.co.uk (Tim Rowe) Date: Fri, 27 Jun 2003 10:46:49 +0100 Subject: shebang strange thing... References: <3EF3A07B.A683F94F@alcyone.com> <3EF7A121.7B4C3775@alcyone.com> <3EF933AA.C16ADFE5@alcyone.com> Message-ID: On 27 Jun 2003 09:33:23 +0950, Ben Finney wrote: >So, it was teletypes that needlessly preserved the CR and LF as separate >control operations, due to the typewriter-based thinking of their >designers. If they'd been combined into the one operation, we would >have all the same functionality but none of the confusion over line >ending controls. It wasn't needless. A CR with no LF was often used for overstriking, as a way of extending the rather limited character set. 'O' overstruck with '-' would make a passable \Theta, for instance.. From Ludger.Humbert at cs.uni-dortmund.de Tue Jun 17 13:42:02 2003 From: Ludger.Humbert at cs.uni-dortmund.de (Ludger.Humbert) Date: Tue, 17 Jun 2003 19:42:02 +0200 Subject: One Problem -- how to implement in three programming paradigms in Python In-Reply-To: References: <3EED97E5.1080100@cs.uni-dortmund.de> <3EEE2898.9080000@cs.uni-dortmund.de> Message-ID: <3EEF52EA.1040901@cs.uni-dortmund.de> Hi Bengt Richter, your post makes my day. Now the problem is solved in a) an imperativ programming style ( Bengt Richter ) b) an objectoriented programming style ( Bengt Richter ) c) a (knowledge based) predicative programming style ( with holmes by Mark Lutz an some rules made by lh ) If there would be someone out there, who is able to realize a solution in the functional programming style, I would be happy again. The problem: http://in.hagen.de/~humbert/vortraege/F.Grundkonzepte_html/22.html TNX .. so much I would like to point out: "You know you're a Pythonista when .. you ask another Pythonista a rather non trivial question, and get an answer, before you wake up next time ..." Ludger -- ______________________________________________________________________ _____ UniDo / Ludger University of Dortmund, LS Informatik XII ___/ / Humbert didactics of informatics \ \ / D-44221 Dortmund \__\/ Phone: +49 231 755 6141, Fax: +49 231 755 6116 Email: ludger.humbert at uni-dortmund.de ______________________________________________________________________ From uwe at oss4u.com Tue Jun 10 00:57:56 2003 From: uwe at oss4u.com (Uwe C. Schroeder) Date: Mon, 09 Jun 2003 21:57:56 -0700 Subject: pyc suffix importer Message-ID: Hi, has anyone written a pure pyc suffix importer for imputil ? The current py suffix importer only handles things when both, the .py and the .pyc are present (or at least the .py) However I only have a .pyc which I need to import. I know there was a patch checked in at sourceforge in July 2002, however one can't see the patches. Anyone ? thanks UC -- Open Source Solutions 4U, LLC 2570 Fleetwood Drive Phone: +1 650 872 2425 San Bruno, CA 94066 Cell: +1 650 302 2405 United States Fax: +1 650 872 2417 From duncan at NOSPAMrcp.co.uk Mon Jun 9 06:43:10 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 9 Jun 2003 10:43:10 +0000 (UTC) Subject: PEP 318: Function Modifier Syntax References: Message-ID: Gerrit Holl wrote in news:mailman.1055151317.13691.python-list at python.org: > I would say: > > funcdef: "def" funcname "(" [parameter_list] ")" [call_list] ":" > call-list: callable ("," callable)* [","] Did you miss out "as" before the [call_list]? Also, I still think that you need to allow optional parentheses around the call-list. > But now the properties: those are more difficult. > A legal syntax would be: > > def __get(self) as property: ... > > However, this doesn't work for set and del. Using function attributes to > accomplish properties, as has been proposed in the past, is a different > story and would require a different PEP. > What would people think of a half-way house where the new syntax is used only on the last part of the definition, and you define the other methods just as you do just now? Since the property type isn't callable today, I think this just about fits without breaking anything: Define a readonly property, implicitly calls property(X) which creates a readonly property: def X(self) as property: return self.__x_value Define a readwrite property, the call to property returns a property object which is itself callable. Calling a property object with an fset but no fget would take the parameter as a new fget: def set_X(self, value): ... def X(self) as property(fset=set_X): return self.__x_value or def get_X(self): ... def X(self) as property(fget=get_X): ... Defining a writeonly property: def X(self, value) as property(fget=None): ... Another thought. When defining a function I can do: f = 3 def f(x=f): pass The parameter name x doesn't conflict with access to the variable x. The same thing should happen in: funcdef: "def" funcname "(" [parameter_list] ")" "as" [call_list] ":" any reference to a variable in callable with the same name as funcname should get the previous value of funcname (if there was one). So it would be possible to write: def X(self) as property: return self.__x_value def X(self, value) as X: print "setting X" which sucks, although if property could take a property as a parameter you might be able to write this instead: def X(self) as property: return self.__x_value def X(self, value) as property(fget=X): print "setting X" Or you could simply define some new wrappers property_get, property_set, property_del and write: def X(self) as property_get: ... def X(self, value) as property_set(X): ... def X(self) as property_del(X): ... with appropriate but confusing definitions. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From aahz at pythoncraft.com Thu Jun 26 20:55:46 2003 From: aahz at pythoncraft.com (Aahz) Date: 26 Jun 2003 20:55:46 -0400 Subject: Exposing object model in Python? References: Message-ID: In article , MK wrote: > >What would be the best way to expose the object model of a Python >application? Depends what you want to do. Are you trying to expose only methods of objects that you provide, or give full access to Python? Or something else? >If I package my app with py2exe, can I ship Python intepreter and >access py2exe-cised app through Python scripts then? Basic answer is yes, depending on exactly what libraries you ship. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Usenet is not a democracy. It is a weird cross between an anarchy and a dictatorship. From gupt_vive at hotmail.com Thu Jun 19 08:56:38 2003 From: gupt_vive at hotmail.com (vivek kumar) Date: Thu, 19 Jun 2003 18:26:38 +0530 Subject: DBI and DBDs 4 Python Message-ID: >From: "J?Gius?" >To: python-list at python.org >Subject: DBI and DBDs 4 Python >Date: Thu, 19 Jun 2003 11:40:46 GMT > >Hi, > >Is there any database access module independent of the actual database >being >used? That is, a module that define methods and conventions in order to >provide a consistent database interface regardless of the picked out RDBMS >. I haven't tried this coz it is a commercial package ;-) but it seems that u are looking for mxODBC >Gius regards Vivek Kumar _________________________________________________________________ Feeling lost and loneyl? Need a little astro guidance? http://www.msn.co.in/Astrology/ From jjl at pobox.com Wed Jun 18 09:31:18 2003 From: jjl at pobox.com (John J. Lee) Date: 18 Jun 2003 14:31:18 +0100 Subject: [long] Comments on urllib2 extensions? Message-ID: <87y8zzms0p.fsf@pobox.com> I'm looking for comments on an extension to urllib2 (see below for code, but read the notes first!). Apologies for posting here instead of SF patch manger (see below for why). Problem with urllib2 as it stands: many things would be nice to implement as a Handler rather than by overriding methods (and inevitably duplicating code and increasing fragility), but it's not always possible to do so. For example (all from HTTP), automatically adding Referer headers, handling 200 responses that should have been non-2xx errors if the server were sane, handling cookies, handling HTTP-EQUIV headers as if they were normal HTTP headers, automatically making responses seekable, and following Refresh headers. I've done all these things, but I had to duplicate code to do it, because I don't see how to do it with Handlers. Two things I'd like to know: 1. will my solution break people's code 2. is there a better way? For 1., I *think* it shouldn't break code. For 2., the obvious problem with my solution (below) is that Handlers are pretty similar to my Processors already. The thing is, I can't see how to reimplement these things in terms of Handlers. First, I need to *see* all requests (responses) -- I can do that using Handlers by giving them low (high) .handler_order in Python 2.3 and returning None from http_open (http_error_xxx). However, 200 responses never get seen by http_error_xxx, so that doesn't work (and changing that would break old code). Second, I sometimes need to actually modify the requests and responses. Sometimes I'd much rather do that by making a new request or response than modifying the old one in-place -- and in general, even if I *am* just modifying in-place, I'd still prefer to explictly return the object than rely on side-effects. I suppose just adding a couple of hooks to AbstractHTTPHandler might get the job done, but I think the increased simplicity of AbstractHTTPHandler.do_open and the various Processors makes my approach worthwhile (assuming it actually works & is backwards-compat., of course...). The code is below, but note: I'm not posting this as a patch yet, partly because the core Python people are likely particularly busy ATM (2.3 etc.), partly because it *isn't* a patch yet (it's code I just wrote and am wondering whether or not to put in my ClientCookie package, which extends urllib2). However, a patch would look almost identical. It's not even working code (not much work to get it working... but I think I want to write some unit tests for urllib2 first). Note also that some implementation code isn't reproduced here (notably the Cookies class, parse_head and seek_wrapper -- all from ClientCookie, and all of which I hope eventually to get into the standard libray, when they're simple & stable enough). You use it like this: # just pass Processors to build_opener as if they were Handlers opener = build_opener(FooHandler, BarProcessor, BazHandler) response = opener.open("http://www.example.com/") Comments?? John #------------------------------------------------------------------------------ # Note that this is useful also for the case where a urllib2 user wants to # handle 200 responses that should have been errors (which unfortunately # does happen -- the content will be something informative like # "An error occurred.", but the code is still 200). # XXX *try* this to check following is true!: It's particularly useful # when you want to retry fetching pages on certain errors. # Maybe something similar could be done just by sticking in a hook in # AbstractHTTPHandler.do_open right at the start (for request munging) # and just before redirection (for response munging)? I think this is # nicer, though. class BaseProcessor: processor_order = 500 def add_parent(self, parent): self.parent = parent def close(self): self.parent = None def __lt__(self, other): return self.processor_order < other.processor_order class HTTPEquivProcessor(BaseProcessor): """Append META HTTP-EQUIV headers to regular HTTP headers.""" def http_response(self, request, response): if not hasattr(response, "seek"): response = seek_wrapper(response) # grab HTTP-EQUIV headers and add them to the true HTTP headers headers = response.info() for hdr, val in parse_head(response): headers[hdr] = val response.seek(0) return response class SeekableProcessor(BaseProcessor): """Make responses seekable.""" # XXX perhaps this should come after ErrorProcessor # (.processor_order > 1000) def http_response(self, request, response): if not hasattr(response, "seek"): return seek_wrapper(response) return response # XXX really, unverifiable should be an attribute / method on Request -- user # may want to make unverifiable requests directly class HTTPCookieProcessor(BaseProcessor): """Handle HTTP cookies.""" def __init__(self, cookies=None): if cookies is None: cookies = Cookies() self.cookies = cookies def http_request(self, request): if hasattr(request, "error_302_dict") and request.error_302_dict: redirect = True else: redirect = False # Stuff request-host of this origin transaction into Request # object, because we need to know it to know whether cookies # should be in operation during derived requests (redirects, # specifically). request.origin_req_host = request_host(req) self.cookies.add_cookie_header(req, unverifiable=redirect) return request def http_response(self, request, response): if hasattr(request, "error_302_dict") and request.error_302_dict: redirect = True else: redirect = False self.cookies.extract_cookies(response, req, unverifiable=redirect) return request class HTTPRefererProcessor(BaseProcessor): """Add Referer header to requests. This only makes sense if you use each RefererProcessor for a single chain of requests only. """ def __init__(self, cookies=None): self.referer = None def http_request(self, request): if ((self.referer is not None) and not request.headers.has_key("Referer")): request.addheader("Referer", self.referer) return request def http_response(self, request, response): self.referer = response.geturl() return response class HTTPStandardHeadersProcessor(BaseProcessor): def http_request(self, request): new_req = copy.copy(request) # For backwards-compat. if req.has_data(): # POST data = new_req.get_data() if not new_req.headers.has_key('Content-type'): new_req.add_header('Content-type', 'application/x-www-form-urlencoded') if not req.headers.has_key('Content-length'): new_req.add_header('Content-length', '%d' % len(data)) scheme, sel = urllib.splittype(req.get_selector()) sel_host, sel_path = urllib.splithost(sel) h.putheader('Host', sel_host or host) for name, value in self.parent.addheaders: name = name.capitalize() if not req.headers.has_key(name): h.putheader(name, value) for args in self.parent.addheaders: apply(h.putheader, args) return new_req # XXX Problems: # Existence of ErrorProcessor is necessary for correct hehaviour of # the other processors (they need to happen before redirection). # But: # ErrorProcessor and RefreshProcessor must come after the rest. # Will it break old code if applied to urllib2? People who override # AbstractHTTPHandler.do_open will do redirection there, which *will* # break Processors -- but since all the Processors I'm suggesting # (other than ErrorProcessor itself) just add new features and # would be off by default, this isn't a problem. ErrorProcessor is # old code in a new form, and I think adds no problems not introduced # by overriding do_open in the first place. # Response object doesn't include response code or message (because # code is always 200). This isn't a showstopper: could always add # code and msg attributes. End user still only gets 200 responses, # because ErrorProcessor ensures that (everything else gets raised # as an exception). class HTTPRefreshProcessor(BaseProcessor): """Perform HTTP Refresh redirections. Note that if a non-200 HTTP code has occurred (for example, a 30x redirect), this processor will do nothing. """ processor_order = 1000 def http_response(self, request, response): code, msg, hdrs = response.code, response.msg, response.info() if code == 200 and hdrs.has_key("refresh"): refresh = hdrs["refresh"] i = string.find(refresh, ";") if i != -1: time, newurl_spec = refresh[:i], refresh[i+1:] i = string.find(newurl_spec, "=") if i != -1: if int(time) == 0: newurl = newurl_spec[i+1:] # fake a 302 response hdrs["location"] = newurl response = self.parent.error( 'http', request, response, 302, msg, hdrs) return response class HTTPErrorProcessor(BaseProcessor): """Process non-200 HTTP error responses. This just passes the job on to the Handler._error_ methods, via the OpenerDirector.error method. """ processor_order = 1000 def http_response(self, request, response): code, msg, hdrs = response.code, response.msg, response.info() if code != 200: # XXX fp has been replaced by response here -- can that cause # any trouble? Same goes for RefreshProcessor. # XXX redundancy -- response already contains code, msg, hdrs. # Oh well, too bad. response = self.parent.error( 'http', request, response, code, msg, hdrs) return None # no more response processing class OpenerDirector(urllib2.OpenerDirector): # XXX might be useful to have remove_processor, too (say you want to # set a new RefererProcessor, but keep the old CookieProcessor -- # could always just create everything anew, though (using old # Cookies object to create CookieProcessor) def __init__(self): urllib2.OpenerDirector.__init__(self) self.processors = [] self.process_response = {} self.process_request = {} def add_processor(self, processor): added = False for meth in dir(processor): if meth[-9:] == "_response": protocol = meth[:-9] if self.process_response.has_key(protocol): self.process_response[protocol].append(processor) self.process_response[protocol].sort() else: self.process_response[protocol] = [processor] added = True continue elif meth[-9:] == "_request": protocol = meth[:-8] if self.process_request.has_key(protocol): self.process_request[protocol].append(processor) self.process_request[protocol].sort() else: self.process_request[protocol] = [processor] added = True continue if added: self.processors.append(processor) # XXX base class sorts .handlers, but I have no idea why #self.processors.sort() processor.add_parent(self) def _request(self, url_or_req, data): if isinstance(url_or_req, basestring): req = Request(url_or_req, data) else: # already a urllib2.Request instance req = url_or_req if data is not None: req.add_data(data) return req def open(self, fullurl, data=None): req = self._request(fullurl) scheme = req.get_type() for meth_name in self.process_request[scheme]: meth = getattr(processor, meth_name) req = meth(req) scheme = req.get_type() # XXX good / bad / unnecessary? response = urllib2.UrlOpener.open(req, data) for meth_name in self.process_response[scheme]: meth = getattr(processor, meth_name) response = meth(req, response) return response def close(self): urllib2.OpenerDirector.close(self) for processor in self.processors: processor.close() self.processors = [] # Note the absence of redirect and header-adding code here # (AbstractHTTPHandler), and the lack of other clutter that would be # here without Processors. class AbstractHTTPHandler(urllib2.BaseHandler): def do_open(self, http_class, req): host = req.get_host() if not host: raise URLError('no host given') h = http_class(host) # will parse host:port if req.has_data(): h.putrequest('POST', req.get_selector()) else: h.putrequest('GET', req.get_selector()) for k, v in req.headers.items(): h.putheader(k, v) # httplib will attempt to connect() here. be prepared # to convert a socket error to a URLError. try: h.endheaders() except socket.error, err: raise URLError(err) if req.has_data(): h.send(data) code, msg, hdrs = h.getreply() fp = h.getfile() response = addinfourl(fp, hdrs, req.get_full_url()) return response # (this wouldn't be in a patch, I'm just deriving from the simplified # AbstractHTTPHandler) class HTTPHandler(AbstractHTTPHandler): def http_open(self, req): return self.do_open(httplib.HTTP, req) if hasattr(httplib, 'HTTPS'): class HTTPSHandler(AbstractHTTPHandler): def https_open(self, req): return self.do_open(httplib.HTTPS, req) def build_opener(*handlers): """Create an opener object from a list of handlers and processors. The opener will use several default handlers and processors, including support for HTTP and FTP. If any of the handlers passed as arguments are subclasses of the default handlers, the default handlers will not be used. """ opener = urllib2.OpenerDirector() default_classes = [ # handlers urllib2.ProxyHandler, urllib2.UnknownHandler, HTTPHandler, # from this module (derived from new AbstractHTTPHandler) urllib2.HTTPDefaultErrorHandler, urllib2.HTTPRedirectHandler, urllib2.FTPHandler, urllib2.FileHandler, # processors # don't use most processors by default, for backwards compatibility #HTTPEquivProcessor, #SeekableProcessor, #HTTPCookieProcessor, #HTTPRefererProcessor, HTTPStandardHeadersProcessor, #HTTPRefreshProcessor, HTTPErrorProcessor ] if hasattr(httplib, 'HTTPS'): default_classes.append(HTTPSHandler) skip = [] for klass in default_classes: for check in handlers: if type(check) == types.ClassType: if issubclass(check, klass): skip.append(klass) elif type(check) == types.InstanceType: if isinstance(check, klass): skip.append(klass) for klass in skip: default_classes.remove(klass) to_add = [] for klass in default_classes: to_add.append(klass()) for h in handlers: if type(h) == types.ClassType: h = h() to_add.append(h) for instance in to_add: # yuck if hasattr(instance, "processor_order"): opener.add_processor(instance) else: opener.add_handler(instance) return opener #------------------------------------------------------------------------------ From stevesusenet at yahoo.com Thu Jun 19 11:35:13 2003 From: stevesusenet at yahoo.com (Steve) Date: 19 Jun 2003 08:35:13 -0700 Subject: Is python good for making database work short? References: <6f8cb8c9.0306181727.9c86095@posting.google.com> Message-ID: <6f8cb8c9.0306190735.abb5d5f@posting.google.com> Paul McNett

wrote > I am a FoxPro developer switching to Python. Python offers a good DB > specification and a bunch of modules to access any kind of backend data. > Python also offers good basic types to store cursor-like views of the dat > a > (a list of dictionaries would provide a recordset-like object, where you > can reference the fields by name). Thanks for the cool opinion. Its nice to have one from a foxpro afficinado saying that python is the next best thing. I have been very impressed with foxpro. I am surprised that the free software community ( or even another proprietary group ) has not produced a work-a-like of foxpro. Steve From mertz at gnosis.cx Wed Jun 18 23:57:13 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Wed, 18 Jun 2003 23:57:13 -0400 Subject: Is python good for making database work short? References: <6f8cb8c9.0306181727.9c86095@posting.google.com> Message-ID: Paul McNett

wrote previously: |FoxPro shines at manipulating data. There is no finer tool for that |purpose. Well... there *is* a finer tool: Clipper :-). But those are pretty close, both being xBase dialects. However, Clipper besides having a moderately better syntax, also has a multi-platform Free Software implementation called Harbour. That said, I still like Python better. It may not be *quite* as agile at manipulating relational tables, but for most everything else it's a bit better. Yours, Lulu... -- 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 wweexxsseessssaa at telusplanet.net Wed Jun 18 19:49:12 2003 From: wweexxsseessssaa at telusplanet.net (John Hall) Date: Wed, 18 Jun 2003 23:49:12 GMT Subject: Windows Program? References: Message-ID: On Wed, 18 Jun 2003 23:25:01 GMT, Ben Finney wrote: >Much nicer, uses native widgets on *nix, Windws and (soon) MacOS, but >needs extra packages: > > and PythonCard (uses wxWindows, wxPython) http://pythoncard.sourceforge.net/ -- John W Hall Calgary, Alberta, Canada. "Helping People Prosper in the Information Age" From bgailer at alum.rpi.edu Fri Jun 27 16:25:03 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 27 Jun 2003 14:25:03 -0600 Subject: Inputbox with win32api? In-Reply-To: <899f842.0306271144.592f9c29@posting.google.com> Message-ID: <5.2.1.1.0.20030627142334.027f5ab8@66.28.54.253> At 12:44 PM 6/27/2003 -0700, Anthony_Barker wrote: >Is there a simple way of throwing up a simple Inputbox with win32 api >in python? > >I could use tk >data=tkSimpleDialog.askstring( title="Input",prompt="Email Address?") > >but that adds 700K to the package when I distribute it to non python >users as it forces me to include tk. (Using MacMillian installer). There is win32all with its version of raw_input(). I don't know how much overhead that adds to a package. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From wooooee at yahoo.com Wed Jun 11 21:00:51 2003 From: wooooee at yahoo.com (Curly Joe) Date: Wed, 11 Jun 2003 18:00:51 -0700 (PDT) Subject: simple text filter Message-ID: <20030612010051.83718.qmail@web41808.mail.yahoo.com> FYI - here is an alternate method, but the test for an empty string is more straight forward IMHO because there is only one read statement and it is within the while loop. Note that in your code, the EOF will be processed like a regular line of data, but nothing will be done in this case because you will be searching an empty string. This is not always the case though, so try to think in terms of how the program executes, which is very difficult for us transistor-challenged beings. f=open('adt100_0489.rpt.txt', 'r') junky = f.readline() while( junky ) : ## statements should be before the ## readline because it will return an ## empty string at EOF junky = f.readline() Keep on keeping on though. > --- In python-list at yahoogroups.com, boutrosp at h... > wrote: > > I need some help on a simple text filter. The > problem I am having is > > when the file comes to the end it stays in the > while loop and does > not > > exit. I cannot figure this out. I would use a for > loop with the > > readlines() but my datasets can range from 5 to 80 > MB of text data. > > Here is the code I am using. Please help. > > > > import sys, re > > > > p1 = re.compile('ADT100') > > p2 = re.compile('AUDIT') > > p3 = re.compile('HARDWARE') > > p4 = re.compile('PACKAGES') > > p5 = re.compile('NODE') > > p6 = re.compile('DROP') > > p7 = re.compile('GRID') > > p8 = re.compile('ATAP') > > > > f=open('adt100_0489.rpt.txt', 'r') > > junky = 1 > > done = False > > while not done : > > junky = f.readline() > > if p1.search(junky) : > > continue > > elif p2.search(junky) : > > continue > > elif p3.search(junky) : > > continue > > elif p4.search(junky) : > > continue > > elif p5.search(junky) : > > continue > > elif p6.search(junky) : > > continue > > elif p7.search(junky) : > > continue > > elif p8.search(junky) : > > continue > > elif junky == None : > > done = True > > else : > > print junky > > > > f.close() > > -- > > > http://mail.python.org/mailman/listinfo/python-list > __________________________________ Do you Yahoo!? Yahoo! Calendar - Free online calendar with sync to Outlook(TM). http://calendar.yahoo.com From eat at joes.com Thu Jun 26 22:57:33 2003 From: eat at joes.com (Jason Kratz) Date: Fri, 27 Jun 2003 02:57:33 GMT Subject: stupid question about os.listdir In-Reply-To: References: Message-ID: Here is more clarification. Here is my script called backup.py import os.path import os def getdirs(path): dirs = [] os.chdir(path) for entry in os.listdir(path): if os.path.isdir(entry): dirs.append(entry) return dirs print getdirs('/') if I run this from the command line on linux with 'python backup.py' it works *if* I have os.chdir in there. if I comment it out it doesnt list starting from the root dir...it starts in my home dir. If go into the interactive command mode by just typing 'python' at the prompt and do: import os os.listdir('/') then it prints out the dirs under root. incidentally this happens on windows as well Jason Kratz wrote: > OK. I've search on google groups and around the web for this and I > haven't found an answer. I'm a Python newbie and have what I assume is > a basic question. os.listdir takes a pathname as an arg but it doesn't > actually list the contents of the dir I pass in. it always operates on > the current dir (wherever the script is run) and I have to chdir > beforehand. Is that how its supposed to work? If so what is the point > in passing in a pathname? > > thanks, > > Jason > From imbosol at aerojockey.com Mon Jun 2 02:49:34 2003 From: imbosol at aerojockey.com (Carl Banks) Date: Mon, 02 Jun 2003 06:49:34 GMT Subject: Named constants -- no such thing as "too obvious" References: <3ed71a14$0$49099$e4fe514c@news.xs4all.nl> Message-ID: <2sCCa.4346$b8.2342@nwrdny03.gnilink.net> Ben Finney wrote: > On Fri, 30 May 2003, Irmen de Jong wrote: >> We might as well name the following constants: >> FIRST_INTEGER_AFTER_ZERO=1 >> NUMBER_OF_DIGITS_IN_BASE_TEN=10 >> FOUR_TIMES_PI=math.pi*4 > > These do not define numbers in terms of *intent*, the way that > HOURS_PER_DAY or BEERS_PER_SLAB do. They give no context that wasn't > already present (i.e., that these are numbers). > > Would you disagree, though, with setting these named constants: > > START_ARRAY_INDEX = 1 > NUMBER_BASE = 10 > DEGREES_IN_RIGHT_ANGLE = 90 Yes. All of these are taking it WAY too far. > Now there is context for these numbers. When I use the literal number > 10 in my code, am I using it because it's the number base I want to use? > How can you know? You can read the source code. IMO, it's a far better to spend your time making code readable enough so that you don't need a silly name to know what a constant is used for. > You'd make an educated guess. But if I would just > use NUMBER_BASE instead, you wouldn't have to guess at all. It's a nice little idea that might be true in your little ideal world. However, I find, in practice, that excessive use of named constants can severely decrease the readability of a program. There are many reasons. First, the names chosen for constants are often misleading and lead to confusion. For example, take your example NUMER_BASE. What is the base? You think it's entirely clear to me what NUMBER_BASE is, but it's not. Sure, I know what it's (supposed to be) used for. But I don't know what it IS. Is it a decimal base? Hexadecimal? Some odd value? If you use the constant NUMBER_BASE in your code, you'd force the reader to have to find the definition; whereas, if you use just a number, then the reader will probably see that it's a base right away since it's the second argument of int. What I'm saying is, your argument depends on constants being well-named, and that's a rare thing, and you have produced a poorly-named yourself. Second, sometimes the value of the constant itself is more important to readability than the name. I'll give you an example. Suppose I have to do the following calculation: math.sin(x*PI/2.0) You want me to write it like this: math.sin(x*RADIANS_IN_RIGHT_ANGLE) I can tell you that it's far, far less readable. I can't overemphasize how much less readable the latter is to me. Why? Because PI/2.0 is ingrained in me. I studied engineering; I am at one with radians. When I see PI/2.0, I immediately know what I'm looking at. When I see RADIANS_IN_RIGHT_ANGLE, I have to think about what it means and what value it has. It's not ingrained; I never studied any engineering equations with such a constant in it. You see, the named constant RADIANS_IN_RIGHT_ANGLE makes it harder to read. The constant PI, on the other hand, increases readability, because it appears in all the equations I learned. I find that a good number of constants I use in my code are more readable as-is. Granted, I'm an engineer, and do a lot of number work. Most other programmers will not find this to be true as often as I, but still, sometimes the constant is more readable itself, and giving such a constant a name is counterproductive. Third, it can be a pain to debug. You looking at your code trying to figure out where the mistake is, and you can't see if there's anything obvious, because you don't know the values of all the constants. Not to mention, there is the possibility of an error in the named constant itself, which is a hard one to track down. Fourth, sometimes a number is just a number. Giving a name to something that isn't anything other than the number 2, or an entry in a matrix, is just silly. Finally, it's often just a lot of work for a very negligible benefit. You might spend an extra ten minutes defining constants, but it might only save a grand total two minutes down the line. What I'm saying is, it's not always a good idea to name every single constant. Like most things, discretion is best. It is very beneficial to name constants in many situations, but not all. Something like DEGREES_IN_RIGHT_ANGLE? It's never going to change, it's not likely to be misunderstood in context, and the number 90 means more to most people reading it than a verbose phrase. -- CARL BANKS From bit_bucket5 at hotmail.com Wed Jun 18 22:03:50 2003 From: bit_bucket5 at hotmail.com (Chris Stromberger) Date: Thu, 19 Jun 2003 02:03:50 GMT Subject: The beauty of Python References: Message-ID: On Tue, 17 Jun 2003 15:10:51 +0200, "Thomas Weholt \( PRIVAT \)" <2002 at weholt.org> wrote: >I'm trying to promote Python as an elegant, easy-to-read and intuitive >language at work and to my programming-buddies. I thought it would be nice >to have a webpage with examples of the beauty of Python, showing small >snippets of code solving real-world problems or tasks. If anybody has any >such examples to offer, I'd be very gratefull. And if it turns out to be any >interest for this in this group, I'll collect the source-snippets and put >them on the net. > >Best regards, >Thomas Weholt > I don't know if this qualifies, but at my sparse website I have written up some snippets of Python to contrast with Perl. This is mostly an outlet for frustrations encountered at work where Perl is king and Python is criticized by people who have never bothered to look at it (and hence Python is not available on our development boxes). It may be off base, but may be somewhat useful. I tried to not make it too vitriolic! http://www.strombergers.com/python/ From peter at engcorp.com Mon Jun 23 15:16:32 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 23 Jun 2003 15:16:32 -0400 Subject: asyncore and (missing) timeout References: Message-ID: <3EF75210.56F1E119@engcorp.com> Dave Brueck wrote: > > By definition, the readable and writable methods are _supposed_ to return > values that make sense as asyncore drives its behavior off those values. The > high CPU problem you're having goes away if you return values that truly > reflect the state of your app. > > Also, I better include the standard "have you tried Twisted yet?" response - > many people seem to like it (although there is terrific educational value in > getting your asyncore-based program working ;-) ). In cases like this, the best reason to consider using Twisted is that it is actually somewhat higher level than asyncore, and you don't have to deal with quite so many minor details. It's a pretty subtle difference, but sockets are tricky enough already that it can be a real help. -Peter From other at cazabon.com Fri Jun 27 01:51:35 2003 From: other at cazabon.com (Kevin) Date: Fri, 27 Jun 2003 05:51:35 GMT Subject: Yet another threading question... References: Message-ID: I've been pondering the exact same issue, but haven't gotten that far in wrapping the 3rd-party C library I'm working with. I was thinking of stubbing the callback to a Python function that sets an event flag, and have a Python thread monitoring that event to handle it. I'm not sure if that will cure your access violation, but it may. You should also make sure that your wrapper gets the GIL (Python Global Intepreter Lock) before making the Python function call to set the event. Let me know if you try that, or if you get it to work some other way... I'll be beating my head into the same problem pretty soon and could use the heads up! Thanks, Kevin Cazabon "Jim West" wrote in message news:mailman.1056639557.22837.python-list at python.org... > Good day all, > > Ok, I'm starting to get the hang of this Python thing...really pretty > cool actually. Again, thanx to those that have helped me thus far. > > I now have another stumbling block to which I would like help. > > Ok, here is my enviroment: > > Windows 2K > Python 2.2 > MinGW and MSys > > I'm writing a Python extension to a 3rd party DLL that controls an > external hardware toy. > > One of the DLL methods is a callback registration interface. The 3rd > party DLL is threaded as the callback is asynchronous. > > I'm able to call my extension function via Python to "register" my > Python function as the callback function via a C function proxy in the > extension. > > All is well until the DLL invokes the callback. When the callback > attempts to invoke my "registered" Python function the Python > interpreter bails with an access violation. > > I'm thinking it may have something to do with threading and thus am > asking for your insight to this. > > I'm thinking I may have to put my proxy C callback function in it's > own thread. If so, then would some kind soul point me in the right > direction as to how to do this with just the MinGW environment since we > do not have nor use MSVC++. > > Thank you. > > - Jim > > > From postmaster at paytec.com Mon Jun 30 11:58:55 2003 From: postmaster at paytec.com (System Administrator) Date: Mon, 30 Jun 2003 11:58:55 -0400 Subject: Undeliverable: Re: Application Message-ID: Your message To: jc.mann at paytec.com Subject: Re: Application Sent: Mon, 30 Jun 2003 12:03:20 -0400 did not reach the following recipient(s): JC.MANN at PAYTEC.COM on Mon, 30 Jun 2003 11:58:47 -0400 The recipient name is not recognized The MTS-ID of the original message is: c=us;a= ;p=payment technolo;l=GROMMIT0306301558NHGWG78P MSEXCH:IMS:Payment Technologies:PTI:GROMMIT 0 (000C05A6) Unknown Recipient -------------- next part -------------- An embedded message was scrubbed... From: python-list at python.org Subject: Re: Application Date: Mon, 30 Jun 2003 12:03:20 -0400 Size: 843 URL: From martin at v.loewis.de Sun Jun 8 02:45:42 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 08 Jun 2003 08:45:42 +0200 Subject: Kerberos authentication for IMAP? References: Message-ID: Alan Hoyle writes: > Which seems a bit more promising than the how can I set this up to use > my Kerberos tokens or TGT? The tricky part is, perhaps, to fetch the token from the ticket cache. This would normally require wrappig the Kerberos library as a Python module, which hasn't been done for Kerberos 4; perhaps you could adapt http://starship.python.net/crew/fdrake/manuals/krb5py/ http://pygss.sourceforge.net/ Alternatively, you could try invoking command line utilities, and try to generate an authenticator from that. HTH, Martin From fredrik at pythonware.com Wed Jun 18 17:34:37 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Jun 2003 23:34:37 +0200 Subject: daily python URL needs to have archives. References: <3eee0e50$1_2@hpb10302.boi.hp.com> Message-ID: Daniel Fackrell wrote: > Google Groups may provide what you need. It appears that there are > presently 522 matches based on the following search, some of which will > undoubtedly be follow-ups. > > http://groups.google.com/groups?q=python-url&meta=group%3Dcomp.lang.python footnote: the daily URL and the weekly URL posting are two different things. From tjreedy at udel.edu Fri Jun 20 12:02:50 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 20 Jun 2003 12:02:50 -0400 Subject: freeing objects References: <3EF2D852.2050101@irst.itc.it> Message-ID: <6S2dndtXzti2rW6jXTWJhQ@comcast.com> "delphiro" wrote in message news:mailman.1056107842.11261.python-list at python.org... > Hi everyone, > > I am writing an application where I use Chaco for the excellent graphical output and now I have a question about creating / freeing objects. > > I use this code to create and assign a chaco-object (a 'vertical') to my dialog: > > self.plotitem = PlotCanvas( pv1, PlotTitle( 'Soilstress in vertical ..' ), plot_type = 'rangebar', axis_index = x_ax, axis = y_ax ) > > now the user has the possibility to change the view to another 'vertical' so self.plotitem should be assigned to another PlotCanvas and the old one should disappear. > > What is the correct way to do this? > > should I 'free' self.plotitem before assigning a new PlotCanvas to self.plotitem and if so, how do you 'free' objects in Python? 'Deleting' an item actually and only deletes the association between the handle (name, attribute, or collection slot) and the object. Assigning a new object to a handle implicitly does a delete with respect to the old association. For this much, an explicit delete would be redundant. When the association or reference count goes to 0, the interpreter *may* do some sort of cleanup, including calling its __delete__ method. Whether and when it *does* so can and does depend on the implementation. If you need to make explicitly sure cleanup is done, give the object a close method and call it before breaking your link to it. Terry J. Reedy From news at manuelmgarcia.com Thu Jun 12 13:36:14 2003 From: news at manuelmgarcia.com (Manuel Garcia) Date: Thu, 12 Jun 2003 17:36:14 GMT Subject: why 'lambda' and 'reduce'? References: Message-ID: On Thu, 12 Jun 2003 02:21:57 GMT, Manuel Garcia wrote: >If anyone ever asks for what good are 'lambda' and 'reduce', show them >this... Last night I was thinking about this silly code, and figured out a way to: 1) add just one more character to the progam, so the expression goes from 298 characters to 299 characters. 2) double the speed 3) most importantly, add another lambda! print (lambda p:p[0]+'.'+p[1:])( str((lambda(x,y,t,a):2L*x*x//a)( (lambda F:(lambda S:reduce( lambda(x,y,t,a),_: (lambda x1,y1:(x1,y1,2L*t, (a-(t*(x1**2-y1**2))//F)))( (x+y)//2L,S((x*y)//F)), [0]*13,(F,(F*F)//S(2L*F),2L,F//2L)))( lambda n:reduce(lambda x,_:( x-x//2L+(n*F)//(2L*x)),[0]*15, n//2L)))(10L**(5010))))[:5000]) the output is still perfectly accurate, of course. (Runs pretty fast in Python 2.3b1, actually) (btw I don't see why it only 'almost' qualifies for an "obfuscated" code contest. I wrote it, and I forgot how it worked around the time I added the third 'lambda' ;-) Manuel From peter at engcorp.com Thu Jun 5 22:22:35 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 05 Jun 2003 22:22:35 -0400 Subject: Twisted Panglossia References: , <3eddd372$0$16609$9b622d9e@news.freenet.de> <%RlDa.239$R44.10990@nnrp1.ozemail.com.au> <3mmDa.18175$8g5.301248@news2.e.nsc.no> <3EDE1F04.30539A1A@engcorp.com> Message-ID: <3EDFFAEB.C7453189@engcorp.com> David Mertz wrote: > But I've noticed something both on the Twisted list, and when Twisted > has come up here on c.l.py recently. The Twisted developers have a > greater excess of enthusiasm for their package than do the developers of > other large frameworks ... [snip perceived examples of this excess] > Now as with all such critics, I will quickly proclaim that the Twisted > developers are excellent programmers, and the range of capabilities in > there is fairly amazing. But there *are* these old stories about the > pitfalls of hubris that keep coming to mind... not that I'm advocating > eye-gauging or anything, just moderation :-). (My eyes are just the size I want them to be, but feel free to measure them if you are into that kind of thing...) I just want to point out, as one of those recently becoming a little enthusiastic about promoting Twisted, that I am *not* one of its developers. I might become one, at some point, once I'm past the stage of putting it to good use to clean up some of the past messes I've created using those other large frameworks you mention... I mention this as a balance point, to demonstrate that at least some people, after experience with a handful of such beasties, are supporting Twisted on its own merits, not just because they have too much of their own egos bound up in it. (*) -Peter (*) I don't mean to say the Twisted folks promote it only, or even at all, for such reasons, but your post might be taking as implying that is the case. From m at moshez.org Tue Jun 17 05:09:18 2003 From: m at moshez.org (Moshe Zadka) Date: 17 Jun 2003 09:09:18 -0000 Subject: does lack of type declarations make Python unsafe? In-Reply-To: References: , <3064b51d.0306151228.22c595e0@posting.google.com> <3EECED65.ACF1A6B7@engcorp.com> Message-ID: <20030617090918.9697.qmail@green.zadka.com> On Tue, 17 Jun 2003, Alex Martelli wrote: > Good thing your job isn't accounting Right > -- if you tried putting, on a > company's balance sheet, the source code it owns under "liabilities", > rather than under "assets", you'd be in for malpractice lawsuits to > dwarf Enron's (tax authorities might be particularly likely to take > a dim view in the matter). And *that's* the reason it's a good thing my job isn't accounting? [What do you think those "salaries for people who maintain the source" and "various developing environments" expenses *are*, if not the translation to accounting-lingo? How come we weren't sued for malpractice when my bosses authorized me to delete heaping gobs of code? Just because translating from sane-speak to accountant-lingo is non-trivial does not mean source code is not a liability] -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From gerard.sookahet at artenum.com Wed Jun 18 05:30:39 2003 From: gerard.sookahet at artenum.com (gerard Sookahet) Date: Wed, 18 Jun 2003 11:30:39 +0200 Subject: Embeding Java code in C-Python Message-ID: <3EF0313F.F7B4C888@artenum.com> Hello, Is it possible to embed Java code in C-Python ? Thanks in advance. GS From bsimuyandi at africonnect.com Wed Jun 11 11:06:01 2003 From: bsimuyandi at africonnect.com (Ben Simuyandi) Date: Wed, 11 Jun 2003 16:06:01 +0100 Subject: Newbie: changing an attribute of objects in a list References: Message-ID: OK, I've read a bit and I've now changed the code. If anyone would like to give feedback (better ways of doing it, where am I going wrong) that would be appreciated: n=0 while n < len(contents): def order(n, contents): m = 0 while m < len(contents): if contents[n].getId != contents[m].getId: norder=int(contents[n].rights) morder=int(contents[m].rights) if norder==morder: if contents[n].modified < contents[m].modified: norder=norder+1 order(n, contents) elif contents[m].modified < contents[n].modified: morder=morder+1 order(m, contents) m=m+1 n=n+1 order(n, contents) "Ben Simuyandi" wrote in message news:bc72gq$cv3$1 at main.gmane.org... > Hello. I am very new to Python and I'm stuck with a problem. I am using > Zope, and the problem is: > > I have a list of objects, each of which has several attributes. I would like > to sort these objects by a specific attribute, which is a string. This I can > manage OK. But if two objects have the same attribute value, I would like to > change the older (age determined by another attribute) object's attribute > to a new value of (old value+1), then go through the list and see if any > other object has this value, if so give it (old value+2) etc. > > I hope I have made the problem clear. I know that my code is wrong, but I > would like some hints as to what I am doing wrong. Some of it comes down to > a lack of understanding of Python. > > The ordering attribute I'll call "ordering", the age attribute I'll call > "age", and the list of objects is "contents". I thought that the way to do > this was by calling a function recursively. Anyway, below is the code, any > feedback is appreciated. > > > def check_listingorder(x, contents): > for y in contents: > if x.Id != y.Id: #each object > has a unique id > xorder=int(x.ordering) #convert the string > to an integer > yorder=int(y.ordering) > if xorder==yorder: #if the ordering > attribute is the same then... > if x.age> y.age: #if x is > older than y then... > xorder=xorder+1 > > check_listingorder(x, contents) > #call function again? > elif y.age> x.age: #if y is > older than x then... > yorder=yorder+1 > > check_listingorder(y, contents) #call > function again? > return contents #return the > list? > > for x in contents: #originally > called with: > check_listingorder(x, contents) > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From pxtl at hotmail.com Mon Jun 9 22:43:41 2003 From: pxtl at hotmail.com (martin z) Date: Tue, 10 Jun 2003 02:43:41 GMT Subject: Error checking in Python References: Message-ID: Actually, in this vein, I often have aproblem with the Python C Api in that it is very rigidly typed. Most of the major documented operations are specifically to the built-in types. That is, there's no PyMap_GetItemString - but there is PyDict_GetItemString, which only works with a dictionary. If there is such a function, it is poorly documented. This sort of problem abounds in the C Api. Idunno, I guess there's no point to this post. I'm just complaining. From paul at boddie.net Tue Jun 24 05:21:20 2003 From: paul at boddie.net (Paul Boddie) Date: 24 Jun 2003 02:21:20 -0700 Subject: XML References: Message-ID: <23891c90.0306240121.6a71a140@posting.google.com> Roman Suzi wrote in message news:... > > OK. When I was talking about plain text, I had in mind that it > has some proprietary format. For example, I can easily write: > > ------------------ > foo = "123" > bar = "456" > zoo = "la\"lala" > ------------------ > > And it's not very hard to parse that. Well, you can just write that in a module and have Python import it. ;-) And I don't see anything wrong with that, actually. In various situations, particularly the oft-quoted configuration file example, this is a lot more interesting than XML, for Python applications at least. > In case of XML I will need something like > > > 123456la"lala > > - not a big deal, but it's harder to parse. And also XML software keeps > changing (or so it seems), and this gives a sense of instability. How hard is it to call a parse function on some XML module? (Bearing in mind that your example isn't a well-formed XML document since it doesn't have a single root element, even though I do like using "zoo" elements in examples myself. :-) ) > XML always gives me a feeling that I do not fully master it (especially it's > DTD part)! And this is after two years of trying to understand it. (Cf: with > Python felt at home after a week or two!) It can often be a question of ambition, since I can imagine that many people don't really use DTDs or XML Schemas to get their work done. In any case, it isn't clear what the corresponding technology to DTD is in the Python environment - optional, but not yet invented, static type annotations? > P.S. Just look at the neighboor thread: > Subject: minidom toxml() not emitting attribute namespace qualifier > > > Using Python 2.2.3, with this example code: > > [Code elided] > > > The output is missing the "myns" namespace qualifier on the "att" > > attribute. Can someone tell me what I'm doing wrong? Could be that if one is calling setAttributeNS on an element, one has to specify the prefix as part of the name parameter - that isn't obvious and I made that mistake before I became more acquainted with the API. > That's a bug in minidom. > > I reported it back in November 2002, but I wasn't precise enough about version > numbers, so it went unaddressed. Well, I was convinced about the bug status until I looked deeper and realised that I was doing stuff wrong. Perhaps it's a documentation issue, and perhaps the maintainers of PyXML really have a lot of work to do, and perhaps it isn't easy to maintain various standard API implementations (as Andrew Kuchling suggests), but I do believe that the various XML technologies available for Python are very useful things to be familiar with, despite what people may claim. It may be the case that you don't see a need for XML in your work. In my opinion it's completely acceptable to not use XML if you find it completely irrelevant, unfathomable or opaque, but I respect your desire to become aware of what the technology can offer. I'm reminded of the occasional article written by people who ask others to "convince me why I should run Linux" - the only useful response is that if one can't see a need to try it without writing a public document asking others to persuade them, then they probably shouldn't be spending too much time worrying about it. Paul From cdreward at riaa.com Fri Jun 6 21:28:07 2003 From: cdreward at riaa.com (Chuck) Date: Sat, 07 Jun 2003 01:28:07 GMT Subject: list.index References: Message-ID: >try: > x = self.selected_points.index( self.pointmarker ) > colour = DEFAULT_SELECTED_POINT_COLOUR you spelled "color" wrong! (*grin*) From a.schmolck at gmx.net Fri Jun 6 16:08:52 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 06 Jun 2003 21:08:52 +0100 Subject: Numeric don't compare arrays correctly References: <3EDFBACD.2090802@wanadoo.es> Message-ID: Maurix writes: > Hi to all, > I'm new in python world and in this group too so, nice to meet you all ;-) > I have a problem with Numeric: (linux, python2.2, numeric 21.0) > > It seem that don't compare correctly arrays. > > See at this session: > > >>> a=array([1.1,2.2,3.3,4.4,5.5]) > >>> print 2. b can return *anything*, not just 0/False 1/True. In particular it is used. In particular, Numeric returns elementwise comparison arrays for ``array1 < array2``. My personal feeling is that allowing this was a bad idea one symptom is that it clashes with Feature 1 ( ``array1 < array2 < array3`` = ``array1 < array2 and array 2< array 3`` = ``array` < array 2`` if at least one element in array1 is smaller than in array 2 = not what you most likely want). 'as From mertz at gnosis.cx Tue Jun 3 19:12:00 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Tue, 03 Jun 2003 19:12:00 -0400 Subject: Help with coroutine-based state machines? References: <3ED622CA.4B01E3C1@hotmail.com> <3ED76105.CB8F3ECF@hotmail.com> <3EDC69DF.A46A97D4@hotmail.com> Message-ID: Alan Kennedy wrote previously: |def squares(n): | for i in xrange(n): | yield n, n*n |sqgen = squares(100) |for i, sq in sqgen(): | print "The square of %d is %d" % (i, sq) Should be: def squares(n): for i in xrange(n): yield i, i*i # <-- i sqgen = squares(100) for i, sq in sqgen: # <-- no parens print "The square of %d is %d" % (i, sq) -- 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 jjl at pobox.com Sat Jun 14 11:07:51 2003 From: jjl at pobox.com (John J. Lee) Date: 14 Jun 2003 16:07:51 +0100 Subject: [ANNOUNCE] PyKota v1.08 is out References: Message-ID: <87isr8g0jc.fsf@pobox.com> Jerome Alet writes: > I'm pleased to announce that PyKota v1.08 is out. Why do people announce to c.l.py, instead of c.l.py.announce? I'm not complaining -- it's just that, I guess, people who want to read announcements, go to the announcements group. :-) John From fredrik at pythonware.com Fri Jun 13 16:30:54 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 13 Jun 2003 22:30:54 +0200 Subject: I don't understand this regex.groups() behaviour References: <20030613183429.GA27641@pedos.es> Message-ID: Grzegorz Adam Hankiewicz wrote: > I don't understand why the last two sentences of the following > interactive session don't return more than two groups. because there are only two group markers in your expression, of course. if you want multiple matches, use findall. From sabu at pure-elite.org Sun Jun 29 19:53:25 2003 From: sabu at pure-elite.org (Xavier) Date: Sun, 29 Jun 2003 19:53:25 -0400 Subject: Re/Unresolved bug? References: <001c01c33d4d$453a9870$6401a8c0@boxen> <20030628072655.A379@tibia.amotlpaa.bogus> <006e01c33dd4$1f3d54a0$6401a8c0@boxen> <20030629124833.A487@tibia.amotlpaa.bogus> Message-ID: <001601c33e99$a17d2ec0$6401a8c0@boxen> Steven, Thanks a lot for your time and great reply -- I appreciate it greatly. -- Xavier oderint dum mutuant ----- Original Message ----- From: "Steven Taschuk" To: Sent: Sunday, June 29, 2003 2:48 PM Subject: Re: Re/Unresolved bug? > Quoth Xavier: > [top-posting fixed] > > From: "Steven Taschuk" > > > Could you post a minimal example of code which provokes this > > > behaviour? > [...] > > Thanks for your reply. Here is the exact, waiting to be fixed code: > > http://sabu.net/routekill.py > > That is very far from a minimal example. What you should do is > cut out some code, verify that the problem still exists, and > repeat until you can't cut out anything without making the problem > go away. Doing so has two advantages: first, a short example is > much more likely to provoke responses here, and second, the > process itself might teach you what the problem is. > > Having had some spare time today, I've done this for you. Here's > the (not *quite* minimal, actually) result: > > def addroutes(IP, METHOD): > global METHOD > > def main(): > global VERBOSE > VERBOSE = '1' > global VERBOSE > > print 'foo' > > On my machine, with 2.2.2 this code issues the SyntaxWarning and > then segfaults, and on 2.3 issues the SyntaxWarning and dies > without printing 'foo'. > > There are two things wrong with this code. To get it running, > first remove the second global statement for VERBOSE. Once that's > done, the code will start producing > SyntaxError: name 'METHOD' is local and global > Thus the second thing you need to do is to decide whether you want > METHOD to be an argument to addroutes() or a global variable to > that function, and then either remove the global statement or > emend the argument list. > > Once you've done these two things the code will run; I leave > determining whether it works to you. > > (Python's reaction to this code *is* buggy -- it seems that the > SyntaxWarning interferes with the SyntaxError somehow. (My > original suspicion that the SyntaxWarning was irrelevant was > wrong.) I'll be looking into this today.) > > -- > 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) > > -- > http://mail.python.org/mailman/listinfo/python-list > From wester at ilt.fhg.de Fri Jun 6 12:03:45 2003 From: wester at ilt.fhg.de (Rolf Wester) Date: Fri, 06 Jun 2003 18:03:45 +0200 Subject: Socket Problem on True64 Alpha Message-ID: Hi, I just tried the socket server examples that are in the Python docs on a Tru64 Alpha machine. My Python version is 2.2.1. Unfortunately these examples don't work. This: import socket HOST = '' # Symbolic name meaning the local host PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) gives the error message: Traceback (most recent call last): File "server.py", line 7, in ? s.bind((HOST, PORT)) socket.gaierror: (9, 'The service passed was not recognized for the specified socket type.') and this: import socket import sys HOST = '' # Symbolic name meaning the local host PORT = 50007 # Arbitrary non-privileged port s = None for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,socket.AI_PASSIVE): results in: Traceback (most recent call last): File "socket2.py", line 8, in ? for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE): socket.gaierror: (8, 'Name does not resolv to supplied parameters; neither nodename nor servname were passed.') I don't have any idea what is wrong here. I would be very appreciative for any help. Thanks in advance Rolf Wester From exarkun at intarweb.us Wed Jun 25 13:20:26 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Wed, 25 Jun 2003 13:20:26 -0400 Subject: Newbie Question: can this snippet be optimized? In-Reply-To: <3ef9ba07.117801375@news.skynet.be> References: <3ef9ba07.117801375@news.skynet.be> Message-ID: <20030625172026.GB26272@meson.dyndns.org> On Wed, Jun 25, 2003 at 03:08:00PM +0000, Hedr at intarweb.us wrote: > Hi Pythonians, > > The underlying snippet is copied from minidom.py which is in the XML > package which I am currently using. Cloning nodes seem to take a > considerable amount of time, hence I went looking in the code whether > optimizations could be made. The following snippet contains a for > loop: > > def cloneNode(self, deep): > clone = Node.cloneNode(self, deep) > clone._attrs = {} > clone._attrsNS = {} > for attr in self._attrs.values(): > node = attr.cloneNode(1) > clone._attrs[node.name] = node > clone._attrsNS[(node.namespaceURI, node.localName)] = node > node.ownerElement = clone > return clone Using "itervalues" instead of "values" may produce some minor improvement. values() creates a new list object containing references to all the values in the dictionary, while itervalues() only creates a very light-weight iterator. 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" From zephyr01 at alltel.net Fri Jun 13 19:51:20 2003 From: zephyr01 at alltel.net (Hans Nowak) Date: Fri, 13 Jun 2003 19:51:20 -0400 Subject: getFoo1() vs. class.foo1 In-Reply-To: References: Message-ID: <3EEA6378.1070206@alltel.net> Manuel wrote: > Hi, I'm python beginner. > My first class is very simple, like > > class VerySimple: > foo1 = 1 > foo2 = 2 > foo3 = 3 > etc... > > Any professional developers tell me that > I must use get and set (to private variable) > method instead. They're wrong. :-) It's possible to define private attributes, kind of, but Python doesn't encourage it, and often you don't need it. But that's a discussion for another time. Besides that, this is how you usually add and initialize attributes: class VerySimple: def __init__(self): self.foo1 = 1 self.foo2 = 2 self.foo3 = 3 These are instance attributes; attributes like class VerySimple: foo1 = 1 are class attributes, which are shared by all instances of that class. > class VerySimple: > __foo1 = 1 > __foo2 = 2 > __foo3 = 3 > > def getFoo1(self): > return __foo1 By the way, this code won't work, because __foo1 isn't known inside the body of method getFoo1. Ditto for the other methods. To set a class attribute, use something like self.__class__.foo = 'bar' HTH, From eric at enthought.com Fri Jun 27 18:08:02 2003 From: eric at enthought.com (eric jones) Date: Fri, 27 Jun 2003 17:08:02 -0500 Subject: [ANN] SciPy '03 -- The 2nd Annual Python for Scientific Computing Workshop Message-ID: <015701c33cf8$96be3670$8901a8c0@ERICDESKTOP> Hey folks, I've been postponing this announcement because the registration page isn't active yet. It's getting late though, and I thought I'd at least let you know SciPy '03 is happening. I'll repost when registration is open. Thanks, Eric ------------------------------------------------------- SciPy '03 The 2nd Annual Python for Scientific Computing Workshop ------------------------------------------------------- CalTech, Pasadena, CA September 11-12, 2003 http://www.scipy.org/site_content/scipy03 This workshop provides a unique opportunity to learn and affect what is happening in the realm of scientific computing with Python. Attendees will have the opportunity to review the available tools and how they apply to specific problems. By providing a forum for developers to share their Python expertise with the wider industrial, academic, and research communities, this workshop will foster collaboration and facilitate the sharing of software components, techniques and a vision for high level language use in scientific computing. The cost of the workshop is $100.00 and includes 2 breakfasts and 2 lunches on Sept. 11th and 12th, one dinner on Sept. 11th, and snacks during breaks. Online registration is not available yet, but will be soon. We would like to have a wide variety of presenters this year. If you have a paper you would like to present, please contact eric at enthought.com. Discussion about the conference may be directed to the SciPy-user mailing list: Mailing list page: http://www.scipy.org/MailList Mailinbg list address: scipy-user at scipy.org Please forward this announcement to anyone/list that might be interested. ------------- Co-Hosted By: ------------- The National Biomedical Computation Resource (NBCR, SDSC, San Diego, CA) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ http://nbcr.sdsc.edu The mission of the National Biomedical Computation Resource at the San Diego Supercomputer Center is to conduct, catalyze, and enable biomedical research by harnessing advanced computational technology. The Center for Advanced Computing Research (CACR, CalTech, Pasadena, CA) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ http://nbcr.sdsc.edu CACR is dedicated to the pursuit of excellence in the field of high-performance computing, communication, and data engineering. Major activities include carrying out large-scale scientific and engineering applications on parallel supercomputers and coordinating collaborative research projects on high-speed network technologies, distributed computing and database methodologies, and related topics. Our goal is to help further the state of the art in scientific computing. Enthought, Inc. (Austin, TX) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ http://enthought.com Enthought, Inc. provides scientific and business computing solutions through software development, consulting and training. ---------------------------------------------- eric jones 515 Congress Ave www.enthought.com Suite 1614 512 536-1057 Austin, Tx 78701 From tertiusc at netscape.net Thu Jun 19 17:49:02 2003 From: tertiusc at netscape.net (Tertius) Date: Thu, 19 Jun 2003 23:49:02 +0200 Subject: sqlite select max() on integer field returns quoted value References: <3EF0D8CB.6010203@netscape.net> <3EF0DA8E.5060800@netscape.net> Message-ID: <3EF22FCE.5050908@netscape.net> Thanks Graham...It does work yes. Also for the explanation of the "max() type". I just presumed that the type of the column in question would be returned. Guess i'll have to pay more attention to sqlite *types* :) Tertius Graham Fawcett wrote: > Does this work? > > cnx = connect('db') > c = cnx.cursor() > c.execute('-- types int') > c.execute('select max(id) from table') > > Check out: > http://pysqlite.sourceforge.net/documentation/pysqlite/node10.html > > "SQLite is typeless. It stores all data as text. However, all data > returned from PySQLite are cast into their respective Python types as > declared in the database schema, provided that said types are standard > ANSI SQL type (e.g. VARCHAR, INT, FLOAT, etc.)." > > Based on this, my guess is that PySQLite is having trouble figuring > out what the type of a max() result ought to be, since max is not in > your schema (of course). > > -- Graham From bokr at oz.net Sat Jun 21 03:09:21 2003 From: bokr at oz.net (Bengt Richter) Date: 21 Jun 2003 07:09:21 GMT Subject: Newbie wordnet and pywordnet References: <9c1c646f.0306201734.7aced3b0@posting.google.com> Message-ID: On 20 Jun 2003 18:34:37 -0700, dwimansjur at hotmail.com (Dwi Sianto Mansjur) wrote: >I am trying to use pywordnet in window environment. >After extracting pywordnet into python folder, I am not sure how to >include the wordnet database so that python recognize it. > >Running a simple example, I got the following error message. >>>>N['dog'] >Traceback (most recent call last): > File "C:\Python23\o90.py", line 5, in ? > N['dog'] >NameError: name 'N' is not defined > >thanks in advance... Suggest typing help('wordnet') which will tell you to import thus: from wordnet import * after which N['dog'] should work, if everything was installed ok. If it wasn't, read INSTALL.txt and README.txt from your downloaded archive (pywordnet-1_4.zip ?) If that doesn't get you there, we'll have to try again ;-) Regards, Bengt Richter From LogiplexSoftware at earthlink.net Fri Jun 6 18:58:03 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 06 Jun 2003 15:58:03 -0700 Subject: Is Python lightweight? In-Reply-To: <8b336527.0306061439.72d23063@posting.google.com> References: <8b336527.0306061439.72d23063@posting.google.com> Message-ID: <1054940283.2139.235.camel@software1.logiplex.internal> On Fri, 2003-06-06 at 15:39, kk wrote: > I just read a comment to an article claiming that an application > sucked, and the reason was because it was written in Python. It went > on to say that it pulls in some 40MB (I assume into memory), and > insinuated that it was "bloat-ware". In case you really care, the > application they were talking about is Redhat's "Up To Date" (software > update tool). Was this on a RH mailing list? Which one? I haven't flamed anyone on any of the RH lists in a couple of weeks and this seems like a good time to get back into the swing . There are a disproportionate number of monkeys pounding on keyboards on a few of those lists. I'd always thought Linux users would be... well, never mind. Apparently the surge in Linux popularity has its downside as well. > I know this is a silly argument, and I should forget about it. > However, I really have fallen in love with Python even though I > haven't been doing it very long. So, I've been thinking... How would > you measure the amount of "bloat" that an application has, on windows? > On Linux? Has anyone compared the Python interpreter "foot-print" to > Java, Perl, PHP, VB, etc... I guess if you had a GUI then you would > have to add the size of the GUI libraries (and with Tk, the TCL > interpreter). Bloatware can be written in any language. Most likely they are keeping huge amounts of data in RAM (dependency trees?) and this has little to do with Python. Of course, the alternative to bloatware is often noware. If RH wasn't using Python for a lot of their administrative tools (and installer) then it seems quite likely that a large number of those tools wouldn't even exist. I can only imagine how complicated up2date would be were it written in C. > Anyway, my question is, how can I measure this for myself? Start Python (without running any Python scripts). Check memory usage. Anything above and beyond that is the application's fault. Well, not entirely, but you get the idea. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From missive at frontiernet.net Tue Jun 17 18:32:11 2003 From: missive at frontiernet.net (Lee Harr) Date: Tue, 17 Jun 2003 22:32:11 GMT Subject: Looking for Info on installing Python and wxPython on a disk. References: Message-ID: In article , Pat wrote: > Hello, I've been trying to find it myself but no luck yet. The problem is > that a friend of mine uses a library computer and is not allowed to install > anything on it. He wants to know if there is a way to install python, > wxpython and another program on a cd and be able to run it from a windows os > machine. I told him that I would look around and see what I can find out. > Neither of us are very good programmers, still learning the basics of python > myself and he wants to start. > > If any one can point me to the site, I would be very grateful. > You should look at knoppix: http://www.knopper.net/knoppix/index-en.html Doesn't look like it has wx, but it has a ton of other interesting things: http://download.linuxtag.org/knoppix/packages.txt You could probably figure out how to get wx in there too. The best part is that it starts to free you from windows. From mis6 at pitt.edu Sun Jun 8 08:04:30 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 8 Jun 2003 05:04:30 -0700 Subject: a = b = 1 just syntactic sugar? References: <2259b0e2.0306070837.789f2a9f@posting.google.com> Message-ID: <2259b0e2.0306080404.47f621bf@posting.google.com> Ed Avis wrote in message news:... > A couple more anomalous cases could be cleaned up by adding dict.set > as a counterpart of dict.setdefault Am I mistaken or you want dict.__setitem__ ? Michele From gh at ghaering.de Sat Jun 7 13:30:21 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 07 Jun 2003 19:30:21 +0200 Subject: Play a short sound... In-Reply-To: References: Message-ID: <3EE2212C.9000409@ghaering.de> Manuel wrote: >>No, only windows platforms > > > :-( > > It's strange...no sound libraries under linux?? Of course there are, just not in the standard library. Wait, there's even a Linux-specific module in the standard library: 'linuxaudiodev', but it's pretty low-level. This again is Linux-specific and won't work on other Unix-like operating systems, like FreeBSD or NetBSD, or Solaris, ... Of course there are many third-party modules not in the standard library that can be used for audio output. I only ever used the one in pygame just for fun. Many of these work cross-platform. Perhaps snack is what you want: http://www.speech.kth.se/snack/ """ [...] Multi-platform, same scripts usable on Windows 95/98/NT/2K/XP, Linux, Macintosh, Sun Solaris, HP-UX, FreeBSD, NetBSD, and SGI IRIX. [...] """ HTH, -- Gerhard From printers at sendme.cz Fri Jun 13 16:52:16 2003 From: printers at sendme.cz (A) Date: Fri, 13 Jun 2003 22:52:16 +0200 Subject: Is it possible to change Content-type? Message-ID: <3EEA55A0.4615.E54103@localhost> Hi, Suppose we have the following form:

What is your name?
What files are you sending?
If the user enters "Larry" in the text input, and selects the text file "file1.txt", the user agent might send back the following data: Content-Type: multipart/form-data; boundary=AaB03x --AaB03x Content-Disposition: form-data; name="submit-name" Larry --AaB03x Content-Disposition: form-data; name="files"; filename="file1.txt" Content-Type: text/plain ... contents of file1.txt ... --AaB03x-- Is it possible to simulate the behaviour of the user agent and use Content-type: application/x-www-form-urlencoded and send the data as submit-name=Larry&files"; filename="file1.txt" Content-Type: text/plain That is the data will be in the form of Name1=Value1&Name2=Value2 Thanks for help Ladislav From patrick at cs.ualberta.ca Mon Jun 16 15:03:19 2003 From: patrick at cs.ualberta.ca (Patrick Earl) Date: Mon, 16 Jun 2003 13:03:19 -0600 Subject: Diamond inheritance with str Message-ID: Hi. I have the need to inherit from multiple classes that share the same base class. This base class is a built in type like str, list, float, or int. The following works: >>> class A(list): pass ... >>> class B(list): pass ... >>> class C(A,B): pass ... >>> It also seems to work for int and float. However, the following does not work: >>> class A(str): pass ... >>> class B(str): pass ... >>> class C(A,B): pass ... Traceback (most recent call last): File "", line 1, in ? TypeError: multiple bases have instance lay-out conflict Why doesn't this inheritance structure work for strings? Is this a bug? Is there a good way to work around this? Using UserString allows the inheritance, but I thought that UserString was considered obsolete due to the ability to subclass built-in types. I appreciate any thoughts on the matter. Thanks. :) Patrick PS. My apologies if this is a duplicate. I'm pretty sure it's not, but I made a posting to python-list at python.org that didn't appear to go through. From aleax at aleax.it Tue Jun 17 03:11:38 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 17 Jun 2003 07:11:38 GMT Subject: passing a C struct to Python and back References: Message-ID: Kevin wrote: > In a Python extension module, I have a struct that I need to pass to > Python, > then back into the extension module later for use. Python doesn't need to > do anything with the struct in the meantime though. > > I'm trying to do it using a CObject through the following, but > PyCObject_AsVoidPtr() returns a void*, not a struct... Right, a void*, i.e. "a pointer to anything". In particular, therefore, it can be a pointer to the struct you want to pass back and forth (it can live on the heap or in statical-lifetime memory -- not on the C stack, obviously). > Is there an easy way to do this? Creating a new Python type seems like a > big pain in the butt for something as "simple" as this. There are many easy ways. One is via a void*, as above. Another is to pass back and forth a string of bytes instead -- PyString_FromStringAndSize to build the string object, PyString_AsString to get back the pointer to the buffer area (as a char* to be cast) -- you shouldn't use this one if you want your C code to modify the struct after it's been passed to Python (strings should be immutable!). Returning a tuple of the struct's fields is another possibility (tuples are immutable, too), requiring more work to pack and unpack (wasted work if Python will never need to access the individual fields). You could also use a "buffer object", as documented at URL http://www.python.org/doc/current/api/bufferObjects.html -- not a very fashionable solution nowadays but perhaps the simplest q&d fix to your problem. PyBuffer_FromReadWriteMemory to build (in order to use the struct's own memory for the buffer -- this needs a struct that won't just go away, e.g. by living on the stack;-) or PyBuffer_New if the buffer must maintain its own memory -- and you can use the PyBufferProcs (see http://www.python.org/doc/current/api/buffer-structs.html) to get the pointer to the buffer's start (e.g. to memcpy the struct at start, &tc). As I said -- plenty of choices... Alex From rickfrm at optusnet.com.au Wed Jun 11 06:15:27 2003 From: rickfrm at optusnet.com.au (Rick Miles) Date: Wed, 11 Jun 2003 20:15:27 +1000 Subject: idle /idlefork slackware In-Reply-To: References: Message-ID: <200306112015.27053.rickfrm@optusnet.com.au> On Wed, 11 Jun 2003 01:30 pm, Todd Stephens was bold enough to write:: > This was brought up on the Tutor mailing list last week, actually. No, > Idle is not included in the Slackware Python packages, and several other > Python "goodies" are also left out. It is pretty much as bare-bones a > package as you could get by with. An email was forwarded to Pat V, but I > doubt he is overly concerned with the Python package. I suppose you could > uninstall the default package, download the source tarball, do a configure > and make, then do makepkg on it, then install it. That way you would get > the full Python install and it would be registered in the package manager. > Personally, I don't use Idle that much. I usually run KDE and use Kate. > Thanks Todd, Just what Python packages and "goodies" should I be looking to install if I were to go for Idle on Slack instead of using Kate? Kate was a surprise, never used it before as I usually use mcedit, sometimes, kedit, and wxpe when I ocasionally mess with C. TIA -- Rick Miles ################################################### A silver bowl filled with snow And a heron hidden in moonlight Are similar but not the same; Put them together and they are distinct. From CousinStanley at hotmail.com Mon Jun 16 13:42:29 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Mon, 16 Jun 2003 10:42:29 -0700 Subject: Python as a Language Choice Message-ID: Someone in another NewsGroup asked why I had picked Python as a language of choice ... I offered the following reply and would be interested in hearing from others of any obvious ommisions that I may have made and as to why they might have chosen Python as well ... Stanley C. Kitching ------------------------------------------------------------ I've been programming other languages since about 1966 but am a relative Python rookie having used it for only a little over a year ... As for Python as a language of choice, I would include the following ... o Free ... Open-Source ... Cross-Platform ... o Easy to learn, easy to use, and VERY readable ... o Power/Punch ratio is fairly high ... That is, get a lot of work done in only a few lines of code ... o Very active and friendly development community centered in comp.lang.python where one can read and learn from daily posts by the authors themselves of popular and current Python books and modules ... o Large and diverse set of Application Programming Interfaces available in many areas ... o Multiple choice for GUI programming ... [ Tk | GTK | QT | wxPy | others ... ] o Core languange is readily extensible through and embeddable in other languages ... -- Cousin Stanley Human Being Phoenix, Arizona From fredrik at pythonware.com Tue Jun 10 16:34:36 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Jun 2003 22:34:36 +0200 Subject: Access "slot" field dynamically? References: <9boFa.674$Hw.872301@news2.news.adelphia.net> Message-ID: Robert Oschler wrote: > I've read the the same comment but I like the bug-prevention aspects of it > too much to not use it and it doesn't seem to harm anything. except performance: http://www.python.org/~jeremy/weblog/030506.html From listbox at cybereal.org Sun Jun 15 19:56:14 2003 From: listbox at cybereal.org (Zac Jensen) Date: Sun, 15 Jun 2003 17:56:14 -0600 Subject: Cannot build Tk under RedHat In-Reply-To: <3EECF794.3030700@zg.hinet.hr> References: <3EECF794.3030700@zg.hinet.hr> Message-ID: <200306151756.18239.listbox@cybereal.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Sunday 15 June 2003 04:47 pm, Haris Bogdanovic wrote: > I get some errors while trying to build Tk and because of that Python's > IDLE won't start. > How should configure and build steps look like to properly build Tk ? > > Thanks > Haris Try a Tk help forum? - -Zac -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) iD8DBQE+7QehV3L7YsSif1URAgt9AJwL96VOpf0tks/Psyhw+Q8dfbstQgCfQkf0 e6xezlaNrmafXnQRGjxittM= =j8en -----END PGP SIGNATURE----- From skip at pobox.com Fri Jun 20 09:24:51 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 20 Jun 2003 08:24:51 -0500 Subject: sourceforge problems In-Reply-To: References: Message-ID: <16115.2851.995073.486228@montanaro.dyndns.org> Robin> There are thousands of projects hosted at sf.net and it seems it Robin> has become a single point of failure for open source. Is it a Robin> good idea. Maybe Microsoft should buy SF? Skip From frobozz_electric at hotmail.com Tue Jun 10 15:36:34 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 10 Jun 2003 19:36:34 GMT Subject: You know you're a Pythonista when.. References: Message-ID: ... the $ight of $igil$ m at kes you $ick to your $tom at ch From andrew-pythonlist at puzzling.org Tue Jun 3 09:11:51 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 3 Jun 2003 23:11:51 +1000 Subject: Passing data into my StreamRequestHandler? In-Reply-To: <3edc96a6$1@mail.hmgcc.gov.uk> References: <3edc96a6$1@mail.hmgcc.gov.uk> Message-ID: <20030603131151.GA12900@frobozz> On Tue, Jun 03, 2003 at 01:37:58PM +0100, Richard wrote: > Hi, > > I have a TCP Server class using SocketServer.TCPServer( ) and a handler > class which inherits from SocketServer.StreamRequestHandler. When an > incoming connection is made, the overridden handle( ) function gets called > which is fine, however can anyone tell me how I go about passing data into > the handler object from my server object? I don't remember enough about SocketServer to remember how to do exactly what you asked, but.... > Here is my code: > > import SocketServer > > class ConnectionEndpointHandler(SocketServer.StreamRequestHandler): > > def handle(self): > print "Connected!" > > class sServer: > > m_InAddress = [] > m_OutAddress = [] > > def __init__(self, inAddress): > self.m_InAddress = inAddress > > def start(self): > m_Server = SocketServer.TCPServer((self.m_InAddress[0], > int(self.m_InAddress[1])), ConnectionEndpointHandler) > m_Server.serve_forever() In Twisted, this looks like: ---- from twisted.internet.protocols import Protocol, ServerFactory from twisted.internet import reactor class MyProtocol(Protocol): def connectionMade(self): print "Connected!" # Write greeting defined in my factory self.transport.write(self.factory.greeting) class MyFactory(ServerFactory): protocol = MyProtocol greeting = 'Homer says: "Welcome to the Internet!"\n' def start(port): reactor.listenTCP(port, MyFactory()) reactor.run() ---- In Twisted, you put a Factory on a port to listen for connections, and build Protocol instances for each incoming connection, so (unless you're intentionally doing something wacky) a Protocol instance corresponds to exactly one connection. [By default, a factory's buildProtocol handler is: def buildProtocol(self, addr): p = self.protocol() p.factory = self return p so that protocols have access to their factory] There are probably similar hooks you can use in SocketServer, but I'd recommend Twisted anyway, as it's a much richer framework. > Also, as it currently stands (I have another file which just creates an > instance of my sServer, provides the inAddress and calls start( ) ) this > just continually runs, printing 'Connected' every time I make a connection > to it. I know that serve_forever( ) does this, but can anyone tell me how I > interrupt this to exit the program? I am running on Win2K and CTRL-C doesn't > seem to work, meaning I am forced to close down the console window. On Win2K, Ctrl-C won't interrupt a call to select.select, and I expect this (or something similar, like perhaps a blocking call to socket.accept) is what is happening to you. You may find Ctrl-Break works (so long as a SIGBREAK handler hasn't been installed), or that hitting Ctrl-C then connecting to your server will work (because this wakes up the select call). You'll see the same problem if you run your code as an NT service using Mark Hammond's win32all package, and try to stop the service. Twisted on Win32 has a timeout on its select call (5 seconds, iirc) to workaround this exact same problem. I'm not sure if there's any easy way to apply the same trick to SocketServer. -Andrew. From bokr at oz.net Thu Jun 12 12:43:35 2003 From: bokr at oz.net (Bengt Richter) Date: 12 Jun 2003 16:43:35 GMT Subject: can we have a filecmp.cmp() that accept a different buffer size? References: <3EE837DC.5080802@nospam.com> Message-ID: On Thu, 12 Jun 2003 08:20:39 GMT, Kendear wrote: >filecmp.cmp() uses a BUFSIZE of 8k to compare. >For files that are 500MB, the hard disk is really >busy, going back and forth, while my 512MB RAM is >sitting there, sipping margarita. Can we have a >version of filecmp.cmp() (and filecmp's other >methods) that accepts a BUFSIZE, such as 1MB or more? > I haven't used it, but as a quick hack, what happens if you import filecmp and just set filecmp.BUFSIZE to whatever you want before using the functions? Regards, Bengt Richter From max at alcyone.com Tue Jun 24 17:34:19 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 24 Jun 2003 14:34:19 -0700 Subject: shebang strange thing... References: <3EF3A07B.A683F94F@alcyone.com> <3EF7A121.7B4C3775@alcyone.com> <7PG++ks/KrDI089yn@the-wire.com> Message-ID: <3EF8C3DB.959B9252@alcyone.com> Mel Wilson wrote: > From another angle, I've been using the program ws-ftp to > move files betweem M$ systems and *nix systems, and it fixes > all the line-end problems for me. I only get bitten now if I > move files another way. Any FTP program will work, if you transfer them in ASCII mode. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I just want to create my own life. I can just be me. \__/ Ekene Nwokoye From ss3canon at earthlink.net Thu Jun 26 23:18:34 2003 From: ss3canon at earthlink.net (Mike) Date: Fri, 27 Jun 2003 03:18:34 GMT Subject: List of lists References: Message-ID: Sorry, must of hit crtl v a couple times. From a.schmolck at gmx.net Fri Jun 6 10:14:00 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 06 Jun 2003 15:14:00 +0100 Subject: Loop over list of pairs References: Message-ID: sismex01 at hebmex.com writes: > > def xgroup(iter,n=2): > > """ > > >>> list(xgroup(range(9), 3)) > > [(0, 1, 2), (3, 4, 5), (6, 7, 8)] > > """ > > last = [] > > for elt in iter: > > last.append(elt) > > if len(last) == n: yield tuple(last); last = [] > > > Since 'n' is known from the start you don't need to > test against it, nor build a list piecemeal. Something > like this seems a bit more solid: > > def xgroup(Iterable, group=2): > """Return a groupwise iterator for Iterable.""" > Iterator = iter(Iterable) > Length = range(group) > while 1: > yield [ Iterator.next() for i in xrange(group) ] Indeed, thanks. In addition, `iter` is also a somewhat poor choice of name. Which I guess goes to show that cutting and pasting some code from somewhere for a usenet should always prompt a second look at it to avoid embarrassment :) So I updated my version to this (which uses a precomputed xrange object for a gain in efficiency, as you clearly intended, but didn't actually do). def xgroup(it, n=2): assert n>1 # ensure it doesn't loop forever it = iter(it) perTuple = xrange(n) while 1: yield tuple([it.next() for i in perTuple]) 'as From bill.allie at mug.org Sat Jun 28 16:17:23 2003 From: bill.allie at mug.org (Billy G. Allie) Date: Sat, 28 Jun 2003 16:17:23 -0400 Subject: OverflowError in pyPgSQL when accessing tables with many rows In-Reply-To: References: Message-ID: <3EFDF7D3.3080801@mug.org> Paolo Alexis Falcone wrote: >Whenever I try to access a table with many rows using PgSQL's >fetchall(), this happens: > > >>>>from pyPgSQL import PgSQL >>>>db = PgSQL.connect("192.168.0.8:5432:whitegold","dondon","dondon") >>>>PgSQL.NoPostgresCursor = 1 >>>>cur = db.cursor() >>>>cur.execute("SELECT * FROM customer") >>>>data = cur.fetchall() >>>> >>>> >Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/site-packages/pyPgSQL/PgSQL.py", line 3106, >in fetchall > return self.__fetchManyRows(self._rows_, _list) > File "/usr/lib/python2.2/site-packages/pyPgSQL/PgSQL.py", line 2684, >in __fetchManyRows > _j = self.__fetchOneRow() > File "/usr/lib/python2.2/site-packages/pyPgSQL/PgSQL.py", line 2660, >in __fetchOneRow > _r.getvalue(self._idx_, _i))) > File "/usr/lib/python2.2/site-packages/pyPgSQL/PgSQL.py", line 717, >in typecast > return PgNumeric(value, _p, _s) > File "/usr/lib/python2.2/site-packages/pyPgSQL/PgSQL.py", line 1335, >in __init__ > raise OverflowError, "value too large for PgNumeric" >OverflowError: value too large for PgNumeric > >The aforementioned table, customer, only has 1023 entries with the >following structure: > >CREATE TABLE customer (ccustcode varchar(80), cgroupcode varchar(10), >clastname varchar(80), cfirstname varchar(80), cmi varchar(10), >ccompany varchar(80), caddress1 varchar(80), caddress2 varchar(80), >ccity varchar(80), cprovince varchar(80), czipcode varchar(10), iterms >integer, ycredit_limit numeric, npenalty_rate numeric, >default_routecode varchar(10), lisdirector boolean); > >PgSQL's fetchone() fortunately works though, as well as using >fetchall() on tables with few rows. Is there any alternative way of >using PyPgSQL that would not overflow in this situation? > Paolo, The problem is not the number of rows, but the fact the conversion of a PostgreSQL numeric to a PgNumeric is failing. This problem has been fixed in the code in the CVS repository for the pyPgSQL project on SourceForge. We will also be releaseing a new version of pyPgSQL within the next couple of weeks. -- ___________________________________________________________________________ ____ | Billy G. Allie | Domain....: Bill.Allie at mug.org | /| | 7436 Hartwell | MSN.......: B_G_Allie at email.msn.com |-/-|----- | Dearborn, MI 48126| |/ |LLIE | (313) 582-1540 | -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Thu Jun 12 10:31:58 2003 From: grante at visi.com (Grant Edwards) Date: 12 Jun 2003 14:31:58 GMT Subject: Octets calculation? References: <65eFa.634621$Si4.577158@rwcrnsc51.ops.asp.att.net> <3EE79F73.E08C2554@alcyone.com> Message-ID: <3ee88ede$0$645$a1866201@newsreader.visi.com> In article , Skip Montanaro wrote: > >> In the real world, nobody ever uses it to mean anything other than 8 > >> bits. > > Erik> That's simply not true. Take embedded systems, for examples, > Erik> where it's not at all uncommon for a byte to be 16 or 32 bits. > > It's not uncommon for a machine word to be 16 or 32 bits, but it's rare > these days for a byte to be anything other than 8 bits. It's not rare in the DSP world. TI's line of FP DSPs all had 32-bit bytes. Where "byte" is used in the sense of the "C" standard as the smallest unite of addressable memory. There are quite a few integer DSPs with 16 and 24 bit "bytes". -- Grant Edwards grante Yow! I just got my PRINCE at bumper sticker... But now I visi.com can't remember WHO he is... From bokr at oz.net Sat Jun 28 18:35:30 2003 From: bokr at oz.net (Bengt Richter) Date: 28 Jun 2003 22:35:30 GMT Subject: code suite as first class object ? Message-ID: Useless example first: def foo(x): a = suite: y = 1 b = suite: y = 2 a() # equivalent effect to local y = 1 above (a,b)[bool(x)]() # effect of suite b if bool(x), otherwise suite a vars()[x]() # succeeds if x in ['a', 'b'] return y Since binding of the result of suite: is in the form of an assignment, it would also be possible to create a switch with anonymous suites directly, e.g., switch = [0]*2 switch[0] = suite: z = 3 switch[1] = suite: z = 4 ... switch[expr]() or named ones in a chosen directory (of course the name 'switch' has no special status ;-) shazam={} shazam['one'] = suite: print 'suite one' shazam['two'] = suite: print 'suite two' ... shazam[suitename]() # or use shazam.get variations if desired or as attributes? class NS(object): pass doatt = NS() ... doatt.one = suite: print 'doatt_one' doatt.two = suite: print 'doatt_two' ... doatt.two() getattr(doatt, attname)() (IWT bindings in potentially non-local namespaces would generally require closures, whereas the vars()[suitename]() usage should not, unless vars() is exported (?)). The above suites are obviously braindead placeholders. I.e., anything legal as a "suite" should be legal, including nested suites both old and new (i.e., under e.g., "if expr:" or "s=suite:") Note that suite: does not introduce a new (name) scope, though one suite object can be invoked from the body of another. I'm not sure how much new stuff this would introduce into stack-unwinding for exceptions, but it feels like there ought to be a way to do better than ignoring suite calls as being internal to a frame ... Implementation would be a parameterless function which uses the *current* local namespace as its local space. I.e., no separate frame, just a byte code to execute a local function (pushing return byte code location) and another to return (popping byte code location and jumping there). This would get the performance benefit of sequence indexing or dict lookup vs if/elif/else equivalents without incurring full function call overhead. I posted something similar before (not the exception thing ;-), but I think this is a little better. I haven't thought through the closure issues, but there ought to be a way to handle them, IWT. Anyone have a real-life example of a long chain of elifs that could be recoded for realistic comparison? BTW, maybe "localfun" or "localcode" or "codeblock" would be better words than "suite"? Of course, this is just HOTTOMH, so fire away and shoot it full of holes ;-) Maybe if something survives the flames, it could be useful. Regards, Bengt Richter From bignose-hates-spam at and-zip-does-too.com.au Sun Jun 22 19:10:08 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Sun, 22 Jun 2003 23:10:08 GMT Subject: newbie: good reasons for learning Python? References: <3ef37a28$0$306$ba620e4c@reader0.news.skynet.be> <_njJa.306597$3n5.22662@news2.central.cox.net> Message-ID: On Sun, 22 Jun 2003 14:51:38 GMT, Steve Holden wrote: > "Mel Wilson" wrote: >> 's'[:i != 1] >> is a cute way to generate the plural endings. > > ... in English ... and is far more "cute" than it is "maintainable" or "readable". -- \ "I don't know half of you half as well as I should like, and I | `\ like less than half of you half as well as you deserve." -- | _o__) Bilbo Baggins | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From mcherm at mcherm.com Wed Jun 4 12:13:33 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 4 Jun 2003 09:13:33 -0700 Subject: Possible PEP: Improve classmethod/staticmethod syntax Message-ID: <1054743213.3ede1aad2784c@mcherm.com> Skip writes: > There ya go. My original post contained this disclaimer: > > (FYI, the above is just right off the top of my sleep-starved brain. > I'm sure it's full of holes.) Of course. The interesting thing here is not that you might have missed this possibility, but that this descriptor thing is turning out to be particularly powerful. I was warry of it at first, but am beginning to become convinced that it is useful enough to be worth adding to the language. I guess in the end it's as they say: "there's only one trick in computer science... adding another layer of indirection". But it's a very powerful trick. -- Michael Chermside From manuelbastioni at tin.it Fri Jun 20 17:36:07 2003 From: manuelbastioni at tin.it (manuel) Date: Fri, 20 Jun 2003 21:36:07 GMT Subject: os.listdir() References: Message-ID: > It's written in C, in Modules/posixmodule.c. os.py >imports it. Thanks. Exist another method to read the files in a directory? I want write a script for Blender, and because the OS module isn't builtin, and I've need only this function, I want write a very simple python class to read only the files in a dir. It's possible? From mis6 at pitt.edu Mon Jun 9 15:04:02 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 9 Jun 2003 12:04:02 -0700 Subject: Thoughts on cooperative methods References: Message-ID: <2259b0e2.0306091104.1d9336d0@posting.google.com> hellen at claggetts.net (Jonathan Claggett) wrote in message news:... > I've recently played around with using cooperative methods in python > via the new super function and I wanted to bounce some of my thoughts > off the python community as a sanity check. So with no particular > rhyme and reason: > > 1) When you've got cooperative methods that are 'public' (i.e., called > from outside of the class), it is generally a good idea to refactor > your method into two new methods: a private cooperative method and a > public non-cooperative method. This is because the parameters of > cooperative methods are more constrained than normal method (since > they are cooperating). For example: > > class A(object): > def __init__(self, arg1): > print arg1 > > class B(A): > def __init__(self, arg1, arg2): > super(B, self).__init__(arg1): > print arg2 > > is refactored into: > > class A(object): > def __init__(self, arg1): > self.c_init(arg1=arg1) > def c_init(**dic): > print dic['arg1'] > > class B(A): > def __init__(self, arg1, arg2): > self.c_init(arg1=arg1, arg2=arg2) > def c_init(self, **dic): > super(B, self).c_init(**dic) > print dic['arg2'] > > 2) The existing super() is limited in that you have to explicitly call > it at every level or the chain of cooperation stops. In the code > above, the method A.c_init can't call super() since there is no c_init > method explicitly defined above it. This limitation means that it is > tricky to use cooperative methods with mixins or other classes. for > example: > > class Mixin(object): > def __init__(self **dic): > self.c_init(**dic) > def c_init(self, **dic): > print dic > super(Mixin, self).c_init(**dic) > > class C(Mixin, B): pass # works > class C(B, Mixin): pass # breaks, will never call Mixin.c_init > m = Mixin(arg1=1, arg2=2) # breaks, super() raises an error > > 3) The existing super() feels awkward to use with all of its > parameters and I'm hoping to see a proper super keyword in a future > release of python. It just seems like a hack at this point (not that > I'm morally opposed to hacks or anything ;-). > > 4) Finally, as an experiment, I've developed an entirely different > approach to cooperative methods which removes the chaining limitation > above and has a slightly less awkward syntax. This approach uses > generators and yes, this is a hack and no, I'm not suggesting its use > for production work. However, I do think it is a good template for how > the super keyword might work. For example the above code becomes: > > class A(object): > def __init__(self, arg1): > cooperate(self.c_init, arg1=arg1) > def c_init(self, **dic): > print dic['arg1'] > > class B(A): > def __init__(self, arg1, arg2): > cooperate(self.c_init, arg1=arg1, arg2=arg2) > def c_init(self, **dic): > yield self > print dic['arg2'] > > class Mixin(object): > def __init__(self, **dic): > cooperate(self.c_init, **dic) > def c_init(self, **dic): > print dic > > class C(B, Mixin): pass > > c = C(arg1=1, arg2=2) > > where cooperate() is defined as: > > from __future__ import generators > import types > > def cooperate(method, *args, **kw): > assert type(method) is types.MethodType > > attr_dict = dict() > gen_list = list() > > for cls in method.im_class.__mro__: > attr = getattr(cls, method.im_func.func_name, None) > if attr is not None and hash(attr) not in attr_dict: > attr_dict[hash(attr)] = None > gen = attr(method.im_self, *args, **kw) > if type(gen) is types.GeneratorType: > try: gen.next() > except StopIteration: pass > else: gen_list.insert(0, gen) > > for gen in gen_list: > try: gen.next() > except StopIteration: pass > > Sorry for the long winded post but I wanted to know what the python > folk thought about these issues. > > Thanks, > Jonathan A simpler alternative is to use metaclasses: class Cooperative(type): """Metaclass implementing cooperative methods. Works well for methods returning None, such as __init__""" def __init__(cls,name,bases,dic): for meth in getattr(cls,'__cooperative__',[]): setattr(cls,meth,cls.coop_method(meth,dic.get(meth))) def coop_method(cls,name,method): # method can be None """Calls both the superclass method and the class method (if the class has an explicit method). Implemented via a closure""" def _(self,*args,**kw): getattr(super(cls,self),name)(*args,**kw) # call the supermethod if method: method(self,*args,**kw) # call the method return _ class A(object): __metaclass__=Cooperative __cooperative__=['__init__'] def __init__(self, *args): print 'A.__init__',args class B(A): def __init__(self, *args): print 'B.__init__',args class C(B): def __init__(self, *args): print 'C.__init__',args C() # Gives: #A.__init__ () #B.__init__ () #C.__init__ () Michele From jjl at pobox.com Tue Jun 10 08:17:40 2003 From: jjl at pobox.com (John J. Lee) Date: 10 Jun 2003 13:17:40 +0100 Subject: interpreted References: <5yednTf1NoAdanmjXTWcpQ@comcast.com> Message-ID: <87n0gqf7ob.fsf@pobox.com> Gerhard H?ring writes: > Ifman1 wrote: > > Thanks.... > > what do you mean "anonymous coward"??? > > Somebody not using their real name on usenet and using a pseudonym > like "Ifman1" instead. I call these people "anonymous cowards" :-)^ [...] Pseudonymous cowards would be more accurate, perhaps. As opposed to nonymous and demi-nonymous cowards. ;-) John From snag at jool.po Sun Jun 22 20:44:54 2003 From: snag at jool.po (kpop) Date: Mon, 23 Jun 2003 01:44:54 +0100 Subject: division Message-ID: Hi, i am writing a maths program where i get input from the user and store it in a string. i then use the eval fucntion to return the right answer. users could type in "(23+ 21) - (4 * 3) + 2" for example and the function would return an int of 34 which I would convert to a string. The problem is division, I would like it that only exact division was aloud, I mean no remainders. In python "22 / 5" returs an int of 5 i would like if that was illegal because 5 doesnt go into 22 , 4 times exactly, and have the eval function raise an execption which i could handle. any advice? Thanks From ykingma at accessforall.nl Sun Jun 8 14:42:56 2003 From: ykingma at accessforall.nl (Ype Kingma) Date: Sun, 08 Jun 2003 11:42:56 -0700 Subject: Prolog-style unification? References: Message-ID: <3ee30682$0$69421$e4fe514c@dreader9.news.xs4all.nl> Simon Burton wrote: > > On Sat, 07 Jun 2003 14:38:40 -0600, junk wrote: > >> Hi Robert, >> >> I am working on a Master's Thesis currently where this issue is of >> concern. I would also like to know if there is such a module. >> >> In the mean time, I have written my own module which does a pretty good >> job of simulating Prolog style calls. Here is what my syntax looks like >> right now: >> >> import logic >> Father = logic.Fact() >> Father("Seth","Alex") >> Father("James","Seth") >> X = logic.LogicalVariable() >> Y = logic.LgocialVariable() ... >> while Father(X,Y): >> print X, Y > > Know about iterators? > > i'd like to see > for x,y in Father(): > print x, y > > are you trying too hard to adhere to prolog syntax maybe? > Calling Father this way could make it difficult to use it in multiple places in a single clause. An iterator per occurence seems just right, although I have to say that it is decades ago that I used Prolog... Some questions: Is logic.Fact the good class for the backtracking needed? Do you use 'yield' for backtracking? Have fun, Ype -- email at xs4all.nl From goboborz at yahoo.com Wed Jun 25 15:02:08 2003 From: goboborz at yahoo.com (Gobo Borz) Date: Wed, 25 Jun 2003 14:02:08 -0500 Subject: better way than: myPage += 'more html' , ... References: <3EF9CBCB.90305@yahoo.com> Message-ID: <3EF9F1B0.9010104@yahoo.com> Thanks, that opens up a world of possibilities I haven't began to explore. In general, I'm not fond of templating systems because of the overhead, but it seems as your suggestion might be fast, since it uses ordinary string substitution. --Gobo mirko-lists at zeibig.net wrote: > In article <3EF9CBCB.90305 at yahoo.com>, Gobo Borz wrote: > >>I remember reading somewhere that building the string with successive >>"+=" statements is inefficient, but I don't know any alternatives, and >>my search attempts came up empty. Is there a better, more efficient way >>to do it than this: >> >>#--------------------------------- >>htmlPage = "

" >>htmlPage += "more html" >>... >>htmlPage += "even more html" >>... >>htmlPage += "" >>print htmlPage >>#------------------------------------- > > Hello Gobo, > > you may use the list solution provided in the former chapters. Some other > solution would be to use string substitution: > --------- snip ----------- > htmlPage = """ > > > %(title)s > > >

%(title)s

> %(body)s > > > """ > > body = [] > body.append("

my first snippet

") > body.append("
    ") > for in range(10): > body.append("""
  • %s. entry
  • """ % i) > body.append("
") > > contents = { "title": "My Foopage", > "body": "\n".join(body) } > > print htmlPage % contents > -------- snap ------------- > > This type of substitution goes for a very simple templating system. > > Best Regards > Mirko > From skip at pobox.com Fri Jun 27 07:47:02 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 27 Jun 2003 06:47:02 -0500 Subject: Activating `-i' from inside a script? In-Reply-To: References: Message-ID: <16124.11958.946104.822670@montanaro.dyndns.org> Troy> I thought this would work, but it doesn't: Troy> import os Troy> if __name__ == '__main__': Troy> discrepancy = True Troy> if discrepancy: Troy> os.environ['PYTHONINSPECT'] = "why yes, i'd like that" Troy> A quick read of Modules/main.c shows that the environment variable Troy> is checked at program start, not at end. Maybe this is a bug? The slight, obvious rearrangement to Modules/main.c seems to work. I'll propose it on python-dev. Skip From gerrit at nl.linux.org Sun Jun 22 11:55:45 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 22 Jun 2003 17:55:45 +0200 Subject: Numeric or numarray? In-Reply-To: References: Message-ID: <20030622155545.GB4175@nl.linux.org> gong li wrote: > 1. the readme says that previous version of numarray must be removed, > is it referring to Numeric also? You don't have to remove Numeric, since numarray is not backward-compatible. You can have them installed both (I have). > 2. which package should i use? Numarray is the future. Older packages use Numeric. I don't know about technical issues, though. > 3. whats the status of these projects? IIRC, Numeric is no longer being developed, but I'm not sure. Gerrit. -- 105. If the agent is careless, and does not take a receipt for the money which he gave the merchant, he can not consider the unreceipted money as his own. -- 1780 BC, 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 staschuk at telusplanet.net Fri Jun 6 13:06:13 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Fri, 6 Jun 2003 11:06:13 -0600 Subject: Totally Confused: Passing variables to functions In-Reply-To: <38ec68a6.0306051955.98a3dff@posting.google.com>; from afriere@yahoo.co.uk on Thu, Jun 05, 2003 at 08:55:36PM -0700 References: <38ec68a6.0306051955.98a3dff@posting.google.com> Message-ID: <20030606110613.A336@tibia.amotlpaa.bogus> Quoth Asun Friere: [...] > >>>sys.ps1 = '? '; sys.ps2 = '= ' #for those reading news on the web Why would those reading news on the web need such a substitution? -- Steven Taschuk staschuk at telusplanet.net "Its force is immeasurable. Even Computer cannot determine it." -- _Space: 1999_ episode "Black Sun" From info at igdnyci.com Wed Jun 4 21:14:36 2003 From: info at igdnyci.com (Unsubscriber) Date: Wed, 4 Jun 2003 20:14:36 -0500 Subject: python-list@python.org Removed Message-ID: <200306050114.h551Ean11856@ns45.dot5hosting.com> You (python-list at python.org) have been removed from the IGDNYC mailing list. We apologize for any inconveniences. From jjl at pobox.com Wed Jun 18 11:56:16 2003 From: jjl at pobox.com (John J. Lee) Date: 18 Jun 2003 16:56:16 +0100 Subject: The beauty of Python References: Message-ID: <87u1anmlb3.fsf@pobox.com> Dirk Gerrits writes: > Thomas Weholt ( PRIVAT ) wrote: > > Well, I was hoping for smaller examples, not too advanced things, more stuff > > you'll find in any programming language, stuff python has solved in a > > particulary elegant way. > > Well what I found particularly elegant when I was first introduced to > Python was it's easy iteration over sequences with the for Iterators now, of course. [...] > And of course I immediately loved its powerful, yet easy to use, data > structures; especially the dictionary. And sets! The new set module is quite handy. In fact, I've just starting using 2.3, and there's a lot of stuff there that's really nice for writing small programs (I don't see much utility in the word 'script'). logging, optparse, sets, along with the iterators and generators from previous releases, key in dict... John From gerrit at nl.linux.org Mon Jun 9 17:32:01 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 9 Jun 2003 23:32:01 +0200 Subject: PEP 317: Eliminate Implicit Exception Instantiation In-Reply-To: References: Message-ID: <20030609213201.GA16749@nl.linux.org> Ed Avis wrote: > Steven Taschuk writes: > > raise_stmt ::= "raise" [expression ["," expression]] > > Why not go further and make it look like a normal function call, that > can take zero one or two arguments? > > raise_stmt ::= "raise" "(" [expression ["," expression]] ")" > > No arguments - raise() - would re-raise the currently active > exception, and so on. Maybe raise could even be made a builtin-function instead of a statement? I think there should be as few statements as possible. Or would it be impossible because of Python's internals? I know nothing about them... yours, Gerrit. -- 250. If while an ox is passing on the street (market) some one push it, and kill it, the owner can set up no claim in the suit (against the hirer). -- 1780 BC, 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 fredrik at pythonware.com Fri Jun 27 12:10:36 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 27 Jun 2003 18:10:36 +0200 Subject: Exposing object model in Python? References: Message-ID: Steve Holden wrote: > > > Unfortunately the techniques used are a little too complicated to > > > describe in a newsgroup posting. > > > > > > with-apologies-to-pierre-de-fermat-ly y'rs - steve > > > > macrosource = getmacro(macroname) > > code = compile(macrosource, macroname, "exec") > > context = {} > > # populate context with fun things > > context["app"] = object_representing_my_app > > exec code in context > > > > (add exception handling as necessary) > > You just *love* proving me wrong, don't you? Oh, it's just that my news reader has wider margins. From aahz at pythoncraft.com Mon Jun 16 22:21:23 2003 From: aahz at pythoncraft.com (Aahz) Date: 16 Jun 2003 22:21:23 -0400 Subject: Backward-compatibility: help or hindrance? References: Message-ID: In article , Ben Finney wrote: >On Mon, 16 Jun 2003 11:01:11 -0700, Michael Chermside wrote: >> >> the range() function could not simply be changed to work the way >> xrange() works now, because there was lots of existing code out there >> that assumed that range() returned a list. You see, the maintainers of >> Python work quite hard to avoid as much backward-incompatibility as >> possible. > >This concerns me. Isn't it the dream of backward-compatibility that >gave us the monster that is C++ trying to advance the programming art >while leaving all the cruft of the old language built in? > >I wonder how long it'll be before Python's clean, simple design is >hindered by anchors of old programming paradigms (that we presently hold >dear), weighing down the language in the much-cursed name of >"backward-compatibility". You left out the part of Michael's post where he said that xrange() is going away in Python 3.0. Balance is everything. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From CousinStanley at hotmail.com Tue Jun 17 14:03:16 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Tue, 17 Jun 2003 11:03:16 -0700 Subject: Python as a Language Choice References: Message-ID: | Agreed - but I would also add: | | Licensing | | the liberal and uncomplicated "Do Whatever You Like With It, | just don't sue us if it doesn't work"-license | is a *big* selling point to organisations like mine | who have to employ people who's task is solely keeping track | of a growing mess of evermore expensive (the norm), | complex (always) and stupid (often) software licenses !! Frithiof ... I think you are correct that a more explicit statement of licensing issues should be included ... This would indeed be more helpful than a casual mention of Open Source as I did which only implies licensing in general and not a particular type of Open Source Licensing ... Thanks for the suggestion ... -- Cousin Stanley Human Being Phoenix, Arizona From ajthomson at optushome.com.au Mon Jun 23 02:37:52 2003 From: ajthomson at optushome.com.au (Andrew Thomson) Date: Mon, 23 Jun 2003 16:37:52 +1000 Subject: Python 2.2.3 test_re.py fails with coredump on FreeBSD 5.0, fails also on FreeBSD4.8 In-Reply-To: References: <2251d03c.0306211009.2596e9fd@posting.google.com> Message-ID: <20030623063752.GU4006@athomson.prv.au.itouchnet.net> one could also just use the ports to install python.. pkg_info| grep python python-2.2.3 An interpreted object-oriented programming language ajt. On Mon, Jun 23, 2003 at 08:25:44AM +0200, Harald Schneider wrote: > import pre as re > > is a practical workaround for most appliacations on the FreeBSD platform. > > --Harald > > > "PieterB" schrieb im Newsbeitrag > news:2251d03c.0306211009.2596e9fd at posting.google.com... > > Ok, > > > > I had a little look at testing Python 2.2.3 under FreeBSD and > > 5.0. When I use './configure ; make ; make test' Lib/test/test_re.py > > gives a Signal 10 (coredump) on FreeBSD5. The test coredumps because > > of the following test from Lib/test/test_re.py: > > > > > > if verbose: > > print 'Test engine limitations' > > > > # Try nasty case that overflows the straightforward recursive > > # implementation of repeated groups. > > try: > > verify(re.match('(x)*', 50000*'x').span() == (0, 50000)) > > except RuntimeError, v: > > print v > > > > > > On FreeBSD 4.8 this test also fails, but doesn't core dump: > > %python2.2.3 test_re.py > > Running tests on re.search and re.match > > Running tests on re.sub > > Running tests on symbolic references > > Running tests on re.subn > > Running tests on re.split > > Running tests on re.findall > > Running tests on re.match > > Running tests on re.escape > > Pickling a RegexObject instance > > Test engine limitations > > maximum recursion limit exceeded > > Running re_tests test suite > > === Failed incorrectly ('(?u)\\w', u'\xc4', 0, 'found', u'\xc4') > > > > Can anybody, give me a clue: > > a) if this is caused by a FreeBSD5.0 issue, or by Python. > > Can somebody test this on FreeBSD 5.1 or FreeBSD5-CVS? > > b) how can I fix the coredump on FreeBSD 5.0? > > c) what should be done to fix the test on FreeBSD 4.8? > > > > Can this related to the FreeBSD python/zope/zwiki stability problems > > for FreeBSD. (see http://zwiki.org/GeneralDiscussion200306). Zwiki > > makes heavy use of regular expressions. > > > > I also made some patches to make regrtest.py aware of freebsd4/freebsd5. > > I've put them online at: http://www.gewis.nl/~pieterb/python/bugs-2.2.3/ > > > > Thanks in advance, > > > > PieterB > > > > -- > > http://zwiki.org/PieterB > > > -- > http://mail.python.org/mailman/listinfo/python-list > From g2h5dqi002 at sneakemail.com Sun Jun 8 23:59:48 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Mon, 09 Jun 2003 15:59:48 +1200 Subject: Postfix/Prefix Operators (++,--) In-Reply-To: <3EE14A55.AD00B185@engcorp.com> References: <3EE05E36.40DF739F@engcorp.com> <3EE0B4D5.736EE894@engcorp.com> <3EE0D19C.7D7FFCA0@engcorp.com> <3EE14A55.AD00B185@engcorp.com> Message-ID: Peter Hansen wrote: > Joshua Marshall wrote: >>List comprehensions let you rebind a variable in an expression, so >>there is some precedent for this: > > I seem to recall several posts to the effect that this was an > unfortunate and/or unexpected and undesirable side-effect of > the implementation but that now that it's here, we're sort of > stuck with it since people believe code already depends on it. I don't think that's accurate -- I doubt there is a substantial body of code out there that relies on the value of a loop variable after a list comprehension finishes. Rather, the current semantics make it possible to describe the effect of a list comprehension in terms of an equivalent for-statement. If the binding behaviour were different, the docs would have to add "except that it doesn't have a side effect on the loop variable" or something like that. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From usenet_spam at janc.invalid Thu Jun 26 09:08:57 2003 From: usenet_spam at janc.invalid (JanC) Date: Thu, 26 Jun 2003 13:08:57 GMT Subject: add empty directory using zipfile? References: Message-ID: Ben Finney schreef: > A better solution might be to use tar (or cpio) for archiving, since > they can add directories as well as files, and can also preserve file > permissions from Unix filesystems. > > You then get the benefit of choosing whatever compression method you > like for the resultant archive. gzip and bzip2 both offer superior > compression to the built-in compression for Zip. You can use bzip2 compression in a zip file (it's in the recent specs), but probably not with zipfile, and most zip utilities can't uncompress it anyway. A disadvantage of .tar.whatever is that it is stream-based: no random access to a single file in the archive... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From sismex01 at hebmex.com Mon Jun 9 11:53:47 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 9 Jun 2003 10:53:47 -0500 Subject: cut off \n Message-ID: > From: Tom [mailto:llafba at gmx.net] > Sent: Monday, June 09, 2003 10:51 AM > > Hi, > > I have to read data from a file to a list. Unfortunately most of the > data that I read into my little list ends with a linefeed \n. > Right now I get rid of this by just cutting off the last > character. (a = > l[:-1]). > This is *almost* the correct way to do it :-) > > My problem is that sometimes the last line of the file has a \n and > sometimes not. With the method above I sometimes cut off parts of my > string. So it would be much nicer if I can find out if the data does > have a \n and then cut it off. > You could do somethint like: if line.endswith("\n"): line = line[:-1] or, if trailing whitespace is not significant (you don't mention it), you can also do something like: line = line.rstrip() or, if leading whitespace is not significant either, you can also trim all leading and trailing whitespace, thusly: line = line.strip() > > This is probably a very common problem but I am pretty new to Phython > and could find anything useful with google. :-( > > Thanks, Tom > Perl has yet-another-kinda-useful-function called "chomp", which deletes a line ending from a string, only if it's found. Alas, python is chompless, not that I'm complaining, the above code is what I use all the time. -gca -- Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From aldo at nullcube.com Thu Jun 5 08:23:19 2003 From: aldo at nullcube.com (Aldo Cortesi) Date: Thu, 5 Jun 2003 22:23:19 +1000 Subject: Totally Confused: Passing variables to functions In-Reply-To: References: Message-ID: <20030605122319.GC30883@nullcube.com> Thus spake Chuck (cdreward at riaa.com): > I'm new here... > > > >>> v = [1,2] > > >>> arg = v > > >>> arg.append(3) > > >>> v > > [1, 2, 3] > > I'm not "getting" variables in Python, then. > > What exactly happens when I say "arg = v"? "v" is just a label, which points at the list [1, 2]. You then set another label, "arg", equal to "v". You now have two labels pointing at the same list. Python objects exist quite independently from the labels that point at them, with the sole caveat that when no more labels point at an object, it is destroyed. Here's a nice little post by Guido explaining all this graphically: http://tinyurl.com/djbc > Not "arg is assigned the value [1,2] that v happens to hold"... > > Not "arg now points to v" (can't be, since you can delete v and arg still > exists) No - "arg" and "v