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" simply both point to the list, which has an independent existence. When we go: del v we are simply unbinding the label "v" from the list. Since a reference to the list is still being held by "arg", the list itself remains in existence. > It seems to say, "arg now points to what v also points to".. is this correct? > > 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? > > If so, I *think* I'm starting to "get it"... ;-) That's right. You've got it. Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com From peter at engcorp.com Sat Jun 7 23:28:46 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 07 Jun 2003 23:28:46 -0400 Subject: program path References: <3EE28ABC.7D6DB511@engcorp.com> Message-ID: <3EE2AD6E.933C6ED7@engcorp.com> kpop wrote: > > "Peter Hansen" wrote in message > news:3EE28ABC.7D6DB511 at 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 > no just the main script thanks peter Good... in that case, usually this is enough: import os import sys scriptPath = os.path.abspath(sys.argv[0]) From max at alcyone.com Tue Jun 10 19:06:22 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 10 Jun 2003 16:06:22 -0700 Subject: PEP 318 - Function Modifier Syntax References: <3EE65444.907E6D87@alcyone.com> Message-ID: <3EE6646E.47555429@alcyone.com> Ian Bicking wrote: > Note that "in" is already overloaded in the same way, i.e., it is an > operator, and it is a keyword when used with "for". I don't think > this > confuses anyone (though perhaps that's because there's more symmetry > in > the two meanings). That's a good point, although note that the original poster's suggestion segued into augmenting the meaning of the `is' operator, as well. > I think "as" is a bit better, as it expresses what's going on a bit > better (which isn't really declarative, and "is" feels very > declarative). 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. If the choice is between `is' and `as', I definitely choose `as'. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I am become death, the destroyer of worlds. \__/ J. Robert Oppenheimer (quoting Hindu legend) From mickel at csc.fi Mon Jun 30 09:02:06 2003 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Mon, 30 Jun 2003 16:02:06 +0300 (EEST) Subject: Placing entry widgets on a canvas in Tkinter In-Reply-To: Message-ID: > try this: > > canvas.create_window(x, y, window=widget, anchor=NW) Yep. I realized this was an alternative, just after I posted my question. (I should learn to think first and bother other people later ...) "create_window" does really solve my problem rather completely, it seems so now anyway. > an alternative solution is to implement text editing for text items; > see > > http://effbot.org/guides/editing-canvas-text-items.htm I tried your code from this page earlier, but decided to go for a different approach as I want the entry field to be of fixed size. Anyway, thanks Fredrik for your help! /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 knightsofspamalot-factotum at gvdnet.dk Sun Jun 8 10:18:07 2003 From: knightsofspamalot-factotum at gvdnet.dk (Martin Christensen) Date: Sun, 08 Jun 2003 16:18:07 +0200 Subject: Python vs emacs (again...) References: Message-ID: <871xy4d55s.fsf@gvdnet.dk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 >>>>> "Tim" == Tim Lesher writes: Tim> I downloaded the newest python-mode.el from SourceForge [...] Where? I haven't been able to find it. Martin - -- Homepage: http://www.cs.auc.dk/~factotum/ GPG public key: http://www.cs.auc.dk/~factotum/gpgkey.txt -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) Comment: Using Mailcrypt+GnuPG iEYEARECAAYFAj7jRZ8ACgkQYu1fMmOQldWt7gCfaaEQwT77XLpId18xQdb5Es0n UV4AoJbZ5LjYvoUS61kJnhyzqHPAoPER =m+ob -----END PGP SIGNATURE----- From cnetzer at sonic.net Sun Jun 22 19:34:26 2003 From: cnetzer at sonic.net (Chad Netzer) Date: 22 Jun 2003 16:34:26 -0700 Subject: Tkinter problem In-Reply-To: <2GiJa.1397$os2.19637@news2.e.nsc.no> References: <2GiJa.1397$os2.19637@news2.e.nsc.no> Message-ID: <1056324865.11054.25.camel@adsl-209.204.179.133.sonic.net> On Sun, 2003-06-22 at 07:02, Eirik wrote: > What does the "if __name__=='__main__':" mean? I do not fully understand > this example. For the example I gave, you can ignore it (and remove the indenting below). But it is used in cases where you want to be able to import a script (to get at its function definitions), as well as run it as a script. Basically, when you run a script, the __name__ global is equal to '__main__', so the example doesn't execute those lines if you import the script. It is a common idiom. Here is the example just as a straightforward script. Let me know if it makes the issue you asked about (setting up the proper callback) more clear. import sys from Tkinter import * def my_test_callback(): global root root.t.set("Test-Text") 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() -- Chad Netzer From rraghuram at metasolv.com Thu Jun 19 07:48:02 2003 From: rraghuram at metasolv.com (Ragu) Date: Thu, 19 Jun 2003 17:18:02 +0530 Subject: XML in python Message-ID: <02dc01c33658$a56641f0$9501060a@comnet49> Hi All, I need to read a XML file content in Python. Can anyone send me link/sample source? Note: Send mails to my personel id, as I didnt still yet subscribed to this list. Many Thanks Ragu "I envy people who drink. At least they have something to blame everything on." --Oscar Levant -------------- next part -------------- An HTML attachment was scrubbed... URL: From mis6 at pitt.edu Thu Jun 12 13:31:38 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 12 Jun 2003 10:31:38 -0700 Subject: PEP 318: Is chaining decorators even possible? References: <20030612080349419-0400@braeburn.themorgue.org> Message-ID: <2259b0e2.0306120931.549ab62e@posting.google.com> Kevin Smith wrote in message news:<20030612080349419-0400 at braeburn.themorgue.org>... > It has been brought up a couple of times in other threads that simply > chaining descriptors won't work (i.e. classmethod(synchronized(foo))). > Another possibility was to use subclassing (i.e. type('newtype',( > classmethod,synchronized,{})(foo)). When I wrote PEP 318, I wasn't sure > myself if it was possible to chain them, but I figured someone would > point it out if it wasn't. So my question is, is it even possible to > chain decorators in a general way? Yes, it is. You can multiply inherit or use Steven Taschuk's solution (see the revised PEP 318 thread). Both are not completely obvious and require some effort to the user writing the custom descriptor. Nevertheless, normal users should not write custom descriptors (at most they are expected to compose pre-defined descriptors), therefore I would not complain even if the recipe to define composable decorators was a little trickier. I think that probably classmethods and staticmethods would be reimplemented. Michele From jepler at unpythonic.net Tue Jun 17 20:44:32 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 17 Jun 2003 19:44:32 -0500 Subject: preventing creation of instance In-Reply-To: References: Message-ID: <20030618004431.GA8034@unpythonic.net> I'm not sure the final block (abel) is guaranteed to work, because gc might collect the old adam later rather than sooner. This might depend on whether 'test' objects are involved in cycles. You must use __new__ to return a non-instance when calling the class like it was a constructor. You could raise an exception in __init__ if you'd rather... $ python mirko.py new [] adam new ['adam'] eve new ['adam', 'eve'] adam new ['eve'] adam import weakref class test(object): names = weakref.WeakValueDictionary() def __init__(self, name): pass def __new__(cls, name): print "new", cls.names.keys(), name if cls.names.has_key(name): return None ret = super(test, cls).__new__(cls, name) cls.names[name] = ret return ret adam = test("adam") eve = test("eve") cain = test("adam") assert eve is not None assert adam is not None assert cain is None del adam abel = test("adam") assert abel is not None From abc at attbi.com Thu Jun 19 21:10:20 2003 From: abc at attbi.com (FooBar) Date: Fri, 20 Jun 2003 01:10:20 GMT Subject: Help with Mailman version 2.0.13 Message-ID: I need some help please. I asked on the Mailman list and no one seems to knwo the answer. I want to set up Mailman so that it just blackholes email that is sent to the list from non-subscribers. I knwo how to configure things so that such posts are not sent to the list, but this makes them go to an admin holding bin and each mail must be manually rejected. The file that handles this is Hold.py and it looks like that line 152 calls the hold_for_approval function. I think that if I could comment that line out and add the line to call the function that black holes the messages but I do not know what that function is. Can anyone point me in the right direction here? Thanks! DB From martin at v.loewis.de Sat Jun 7 13:28:41 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 07 Jun 2003 19:28:41 +0200 Subject: a = b = 1 just syntactic sugar? References: Message-ID: Ed Avis writes: > I can think of another rule which is just as simple: allow any > construct which fits on one line. Simpler to explain, for sure. What is the output of print a,lambda:print b,c ? > I gave several examples of where it didn't seem to make any sense - > sys.stdout.write is an expression while print is a statement, > setdefault is an expression but ordinary setting of dictionary > elements is a statement, and so on. The distinction of statement vs. expression is of purely syntactical nature. Expressions are operators and function invocations; statements are more complex. Expressions nest "naturally", statements nest by indentation, or don't nest at all. It just can't work any other way. Your failed attempt to allow statements inside lambdas just demonstrates this: Since statements don't nest naturally, any attempt to make them nest will cause syntactical ambiguities. > You can sit down and start writing Python code - whether it be > 'print', 'x = 3', 're.match', 'sys.exit' - without worrying about > whether the line you're typing is really an expression or a statement. > You just go ahead and type it, and it works. This is a strength of > the language. It's a weakness that the same simplicity is not there > when you're writing the body of an anonymous function. This weakness is inherent; there is no easy way to fix that, or else it would have been fixed long ago. Regards, Martin From h_schneider at marketmix.com Tue Jun 24 09:52:55 2003 From: h_schneider at marketmix.com (Harald Schneider) Date: Tue, 24 Jun 2003 15:52:55 +0200 Subject: SOLVED: py2exe and dynamic service installation ? References: <3ci0syqd.fsf@vfa.com> Message-ID: OK -- I catched the point :-) I generated the service exe like usual and used XNET.EXE (part of the free KIX package, see www.kixstart.org ) to install the service under any name. Thanks! --Harald "Thomas Heller" schrieb im Newsbeitrag news:wufbfwlg.fsf at python.net... > "Harald Schneider" writes: > > > Thomas, > > > > do I need to prepare my Python app for the use with WISE, when I want to > > install it as a service? Does it need to provide a certain service API or > > some special response codes ? > > No, you create your service with py2exe as always, and Wise does the > rest - create a windows installer, install the files on the target > machine and register the serice there. The registration is done from the > installer, not from the service. > > I'll try to attach a screenshot of the dialogbox that the wise program > displays (at build time), so you can see the options which are > available. > Hm, doesn't work in the newsgroup - will send by private mail. > > Thomas From oren-py-l at hishome.net Mon Jun 2 03:35:48 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Mon, 2 Jun 2003 03:35:48 -0400 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: <20030602073548.GA5862@hishome.net> On Mon, Jun 02, 2003 at 05:45:32AM +0000, dsavitsk wrote: > (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. >>> [hash(i) for i in range(1,12)] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] Dictionaries use the hash function of objects and the hash function of an integer is the number itself. This is not guaranteed to generate the keys in numeric order, but it usually does. One thing it does guarantee is that a dictionary indexed by any contigous range of numbers will never have collisions in its internal hash table. You don't see such collisions but they affect performance. Don't write code that relies on this ordering, though. Oren From alanmk at hotmail.com Mon Jun 9 11:17:49 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 09 Jun 2003 16:17:49 +0100 Subject: xmlrpc client on windows + https: error References: Message-ID: <3EE4A51D.9F6AC84D@hotmail.com> Ruslan Spivak wrote: > I've installed Python-2.2.2 on WinXP and trying to make xmlrp request > with https > Your version of httplib doesn't support HTTPS > Can you tell me what to do? How to make it work on windows, cause on my > linux box it's ok with python2.2.2. You could upgrade to python 2.3. 2.2 does not come with inbuilt SSL support, whereas 2.3 does. Try the following piece of code on 2.2 and 2.3, and you'll see what I mean. import socket if hasattr(socket, "ssl"): print "Yep, secure sockets supported" else: print "Nope, secure sockets not supported" HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From alanmk at hotmail.com Tue Jun 3 13:29:41 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 03 Jun 2003 18:29:41 +0100 Subject: Variable Modifications in a class References: Message-ID: <3EDCDB05.8E12F97@hotmail.com> "Mehta, Anish" wrote: > I am having a problem in tackling the variables in the class. > > class AB: > def __init__(self): > self.a = None > self.b = None > > def func(ab): > b = ab() > c = ab() > > b.a = 5 > b.b = 10 > > c = b ^^^^^ This is where you are misunderstanding python. "b" and "c" are not variables, they are references. They are simply a name, which is "bound" to something, so the name "refers to" the something. So let's run through your function line by line def func(ab): b = ab() This creates a new AB object, the first one. It also creates the name "b", and binds it to the new AB object. c = ab() This also creates a new (and different) AB object, the second one. It also creates the name "c", and binds it to the second AB object. b.a = 5 Set the "a" member of the AB object *referred to* to by "b" to 5 b.b = 10 Set the "b" member of the AB object *referred to* to by "b" to 10 c = b Make the name "c" refer to whatever "b" refers to (in this case, the *first* AB object). Note also that you now have no way of getting at the second AB object, since you have no reference to it. It has fallen into the garbage heap, and will be recycled eventually. c.a = 30 Set the "a" member of the AB object referred to by c (i.e. the first AB object) to 30 c.b = 40 Set the "b" member of the AB object referred to by c (i.e. the first AB object) to 40 I think you will understand the behaviour better now. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From bdesth at removethis.free.fr Mon Jun 2 19:11:49 2003 From: bdesth at removethis.free.fr (laotseu) Date: Mon, 02 Jun 2003 23:11:49 +0000 Subject: Python get's a mention on University Challenge References: Message-ID: <3EDBD9B5.20201@removethis.free.fr> sismex01 at hebmex.com wrote: >>What was the question? >> >>--Irmen >> > > > 42 Hmmm... Doesn't work. What about 'how many roads...' ?-) From sjmachin at lexicon.net Thu Jun 12 09:28:33 2003 From: sjmachin at lexicon.net (John Machin) Date: 12 Jun 2003 06:28:33 -0700 Subject: simple text filter References: Message-ID: boutrosp at hotmail.com wrote in message news:... > 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') [snip] > 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 [snip] > elif p8.search(junky) : > continue > elif junky == None : > done = True > else : > print junky > f.close() Try this: import sys, re good_stuff = re.compile( 'ADT100|AUDIT|HARDWARE|PACKAGES|NODE|DROP|GRID|ATAP' # list these in descending frequency order ).search for aline in file(sys.argv[1]): # hardcoded file names not a good idea if not good_stuff(aline): print aline You may want to ensure that you don't match e.g DROPKICK when you only want DROP. E.g. r'\b(ADT100|AUDIT|HARDWARE|PACKAGES|NODE|DROP|GRID|ATAP)\b' Note carefully the r prefix (raw string). From piet at cs.uu.nl Sat Jun 14 17:08:34 2003 From: piet at cs.uu.nl (Piet van Oostrum) Date: 14 Jun 2003 23:08:34 +0200 Subject: python-mode on OS X References: Message-ID: >>>>> spam at fisher.forestry.uga.edu (Chris Fonnesbeck) (CF) wrote: CF> Here is my .emacs: CF> (custom-set-variables CF> ;; custom-set-variables was added by Custom. CF> ;; If you edit it by hand, you could mess it up, so be careful. CF> ;; Your init file should contain only one such instance. CF> ;; If there is more than one, they won't work right. CF> (setq auto-mode-alist CF> (cons '("\\.py$" . python-mode) auto-mode-alist)) CF> (setq interpreter-mode-alist CF> (cons '("python" . python-mode) CF> interpreter-mode-alist)) CF> (autoload 'python-mode "python-mode" "Python editing mode" t)) That's wrong. This code should be placed outside of the custom-code. (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist)) (setq interpreter-mode-alist (cons '("python" . python-mode) interpreter-mode-alist)) (autoload 'python-mode "python-mode" "Python editing mode" t) (custom-set-variables ;; custom-set-variables was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. ) (custom-set-faces ;; custom-set-faces was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. ) As the custom stuff is empty it could even be deleted. But it will be added at the next customization. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From tjreedy at udel.edu Thu Jun 5 00:48:23 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 5 Jun 2003 00:48:23 -0400 Subject: Using instance as __doc__ References: <45e6545c.0306041804.4ea5e07c@posting.google.com> Message-ID: <5SKdnbYwob4BVkOjXTWcpw@comcast.com> "Seo Sanghyeon" wrote in message news:45e6545c.0306041804.4ea5e07c at posting.google.com... > So... Python throws out __doc__ if it is not a real string. Why not use > something like "doc = str(doc)" instead? Yeah, quite useless, perhaps. > I have no idea of possible use cases. But if there is some hidden reason > for not to use str() on instance __doc__, please enlighten me. Probably no one ever thought to do so. And developers are reluctant to penalize 99.999% of uses for the .001% that might do something wierd like this tjr From ianb at colorstudy.com Thu Jun 5 03:22:57 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 05 Jun 2003 02:22:57 -0500 Subject: Help with dictionary In-Reply-To: <9afd3f36.0306042301.5243a9e8@posting.google.com> References: <9afd3f36.0306042301.5243a9e8@posting.google.com> Message-ID: <1054797777.676.36.camel@lothlorien> On Thu, 2003-06-05 at 02:01, Jim Shady wrote: > 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} You can't sort dictionaries, you can only sort lists. So maybe what you want is: source = {(1, (21353, 21418)): 3900, (2, (53006, 53164)): 3800, (0, (19697, 19763)): 4100} dest = source.items() dest.sort() print dest [((0, (19697, 19763)), 4100), ((1, (21353, 21418)), 3900), ((2, (53006, 53164)), 3800)] Each item of the list is a (key, value) pair. Ian From maschio_77 at hotmail.com Thu Jun 5 16:49:09 2003 From: maschio_77 at hotmail.com (Federico) Date: Thu, 5 Jun 2003 22:49:09 +0200 Subject: changing icon of a Tkinter window Message-ID: Please can someone give me an example on how to change the icon of a Tkinter window ? I use python 2.2.3 under mswindows... Thanks From jansun at home.se Thu Jun 5 19:03:05 2003 From: jansun at home.se (=?ISO-8859-1?Q?Jan_Sundstr=F6m?=) Date: 5 Jun 2003 16:03:05 -0700 Subject: Characters in Python References: Message-ID: jansun at home.se (Jan Sundstr?m) wrote in message news:... > >>> str = '???' > UnicodeError: ASCII encoding error: ordinal not in range(128) I should have mentioned that I tried the unicode approach too but it didn't work. This is what I get: Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> theStr = u"???" UnicodeError: ASCII encoding error: ordinal not in range(128) >>> From calderano at sgaspa.it Fri Jun 13 06:07:24 2003 From: calderano at sgaspa.it (Luca Calderano) Date: Fri, 13 Jun 2003 12:07:24 +0200 Subject: http connection via proxy server Message-ID: <000001c33193$96e7c0f0$410100a4@utente65> I'm trying to connect to a web page via my proxy server using the following code .............................. import os import httplib os.system("Set %http_proxy% = \\xxx.xxx.xxx.xxx:80") myurl = "securityresponse.symantec.com/avcenter/download/pages/US-N95.html" req=httplib.HTTP(myurl) req.putrequest("GET","/") req.endheaders() ................................ but it returns this traceback: ............................................................................ ................. Traceback (most recent call last): File "C:\Python22\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "C:\Script1.py", line 14, in ? req.endheaders() File "C:\Python22\lib\httplib.py", line 695, in endheaders self._send_output() File "C:\Python22\lib\httplib.py", line 581, in _send_output self.send(msg) File "C:\Python22\lib\httplib.py", line 548, in send self.connect() File "C:\Python22\lib\httplib.py", line 516, in connect socket.SOCK_STREAM): gaierror: (7, 'getaddrinfo failed') ............................................................................ ................. can someone help me ??? Thanks in advance! Luca Calderano From alexferri at email.it Sun Jun 29 04:37:16 2003 From: alexferri at email.it (Alex) Date: Sun, 29 Jun 2003 08:37:16 GMT Subject: File sharing Message-ID: <0zxLa.156922$pR3.3597279@news1.tin.it> Hi all, I want to write a "File sharing system". Is posssible with socket and thread create multisuer connection at the same time ? or is wrong my idea?? thanks Alex From Tom_Web at gmx.net Wed Jun 25 06:02:10 2003 From: Tom_Web at gmx.net (Thomas Weber) Date: Wed, 25 Jun 2003 12:02:10 +0200 Subject: Newbie: "compiling" scrips (?) Message-ID: Hi, I've just started to play around with python, I like the syntax quite a lot... But I have some problems to execute my scripts (in Linux, bash) that I wrote in an editor. Is there a way to compile the scripts into binary form like like in C: 'gcc source.c -o binary' Sorry, if this was a silly question... Tom From max at alcyone.com Tue Jun 3 23:27:09 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 03 Jun 2003 20:27:09 -0700 Subject: a = b = 1 just syntactic sugar? References: <3EDCE9C2.5020805@nospam.com> Message-ID: <3EDD670D.4D2DBAA2@alcyone.com> Ed Avis wrote: > Is there a way to write an expression which sets b and does return > something? Sure, with difficulty. But if the language has been specifically designed so that assignment is a statement, not an expression, wouldn't you think it's not considered such a good idea? There might be enlightenment on the road of figuring out why the language is designed that way, rather than trying to get around what you perceive as a limitation but which the community in general considers a feature. -- 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 carsten at gehling.dk Sun Jun 1 05:11:53 2003 From: carsten at gehling.dk (Carsten Gehling) Date: Sun, 1 Jun 2003 11:11:53 +0200 Subject: SV: CGI question: safe passwords possible? In-Reply-To: <3ED88344.8000803@ghaering.de> Message-ID: > Fra: python-list-admin at python.org > [mailto:python-list-admin at python.org]Pa vegne af Gerhard Haring > Sendt: 31. maj 2003 12:26 > That's why I recommended to use digest authentication. > > See http://httpd.apache.org/docs/mod/mod_auth_digest.html > > It implements a similar algorithm that your proposed JavaScript gimmick > did. Only that it works with all modern browsers, JavaScript enabled or > not and that it's a standard. >From http://httpd.apache.org/docs/mod/mod_auth_digest.html : "Note: MD5 authentication provides a more secure password system than Basic authentication, but only works with supporting browsers. As of this writing (October 2001), the only major browsers which support digest authentication are Opera 4.0, MS Internet Explorer 5.0 and Amaya. Therefore, we do not yet recommend using this feature on a large Internet site. However, for personal and intra-net use, where browser users can be controlled, it is ideal." - Carsten From llafba at gmx.net Thu Jun 12 09:48:38 2003 From: llafba at gmx.net (Tom) Date: Thu, 12 Jun 2003 15:48:38 +0200 Subject: index(x) Message-ID: <3EE884B6.3070105@gmx.net> 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. 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? Thank you very much for your help. Regards, Tom From wweexxsseessssaa at telusplanet.net Sun Jun 15 16:44:22 2003 From: wweexxsseessssaa at telusplanet.net (John Hall) Date: Sun, 15 Jun 2003 20:44:22 GMT Subject: Python articles References: <3eecd89a$0$49116$e4fe514c@news.xs4all.nl> Message-ID: On Sun, 15 Jun 2003 22:35:39 +0200, Irmen de Jong wrote: >> 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) >> > >No trouble here with Mozilla 1.3.1, and Konqueror. >You're probably suffering from IE's flaky CSS support. > >I did have to accept an invalid SSL certificate though... > Me too on the certificate. Re the suffering hordes of IE users: I'm just one of millions. However, as the rising line of MS/Windows annoyance threatens to cross the falling line of Linux annoyance, I'm preparing to switch. -- John W Hall Calgary, Alberta, Canada. "Helping People Prosper in the Information Age" From domma at procoders.net Mon Jun 16 02:20:06 2003 From: domma at procoders.net (Achim Domma) Date: Mon, 16 Jun 2003 08:20:06 +0200 Subject: Anyone did this: Magick++ + boost.python References: Message-ID: "Yan Weng" wrote in message news:bcjkqn$vji$1 at pith.uoregon.edu... > It seems a very natural way to wrap ImageMagick. ImageMagicks interface is not very stable, so I decided to wrap GraphicsMagick. See www.graphicsmagick.org and www.procoders.net/pythonmagick for details. It's not perfect yet, but quite usable for simple image manipulations. > Your opninion? It's a lot of work! ;-) Achim From listbox at cybereal.org Sat Jun 14 23:05:43 2003 From: listbox at cybereal.org (Zac Jensen) Date: Sat, 14 Jun 2003 21:05:43 -0600 Subject: Reading from a FIFO, burning CPU In-Reply-To: <3EEB9D91.D2DE38A@engcorp.com> References: <3EEB9D91.D2DE38A@engcorp.com> Message-ID: <200306142105.44872.listbox@cybereal.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Saturday 14 June 2003 04:11 pm, Peter Hansen wrote: > "Elmar W. Hoefner" wrote: > > Hi there! > > > > 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? > > I did it this way: > > > > 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...) > > Don't know about FIFOs on Linux, but if it's an entity which returns > '' when there's nothing else to read for the moment, you will of course > consume CPU when it has nothing to give you. Doesn't it block? Perhaps > investigating the select.select() function would be a good idea, if it > works with a fifo... > > -Peter I second that, select() is a much better solution if you're not using win32. It won't return unless there is data if you use it correctly, making the script even more effective than the previous in the thread about using sleep's... - -Zac -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) iD8DBQE+6+KHV3L7YsSif1URAiZ/AJ9F7DFhHi3SIcavfldBExnJqWYmXgCfafrh uvy8BTlJ8hKmnwJXJ3llI4Q= =PpSl -----END PGP SIGNATURE----- From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Jun 2 16:54:59 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 02 Jun 2003 22:54:59 +0200 Subject: Python get's a mention on University Challenge In-Reply-To: References: Message-ID: <3edbb9a3$0$49107$e4fe514c@news.xs4all.nl> sismex01 at hebmex.com wrote: >>What was the question? >> >>--Irmen >> > > > 42 Ermm... 42 is actually the *answer* to the question. From calderano at sgaspa.it Fri Jun 13 06:33:04 2003 From: calderano at sgaspa.it (Luca Calderano) Date: Fri, 13 Jun 2003 12:33:04 +0200 Subject: R: http connection via proxy server In-Reply-To: Message-ID: <000101c33197$2cf74090$410100a4@utente65> Great! it works.... thanks a lot. Luca Calderano Fredrik Lundh wrote: >does this work better? > > import os > import urllib > > os.environ["http_proxy"] = "http://xxx.xxx.xxx.xxx:80" > myurl = "http://securityresponse.symantec.com/avcenter/download/pages/US-N95.html" > page = urllib.urlopen(myurl).read() Luca Calderano wrote: > I'm trying to connect to a web page via my proxy server > using the following code > > .............................. > import os > import httplib > > os.system("Set %http_proxy% = \\xxx.xxx.xxx.xxx:80") > myurl = "securityresponse.symantec.com/avcenter/download/pages/US-N95.html" > req=httplib.HTTP(myurl) > req.putrequest("GET","/") > req.endheaders() > ................................ From eppstein at ics.uci.edu Wed Jun 18 16:54:14 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 18 Jun 2003 13:54:14 -0700 Subject: Algorithm help per favore In-Reply-To: <16112.53102.408440.129703@montanaro.dyndns.org> References: <2ec1bc1c.0306180746.159679d6@posting.google.com> <3EF0AAFB.DDA5F555@engcorp.com> <3v3Ia.109349$pR3.2389728@news1.tin.it> <16112.53102.408440.129703@montanaro.dyndns.org> Message-ID: <11363196.1055944454@dhcp31-78.ics.uci.edu> On 6/18/03 3:45 PM -0500 Skip Montanaro wrote: > David> It's tempting to use "not L[0]" instead (since what I want is > an David> object that's not equal to L[0]) but that fails when L is > empty. > > How about "not L[0:1]"? Since L is a sequence (right?), "not L[0:1]" will > be True if L is empty and False otherwise. That fails to produce an object that is guaranteed to be unequal to L[0] when L is nonempty. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From peter at engcorp.com Fri Jun 20 06:09:49 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 20 Jun 2003 06:09:49 -0400 Subject: Alternatives to Python ? References: <3EF18A03.3050706@netspace.net.au> <3EF28908.1CE42D62@easystreet.com> Message-ID: <3EF2DD6D.F4065AF3@engcorp.com> achrist at easystreet.com wrote: > > This is not to say that everything else is worthless, just that > Python aims at a certain niche, and there isn't much else that > does exactly the same. It depends on what you want to do, but > when you want to do what Python does, the alternatives feel a > little like a tube running down your leg with a bottle in your > boot. For example, using Perl, which is a lot like what you describe above, minus the tube and the bottle... -Peter From a.schmolck at gmx.net Thu Jun 12 15:53:57 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 12 Jun 2003 20:53:57 +0100 Subject: vector subscripts in Python? References: <3064b51d.0306111512.7701dbbc@posting.google.com> Message-ID: Alex Martelli writes: > Alexander Schmolck wrote: > ... > > function is worthwhile (note that it allows works for dicts and other > > iterables). > > > > def at(iterable, indices): > > return [iterable[i] for i in indices] > > Careful: it does NOT allow for iterables -- it needs 'indexables', i.e., > sequences or mappings. Indeed, thanks for that correction. Being iterable is of course only sufficient for the indices. 'as From peter at engcorp.com Wed Jun 25 17:00:36 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 25 Jun 2003 17:00:36 -0400 Subject: Staying Connected to a POP3/SMTP Server References: <5a8e622e.0306251107.1d5e3202@posting.google.com> Message-ID: <3EFA0D74.CAF5231@engcorp.com> 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? Isn't it the case that POP3 servers basically "lock" the mailbox when you authenticate yourself, such that you would never see these new messages that might possibly be arriving? If that's so, it wouldn't be "bad" except in the sense that it would do nothing useful, and would prevent any subsequent login attempts from succeeding on that mailbox until you disconnected. With SMTP you could, however, stay connected as long as the server lets you, sending messages only when you feel like it. Given how fast the typical SMTP server accepts connections, however, you likely shouldn't need/want to do that. -Peter From theller at python.net Thu Jun 12 04:57:32 2003 From: theller at python.net (Thomas Heller) Date: 12 Jun 2003 10:57:32 +0200 Subject: Matching C integer constants with re References: <1xxzofj8.fsf@python.net> Message-ID: Just writes: > In article <1xxzofj8.fsf at python.net>, > Thomas Heller wrote: > > > I'm trying to match C integer constants with the re module, but cannot > > get it to work correctly. > > This is the pattern I use: > > > > re.compile(r"(0[xX][0-9a-fA-F]+|\d+)([uU]|[lL]|[uU][lL]|[lL][uU])?") > > > > and it fails to match constants with a two character suffix like > > these: "123ul" and "123lu", although "123u" and "123l" are found correctly. > > Can anyone see what's wrong? > > I'm by no means a regex expert, but I think you have to match the longer > ones first: > > r"(0[xX][0-9a-fA-F]+|\d+)([uU][lL]|[lL][uU]|[uU]|[lL])?" > > This seems to fix your script for me. Yup. Thanks, Thomas From tjreedy at udel.edu Mon Jun 9 23:00:03 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 9 Jun 2003 23:00:03 -0400 Subject: PEP 317: Eliminate Implicit Exception Instantiation References: <20030609001830.A1089@tibia.amotlpaa.bogus> Message-ID: "Evan Simpson" wrote in message news:mailman.1055178857.27669.python-list at python.org... > Rather than eliminating string exceptions, On PyDev, Guido stated clearly that Python 3 will not have string exceptions. So discussion is better aimed at other issues. TJR From p at ulmcnett.com Thu Jun 5 13:15:21 2003 From: p at ulmcnett.com (Paul McNett) Date: Thu, 5 Jun 2003 10:15:21 -0700 Subject: Tk vs wxPython ? In-Reply-To: <1054832228.2139.19.camel@software1.logiplex.internal> References: <200306050951.07037.p@ulmcnett.com> <1054832228.2139.19.camel@software1.logiplex.internal> Message-ID: <200306051015.21331.p@ulmcnett.com> Cliff Wells writes: > However, I think you miss my point. This isn't > about whether Trolltech's scheme is reasonable (I think it is), but what > constraints including it in the standard library would put on Python > users. Oh right. This thread was originally about what goes into the standard library. Of course you are correct! Qt definitely doesn't belong there. Sorry, the original subject got lost on my when the thread started drifting to discussing relative merits of PyQt verus wxPython. -- Paul McNett From tim at remove_if_not_spam.digitig.cix.co.uk Sun Jun 8 16:33:12 2003 From: tim at remove_if_not_spam.digitig.cix.co.uk (Tim Rowe) Date: Sun, 08 Jun 2003 21:33:12 +0100 Subject: Factorials References: <3ee1e6f1@shknews01> <3ee1fa98$0$45181$65c69314@mercury.nildram.net> Message-ID: <4067ev4btufgkb6h4frm5lvej605650kks@4ax.com> On Sat, 07 Jun 2003 15:45:37 +0100, Andrew Wilkinson wrote: >The other replies give a much more readable way of getting the factorial, >but if you're looking for the ultimate in speed then... > >def fac(n): > return reduce(long.__mul__, range(1,n+1), 1L) I thought I'd try these out. Taking Anton's challenging test case of 10000: - The simple recursive solution runs out of stack space. - Anton's solution barfs on R = [x*y for x,y in zip(R[::2],R[1::2])], complaining that the sequence index must be an integer. - Yours works fine. You're winning! Is it worth mentioning that for all their elegance recursive solutions are usually /not/ the way to go unless the language is designed for it -- especially when the solution is tail-recursive and so can be replaced with a simple loop anyway... From marc.engel at recif.com Tue Jun 17 11:00:29 2003 From: marc.engel at recif.com (Marc ENGEL) Date: 17 Jun 2003 08:00:29 -0700 Subject: Events with Python COM local server Message-ID: <6411841c.0306170700.63d0d5a1@posting.google.com> Hi, Is it possible to use events with a Python COM local server? I have a COM server implemented in Python. This server generates event by inheriting from win32com.server.connect.ConnectableServer The client application is also in Python. If I register my server as an Inproc Server, I got the event generated, everything is OK. Now if my server is a local server (I can check that it is launched inside pythonw.exe process) I cannot get events. When calling the Advise method, I got the exception: CONNECT_E_NOCONNECTION The main difference I can see between Inproc and Local server is that when queriing interface, the system automatically queries interface ICallFactory which I don't support. Is it the problem? I read also some stuff related to security policies and marshalling in previous post. Is it the problem? Is it supported by the PythonCOM framework? Thanks for any hint, Marc From news at datatailors.xs4all.nl Thu Jun 19 19:17:37 2003 From: news at datatailors.xs4all.nl (Peter van Kampen) Date: Fri, 20 Jun 2003 01:17:37 +0200 Subject: Feature Structures in Python (Part I) References: <20030619053141.6BF4835EC4@www.fastmail.fm> <3EF16277.FE8042B4@alcyone.com> <3EF1AFB2.45688CC1@engcorp.com> Message-ID: In article <3EF1AFB2.45688CC1 at engcorp.com>, Peter Hansen wrote: > Andrew Bennetts wrote: >> >> On Thu, Jun 19, 2003 at 12:12:55AM -0700, Erik Max Francis wrote: >> > Andrew Bennetts wrote: >> > >> > > What's a "feature structure"? >> > >> > I wondered the same thing. Google provided the answer. >> >> My instinctive google-twitch got put off by how generic the terms "feature" >> and "structure" are, so I didn't expect searching would find any useful >> results... > > Unfortunately for many of us, Google hasn't existed for long enough for > this to be a truly *instinctive* thing. It will take a few generations, > or more :-), to breed this into the gene pool... until then, sadly, it > must remain merely automatic --- for the fortunate and well-practiced --- > or nearly habitual --- for the more forgetful amongst us. :-( > > -Peter But note that google can search for phrases when you put the words in double quotes. "feature structure" or "test driven development" to name some 'arbitrary' terms ;-) PterK -- Peter van Kampen pterk -- at -- datatailors.com From aleax at aleax.it Tue Jun 17 03:56:14 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 17 Jun 2003 07:56:14 GMT 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: Tim Rowe wrote: ... > And the research I've seen indicates that the two techniques catch > pretty much non-overlapping sets of bugs. I guess that's the crux of the matter -- and this "research you've seen" appears to give results that directly contradict the everyday experience reported by the growing band of users of dynamically typed languages. Refer, for example, to Robert Martin's article I already gave the URL to, the one that starts with the confession that he used to be a static-typing bigot: typing issues *just do not arise in practice* when he develops in dynamically typed languages (he quotes Python and Ruby) in a test-driven way (which, he says, he's now addicted to, and uses all the time even when he has to program in statically typed languages on the job). My own personal experience is quite similar (I also started out as a static-typing bigot, although in my case the epiphany about the usability of dynamically typed languages came earlier, with APL, REXX, Scheme). If TDD was indeed prone to leave in the code the kind of bugs that statically-typed languages can catch, then I just don't see how to explain "Uncle Bob"'s empirical observations, which match so well with mine (and many other such reports such as Eckel's). Thus, I tend to be skeptical about the "research you've seen" -- what _were_ they comparing? Was it actually about the copious mass of simple but thorough unit-tests that emerges from TDD, or about the more traditional practice of slapping on a few sample runs as an afterthought and _calling_ those "tests"...?-) Alex From marc at informatik.uni-bremen.de Sun Jun 22 17:58:08 2003 From: marc at informatik.uni-bremen.de (Marc Recht) Date: Sun, 22 Jun 2003 23:58:08 +0200 Subject: Does current Python2.3CVS work on FreeBSD5.1 or FreeBSD5-current? In-Reply-To: <20030622110043.X48767@bullseye.apana.org.au> References: <2251d03c.0306211119.64824456@posting.google.com> <20030622110043.X48767@bullseye.apana.org.au> Message-ID: <85190000.1056319088@leeloo.intern.geht.de> > It will if you tell it to use a threads library. > > Find the LIBC variable in the Makefile, and add -lkse to it. > > This was discussed in SF patch #745320 (now closed). > > The building of threaded apps has changed on 5.x, and nobody has yet > contributed a patch to configure.in to cater for the difference between > 5.x and 4.x. I've just submited a patch (#758910) to SourceForge which fixes that problem by adding -pthread to CXX, too. (Tested on today's -current.) HTH, Marc mundus es fabula -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From kamikaze at kuoi.asui.uidaho.edu Sun Jun 29 01:42:50 2003 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 29 Jun 2003 05:42:50 GMT Subject: Possible project - Python mail proxy to do greylisting, etc. References: Message-ID: Fri, 27 Jun 2003 18:49:38 +0200, Fredrik Lundh : > Richie Hindle wrote: >> async and Twisted are basically >> the same thing. > yeah, but one of them comes with more hype. I'm using asyncore in my new Python online game project: So far, it's worked well. It's fast, reliable, and easy to use. The only major complaint I have is that on Windows, it can hang on a sudden exit; I can kill it from Cygwin, but normal Windows users will have zombie processes. I'm not sure if I care enough to find out why. I just didn't see any real advantage to using Twisted, when I could use something already in the library. -- Mark Hughes "We remain convinced that this is the best defensive posture to adopt in order to minimize casualties when the Great Old Ones return from beyond the stars to eat our brains." -Charlie Stross, _The Concrete Jungle_ From a.schmolck at gmx.net Wed Jun 18 11:34:41 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 18 Jun 2003 16:34:41 +0100 Subject: a clean way to define dictionary References: <3EEFEBFD.8090003@nospam.com> Message-ID: Alex Martelli writes: > Sean 'Shaleh' Perry wrote: > > > On Tuesday 17 June 2003 21:35, Kendear wrote: > >> > >> or is there a more common way to define a dictionary > >> without all the punctuation marks? > > > >>>> def make_dict(**kwargs): > > ... return kwargs > > ... > >>>> make_dict(foo=1, bar='sean') > > {'foo': 1, 'bar': 'sean'} > > > > is the most common form I have seen. Not sure if it works for you. > > In 2.3, you can express this as dict(foo=1, bar='sean') without a > need to define a function for the purpose. Yuck! This seems like a really bad idea to me. This effectively makes it impossible to specify any options (such as initial size, default value etc.) at dict creation for dict subclasses or lookalikes or indeed future versions of dict itself! Not a good tradeoff for minor syntactic sugar, IMO! If this sugar is really needed, couldn't dict grow an appropriate classmethod instead (e.g dict.with(foo=1, bar='sean))? 'as From gh at ghaering.de Mon Jun 30 11:39:44 2003 From: gh at ghaering.de (=?ISO-8859-9?Q?Gerhard_H=E4ring?=) Date: Mon, 30 Jun 2003 17:39:44 +0200 Subject: Partition names with Python In-Reply-To: <1056984252.3f004cbc6abd6@mail.uzem.itu.edu.tr> References: <1056984252.3f004cbc6abd6@mail.uzem.itu.edu.tr> Message-ID: <3F0059C0.1090102@ghaering.de> Erhan Ekici wrote: > Hi, > > How do I get partition names (i.e. C:\ , D:\ ,E:\ on windows, hda,hda1 , hda2 > on Linux machines) using Python. On Windows, this requires the win32 extensions. See http://www.faqts.com/knowledge_base/view.phtml/aid/4670/fid/245 Why would you want to do this on Unix? Anyway, you could use commands.getoutput() to read in the result of the 'mount' command and parse it. -- Gerhard From kkennedy65 at yahoo.com Fri Jun 6 17:58:52 2003 From: kkennedy65 at yahoo.com (kk) Date: 6 Jun 2003 14:58:52 -0700 Subject: Newbie in developping Webapplications needs tips. References: Message-ID: <8b336527.0306061358.531b1073@posting.google.com> "Raaijmakers, Vincent (IndSys, GE Interlogix)" wrote in message news:... > Currently I try to to gather information about web development by > reading books (Python Webprogramming, PHP and MySQL Web Development) > searching on Google etc etc.. > The plan is to develop HTML pages for presenting data from a database, > configure objects and execute python code from these pages. > > My aim is to use as much python as possible because of 1) the experience > in that area and 2) the existing python application we would like to > support with HTML. > I'm familair with java's JSP technology, so PSP could be a good choice. > However, when I read about PHP, this looks also very usefull. But, it is > not python.... > > So my question is, what advise can the guru's give me here? > What is a good start. > > Any advise, tips, references to articles would be appriciated. > > Thanks, > Vincent I would start here: http://www.modpython.org/ It is probably closer to the Java Servlet model rather than JSP. From Mathieu.Malaterre at creatis.insa-lyon.fr Wed Jun 11 13:52:52 2003 From: Mathieu.Malaterre at creatis.insa-lyon.fr (Mathieu Malaterre) Date: Wed, 11 Jun 2003 19:52:52 +0200 Subject: list.remove(): bug ?? Message-ID: Hi all, here is a very simple script: liste = ['foo1' , 'foo2', 'foo3', 'foo4', 'foo5' ] for i in liste: if i == 'foo2': liste.remove( i ) else: print i But the result is: foo1 foo4 foo5 How should I do to still print 'foo3' ?? thanks a lot, mathieu From peter at melchart.com Wed Jun 4 11:28:12 2003 From: peter at melchart.com (Peter Melchart) Date: Wed, 04 Jun 2003 15:28:12 GMT Subject: nntplib body question References: <879Da.1139848$uT2.175876@news.easynews.com> <7xhe7678dk.fsf@ruckus.brouhaha.com> Message-ID: > The overview database (xover command) might be able to provide a > solution without pounding on the news server too badly. Simply > breaking the connection in the middle is going to leave a nnrpd > lingering around. Are you intending to only do this once in a while, > or are were you planning to do this for lots of articles in some sort > of scan? that's the problem. i would like to do that on a huge basis. problem is: i would like to extract the filename of a binary posts. and i think there's no other way of doing that but reading the body and looking for a "begin 664 name" or "name=..." for yEnc encoded post. but if i would read ALL binary posts that would be a little bit too much traffic to spend. :( but i don't feel fine cutting all connection on every file. cheers Peter From danb_83 at yahoo.com Thu Jun 12 01:01:43 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 11 Jun 2003 22:01:43 -0700 Subject: Looking for the greatest negative float value References: Message-ID: mwilson at the-wire.com (Mel Wilson) wrote in message news:... > In article , > "Gilles Lenfant" wrote: > >Hi, > > > >I need the same as... > > > >import sys > >negmaxint = - sys.maxint -1 > > > >... but for float data [snip] > -1.7976931348623157e+308 > > and that last number seems credible. Close. The exact value, per the IEEE 754 standard, is -(2 ** 1024 - 2 ** 972), or -1.7976931348623155e+308. How did you get a *higher* magnitude? From belred1 at yahoo.com Tue Jun 3 20:23:51 2003 From: belred1 at yahoo.com (Bryan) Date: Wed, 04 Jun 2003 00:23:51 GMT Subject: Yield inside try...finally References: <3EDCEC1F.96CB0766@hotmail.com> Message-ID: i thought i just read in another thread that you couldn't/shouldn't put yield inside of the try block. does this thread contradict the other thread? someone please explain. thanks, bryan "Alan Kennedy" wrote in message news:3EDCEC1F.96CB0766 at hotmail.com... > Michael Sparks wrote: > > > What I'd *like* to do (which doesn't work) is: > > > > try: > > sock = socket(AF_INET, SOCK_STREAM); > > try: > > sock.setblocking(0); yield stage.done(0) > > try: > > sock.connect((self.host, self.port)); yield stage.done(1) > > yield newComponent([self.setupCSA(sock)]) > > while self.waitCSAClose(): > > yield stage.current(2) > > yield stage.done(2) > > finally: > > result = s.shutdown(1) ; yield stage.done(3) > > finally: > > sock.close() ; yield stage.done(4) > > except error, e: > > # Would handle error more interestingly here > > print stage.lastdone, e > > > > OK, I think this one works now. I've coded and successfully run a dummy > version which reacts properly, even when exceptions are explicitly raised. > > The code below obviously won't run, because the "yield"s are used outside of a > function definition. But it is a direct modification of the code you said you > would like to have. > > You will still have to *guarantee* that the generator is resumed for this to > work. > > #-------------------------------------------------- > > class Finality(Exception): pass > > try: > sock = socket(AF_INET, SOCK_STREAM); > try: > sock.setblocking(0); yield stage.done(0) > try: > sock.connect((self.host, self.port)); yield stage.done(1) > yield newComponent([self.setupCSA(sock)]) > while self.waitCSAClose(): > yield stage.current(2) > yield stage.done(2) > raise Finality > except Exception, x: > result = s.shutdown(1) ; yield stage.done(3) > raise x > except Exception, x: > sock.close() ; yield stage.done(4) > raise x > except error, e: > # Would handle error more interestingly here > print stage.lastdone, e > except Finality: > pass > > #-------------------------------------------------- > > fingers crossed behind back, alan hopes he won't embarass > himself again, and gives a nervous smilie :-} > > -- > alan kennedy > ----------------------------------------------------- > check http headers here: http://xhaus.com/headers > email alan: http://xhaus.com/mailto/alan From djc at object-craft.com.au Thu Jun 19 21:11:48 2003 From: djc at object-craft.com.au (Dave Cole) Date: 20 Jun 2003 11:11:48 +1000 Subject: ANNOUNCE: JOTWeb 1.11, preview of new web application system. References: <20030617162210.GB5896@tummy.com> <1055884182.1169.11.camel@emilio> <20030619102215.GC23876@tummy.com> Message-ID: >>>>> "Sean" == Sean Reifschneider writes: >> 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. Sean> Sure. Along those lines, I'm adding to JOTWeb a way to set up Sean> per-site startup scripts (probably of both HTML/TAL and Python Sean> varieties, so that you can use whichever one is more Sean> comfortable). I'm tempted to add per-page "configuration" Sean> because it would be easy, but it seems that it can be handled Sean> directly in the HTML/TAL (tal:define) or in the normal python Sean> modules. >> 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() Sean> I don't really think that it makes sense to have the user have Sean> to build up the namespaceto say what "currenttime" is. I think I am getting confused now. Does the above mean that JOTWeb development is performed by both users and developers, or does it mean that all developers who use JOTWeb to build applications are users of JOTWeb? If you mean developer when you say user then the developer is the person designing the layout of the directory tree containing code.py so it can be visible to the namespace mechanisms in JOTWeb. This is still building up a namespace. Sean> It just makes sense to me that if you ask for the "currenttime" Sean> attribute of the "code" entity, and you have a module called Sean> "code" which contains a function "currenttime", that you (as an Sean> application framework) can go ahead and call that for the user, Sean> instead of making the user go through the extra step of creating Sean> a context, importing the module, and setting up a name in the Sean> name-space... All true. But you are still building a namespace. I still go back to me original point - if you are building an application with more functionality than simply poking values into templates then this is a minor issue. A issue with this (at least in my mind) is that the most obvious use of the toolkit has it reaching its tentacles deeper into your application. I can see ways to work around this which means it is not such a big deal. Maybe I should try to explain where I am coming from. I firmly believe that for all but the most trivial of applications you need to separate the presentation and implementation. This allows you to develop and modify the one aspect of the application mostly without breaking the other. Initially the effort is higher as you trade both elements off against the other until an effective interface emerges. In the medium to long term though, the separation yields savings. Mind you there is no need to separate implementation and presentation if your application is all presentation. Assuming that we are talking about the same thing here, and there is some implementation component of the application, then it is worthwhile separating the two elements. Once you have separated the two elements you need some mechanism to connect them. In Model View Controller (MVC) talk, the view is the presentation, the model is the implementation, and the connecting code is the controller. In building a non trivial MVC application (especially a web based application), the vast majority of the effort goes into building the model and the view. Relatively speaking the controller pales into insignificance. Having said that maybe I can go back and make my point again. Toolkits such as JOTWeb and Albatross provide a framework in which you implement your glue or controller. You are still responsible for providing the presentation and implementation components. Whether you import your code explicitly, or have it imported for you via JOTWeb attributes is no big deal. Sean> Big Deal or not, it seems to me that like 90% or more of the Sean> time when you have a template and somebody references it, you Sean> want to provide a name-space and render it. I put a template Sean> there for a reason -- to be rendered to the browser. I really Sean> believe that if that is such a common case, that the user Sean> shouldn't have to do anything special to make it happen. But they do need to do something special. They need to place the code into a module so it can be imported by JOTWeb. When it comes down to it the only thing that JOTWeb is saving over Albatross is one import statement. I am still maintain that is not a big deal. Sean> It's no big deal to specify time.localtime(time.time()) as the Sean> argument to strftime(), but I definitely think that making that Sean> the default was a good thing... >> 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> That's what it boils down to... Sean> It seems to me, now, that you could do the same thing with Sean> Albatross, using a default handler with mod_python and Sean> overriding the context. I am not sure I follow here, but you are probably right. >> When you make something implicit you remove some flexibility from >> the application developer. I imagine you wondered from time to >> time when Sean> I'm not sure that I agree that making something implicit Sean> prevents it from being overridden. So far, in the development Sean> I've done with JOTWeb, I haven't really run into a case where I Sean> wanted to change the default behavior in a way that required me Sean> to override the default rendering code, yet still have it do Sean> template rendering. I hope that my discussion above clarifies what I was trying to say. I think that each approach has merit. Both toolkits provide a way to cut down on the amount of code you need to write in order to deliver a web application, and both provide a framework for organising your application code. This is a big win for the developer. If a developer finds the JOTWeb approach a more natural fit for their application requirements and development style then that is a win for them. The same goes for Albatross. I really don't think there is a killer framework that is suitable for all applications. - Dave -- http://www.object-craft.com.au From sameer_ at email.com Mon Jun 9 12:25:47 2003 From: sameer_ at email.com (sameer) Date: 9 Jun 2003 09:25:47 -0700 Subject: reading/writing files in windows Message-ID: <6bd9f01b.0306090825.37845495@posting.google.com> I create files in windows using python. I have tried using \n and \r\n as the return character and they both work fine. It's when I move a text file, written by my python program, across a network, open the file and save to it that all the text becomes jumbled up, and all return characters are lost. How can I make it so this doesn't happen? From ed at membled.com Sat Jun 7 16:44:04 2003 From: ed at membled.com (Ed Avis) Date: 07 Jun 2003 21:44:04 +0100 Subject: a = b = 1 just syntactic sugar? References: Message-ID: Steven Taschuk writes: >Ignoring the problems due this just being an example, and >concentrating just on the question of lambda's restrictions, I >don't see why you can't just use def: > > def maybe_unify(x, y): > if x == y: > def change(X): > pass > elif x == []: > def change(X): > X.extend(y) > else: > change = None > return change Yes - I don't know why I didn't think of that. Thanks for the suggestion. Of course it seems a little clunky to define these functions with a name that is then never used except to return them anonymously, but it should work. -- Ed Avis From artyprog at wanadoo.fr Fri Jun 13 13:20:24 2003 From: artyprog at wanadoo.fr (Salvatore) Date: Fri, 13 Jun 2003 19:20:24 +0200 Subject: Twice instanciation In-Reply-To: References: Message-ID: anton muhin wrote: > Salvatore wrote: > >> Hello, >> >> Is it possible to avoid twice instanciation >> of the same variable ? >> >> class Global: >> def __init__(self,init=0): >> self.value = init >> >> g = Global() #instanciating one time ok >> g = Global() #instanciating two times would raise an exception >> >> >> Regards >> >> Salvatore >> > > Bindings class might be of help (see > http://www-106.ibm.com/developerworks/linux/library/l-prog2.html for > more details). > > hth, > anton. > That's exactly what I wanted :-) Thank you very much Anton From husam at macrozon.net Fri Jun 6 10:55:18 2003 From: husam at macrozon.net (Husam) Date: Fri, 6 Jun 2003 16:55:18 +0200 Subject: Newbie: How do you enable python scripts in apache server? References: <3EDF5EC6.6050704@sci.kun.nl> Message-ID: Thanks alot for the tips. I solved it. The problem was the absence of this statement AddHandler cgi-script .py in httpd.conf From roy at panix.com Fri Jun 27 00:11:33 2003 From: roy at panix.com (Roy Smith) Date: Fri, 27 Jun 2003 00:11:33 -0400 Subject: Python executables? References: <3EFAFB13.1090506@removeme.free.fr> Message-ID: W Isaac Carroll wrote: > When choosing between programming languages there is little correlation > between size of code and speed of execution. However, within a given > language size and speed are usually opposing considerations. For > example, to speed up a loop you often unroll it thus decreasing > execution time at the expense of increasing code size. With the kinds of I-cache architectures common today, you can get some unexpected effects. It's possible that the increase in code size from unrolling a loop blows your cache and ends up running slower. If you ever get to the point where you're worrying about loop unrolling, you'd better really understand the hardware you're running on, and do a lot of benchmarking to make sure you're getting the improvement you expect. Benchmarking non-deterministic things like cache behavior is an adventure in itself. My general philosophy these days is to write it how it makes sense and let the compiler take care of the optimizing. But then again, I don't do the kind of stuff where grubbing a CPU cycle here or there makes a difference. From mlh at furu.idi.ntnu.no Fri Jun 6 13:11:11 2003 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Fri, 6 Jun 2003 17:11:11 +0000 (UTC) Subject: Efficient data flow between orthogonal C extensions? References: <87el29rpmv.fsf@smtp.gsi.de> <87znkwwmbg.fsf@smtp.gsi.de> Message-ID: In article , Thomas Heller wrote: >mlh at furu.idi.ntnu.no (Magnus Lie Hetland) writes: [snip] >I have no answer to this question, and haven't really followed the >thread, but I have the vague impression that ctypes could also help >here. It allows to create C callable callback functions from Python >callable objects, see the qsort example in the tutorial. Sounds good -- but that's only under Windows? (Or?) >Thomas -- Magnus Lie Hetland "In this house we obey the laws of http://hetland.org thermodynamics!" Homer Simpson From drs at ecp.cc Sat Jun 21 02:32:33 2003 From: drs at ecp.cc (drs) Date: Sat, 21 Jun 2003 06:32:33 GMT Subject: Find a substring withing a string... References: Message-ID: <5_SIa.672$BM.513812@newssrv26.news.prodigy.com> "FooBar" wrote in message news:MPG.195db98e90b83bb49899fe at netnews.attbi.com... > OK I will be the first to admit that I am VERY new to Pythin and > know little of the syntax of this language. I want to perform the > simple task of testing to see if a substring exists within string. I > think the syntax is find(sting,substring) and the return is -1 if the > substirng is not found otherwise the start position of the substring in > the string. is this correct? > > Moreover is this code totally screwed? > > > takeaction = find(stringvar,'LITERALSUB') > if takeaction != -1: > action_to_take_if_found > else: > action_tp_take_if_not_found find() is not builtin, so you would need to do something like >>> import string >>> string.find(stringvar,'LITERALSUB') but this is the old way of doing things. since 2.0 (?) one can do it this way >>> if stringvar.find('LITERALSUB') >= 0: >>> action_to_take_if_found >>> else: >>> action_tp_take_if_not_found as the string is an object with a find method. more importantly, however, is that you should test code snippets like this at the command prompt. it's the best way to learn. -drs From tireseas at onetel.com Fri Jun 20 13:04:06 2003 From: tireseas at onetel.com (valhalla) Date: Fri, 20 Jun 2003 18:04:06 +0100 Subject: Using OS time In-Reply-To: <16115.12621.163636.630622@montanaro.dyndns.org> References: <20030620152602.22899.77521.Mailman@mail.python.org> <200306201645.16587.tireseas@onetel.com> <16115.12621.163636.630622@montanaro.dyndns.org> Message-ID: <200306201804.06330.tireseas@onetel.com> Hmmm - I'm not at all familiar with signal.alarm() nor how to use it Skip. After googling for info on this, I found this at http://www.linuxjournal.com/modules.php?op=modload&name=NS-lj-issues/issue73&file=3946l5 ---begin code--------- Listing 5. Using Alarm Signal #! /usr/local/bin/python import signal import sys def alarm_handler(signal, frame): print 'BOOM!' sys.exit(0) signal.signal(signal.SIGALRM, alarm_handler) signal.alarm(5) # generate SIGALRM after 5 secs n = 0 while 1: print n n = n+1 -----end code------ This seems to be the closest to what you describe. I'll play around with this and see what it does. I suppose a lengthier but more n00bie friendly way of doing this 'countdown' would be to countdown from a given number (e.g. 60) and import time.sleep to sleep for 1 second at each new iteration in the for loop. I think this would do the same thing. Anyway, I'll fool around with both of these options and see which one I find easier to work with. Thanks Skip. Andy On Friday 20 Jun 2003 17:07, Skip Montanaro wrote: > 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 -- ==================== || Reg. Linux User: 313143 || ==================== Sign the Petition: http://www.PetitionOnline.com/endtcpa1/ From 2002 at weholt.org Sat Jun 21 23:11:01 2003 From: 2002 at weholt.org (Thomas Weholt) Date: Sun, 22 Jun 2003 05:11:01 +0200 Subject: FOAF-parser?? References: Message-ID: I've come abit further parsing FOAF-files. The result is available for download at http://www.weholt.org, but it's still a bit buggy, for instance it crashes when I tried to load Mark Pilgrims FOAF-profile. Still, it can generate rather easily a structured FOAF-document and load data from a xml-file or an url. It has some special properties not part of the FOAF-standard, but they're in a seperate namespace in the xml-file and should not be hard to remove or not use for people who want to use it for ordinary FOAF-stuff. If anybody has time to test it that would be nice. Problems remaining are : 1. cannot get the encoding set correctly in the generated document. This means norwegian characters and other non-english characters will cause the document to be seen as invalid xml. THIS IS A MAJOR PROBLEM. Any help here would be appreciated. 2. The code is very verbose. I'm not good at creating xml in code other than doing the old hard way. Hints on how to do it more object-like are welcome, allthough the way I do it now works ok too. 3. The parser uses DOM, ie. everything is read into memory. Other solutions, like using minidom or SAX/Expat are welcome. I cannot use anymore time on this at the moment, due to other deadlines. It has not been tested on huge documents so I know nothing about speed etc. 4. Better support for all the goodies available in RDF, like Dublin Core and Syndication elements. Eh ... support for some of them, any support at all, would be an improvement. Best regards, Thomas Weholt "Thomas Weholt" <2002 at weholt.org> wrote in message news:M6XIa.8186$Hb.144201 at news4.e.nsc.no... > Hi, > > I need a FOAF[1]-parser that can handle deep-hierarchy of nodes ( ie. > Friends knowing friends knowing friends etc. ) So far I've looked at > 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. > > Any help would be highly appreciated. > > [1] : http://xmlns.com/foaf/0.1/ > [2] : http://www.aaronsw.com/2002/tramp > > Best regards, > Thomas Weholt > > From elmar.hoefner at uibk.ac.at Sat Jun 14 18:22:09 2003 From: elmar.hoefner at uibk.ac.at (Elmar W. Hoefner) Date: Sun, 15 Jun 2003 00:22:09 +0200 Subject: Reading from a FIFO, burning CPU References: Message-ID: Hi Terry! Terry Reedy wrote: > Like you told it to do. Unless you have some other work to interleave > with this process, this is no more wasteful than the CPU's or OS's own > idle loop Well, here it seems like ball and chain: even moving my mouse is exhausting, but anyway... > Simplest: try sleeping between readline() calls to free up CPU time ...this works perfectly now, thank you! >> >> 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 now: if line == '': time.sleep(1) else: print line Thanks for your help, E. -- | Elmar W. Hoefner | You can send me encrypted mail. Get my public GPG key from | http://home.pages.at/oeller/files/pubkey.txt | Fingerprint: B5D9 2544 A06A 6760 E16A 46BF 5A6B B7EF B530 08E2 From aahz at pythoncraft.com Thu Jun 19 10:37:44 2003 From: aahz at pythoncraft.com (Aahz) Date: 19 Jun 2003 10:37:44 -0400 Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> Message-ID: [As usual, Alex demonstrates his logorrhea right before he has to vanish on a long trip. ;-) I was unable to read the whole thing, but managed to get far enough to nitpick something.] In article , Alex Martelli wrote: > >In Python one generally identifies (just as informally) a container as >"an object which has a length" (using "length", perhaps a suboptimal >choice of wording, to mean "number of items currently contained") and >simultaneously express both 'c is a container' and 'that container is >not empty' by > > assert len(c) Hmmmm.... I would only do that for a sequence. From my POV, classes, class instances (even those not implementing any special methods), and modules all serve as containers for the purpose of determining what an appropriate "container object" is for any particular program. -- 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 fperez528 at yahoo.com Mon Jun 2 14:50:05 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 02 Jun 2003 12:50:05 -0600 Subject: Request for feedback on my first Python program References: Message-ID: Martin Franklin wrote: > as of Python 2.0 the string module is not needed (string's have methods...) Not true. Until strings have _all_ the methods in the strings module, we'll still need it: In [8]: import string In [9]: s='abc' In [10]: string.zfill(s,9) Out[10]: '000000abc' In [11]: s.zfill(9) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) ? AttributeError: 'str' object has no attribute 'zfill' Best, f. From mis6 at pitt.edu Mon Jun 16 13:42:31 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 16 Jun 2003 10:42:31 -0700 Subject: class variable declarations... References: <3EEDD08E.C973E017@hotmail.com> Message-ID: <2259b0e2.0306160942.2c3a5cca@posting.google.com> Alan Kennedy wrote in message news:<3EEDD08E.C973E017 at hotmail.com>... > Lee John Moore wrote: > > > My biggest mental block with python seems to be undeclared variables. A > > declaration block alone is handy for reference. Statically typed > > languages have really messed me up. Is there a therapy group for > > refugees? ;-) > > How about this, using new style classes:- > > class SpeedTouchComm(object): > "Interface with the SpeedTouch router" > > __slots__ = ['connect', 'uid', 'pwd', 'rtuid', 'rtpwd'] > > def __init__(self, connect, uid, pwd, rtuid, rtpwd): > self.connect = connect > self.uid = uid > self.pwd = pwd > self.rtuid = rtuid > self.rtpwd = rtpwd > self.namenotinslots = '' > > >>> o = SpeedTouchComm(1,2,3,4,5) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 12, in __init__ > AttributeError: 'SpeedTouchComm' object has no attribute 'namenotinslots' > >>> > > There are more sophisticated ways to manipulate object instances and data, for > example using descriptors or __metaclasses__. But I think that this mostly > solves your difficulty. > > HTH, A recent thread (google is your friend) pointed out that __slots__ should NOT be used as a way of declaring variables. It is much better if you use descriptors or metaclasses. Here is a (little tested) solution: class UndeclaredNameError(Exception): pass class WithDeclaredNames(type): def __init__(cls,name,bases,dic): declared=getattr(cls,'declared') def setattr(self,k,v): if k in declared: object.__setattr__(self,k,v) else: raise UndeclaredNameError(k) if declared is not None: cls.__setattr__=setattr class SpeedTouchComm(object): "Interface with the SpeedTouch router" __metaclass__=WithDeclaredNames declared = ['connect', 'uid', 'pwd', 'rtuid', 'rtpwd'] def __init__(self, connect, uid, pwd, rtuid, rtpwd): self.connect = connect self.uid = uid self.pwd = pwd self.rtuid = rtuid self.rtpwd = rtpwd self.namenotinslots = '' o = SpeedTouchComm(1,2,3,4,5) Traceback (most recent call last): File "", line 28, in ? File "", line 26, in __init__ File "", line 11, in setattr __main__.UndeclaredNameError: namenotinslots From peter at engcorp.com Sat Jun 14 11:49:35 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 14 Jun 2003 11:49:35 -0400 Subject: wxPython download References: Message-ID: <3EEB440F.49A1D3C2@engcorp.com> Lorenzo Bolognini wrote: > > 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 Works, here, now. If by "aren't working" you meant that you couldn't select a mirror, start a download, and see the progress dialog box showing data streaming to your machine, then either it's fixed or it's not a general problem. I didn't actually complete the 6.72MB download that I started, nor did I try to run the resulting file. (This was with the Py2.2 version of the Win32 wxPython, BTW.) -Peter From bogus@does.not.exist.com Thu Jun 26 20:17:11 2003 From: bogus@does.not.exist.com (Me Mine) Date: Thu, 26 Jun 2003 20:17:11 -0400 Subject: win32ui screen capture Message-ID: 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 ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From aleax at aleax.it Thu Jun 12 12:58:20 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 12 Jun 2003 16:58:20 GMT Subject: vector subscripts in Python? References: <3064b51d.0306111512.7701dbbc@posting.google.com> Message-ID: Alexander Schmolck wrote: ... > function is worthwhile (note that it allows works for dicts and other > iterables). > > def at(iterable, indices): > return [iterable[i] for i in indices] Careful: it does NOT allow for iterables -- it needs 'indexables', i.e., sequences or mappings. You can't pass it a file object, a generator, and other iterables yet. On the other hand, it WILL be perfectly happy with a mapping that's not iterable (i.e. doesn't implement __iter__) as long as it does implement __getitem__ -- that's what it needs, and all it needs. So, I would suggest choosing a different name for the formal argument that you have chosen to name 'iterable', as that name might be slightly misleading. Alex From rnd at onego.ru Tue Jun 24 11:23:58 2003 From: rnd at onego.ru (Roman Suzi) Date: Tue, 24 Jun 2003 19:23:58 +0400 (MSD) Subject: XML In-Reply-To: <3EF85DDA.4F4B57C6@hotmail.com> Message-ID: On Tue, 24 Jun 2003, Alan Kennedy wrote: >> I initially thought there might be some gain from being able to use >> material written for other languages to learn the API, but don't >> know how most users learn the DOM; do they read the DOM Recommendation, >> look at tutorials, read the implementation source, or just copy >> existing code? > >I read the DOM Recommendation :-)& But I did all of the others as well, >at different stages, and I think most people end up doing more than one >as well. As for me, I read Python programs which operated DOMs ;-) I think, I learned some parts of C library in the same way. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From gh at ghaering.de Sun Jun 22 14:14:40 2003 From: gh at ghaering.de (=?UTF-8?B?R2VyaGFyZCBIw6RyaW5n?=) Date: Sun, 22 Jun 2003 20:14:40 +0200 Subject: Updating to Python 2.2.3 In-Reply-To: <3ef5ef46@news.mt.net.mk> References: <3ef5ef46@news.mt.net.mk> Message-ID: <3EF5F210.8000809@ghaering.de> ?????? ?. wrote: >>I would like to update Python 2.2.2 to the newest version (2.2.3). Do I >>have to uninstall the older version first? Do i have to reinstall all >>the side-packages (VPython, wxPython etc.)? I'm running Windoze XP. > > In Linux I've installed 2.2.3 over 2.2.1 and everything is working, even > modules written in C like cx_Oracle,MySQLdb, PyQT etc... Sure, given Python versions a.b.c and x.y.z with (a == b) and (b == y), they're guarantee'd to be binary compatible. With a != x, the Python developers try to keep binary compatibility, but it's sometimes not possible. The reason this doesn't work on Windoze is AFAIK that the extension module is linked to a specific DLL, so either python22.dll or python23.dll. -- Gerhard From delphiro at zonnet.nl Fri Jun 6 09:49:58 2003 From: delphiro at zonnet.nl (delphiro) Date: Fri, 06 Jun 2003 15:49:58 +0200 Subject: list.index Message-ID: <5.2.1.1.0.20030606154116.009ed760@pop3.zonnet.nl> 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] Thanks in advance, Rob From peter at engcorp.com Mon Jun 9 07:36:39 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 09 Jun 2003 07:36:39 -0400 Subject: Hardware take on software testing. References: <2ae25c6b.0306060450.78e988f9@posting.google.com> <3EE3FA53.7FC50F50@engcorp.com> <3EE4577D.2020409@blueyonder.co.ukNOTthisBIT> Message-ID: <3EE47147.4954C6A2@engcorp.com> Donald 'Paddy' McCarthy wrote: > > I guess one of the things I question about XP then is this notion that > you only add good code to your program because of the quality of your > tests; and that prudent re-factoring also gets rid of unnecessary code. > If you are doing the above manually then I think that you could gain a > lot by using coverage tools to help assess the quality of your tests not > necessarily w.r.t. a spec, but in how well those tests cover your > program. Coverage tools can be applied automatically for simple but > useful results, or can give more detailed results with manual > intervention. If someone is doing XP for a commercial project, why not > invest in coverage tools? A coverage report could be part of every peer > review, or generated as a matter of course during development if > runtimes are not too long. Well, XP certainly neither requires nor prevents you from using coverage tools, but merely suggests strongly that you should do so only when the benefits outweigh the costs. It also suggests not doing so "just because" but only when there is a specific driving need. I suggest that most XP groups find that their test coverage is already excellent and they find little reason to add another layer to their process. My own group, for example, has easy access to PyCover (or whatever it's called) but hasn't bothered to implement it yet. The areas of code which have been driven with tests seem to have 100% coverage, and until we get bitten at least once, there's no particular reason to check up on that theory. I realize that will sound backwards to some people, but in practice it's an approach that works rather well in the face of tight resource constraints. > Random constrained generation wouldn't have to be seen as outside XP or > TDD. If the language used for writing tests had good support for random > generation, and software engineers were trained in the technique, it > would just become another type of arrow in their quiver on their hunt > for bugs on their quest for quality software. (Whoops, getting a little > flowery towards the end there :-) We have also considered using randomized test input but we haven't seen a test case where we felt that would add much value (for the higher cost of implementing it properly). Again, XP neither requires nor prevents a group from using such a thing, it merely doesn't discuss it. This is the case with dozens of specific tools that other processes might mention and require. XP tries to be lightweight and avoid forcing specific tools or very fine-grained processes on people. To paraphrase Yogi Berra, then, on randomized tests: if people don't want to use them, XP isn't stopping them! :-) -Peter From roman at syxx.de Tue Jun 17 03:46:44 2003 From: roman at syxx.de (Roman Meisl) Date: Tue, 17 Jun 2003 09:46:44 +0200 Subject: Question about Python-Grammar References: <6qk7bmnq7e.fsf@salmakis.intevation.de> Message-ID: <6hhtev0t34c0lnj8i4g4b41iqcmhj7qr0d@4ax.com> Hello, On Mon, 16 Jun 2003 13:53:57 -0700, W Isaac Carroll wrote: >The basic idea here is that "as" ought to be a keyword in Python, but >for historical reasons isn't. My understanding is that making it a >keyword has been looked into and it would be more trouble than it's worth. Thank you for your help. But I've to commit, with every glance I look deeper into python-grammar, I realize this all is weird crap! Why aren't things statet clear and correctly? (see also my posting above) Bye Roman From enrico_morelli at yahoo.com Thu Jun 5 10:37:18 2003 From: enrico_morelli at yahoo.com (Enrico Morelli) Date: Thu, 05 Jun 2003 16:37:18 +0200 Subject: Python & CGI. HELP please... References: Message-ID: On Thu, 05 Jun 2003 07:54:26 -0400, Jay Dorsey wrote: > 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 > You are ready. I rewrite the method as follow and seems to be works: Thanks a lot. def download(self, fullname, file): try: f=open(fullname,"r").read() print 'Content-type: application/octet-stream; name="%s"' % file print 'Content-Disposition: inline; filename="%s"' % file print 'Content-length: %s' % len(f) print sys.stdout.write(f) except: msg="An error occurred during file transfer." Display(msg, "") sys.exit() >> 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() From tjreedy at udel.edu Sat Jun 21 16:44:53 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 21 Jun 2003 16:44:53 -0400 Subject: "a in b" calls a.__cmp__, why? References: Message-ID: "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. 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. Terry J. Reedy From rochkind at basepath.com Sun Jun 22 13:21:03 2003 From: rochkind at basepath.com (Marc Rochkind) Date: Sun, 22 Jun 2003 11:21:03 -0600 Subject: Choosing between two Jython books... References: <3EF59459.D7732CE7@hotmail.com> Message-ID: On Sun, 22 Jun 2003 12:34:49 +0100, Alan Kennedy wrote: [snip] > 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. > Yes... that's me. Thanks for the kind words! I'm working on the 2nd edition, which is scheduled to be out this Fall. Thanks for the book advice! My interest in Jython is mainly because then I can use Swing instead of Tkinter. Because I use Swing with Java, it allows me to learn only one GUI. --Marc From peter at engcorp.com Thu Jun 26 11:28:52 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 26 Jun 2003 11:28:52 -0400 Subject: Reading a binary file References: <3EFAF999.2F77CACF@engcorp.com> Message-ID: <3EFB1134.3140F39A@engcorp.com> Sorin Marti wrote: > > Byte Number/Length Type Hex-Value > ---------------------------------------------------------------- > Byte 12,13,14,15,16: Real BB 42 C8 00 00 > > you can call > getValue('REAL',12,16) and you should get back 100 because if you have > 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 think you might be interpreting (or explaining?) the format of that real incorrectly. If the first bit is the sign, and the next 8 bits are the exponent, and the rest is mantissa, then your exponent should be 01110110 (or h76 or d118) and your mantissa value in hex would be all of the 42 C8 00 00, or 1120403456 in decimal. (Basically, your binary value as shown is wrong. BB42C80000 is really 1010 1010 0100 0010 1100 1000 0000 0000 0000 0000 0000 and not your value of 0100 0010 1100 1000 0000 0000 0000 0000 as shown above.) -Peter From ed at membled.com Mon Jun 9 15:00:09 2003 From: ed at membled.com (Ed Avis) Date: 09 Jun 2003 20:00:09 +0100 Subject: a = b = 1 just syntactic sugar? References: <5XudnbZ19_UAZ36jXTWcpg@comcast.com> Message-ID: "Terry Reedy" writes: >>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() [one of three ways to resolve this] >3) adding the return-deleted template as an alternative, with the >compiler choosing the 'correct' version. As things stand, this is >problematical (ambiguous) because, as Martin noted in another post, >expressions are (a subset of) expression-lists are >expression_statements are (a subset of) simple_statements. I believe >disambiguation would require new grammar productions for >multiple_expression_list and non_expression_simple_statement and >corresponding revision of expression_list and simple_statement. Yes, it might. Or it might be possible to set some flag for 'please save the return value of an expression used as an expression_stmt, rather than throwing it away', and set this flag while executing the body of a lambda function, returning the value given. Then no need for a further grammar change. But I need to look at the code. >(Whether the result would still be LL(1) remains to be tested.) I do not know whether the change to allow simple_stmt inside lambda would keep the grammar LL(1). However, a simple splitting of the existing simple_stmt production into two different cases would not change the strings produced by the grammar or its LL(1)-ness. >Choice 3) would complexify the meaning (translation) of lambda to >depend on the nature of the body. Yes, because although you could write f = lambda x: x + 1 and get a return value from f(), you would get different results from def f(x): x + 1 So the surprise of 'hmm, putting x[0] = 5 in my lambda function body doesn't seem to work' has been replaced by the surprise of 'hey, why isn't a value being returned from my function, it worked fine as a lambda'. I think this is probably a smaller inconsistency in the language but it is a matter of opinion. (FWIW, maybe it would be a good idea for an error to be raised if you try to get the return value of a function that did not have a return statement, rather than getting the default None as at present. If you write 'x = f()' then this shows an expectation that f is a function returning a value, not a mere procedure which finishes execution with no return statement.) -- Ed Avis From goodger at python.org Tue Jun 24 22:48:38 2003 From: goodger at python.org (David Goodger) Date: Tue, 24 Jun 2003 22:48:38 -0400 Subject: [ANN] Docutils 0.3 released Message-ID: <3EF90D86.6010801@python.org> Docutils is a system for processing plaintext documentation (reStructuredText markup). Docutils currently supports input from standalone files and PEPs; a future release will be include support for inline documentation from Python modules and packages. It currently produces simple HTML4 for CSS1, LaTeX (which can be processed to PDF), and Docutils-native XML. DocBook XML output is under development, and other formats will become available in time. Quick link to the download: http://prdownloads.sourceforge.net/docutils/docutils-0.3.tar.gz Docutils home page: http://docutils.sourceforge.net/ Although useful and solid, Docutils should be considered experimental software. There are plans to overhaul the configuration system and rename the front-end tools. Internal and API details may change. There have been many improvements since release 0.2: * Extensions to reStructuredText syntax & parser: embedded URIs in hyperlink references; interpreted text; block quote attributions. New directives: admonition, topic, sidebar, line-block, parsed-literal, rubric, epigraph, highlights, pull-quote, include, raw, replace, unicode, class, sectnum, target-notes. * Added convenience functions for easy programmatic/library use. * Added LaTeX output support (thanks to Engelbert Gruber). * The front-end tools have increased in number and now have support for command-line options (thanks to Greg Ward's Optik) and configuration files. * reStructuredText has become an official format for PEPs (see http://www.python.org/peps/pep-0001.html). * Thanks to international Docutils users, language support has been added for Spanish, French, Italian, and Slovak. These join the existing Swedish, German, and English language support. Support for more languages is welcome and easy to add! * Lots of improvements and bug fixes. Details in HISTORY.txt. To subscribe to the mailing lists: * Development discussions (docutils-develop at lists.sourceforge.net): http://lists.sourceforge.net/lists/listinfo/docutils-develop * Docutils usage Q&A (docutils-users at lists.sourceforge.net): http://lists.sourceforge.net/lists/listinfo/docutils-users * CVS checkin messages: http://lists.sourceforge.net/lists/listinfo/docutils-checkins High-level discussions also take place on the Python Doc-SIG mailing list: http://mail.python.org/mailman/listinfo/doc-sig. User documentation: * A ReStructuredText Primer (gentle introduction): http://docutils.sf.net/docs/rst/quickstart.html * Quick reStructuredText (user reference): http://docutils.sf.net/docs/rst/quickref.html * Docutils Front-End Tools: http://docutils.sf.net/docs/tools.html Further details here: * Docutils FAQ: http://docutils.sf.net/FAQ.html * Docutils README: http://docutils.sf.net/README.html * Docutils History: http://docutils.sf.net/HISTORY.html * Copying Docutils: http://docutils.sf.net/COPYING.html * reStructuredText Markup Specification: http://docutils.sf.net/spec/rst/reStructuredText.txt * PEP 256, Docstring Processing System Framework: http://www.python.org/peps/pep-0256.html * PEP 258, Docutils Design Specification: http://www.python.org/peps/pep-0258.html * PEP 287, reStructuredText Docstring Format: http://www.python.org/peps/pep-0287.html There are still many features to be added. Contributors are welcome! -- David Goodger http://starship.python.net/~goodger Programmer/sysadmin for hire: http://starship.python.net/~goodger/cv From andymac at bullseye.apana.org.au Wed Jun 11 07:25:27 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Wed, 11 Jun 2003 21:25:27 +1000 (EST) Subject: Python Coredump on FreeBSD In-Reply-To: References: <0pCdnbUTkYU6W16jXTWcow@speakeasy.net> Message-ID: <20030611204615.C89523@bullseye.apana.org.au> On Tue, 10 Jun 2003, Harald Schneider wrote: > Sorry for the huge delay ... if I compile with this option, my app fails > with a missing 'import thread' in line 5 of threading.py .... > "Andrew MacIntyre" schrieb im Newsbeitrag {...} > > ./configure --without-threads Ok, so you're using threads... I have verified that: - FreeBSD's pthreads implementation (libc_r) has a hard coded 1MB stack for the "initial" thread (the one that starts all other threads), that cannot be changed without rebuilding the library; - the Linuxthreads port doesn't have the same limitation, and appears to function sufficiently similarly to libc_r that the regression test doesn't fail. You should be able to try the linuxthreads build out by: - install the linuxthreads port - configure Python as normal - modify the Makefile as follows: + remove any "-pthread" from the CC variable; + remove any "-lc_r" from the LIBS variable; + add "-I/usr/local/include/pthread/linuxthreads" to the CPPFLAGS variable; + add "-L/usr/local/lib -llthread" to the LIBC variable. - make - make test I've just checked this recipe with a 2.2.3 build; it should also work with a recent CVS sourcebase. The sre recursion limits have been tweaked again in the current CVS tree for FreeBSD, to reduce the risk of hitting the stack size limit. Regards, Andrew. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From jfabiani at yolo.com Wed Jun 11 21:00:26 2003 From: jfabiani at yolo.com (John Fabiani) Date: Thu, 12 Jun 2003 01:00:26 GMT Subject: Why not BOA GUI builder? Message-ID: Hi, I just found BOA and I'm wondering why it took so long to here about it. Why doesn't everyone use BOA? What are the negatives? It appears to be roses just running the demo. So before I spend lots of time on BOA I'd like to hear from the neighborhood. TIA -- John Fabiani From dwblas at yahoo.com Thu Jun 19 20:03:08 2003 From: dwblas at yahoo.com (DavidW Blaschke) Date: Thu, 19 Jun 2003 17:03:08 -0700 (PDT) Subject: Python Mega Widget doubt. Message-ID: <20030620000308.85009.qmail@web21605.mail.yahoo.com> With a getvalue(). It is in the documentation with an example on the Pmw web site (next time please check the docs first): http://pmw.sourceforge.net/doc/EntryField.html > --- In python-list at yahoogroups.com, Rajesh Sudarsan > wrote: > > Hi, > > I am using PMW for creating a GUI. The input is > given > through XML file. A class parses through the XML > file and > creates the GUI using the PMW. The GUI consists of > EntryWidgets and combo boxes. This is carried out at > loading > time. Now at runtime, when I change the value of > these Entry > Fields , how do I read these values? There are > multiple XML > files and hence multiple windows are created .. > > Please help.. > > Regards, > > Rajesh > > > > > > --------------------------------- > > Do you Yahoo!? > > SBC Yahoo! DSL - Now only $29.95 per month! > __________________________________ Do you Yahoo!? Yahoo! Calendar - Free online calendar with sync to Outlook(TM). http://calendar.yahoo.com From max at alcyone.com Wed Jun 11 19:35:34 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 11 Jun 2003 16:35:34 -0700 Subject: Octets calculation? References: <65eFa.634621$Si4.577158@rwcrnsc51.ops.asp.att.net> <3EE79F73.E08C2554@alcyone.com> Message-ID: <3EE7BCC6.5903B43F@alcyone.com> Skip Montanaro wrote: > 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. No, I'm referring to embedded systems where the smallest addressable unit really is 16 or 32 bits. In those systems, a byte is larger than an octet. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ We grow in time to trust the future for our answers. \__/ Ruth Benedict From mertz at gnosis.cx Sat Jun 21 23:39:05 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sat, 21 Jun 2003 23:39:05 -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 carljohan.rehn at chello.se Sun Jun 15 05:18:37 2003 From: carljohan.rehn at chello.se (carljohan.rehn at chello.se) Date: Sun, 15 Jun 2003 11:18:37 +0200 Subject: Interfacing Python with C++ Message-ID: <1wWGa.11812$KF1.273586@amstwist00> I have understood that there are many toolkits and libraries available for extending Python with C++ (eg SWIG, CXX, Boost, etc). Can someone guide me on the advantages and disadvantages? Which one is the simplest to learn and use? Do they work equally well with Linux and Windows (eg using Visual C++ and DLL:s)? Yours /Carl From Chris.Rennert at mdi-oshkosh.com Wed Jun 25 12:23:57 2003 From: Chris.Rennert at mdi-oshkosh.com (Chris Rennert) Date: Wed, 25 Jun 2003 11:23:57 -0500 Subject: SSL in Python Message-ID: <3ef9cc58$0$837$39cecf19@news.twtelecom.net> I noticed in the documentation that they have ssl() in Python, but it says only if configured. I just can't find info on how to configure SSL in Python. My goal is to write a simple p-2-p chat, but have all info encrypted between clients. Any help you could give me would be greatly appreciated! Chris From aahz at pythoncraft.com Tue Jun 3 23:43:37 2003 From: aahz at pythoncraft.com (Aahz) Date: 3 Jun 2003 23:43:37 -0400 Subject: Possible PEP: Improve classmethod/staticmethod syntax References: <20030603164521903-0400@braeburn.themorgue.org> Message-ID: [BTW, please make sure to attribute quotes. I've restored the correct attributions.] In article , Bryan wrote: >Aahz wrote: >>In article <20030603164521903-0400 at braeburn.themorgue.org>, >>Kevin Smith wrote: >>> >>>The current way of declaring a method to be a class method or a static >>>method leaves much to be desired. While it is flexible in the sense >>>that new types of method modifiers can be created without any >>>syntactical backwards incompatibilities, it just isn't that user- >>>friendly (and, in turn, not Pythonic). >> >> No argument; Guido considers the current method experimental. The >> current front-runner for fixing this is to add function decorators: >> >> def myMethod(args) [staticmethod]: >> blah, blah, blah >> >> staticmethod would be a callable object that would return the >> replacement function object. This would allow chained decorators. > > i'm sorry, but i'm not following you. can you please explain to me >what you mean by staticmethod being a replacement function object? so, >staticmethod isn't a keyword here? i must be missing something here, >because this seems weird to me. staticmethod is not a replacement function object, it *returns* a replacement function object for myMethod. That is, the object bound to myMethod (*not* "myMethod()") is passed to staticmethod, and staticmethod returns an object that is re-bound to myMethod. You are correct that staticmethod is not a keyword, any more than "str", "list", "len", or "myMethod" are keywords -- that is in fact the whole point of this proposal, because it requires no new keywords and a minimal change to the Python parser. A key advantage is that adding Design By Contract to Python becomes much easier this way. -- 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 mis6 at pitt.edu Mon Jun 16 12:49:06 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 16 Jun 2003 09:49:06 -0700 Subject: Cannot build Tk under RedHat References: <3EECF794.3030700@zg.hinet.hr> Message-ID: <2259b0e2.0306160849.12f1d442@posting.google.com> Haris Bogdanovic wrote in message news:<3EECF794.3030700 at zg.hinet.hr>... > 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 I do not understand if you are trying to build Python from sources or from the rpm packages. I have found (under Red Hat 7.3) that it is actually simpler to build from sources. The rpm dependencies are mixed up and you must install the various rpm in a given order to get it working. BTW, I have found problems in building Tkinter from sources in a system with an old version of PMW installed, is this your case? Michele From jtauber at jtauber.com Thu Jun 19 03:32:24 2003 From: jtauber at jtauber.com (James Tauber) Date: Thu, 19 Jun 2003 15:32:24 +0800 Subject: Feature Structures in Python (Part I) In-Reply-To: <20030619055903.GC10203@frobozz> References: <20030619053141.6BF4835EC4@www.fastmail.fm> <20030619055903.GC10203@frobozz> Message-ID: <20030619073224.1515D34CD2@www.fastmail.fm> On Thu, 19 Jun 2003 15:59:03 +1000, "Andrew Bennetts" said: > On Thu, Jun 19, 2003 at 01:31:41PM +0800, James Tauber wrote: > > > > This is the first part of a tutorial/cookbook I'm writing up on > > implementing feature structures in Python. > > What's a "feature structure"? It's a data structure commonly used in linguistics. Its use in phonology goes back to the early twentieth century and it was first used for syntax by Chomsky in 1955. Recently (the last twenty years, say), it has become the prominent formal structure in a number of approaches to grammar (particularly head-driven phrase structure grammar and related constraint-based approaches) and computational linguistics. Part I of my doc pretty much covers the actual data structure (there's not really much more I could tell you without getting in to the specific application to linguistics). The next two parts (which I'll send soon) cover "subsumption" which is the feature-structure equivalent of set-theoretic subset and "unification" which is the equivalent of set-theoretic union. A lot of feature-structure-based tools are written in Lisp or Prolog. I believe there is at least one Java library too. I'd like to see Python used more in linguistics and this is part of my contribution towards that goal :-) > > I'd love any feedback (particularly on the Pythonicity of my approach). > > [...] > > > # The del operator can be used to remove features. For example > > Actually, del is a statement. Thanks for that catch. Normally I'm more careful about such things :-) > > del fs5[HEAD][AGR][NUMBER] > > [...] > > > # If you wish to delete all features in a particular structure or > > # sub-structure, you can iterate over the keys of the dictionary and > > # delete each one. > > But you'd be better off just using the .clear() method of dicts. > > > for f in fs5[HEAD][SUBJ][AGR].keys(): > > del fs5[HEAD][SUBJ][AGR][f] > > So this would become simply: > > fs5[HEAD][SUBJ][AGR][f].clear() Oops. Forgot about clear(). Thanks! James -- James Tauber http://jtauber.com/ From mrdovey at iedu.com Thu Jun 5 21:37:30 2003 From: mrdovey at iedu.com (Morris Dovey) Date: Thu, 05 Jun 2003 20:37:30 -0500 Subject: LANGUAGE QUESTION??? References: <8dcf2300.0306040159.118c24e8@posting.google.com> Message-ID: <3EDFF05A.2040106@iedu.com> Reginald Blue wrote: > 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? Monkey wrench. Care should be exercised to avoid being bitten during (and immediately after) use. Avoid over-tightening as it makes them scream. -- Morris Dovey West Des Moines, Iowa USA C links at http://www.iedu.com/c From max at alcyone.com Mon Jun 2 23:05:24 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 02 Jun 2003 20:05:24 -0700 Subject: 123.3 + 0.1 is 123.3999999999 ? References: <3EC3BCCD.3090605@nospam.com> <895e4ce2.0306021736.13c657a5@posting.google.com> Message-ID: <3EDC1074.CA05EC23@alcyone.com> Grant Edwards wrote: > In article <895e4ce2.0306021736.13c657a5 at posting.google.com>, D.W. > wrote: > > > 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... > > Wha? I defy you to find a system where 1 isn't stored exactly. I suspect he's being facetious, since 0.999... = 1. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Success and failure are equally disastrous. \__/ Tennessee Williams From jeewee.AND.NO.SPAM at ai.rug.nl Mon Jun 2 06:39:12 2003 From: jeewee.AND.NO.SPAM at ai.rug.nl (jeewee) Date: Mon, 2 Jun 2003 12:39:12 +0200 Subject: pypgsql installation Message-ID: after installing postgresql-python.rpm I get this when I try to run my code: [jeewee at shakira blog]$ python pg-test.py Traceback (most recent call last): File "getupdates.py", line 5, in ? from pyPgSQL import PgSQL File "/usr/lib/python2.2/site-packages/pyPgSQL/PgSQL.py", line 349, in ? from libpq import * File "/usr/lib/python2.2/site-packages/pyPgSQL/libpq/__init__.py", line 23, in ? from libpq import * ImportError: /usr/lib/python2.2/site-packages/pyPgSQL/libpq/libpqmodule.so: undefined symbol: PyUnicodeUCS2_EncodeDecimal could someone lead me to the light? From m at moshez.org Fri Jun 13 12:27:53 2003 From: m at moshez.org (Moshe Zadka) Date: 13 Jun 2003 16:27:53 -0000 Subject: OT: swearing (was: RE: OnFileOpent(self, event)) In-Reply-To: References: Message-ID: <20030613162753.3750.qmail@green.zadka.com> On Fri, 13 Jun 2003, Tim Golden wrote: > We don't pretend it's the worst thing you can do, but still we encourage > them to gain a degree of control over what they say, and when, and in what > circumstances, and to whom. Well, I must say that if I was a boy in the club, I'd probably make a point of "casual swearing" just to piss off people like you. Seriously :) Now, maybe I was a pretty annoying kid (actually, I'm sure I was), but that kind of policy just gives the boys an easy way to apply laverage... PS Re: making a point: When I make a point, "fuck" seems way too dreary. Perhaps it is the result of its overuse, but I think it's *good* to encourage people to substitute the unthoughtful "fuck you" with things like "I'll kill you, slaughter your family, harass your friends, then dig up your ashes out and piss on them". Or "I hope you choke, go to hospital and have an operation which lives you unable to speak louder than a whisper" I mean, come *on*, sex isn't insulting. If the boys in your club aren't able to come up with colourful swears containing no explicit language, they should be taught creative writing. -- 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 Hedr Wed Jun 25 11:08:00 2003 From: Hedr (Hedr) Date: Wed, 25 Jun 2003 15:08:00 GMT Subject: Newbie Question: can this snippet be optimized? Message-ID: <3ef9ba07.117801375@news.skynet.be> 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 I just wondered if this could be optimized (mao, array, whatever) and if so, how? I do not have much experience with Python, hence the question. Thanks for suggestions, Hedr From fredrik at pythonware.com Thu Jun 26 11:21:24 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Jun 2003 17:21:24 +0200 Subject: catch non-blocking socket exceptions References: Message-ID: Axel Bock wrote: > or better still - does someone know how to set the tcp timeout value? THIS > would greatly simplyfy my task :-) for 2.3, use the "settimeout" socket method (or the setdefaulttimeout function): http://www.python.org/dev/doc/devel/lib/module-socket.html http://www.python.org/dev/doc/devel/lib/socket-objects.html older versions: http://www.timo-tasi.org/python/timeoutsocket.py or use asyncronous sockets, and time out when you get bored waiting for some socket action: http://www.effbot.org/zone/effnews-1.htm (asyncore basics) http://www.effbot.org/zone/effnews-3.htm (look under "managing downloads") From peter at engcorp.com Tue Jun 3 11:50:16 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 03 Jun 2003 11:50:16 -0400 Subject: "for line in fd" twice References: Message-ID: <3EDCC3B8.F036F097@engcorp.com> "cqx": please don't top-post! "cqx.purple.gold" wrote: > Thomas G?ttler writes: > > > the following does not work: > > > > """ > > fd=open(file) > > for line in fd: > > if line.startswith("mymark"): > > break > > # seek backwards the length(line) > > > for line in fd: > > #Read lines after "mymark" > > .... > > fd.close() > > """ > > You probably need to rewind the file using 'seek'. I don't think he wants to go back to the beginning, although it was a little unclear. I think he wants to be able to continue from where he left off... Since with .readlines() the fd object maintains its state, presumably if there is a similar approach using the implicit iterator that is produced when you do "for line in fd" you would be able to use that. I doubt you can do it with the implicit iterator, however, since the reference to it would be lost after you exit the for block, so why not try an *explicit* iterator: fiter = iter(open(file)) for line in fiter: if line. blah blah: break for line in fiter: if line blah blah: break This seems to work. -Peter From P.Schnizer at nospam.gsi.de Thu Jun 5 11:55:47 2003 From: P.Schnizer at nospam.gsi.de (Pierre Schnizer) Date: 05 Jun 2003 17:55:47 +0200 Subject: Efficient data flow between orthogonal C extensions? References: <87el29rpmv.fsf@smtp.gsi.de> Message-ID: <87znkwwmbg.fsf@smtp.gsi.de> mlh at furu.idi.ntnu.no (Magnus Lie Hetland) writes: > In article <87el29rpmv.fsf at smtp.gsi.de>, Pierre Schnizer wrote: > >mlh at furu.idi.ntnu.no (Magnus Lie Hetland) writes: > > > [snip] > >If you are using callbacks, > > That was, at least, my original idea, although a more centralized > version would also be possible. > > >you can wrap the callbacks with swig. > > Sounds good.... > > >While swig will not generate helpers to call python functions from C, > >you can pass pointers to C functions. > >http://www.swig.org/Doc1.3/SWIG.html#n30 Yes but as far as I understand the callbacks must be implemented in C. > > Hm. I don't quite get this... This piece of documentation does seem to > work with Python-implemented callbacks... And the name-based approach > strikes me as a bit impractical. A callback has to have a given name > to be applicable -- or am I misunderstanding? Even though this doesn't > mean that the extensions need to know about each other, conceptually, > the would need to know what the methods of the other extensions are > called... > > It would be nice to be able to supply the extension with an arbitrary > object (e.g. a PyCObject) and have it cast it and use it itself. Of > course, assigning a function to a variable with the correct name (if > that would work) isn't too much of a nuisance. > > Any input on this? Am I misunderstanding the functionality? And... I > suppose the declared callbacks would be in the namespace of the > extension module? (Otherwise, how would it be imported?) In that case, > wouldn't it be necessary to assign a function pointer to it anyway? > Hm... > > I guess I'll have to look into whether this is the way to go (and > perhaps actually try it before speculating too much ;). Thanks for the > input. > Perhaps I should have been more explicit. If I get your viewpoint correctly, I can answer: SWIG generally can do the job you described above. Here now the explanation in more detail. You can wrap your C Function (which in your case happens to live in an other module). SWIG will export that function to Python as a string or a PyCObject, as you wish. You pass this "variable" to the module. The SWIG wrapper will convert the PyCObject into the approbriate callback and call your C extension. What I wanted to stress and what misled you, (I guess), was that SWIG does not help you to automatise writting a C callback, which will call the python function. (At least I do not know about ...). For example f2py can parses the code of a Fortran ODE solver and will automatically generate a wrapper and a callback wrapper. Thus one can use it to integrate a function written in Python. In the SWIG case you have to write the callback wrapper by hand. But as you want to use C Functions in both cases that is not too much of concern for you. Perhaps a example. Consider the gsl root solver (partly taken from http://pygsl.sf.net). The swig interface part for the root solver looks like that: extern int gsl_root_fsolver_set (gsl_root_fsolver * s, gsl_function * BUFFER, double X_LOWER, double X_UPPER) This is the C description from the header. gsl_function is the interesting part. This is the function to integrate. If you had a C function you would wrap this function and then pass the wrapped "variable" from python as a variable. Here it is interesting to be able to integrate a python function. Therefore a C wrapper was written. This function is called by the gsl roots solver. double PyGSL_function_wrap(double x, void * params) { double result; callback_function_params *p = NULL; p = (callback_function_params *) params; tmp = PyEval_CallObject(p->function, p->arguments); result = PyFloat_AsDouble(tmp); return result; } On the entry side, there is an other wrapper which puts the callback and its arguments in the p struct and sets PyGSL_function_wrap as callback for the root solver. I hope that cleared the point a bit what I wanted to express. Regards Pierre From tom_verbeure at hot.nospam.mail.com Sat Jun 7 21:43:10 2003 From: tom_verbeure at hot.nospam.mail.com (Tom Verbeure) Date: Sun, 8 Jun 2003 03:43:10 +0200 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> <2ae25c6b.0306070624.141e4b42@posting.google.com> Message-ID: <3ee29460$0$268$ba620e4c@reader0.news.skynet.be> > 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. There are some major differences between hardware and software develoment that make directed random testing (DRT) much less efficient for software. Conceptually, a software program is basically one HUGE statemachine where every variable in the data memory influences the progress of the state machine (even if you don't usually think like it that way.) In hardware, you also have a whole bunch of explicitly designed state machines that work in parallel. Those statemachines will change state based on the input simuli and the time at which they arrive. The goals of directed random testing in hardware is to find cases where one or more statemachines get tricked into certain corner cases that are hard to trigger manually. 2 parallel but interacting statemachines come to mind here. By randomly changing input data AND the time at which it arrives for a long time, you can be reasonably sure that you trick the hardware into most corner cases. This technique is not very useful for software, especially if it's single threaded: if the software isn't interactive, there isn't much chance of problems due to arbitration between parallel events, since there aren't any. :-) (A lot of DRTs are written to find arbitration errors between statemachines.) I In addition, to make DRT really useful, you need a golden model to verify that the results generated by randomly generated data is correct. This means you need to write a certain piece of software twice, with exactly the same higher level behaviour. How would you verify, say, a Python interpreter with random testing? By writing one in C and another one in Java, throwing random instructions at them and checking the behaviour, right? Well, you just created 2 highly complex multi-man-year projects. :-) Due to the huge up front costs and turn around time, it makes sense for hardware to make a golden model. Not in the least because it's very easy to describe complicated hardware with simple logical statements. Eg. a linked list manager in hardware can cost you weeks of design time, but in your verification language (eg. Specman's 'e', it's 1 line of code.) That being the case, the cost of writing a gold model is minimal compare to the cost to design the hardware. For software, it's the same effort... twice. In other words, for software, it's not cost effective, since it's usually quite easy to make bugfixes in later revisions and tell a customer not to use a particular feature for a while or quickly ship a patch. It's much harder to tell the user of an IP router chip to avoid packets that contain a certain sequence of bytes and to wait 6 months for a new revision of the chip that can then be replaced on the PCB. > 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? Apparently it is good enough for most people, since virtually nobody will go farther than that. Tom From mertz at gnosis.cx Tue Jun 10 15:11:12 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Tue, 10 Jun 2003 15:11:12 -0400 Subject: PEP 318 - Function Modifier Syntax References: Message-ID: Courageous wrote previously: |As well, I. While it would be better on general principle to find a |better word, if no such word is forthcoming this particular use of 'as' |isn't at all confusing to me. As you point out, 'as' is a high utility |English word already. Users ought to be familiar with its inherit |dynamicity. :) I would be quite happy with the word 'as' to list function modifiers. It seems like good English to me--albeit a somewhat different connotation than 'import x as y'. But just to throw options out, 'make' is another short word that works in the context, IMO. And 'make' is not used in a different sense within Python. I.e. def foo(x,y) make staticmethod: ...do stuff... Yours, Lulu... -- _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/ _/_/ ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~ _/_/ _/_/ The opinions expressed here must be those of my employer... _/_/ _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/ From timr at probo.com Thu Jun 19 00:43:19 2003 From: timr at probo.com (Tim Roberts) Date: Wed, 18 Jun 2003 21:43:19 -0700 Subject: Bug (??) in the time module? References: <_wuHa.4165$87.2880721@newssrv26.news.prodigy.com> <3eef2d20$1_1@themost.net> Message-ID: Anoop Aryal wrote: >Paul Watson wrote: >> >> C:\src\python\t>tim.py >> Tue Jun 17 09:48:01 2003 >> (2003, 6, 17, 9, 48, 1, 1, 168, -1) >> Tue Jun 17 09:48:01 2003 >> >> > >your time tuple is different from mine (of course. but i'm talking about >the last number in the list). it would be interesting to see if you got >the same number on linux and windows at the last position in the tuple >(here it's -1) The last number in the list is the "is this daylight savings time" flag, so it is vitally relevant to your problem. You could get around your problem by forcing the proper value (time.daylight) into that element, but I agree with you that you should not need to do so. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From news at manuelmgarcia.com Mon Jun 2 12:10:36 2003 From: news at manuelmgarcia.com (Manuel Garcia) Date: Mon, 02 Jun 2003 16:10:36 GMT Subject: dictionary issue (and maybe PEP ... depending on the answer) References: <0wBCa.651$ig1.627675@newssrv26.news.prodigy.com> Message-ID: <1eqmdvo7m7dqptpcvpeg44afccln67djr6@4ax.com> Cheap trick for 1-based lists, just have an extra 'None' in the 0th position: _month_names = [ None, 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] Steven Taschuk's code is the most general technique: months = [(1, 'January'), (2, 'February'), # ... ] monthdict = dict(months) monthnames = [name for number, name in months] Trivial to write a function: def sorted_keys(dict0): newlist = dict0.keys()[:] newlist.sort() return newlist print [_months[i] for i in sorted_keys(_months)] The reason Python doesn't have a 'return a sorted copy' (non-destructive) built-in method for lists is that the fastest sorting algorithms are all 'in-place' (destructive). Python has as a rule "there is only one way to do it", so the 'in-place' sort was chosen as the only built-in method. As you can see above, it is easy to write your own 'non-destructive' sort. The reason that list0.sort() returns 'None' when used in an expression, is so that you will never use it in an expression! The sort's 'in-place' behavior is thus made explicit. Manuel From ngps at netmemetic.com Tue Jun 3 20:50:54 2003 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 4 Jun 2003 00:50:54 GMT Subject: Blogging Software References: <87add0b98l.fsf@mally.pyrite.org> Message-ID: According to Rob Tillotson : > There are quite a few... here are just a few links culled from my own > weblog, wherein I try to link to all of them as I find them, lest I > forget: > > Weblog server tools: > Vellum - http://www.kryogenix.org/code/vellum/ > pyblosxom - http://roughingit.subtlehints.net/pyblosxom/ > mombo - http://www.intertwingly.net/code/mombo/ > Python Desktop Server - http://pyds.muensterland.org/ > Rantelope - http://www.rantelope.com/ > Byline Server - http://pyrite.org/byline/ > > Other weblog related Python stuff: > HEP Message Server - http://www.fettig.net/projects/hep/ > tblib (outgoing Trackback library) - > http://postneo.com/projects/tblib/ > TBPY (incoming Trackback CGI) - http://markpasc.org/code/tbpy/ > pyblogger and RSS tools - http://diveintomark.org/projects/ > Byline - http://pyrite.org/blogauthor/ Thanks Rob and Moshe for the pointers. Cheers. -- Ng Pheng Siong http://firewall.rulemaker.net -+- Manage Your Firewall Rulebase Changes http://www.post1.com/home/ngps -+- Open Source Python Crypto & SSL From LogiplexSoftware at earthlink.net Thu Jun 5 12:04:07 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 05 Jun 2003 09:04:07 -0700 Subject: Tk vs wxPython ? In-Reply-To: References: Message-ID: <1054829046.2139.5.camel@software1.logiplex.internal> On Wed, 2003-06-04 at 22:41, Christian Tanzer wrote: > What you seem to miss is the number of viable toolkits for GUI > development. Contrary to your impression, it is not obvious that > wxPython is the way to go. IMHO, wxPython scores worse than both pygtk > and pyqt. I doubt that any real consensus about the *one* toolkit will > emerge any time soon. wxPython would be preferred over pygtk because it has been ported to more platforms. pyqt would be problematic for people not developing open source projects. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From martin at v.loewis.de Wed Jun 25 14:13:31 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 25 Jun 2003 20:13:31 +0200 Subject: Got it: printing Unicode characters during telnet session References: Message-ID: Pekka Niiranen writes: > How about adding better font to Python distribution ? -1. Dealing with operating system fonts is not our business. Regards, Martin From max at alcyone.com Thu Jun 19 14:17:58 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 19 Jun 2003 11:17:58 -0700 Subject: Algorithm help per favore References: <2ec1bc1c.0306180746.159679d6@posting.google.com> <5ab0af73.0306181828.512d5b00@posting.google.com> <3EF12866.CE8C3913@alcyone.com> <5ab0af73.0306190740.49202cb3@posting.google.com> Message-ID: <3EF1FE56.F8C2BA9C@alcyone.com> Matt Shomphe wrote: > I think this may be faster than calling enumerate() repeatedly. Unlikely, since you're only calling enumerate once. `for x in seq' evaluates seq once and then iterates over it; it doesn't evaluate seq each time through the loop. Indeed, enumerate was introduced precisely to obviate the need for indexing over lists of indices and mapping those to the original sequence. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Wars may be fought with weapons, but they are won by men. \__/ Gen. George S. Patton From goboborz at yahoo.com Fri Jun 20 10:57:29 2003 From: goboborz at yahoo.com (Gobo Borz) Date: Fri, 20 Jun 2003 09:57:29 -0500 Subject: cgi getlist() problem (my first python program) References: <3EF1CFC0.2010803@yahoo.com> <3EF1DA5E.AC6C4F68@hotmail.com> <3EF216A2.8040508@yahoo.com> <3EF31CAA.B5DB5FCD@hotmail.com> Message-ID: <3EF320D9.8040909@yahoo.com> Thank Alan and everyone. It's good to have a forum where people like you and Max M and John J. Lee, and countless others take the time to help Python newbees like me. --Gobo Alan Kennedy wrote: > Alan Kennedy wrote: > > >>>One way to approach the problem is by numbering the fields in your >>>HTML form >> > > Gobo Borz wrote: > > >>I didn't want to use this approach because I thought I would have to use >>eval() or something like that on the server side to build the field name >>during iteration. > > > You don't need to use eval. You could just extract the numeric part and > turn that into an integer, for example using regular expressions: > > import re > > s = "name123" > pattern = re.compile("name([0-9]+)") # Pedants go bother someone else ;-) > match = re.search(pattern, s) > if match: > print "Your number is %d" % int(match.group(1)) > > >>Maybe there's an easier way in Python to iterate >>through a list of names like this, > > > Yes, there is. Max M wrote it in another message (and a nice solution it is too, > Max). That's probably the way to go. > > Best of luck. > From achrist at easystreet.com Tue Jun 10 11:06:06 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Tue, 10 Jun 2003 08:06:06 -0700 Subject: data base References: Message-ID: <3EE5F3DE.ABBF797B@easystreet.com> sismex01 at hebmex.com wrote: > SQLite is a C libary which embeds a SQL engine and a database > manager into your applications; it's quite small, and terribly > fast (err... "hideously fast".. hmmm... "awfully fast"...) > very, very fast. :-) > I think I saw in the docs that SQLite uses a 1k page size. OTOH, looking at other database software I see page sizes typically 8k-32k. Don't Windows computer want to always read disk in 4k chunks? Why does SQLite have such small page size? Does this help or hurt performance? I'm using SQLite with good results and no complaints. Just curious. Al From manuelbastioni at tin.it Sat Jun 7 09:02:39 2003 From: manuelbastioni at tin.it (Manuel) Date: Sat, 07 Jun 2003 13:02:39 GMT Subject: Play a short sound... Message-ID: I'm almost a newbie in python... Exist a way to play a short sound (i.e. .wav) ? thx, Manuel From andy at wild-flower.co.uk Sun Jun 22 15:10:05 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Sun, 22 Jun 2003 20:10:05 +0100 Subject: Remove duplicate letters in a word In-Reply-To: <20030622181107.GA13125@rootshell.be> References: <20030622181107.GA13125@rootshell.be> Message-ID: <200306222010.05755.andy@wild-flower.co.uk> On Sunday 22 Jun 2003 7:11 pm, Eliran Gonen wrote: > Hello ! > > I'm new in this list. > > Anyway, I'm trying to write some sort of encryption program (pretty > trivial and simple) that need to check for several occurences of a letter > in a specific word. > > For example, in the word SECRET, E appears twice, I need to get rid of > the second instance of E. > > 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, > > TIA, EG I notice Steven Taschuk and Roman Suzi have jsut replied whilst I was testing out my answer... oh, well - I'll throw in my penny's worth anyway.... As steven says, because strings are immutable (meaning you can't change them once created) the code above can't work. Here's a trace of waht I came up with (I've cut out the stuff that duplicates Steven's work): >>> word=list("flibble dibble dee doo") >>> n=0 >>> while n < len(word): while word[n] in word[n+1:]: sec=word[n+1:].index(word[n]) del word[n+1+sec] n+=1 >>> word ['f', 'l', 'i', 'b', 'e', ' ', 'd', 'o'] >>> word="".join(word) >>> word 'flibe do' >>> word=list("secret") >>> n=0 >>> while n < len(word): while word[n] in word[n+1:]: sec=word[n+1:].index(word[n]) del word[n+1+sec] n+=1 >>> word="".join(word) >>> word 'secrt' >>> I wasn't sure you wanted to remove *all* subsequent occurrences, but that's what this code does. The outer while loop iterates over each item in the list. As we're changing the list, we have to use an index into it (that's 'n'). Next we have a loop which checks if the letter we're now looking at (word[n]) exists in the *rest* of the list (word[n+1:]). Inside the inner loop, we then pinpoint the *next* occurrence of the letter, the zap it (del word[n+1+sec]). Now, again outside the inner loop, we increment to pointer (n) and have another go, until n is past the end of the list. Outside the main loop, we join the list back together as a string and show it. Hope that helps. BTW if you only want to remove the second occurrence of each letter, just use an 'if' rather than a 'while', but beware that it'll remove every second occurrence, unless you use some way to remember which letters you've already zapped... maybe a further exercise. good luck -andyj From frobozz_electric at hotmail.com Sun Jun 1 12:47:39 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 1 Jun 2003 16:47:39 GMT Subject: Is there a better way of coding this? References: <1qpCa.1442$V77.44294@news20.bellglobal.com> Message-ID: Here's a possible solution, although it does not address your problem completely. For instance, it requires optf to be a method that takes no arguments (other than 'self'). def readonly(attrname, default, optf=None): def get(obj): value = default try: value = getattr(obj, attrname) except AttributeError: setattr(obj, attrname, default) if optf is not None: value = optf(obj) return value return property(fget=get) class C: def __init__(self, data): self.data = data def adjustfoo(self): return 2*self.data # this statement must be placed somewhere # after the definition of your optf functor foo = readonly('_foo', 1, optf=adjustfoo) instance = C(2) print instance.foo # outputs 4 From deja-google at wotevah.com Thu Jun 19 19:48:12 2003 From: deja-google at wotevah.com (L.C.) Date: 19 Jun 2003 16:48:12 -0700 Subject: threads duplicated on fork() prevent child from terminating Message-ID: The simple program below launches a thread, then forks() and attempts to clean the mess up on exit like the nice process it is. Only problem is, the child does not want to die, looks like it detached and is sitting on schedule_timeout() (according to ps). This is, I suspect, because the thread and its state are duplicated on fork() but the state structure is not updated to indicate that the thread is in fact NOT active so the child is fooled into waiting for its termination, which will never happen. If the parent terminates without executing waitpid(), the child will hang there indefinitely wasting resources. I can see the following ways to actually have it finish normally: 1) parent join()-s all the threads before fork(): not always possible. 2) parent kill()-s the child: not nice. 3) child does os._exit(): IMHO the best option but os._exit() is not described as an elegant exit method. Using this also means that if all exceptions are not handled in the thread, we risk the same problem. I guess I have answered 90% of my question (which I have not stated) already. At any rate, it seems to me that this matter should be handled internally in Python's core. Regardless of whether os._exit() is mandated for use in child processes or not instead of sys.exit() or other exception handlers, I find it somewhat illogical to have the child process wait for a thread that is not really there. I would probably expect that os.fork() would clean up the thread list in the child unless we know (Solaris) that the threads are really there. import os, sys from threading import * def log( message ): print ( "%d %s" % (os.getpid(), message) ) if __name__ == "__main__": log( "is parent" ) t = Thread() t.start() # t.join() # OPTION 1 childPID = os.fork() if childPID == 0: log( "is child" ) log( "threads: %s" % str(enumerate()) ) if childPID == 0: #os._exit(0) # OPTION 2 pass else: t.join() #os.kill( childPID, 15 ) # OPTION 3 log( "parent done waiting for %s, now waiting for %d" % (t.getName(), childPID) ) os.waitpid(childPID, 0) log( "exiting" ) From kdahlhaus at yahoo.com Mon Jun 16 08:16:52 2003 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 16 Jun 2003 05:16:52 -0700 Subject: Python articles References: Message-ID: <283adf56.0306160416.4d52ad6b@posting.google.com> > >> 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) Looks great on Mozilla Firebird 0.6 under Win 2K Pro. From jfabiani at yolo.com Sat Jun 7 16:22:14 2003 From: jfabiani at yolo.com (John Fabiani) Date: Sat, 07 Jun 2003 20:22:14 GMT Subject: [Pycrust] Seg fault Message-ID: Hi, Using SuSE 8.2 Python 2.2.2 I'm having one heck of a time getting Python things right on this Distro. Currently, Pycrust creates an segment fault anytime I attempt to start it. The wxPython demo works without issues. I can run PythonCard minimal.py. The only other issue is with Idle - after I have been using Idle for about 20 minutes (maybe more) I lose the contents of the windows. This happens after I minimize the editing window and the Idle window and attempt to reopen them. So when they reopen - the window is there (but does not respond) and it has no contents (controls etc) - it's blank. Anyone have a clue what's happening. -- John Fabiani From nas-usenet at arctrix.com Sun Jun 1 22:57:58 2003 From: nas-usenet at arctrix.com (Neil Schemenauer) Date: Mon, 02 Jun 2003 02:57:58 GMT Subject: Defensive programming References: <7xn0h11gpu.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin <> wrote: > The paper proposed a good solution, which is use a hash function that > the attacker doesn't have enough information to manipulate. Why should everyone have to use a slower or more complicated hash function? People who really care can use a custom __hash__ or use a different container (like a tree). If you are worried about DoS attacks then you have a lot more problems than just a deterministic hash function. Neil From Henk Thu Jun 19 11:22:41 2003 From: Henk (Henk) Date: Thu, 19 Jun 2003 15:22:41 GMT Subject: XML parser: fast/slow? Message-ID: <3ef1d480.1238136453@news.skynet.be> Dear Pythonians, I am using the minidom from the xml.dom package. I am using the parse-functionality written in that module to parse xml-files into a DOM-tree. The larger the file the slower the process, of course. But I wonder wether there are modules/packages out there which use a C-implementation of the parsing which could speed up things significantly. Any ideas/suggestions? Thanks for your time, Henk From kp at kyborg.dk Tue Jun 24 05:16:47 2003 From: kp at kyborg.dk (Kim Petersen) Date: Tue, 24 Jun 2003 11:16:47 +0200 Subject: "Newbie" questions - "unique" sorting ? In-Reply-To: References: <8da5fvsnidpjtblgfj4484spso2t9e6r95@4ax.com> <3ef80342$0$13176$edfadb0f@dread15.news.tele.dk> Message-ID: <3ef816ff$0$13210$edfadb0f@dread15.news.tele.dk> Cousin Stanley wrote: > | How about the simple approach? > | ... > > Kim ... > > The approach I used is fairly simple and similar > to the one you posted, basically just > stuffing words from split lines into > a dictionary ... yeah it is - a reminder to me not to do any scanning of code before my morning coffee ;-) > Perhaps skipping the dictionary word count update > in the following line might speed things up ... 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 > -- Med Venlig Hilsen / Regards Kim Petersen - Kyborg A/S (Udvikling) IT - Innovationshuset Havneparken 2 7100 Vejle Tlf. +4576408183 || Fax. +4576408188 From enrico_morelli at yahoo.com Thu Jun 5 05:57:38 2003 From: enrico_morelli at yahoo.com (Enrico Morelli) Date: Thu, 05 Jun 2003 11:57:38 +0200 Subject: Python & CGI. HELP please... Message-ID: Dear all, 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() Can someone help me?? Thanks a lot Enrico From martin at v.loewis.de Sun Jun 22 03:09:09 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 22 Jun 2003 09:09:09 +0200 Subject: XML References: <3EF471BA.EE4F056@hotmail.com> Message-ID: Lulu of the Lotus-Eaters writes: > Perhaps you missed the extensions *.mbox and *.news? (or whatever style > your MUA uses). By the definition of http://info.astrian.net/jargon/terms/f/flat-ASCII.html RFC-822 message are not flat ASCII. > 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). But the news reader has done some rendering of the messages, no (e.g. header, body, it probably suppressed the Message-ID altogether)? this would indicate that they are not flat... Regards, Martin From mis6 at pitt.edu Wed Jun 11 13:26:36 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 11 Jun 2003 10:26:36 -0700 Subject: Revised PEP 318 - Function/Method Decorator Syntax References: <20030610082514442-0400@braeburn.themorgue.org> Message-ID: <2259b0e2.0306110926.27c4412b@posting.google.com> Kevin Smith wrote in message news:<20030610082514442-0400 at braeburn.themorgue.org>...> > This syntax could also be extended to allow multiple function > decorators in the form of a space delimited list as follows: > > def protected classmethod foo(self): > perform method operation > > which would be equivalent to the current form: > > def foo(self): > perform method operation > foo = protected(classmethod(foo)) > I have just realized that there is an issue here. IMHO, there is only one reasonable way of defining a "decorator": it should be defined as a descriptor class, that takes a function and returns a descriptor object. classmethods and staticmethods work this way and "protected" should be the same. Now, if 'protected' is such a decorator, it would only accepts *functions* as input, not classmethod objects. Therefore def protected classmethod foo(self): perform method operation or def foo(self)[protected,classmethod]: perform method operation or whatever would give an error if interpreted as foo = protected(classmethod(foo)) since protected would expect a function, not a classmethod object. I think 'def foo(self)[protected,classmethod]' should be interpreted as foo=type('protectedclassmethod',(protected,classmethod),{})(foo) and protected.__init__ should be cooperative with classmethod.__init__. IOW, the only thing that makes sense here is multiple inheritance, not composition: descriptors are classes, not functions! Michele From martin at v.loewis.de Wed Jun 4 14:53:38 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 04 Jun 2003 20:53:38 +0200 Subject: How do I obtain the filenames' encoding after os.listdir? References: Message-ID: Grzegorz Adam Hankiewicz writes: > I want to transform the strings to unicode objects so I can use them > with pygtk, and the current process works ok for my machine. The > question is how do I know the encoding of the filenames? Currently > I'm presuming latin1, but if somebody else uses a different encoding, > how do I know which one? The convention is that all file names are in the locale's encoding, which is exposed as locale.nl_langinfo(locale.CODESET) (after setlocale has been invoked). > The documentation says string.decode can use as parameter "ignore" > or "replace", but using them only raises LookupErrors. You still need to provide an encoding. The error arguments is the *second* argument to decode. Regards, Martin From hc_74 at yahoo.com Sat Jun 7 22:46:16 2003 From: hc_74 at yahoo.com (Eugene C.) Date: Sun, 08 Jun 2003 02:46:16 GMT Subject: Python-ASP Message-ID: 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. Basically, I have ActiveState Python 2.2.2 installed on a Win2k Server machine running IIS5.0. Whenever I go and fetch an .ASP page via my browser to my webserver I can see the results of the .ASP page; however, if I click refresh, the page becomes blank. From there on out, it will continue to draw blank pages whenever requesting this web page. It does this even if I access the same page using a different browser on another computer. Now, if I modify the .ASP file and save it, the page reappears! Even more interesting, I don't have to actually modify the .ASP file at all. Just by simply saving the file, without any changes, the web page reappears when I access it via my web browser! Anyone ever have this "problem"? I suspect it's something that can be easily fixed. But, not for me yet! Thanks much. From gh at ghaering.de Sun Jun 1 17:55:07 2003 From: gh at ghaering.de (Gerhard Haering) Date: Sun, 1 Jun 2003 23:55:07 +0200 Subject: Problems with importation of regsub module in 2.2 In-Reply-To: References: Message-ID: <20030601215507.GA2756@mephisto.ghaering.de> * morden [2003-06-01 15:22 -0700]: > I got this trace after upgrade from 1.x tro 2.2: > > ... > import regsub > File "/usr/local/lib/python2.2/regsub.py", line 20, in ? > import regex > ImportError: /usr/local/lib/python2.2/lib-dynload/regex.so: undefined > symbol: _Py_NoneStruct Strange. There must have been something gone wrong when you compiled Python. What you should be getting is this: #v+ >>> import regsub /usr/lib/python2.2/regsub.py:15: DeprecationWarning: the regsub module is deprecated; please use re.sub() DeprecationWarning) #v- Do you get the same error message if you try to import something else from dynload, like 'time' or 'sha'? Gerhard -- http://ghaering.de/ From theller at python.net Thu Jun 12 13:05:46 2003 From: theller at python.net (Thomas Heller) Date: 12 Jun 2003 19:05:46 +0200 Subject: py2exe COM server frustration References: <34ac6a99.0306101403.74e60bc3@posting.google.com> Message-ID: shi at imaging.robarts.ca (Shi Sherebrin) writes: > hello, > > I have spent today trying a number of different samples that I found, > including the two listed on the py2exe > homepage(http://aspn.activestate.com/ASPN/Mail/Message/543305, > http://aspn.activestate.com/ASPN/Mail/Message/766627). With the first > I've gotten the closest to success (for the second I couldn't find any > of the Agent* routines). When I try running testCOMserver.py at the > command line I am able to find the COM object using the Visual Studio > OLE/COM browser, and to 'open' the item in the list to see the various > sub-elements. When I tried using py2exe to package the module, > everything seemed to work (besides some warnings about modules not > found such as win32dbg and I had to add the line "sys.frozen = 1", to > avoid an error). Registering worked ok, but when I tried to open the > item in the OLE/COM browser, a console window appeared, doing nothing, > and the system would just wait and wait, eventually timing out with > some kind of CoCreation error. > > I'm using build 151 (Python v2.1) of win32all, and v0.3.3 of py2exe. > I used 'vanilla' setup config files for py2exe. I'd really appreciate > any light anyone could shed on this matter. All I want to do is make > a COM object that can be called on a system that doesn't have Python > installed. Mark built support for McMillan installer into win32com.server, and that broke the recipes I posted - I get exactly the same problems you describe. At the end of this post you find a changed sample that should work, although I'm using Python2.2, win32all build 152 (?) on WinXP pro. And the yet unreleased py2exe-0.4 ;-). Let me know how it goes. Thomas From afriere at yahoo.co.uk Mon Jun 2 01:22:01 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 1 Jun 2003 22:22:01 -0700 Subject: Named constants -- no such thing as "too obvious" References: <3ed71a14$0$49099$e4fe514c@news.xs4all.nl> Message-ID: <38ec68a6.0306012122.7e07a6c3@posting.google.com> Ben Finney wrote in message news:... > What if the code has to deal with several other "obvious" constants, > that just happen to have the value 24? How will the reader know which > instance of 24 is HOURS_PER_DAY and which is BEERS_PER_SLAB? If you > don't write it so, then they're guessing -- and when reading code, > especially when trying to debug it at the same time, guesswork is to be > avoided as much as possible. Look I don't want to take issue with anything you've said, but wouldn't TINNIES_PER_SLAB be the more 'obvious' name? ;) From Kepes.Krisztian at peto.hu Mon Jun 30 08:59:20 2003 From: Kepes.Krisztian at peto.hu (Krisztian Kepes) Date: Mon, 30 Jun 2003 14:59:20 +0200 Subject: Python - Execute more programs Message-ID: Hi ! I want to start many py programs - with other parameters. Because the programs have many to-do, I don't want to wait for them. In Delphi it is like this: >>>>>>>>>>>>>>> program startmore; uses Windows, Classes, SHELLAPI; var SL:TStringList; FileName:string;i:integer; begin SL:=TStringList.Create; try if (ParamCount<1) then Exit; SL.LoadFromFile(ParamStr(1)); FileName:=SL[0]; for i:=1 to SL.Count-1 do begin ShellExecute(0,'open',PChar(FileName),PChar(SL[i]),nil,sw_SHOW); end; finally SL.Free; end; end. In the param (sm.txt) file: Neurolotto.py -W1 -S1 -W2 -S1 -W3 -S1 -W4 -S1 -W5 -S1 -W1 -S2 -W2 -S2 -W3 -S2 -W4 -S2 -W5 -S2 -W1 -S3 -W2 -S3 -W3 -S3 -W4 -S3 -W5 -S3 -W1 -S4 -W2 -S4 -W3 -S4 -W4 -S4 -W5 -S4 -W1 -S5 -W2 -S5 -W3 -S5 -W4 -S5 -W5 -S5 startmore.exe sm.txt The shell is doing his work good, it is find the py -> python.exe assoc., start the py in other cmd window, etc. But I want to write it in py. import os parlist=['-W1 -S1','-W2 -S1' ] pypath='c:\Python\python.exe' filename='c:/homedev/neurolotto/bin/v1.0/Neurolotto.py' for params in parlist: s='"'+filename+' '+params+'"' print pypath+' '+s os.spawnv(os.P_NOWAIT,pypath,[s]) But it is not working. Startfile is seems to good (assoc !), but it is not handle the arguments. How I do an Delphi compatible but Python based program ? Thx: KK From jjl at pobox.com Tue Jun 24 16:37:38 2003 From: jjl at pobox.com (John J. Lee) Date: 24 Jun 2003 21:37:38 +0100 Subject: multi-platform python app on cd References: Message-ID: <87he6fb4a5.fsf@pobox.com> Peter Maas writes: [...] > I want to create a Python based application with a GUI that runs > from CD without the need to install Python. Is that possible? > Is that possible for Linux, UNIX, Win32 and Mac? E.g. with wxPython > and something like Py2Exe for Win32? Not meaning to be facetious, but: Yes. As to how exactly, dunno. Apologies in advance for stating what's probably obvious to you, but: If it has to be cross-platform, I'm sure many of the issues are independent of Python, so you'll probably want to try googling for that & then (when you've got your head around the issues), maybe posting to other groups / lists. John From timr at probo.com Mon Jun 9 01:45:39 2003 From: timr at probo.com (Tim Roberts) Date: Sun, 08 Jun 2003 22:45:39 -0700 Subject: Newbie Question re Python 2.2.2 WIN References: Message-ID: Ben Minton wrote: > >Also, what is the recommended format for displaying your email address, if >you want to reduce the likelihood of SPAM.Does this group daemon accept >munged email addresses? There is no group daemon. This newsgroup is not moderated. I hate shrouded e-mail addresses. Good spam filtering on my server is a better answer. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tjreedy at udel.edu Tue Jun 3 16:32:11 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 3 Jun 2003 16:32:11 -0400 Subject: sandboxing python code References: Message-ID: <3VmdnfvJNKBRmECjXTWcoQ@comcast.com> "Michael Chermside" wrote in message news:mailman.1054662971.17122.python-list at python.org... > What to do? Well, what you need is a large and complex system for > managing resources. It should be responsible for providing nearly all > resources -- timeslicing CPU use, allocating memory, mitigating access > to disk, network sockets, etc, etc. Such a system is called an > "operating system". In a house with kids (see first word of subject line), its called 'responsible adult supervision'. The OPs question is a lot like "How do I make sure a kid does X in a reasonable amount of time" without supervision or at even checking on progress from time to time. > Okay, forgive me my dramatic phrasing... the truth is that resource > restriction is best done by the operating system... and, in fact, pretty > much can ONLY be done by the operating system (if you built something > to manage resources this well, you'd be creating your own OS). So the > REAL solution is to use the OS. Back in the days when CPU time cost $6/minute, etcetera, IBM's OSes monitored usage of scarce resources. The usage limit per run was the lesser of what the user had in his/her account and what the user explicitly allocated to the run. Limit reached? Process killed! ... One learned to read code carefully and expend time frugally. Terry J. Reedy From fperez528 at yahoo.com Wed Jun 11 17:07:45 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Wed, 11 Jun 2003 15:07:45 -0600 Subject: finding unused variables in Python code References: <3064b51d.0306111252.61cdfa2e@posting.google.com> Message-ID: beliavsky at aol.com wrote: > Is there any tool to find variables in Python code that are defined but never > used? google("pychecker")[0] It does that and much, much more. Best, f. From jafo at tummy.com Thu Jun 19 06:22:15 2003 From: jafo at tummy.com (Sean Reifschneider) Date: Thu, 19 Jun 2003 04:22:15 -0600 Subject: ANNOUNCE: JOTWeb 1.11, preview of new web application system. In-Reply-To: References: <20030617162210.GB5896@tummy.com> <1055884182.1169.11.camel@emilio> Message-ID: <20030619102215.GC23876@tummy.com> 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. There were no examples demonstrating that... Sure, I'd love to spend a couple of weeks getting really familiar with all the different web application frameworks out there so that I could really make an informed decision based on the implementation of a represenative application. However, if I had 3 months off work I'm not sure I'd spend it re-writing a web app a dozen times... :-) >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. Adding complexity to every page in a complex application is also a serious problem. It means that every time I have to look at some page code, I have to understand what's going on in this setup code. It also means that if I set up one page that has different setup code, I'm likely to miss it unless I read all the code fairly carefully. I *LIKE* systems that take care of the common things for you. Sean -- Language is the most important .. uh.. I think you know what I'm trying to say. -- Steve Martin Sean Reifschneider, Inimitably Superfluous tummy.com, ltd. - Linux Consulting since 1995. Qmail, Python, SysAdmin From peter at engcorp.com Thu Jun 19 21:35:51 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 19 Jun 2003 21:35:51 -0400 Subject: Feature Structures in Python (Part I) References: <20030619053141.6BF4835EC4@www.fastmail.fm> <3EF16277.FE8042B4@alcyone.com> <3EF1AFB2.45688CC1@engcorp.com> Message-ID: <3EF264F7.E843B1D6@engcorp.com> Peter van Kampen wrote: > > In article <3EF1AFB2.45688CC1 at engcorp.com>, Peter Hansen wrote: > > Unfortunately for many of us, Google hasn't existed for long enough for > > this to be a truly *instinctive* thing. It will take a few generations, > > or more :-), to breed this into the gene pool... until then, sadly, it > > must remain merely automatic --- for the fortunate and well-practiced --- > > or nearly habitual --- for the more forgetful amongst us. :-( > > But note that google can search for phrases when you put the words in > double quotes. "feature structure" or "test driven development" to > name some 'arbitrary' terms ;-) As a reply to my post, this makes no apparent sense. I think as a reply to Andrew Bennetts' post it would make a lot of sense... -Peter From peter at engcorp.com Wed Jun 25 13:43:51 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 25 Jun 2003 13:43:51 -0400 Subject: Platform-independent way to refer to execute path References: Message-ID: <3EF9DF57.59EA5550@engcorp.com> MK wrote: > > What would be the best platform-independent way to refer > to the current (execute) path for a Python script? > > self.dirname = ??? > > This variable should contain directory name for the current path. The question seems ambiguous to me. What is the "current path"? There is a PATH environment variable, but you probably don't mean that. There is also a current directory, or "current working directory", which is accessible through os.getcwd(). Will that do? If so, make sure you read the rest of the docs on the "os" module so you'll know what is there for later. -Peter From mis6 at pitt.edu Mon Jun 9 10:08:07 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 9 Jun 2003 07:08:07 -0700 Subject: solving the metaclass conflict References: <2259b0e2.0306070629.7f5fcad7@posting.google.com> <25b5433d.0306071443.63b27df6@posting.google.com> <2259b0e2.0306080334.329fa409@posting.google.com> <25b5433d.0306081024.517d855e@posting.google.com> Message-ID: <2259b0e2.0306090608.69139e0a@posting.google.com> pje at telecommunity.com (Phillip J. Eby) wrote in message news:<25b5433d.0306081024.517d855e at posting.google.com>... > mis6 at pitt.edu (Michele Simionato) wrote in message news:<2259b0e2.0306080334.329fa409 at posting.google.com>... > class M1(type): pass > class M2(type): pass > class B1(object): __metaclass__ = M1 > class B2(object): __metaclass__ = M2 > class B3(B2): pass > > class C1(B1,B2): __metaclass__ = funcThatMakesMetaclass > class C2(B1,B3): __metaclass__ = funcThatMakesMetaclass > > If I understand your code correctly, a new metaclass will be generated > for C2, even though the metaclass generated for C1 would be adequate. You are indeed correct and I have fixed this issue in the last version in the cookbook, which fixes all the problems you pointed out until now (and it is even shorter, under the 20 lines of code!). Of course, there could be new ones, and I welcome your criticism ;) > Anyway, *writing* it wasn't the hard part. Getting it to be *correct* > for all inputs was the hard part. :) > I couldn't agree more! > Under Python 2.2, you can't mix a new-style class with 'type' (and not > cause Python to core-dump when you inspect the resulting class!). So > if you want to create a mixin that can be used with 'type' as well as > other kinds of classes, you *have* to use a classic class. Really ? I did this kind of games without problems ... In Python 2.2.0 (in 2.3 too) the following works: class N(object): pass # new style class M(N,type): pass # type help(M) # this inspects the metaclass Can you give my an example of core-dump, just for curiosity sake? Thanks again for the feedback, Michele From jepler at unpythonic.net Mon Jun 2 12:23:20 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 2 Jun 2003 11:23:20 -0500 Subject: function pointers In-Reply-To: References: Message-ID: <20030602162320.GB4765@unpythonic.net> On Mon, Jun 02, 2003 at 09:17:20PM +0530, Jimmy verma wrote: > Hello ! > > I have a few statements in C for which i want to write the equivalent code > in python: > > typedef int (*AB)(int a, int b); #a function pointer type used to > describe signature of some function. No static typing in Python. You might want to be aware of the built-in function callable(), though. It returns True if the argument is callable (function, method, or class-with-__call__). Just like in C, you can "assign the function pointer" with the regular assignment operator. For instance, x = max print x(1, 2, 3) #-> prints 3 x = min print x(1, 2, 3) #-> prints 1 > Then a structure of the form > > typedef struct abc > { > AB make; > int a; > }ABC; class ABC: def __init__(self, make, a): self.Make = make self.a = a > > Now this structure is getting passed to some function > > xyz(const ABC* inter) > { > #some code here > e = inter->Make(a, b); > } (I'm guessing that 'a' is actually inter->a) def xyz(inter): # some code here e = inter.Make(inter.a, b) It may make sense for xyz to be a method of ABC, or it may not. If it were, then you'd write it together with the 'class' definition: class ABC: def __init__(self, make, a): self.Make = make def xyz(self): # some code here e = self.Make(inter.a, b) Jeff From aldo at nullcube.com Thu Jun 5 08:07:11 2003 From: aldo at nullcube.com (Aldo Cortesi) Date: Thu, 5 Jun 2003 22:07:11 +1000 Subject: Singleton class: what is the purpose? In-Reply-To: <20030605111536.GA3436@nl.linux.org> References: <20030605111536.GA3436@nl.linux.org> Message-ID: <20030605120711.GB30883@nullcube.com> 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 From staschuk at telusplanet.net Wed Jun 18 12:41:23 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 18 Jun 2003 10:41:23 -0600 Subject: Algorithm help per favore In-Reply-To: <2ec1bc1c.0306180746.159679d6@posting.google.com>; from wrbt@email.com on Wed, Jun 18, 2003 at 08:46:05AM -0700 References: <2ec1bc1c.0306180746.159679d6@posting.google.com> Message-ID: <20030618104123.H637@tibia.amotlpaa.bogus> Quoth Larry: > 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. If speed is the goal, removing elements from the existing list is not indicated; that would take O(n**2) time, since each removal has to shift all subsequent elements down one spot. Building a new list seems not only like the obvious approach, but probably the fastest. I think it quite unlikely that there's any faster clever algorithm. def unique(iterable): result = [] append = result.append # avoid attribute lookup in loop next = iter(iterable).next # ditto try: previous = next() append(previous) while True: value = next() if value != previous: append(value) previous = value except StopIteration: pass return result (If latency is important, this could be changed into a generator easily; that would also decrease memory usage. I'm not sure what it would do to throughput -- try it and see.) I don't see any way to use built-ins or whatnot to move the loop into C. Of course, you could recode the whole thing in C. -- 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 peter at engcorp.com Tue Jun 17 17:45:48 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 17 Jun 2003 17:45:48 -0400 Subject: How to permanently remove __import__? References: Message-ID: <3EEF8C0C.23E93E18@engcorp.com> martin z wrote: > > Hi - simple problem, but I can't find an answer. I'm working on an embedded > Python interpreter, and I am overriding the __import__ statement. This is > for several reasons, but suffice to say I do not want users to be able to > access the traditional __import__ function under any circumstances. Now, my > problem is this: I can replace __builtins__.__import__ but all the user has > to do is call reload(__builtins__) > > I'd just do the same to reload, but reload is a handy function that would be > even messier to re-implement. That, and I'd always be worried there was > another way to tap into the missing __import__ statement. What you're doing is bizarre, and probably prone to massive security wholes as well, but if you really want to do that, why not override reload() in the same manner, but after checking that the argument is not the __builtins__ module, pass the call on to the original, to which you've preserved a reference. (And I can immediately think of about three problems both with this and the original approach.) Have you read about Bastion and RExec and their ilk, and the concerns about their safety? -Peter From db3l at fitlinxx.com Wed Jun 11 20:13:04 2003 From: db3l at fitlinxx.com (David Bolen) Date: 11 Jun 2003 20:13:04 -0400 Subject: Octets calculation? References: <65eFa.634621$Si4.577158@rwcrnsc51.ops.asp.att.net> <0modevgetee4eh0pg2k7s4qhacq7s6bbkm@4ax.com> Message-ID: William Yeo writes: > In article <0modevgetee4eh0pg2k7s4qhacq7s6bbkm at 4ax.com>, > Tim Roberts wrote: > > > "Greg Ewing (using news.cis.dfn.de)" wrote: > > > > >Tyreal wrote: > [snipt] > > > > > >In my experience, this supposed ambiguity about the meaning > > >of the word "byte" is something that only exists in the > > >rarified imaginations of standards writers. In the real > > >world, nobody ever uses it to mean anything other than > > >8 bits. > > > > Today this is true, but remember that POP, like most of the Internet > > protocols, is very old (in computer years). At the time the early Internet > > RFCs were written, there were a number of popular mainframe computers that > > did not use 8-bit character sets. The Control Data 6000s and Cybers used > > 6-bit characters. > > > 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. Not to mention the DEC PDP-10 series (also 36-bit machines), which were certainly popular at several of the larger universities that had significant impact on the early Internet protocol development. On those machines, the "byte" instructions actually operated on "bytes" of specified bit length, so you could pack all sorts of different sized bytes into a 36-bit word. I believe the processor manual defined a "byte" as any contiguous set of bits within a word (36-bit). How relevant bytes versus octets may be in today's typical hardware is debatable, but it doesn't seem harmful to me to have the more precise nomenclature used in the standards. -- David From listbox at cybereal.org Sat Jun 14 22:59:16 2003 From: listbox at cybereal.org (Zac Jensen) Date: Sat, 14 Jun 2003 20:59:16 -0600 Subject: getFoo1() vs. class.foo1 In-Reply-To: <87smqcg2dt.fsf@pobox.com> References: <87smqcg2dt.fsf@pobox.com> Message-ID: <200306142059.18543.listbox@cybereal.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Saturday 14 June 2003 08:27 am, John J. Lee wrote: > "Manuel" writes: > > Thanks! > > I love python: without set and get boring instructions, > > the class is more simple and readable. :-) > > But note that sometimes, it *is* more readable to give a set_x (and > maybe get_x) function, if you want to suggest to your users that > something interesting is going on there. > > > John The funny thing is, right after I read this I had a need for the property (well, it was a convenience anyway) for this code: #casemod.py """Case module to provide an object oriented implentation of a case structure.""" class Case: """Case class is designed to work like the case directive in some other languages. The idea is to subclass the class for your use. i.e. if you created the subclass like class mycase(Case): def case_pie(self): print self.o_data and then created an instance like: case = mycase("pie") and then ran case("Hahahah") then "Hahahah" would be printed on stdio if you do case.t_item = "something else" then nothing will happen. it's worth noting that care should be taken as to which test item strings you use spaces are converted to underscore for the inherited definition but, nothing else. o_data is assigned in the call but is optional, i.e. case(blah) will assign blah to o_data. """ def __init__(self): UserDict.__init__(self) self.o_data = None def gett_item(self): return self.__t_item def sett_item(self, value): self.__t_item = str(value) def delt_item(self): del self.__t_item t_item = property(gett_item, sett_item, delt_item, "Test item property") def default(self): return bool(0) def __call__(self, testitem, optdata=None): self.t_item = testitem self.o_data = optdata ret = None if hasattr(self, "case_" + self.t_item.replace(" ", "_")): func = getattr(self, "case_" + self.t_item.replace(" ", "_"), self.default) #previous line moved down for message width limit if callable(func): ret = func() self.o_data = None return ret -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) iD8DBQE+6+EEV3L7YsSif1URApg7AJ9exbYR/iby94TNcERm+cBY6ksfWwCfU6Ew E8Am8sghbVDGOi2B5g7Wqlo= =kkNe -----END PGP SIGNATURE----- From mcfletch at rogers.com Mon Jun 9 12:38:37 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 09 Jun 2003 12:38:37 -0400 Subject: simple, old-style graphic ? In-Reply-To: References: Message-ID: <3EE4B80D.5010500@rogers.com> For 2D graphics, you might try PyGame, which is normally used for 2D (it can support an OpenGL context as well, if you want to go that way eventually). It's fairly robust, has lots of sample code, and a supportive community mailing list. It's also got lots of support for bitmap operations (including blended alpha IIRC), multimedia (sounds, movies) and the like. You can even, IIRC, find an educationally-focussed module... "pygsear" (sp?) for it with a little googling. For starting off into 3D graphics, I'd suggest picking up one of the scenegraph (also refered to as "retained mode") engines rather than working directly in OpenGL (unless your goal is "learn OpenGL so I can eventually write my own engine (or modify someone else's)", it's not a good way to start doing graphics). I like OpenGL (god help me), but it's not a beginner-friendly programming system. Enjoy, Mike sismex01 at hebmex.com wrote: >>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. >> >> ... _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From goodger at python.org Tue Jun 3 14:59:46 2003 From: goodger at python.org (David Goodger) Date: Tue, 03 Jun 2003 14:59:46 -0400 Subject: reStructured Text - suitable for non-documentation? In-Reply-To: References: Message-ID: Niklas Frykholm wrote: > At work we use a reST-based Wiki for all our internal documentation > (which is not Python-related). Which wiki are you using? If it's not already available, would you consider contributing your work back to Docutils and/or to the wiki project? (I wanted to send this privately. Another victim of spam.) -- David Goodger From bignose-hates-spam at and-zip-does-too.com.au Tue Jun 24 07:07:51 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 24 Jun 2003 20:57:51 +0950 Subject: XML References: <3EF6E9A1.74E45E69@hotmail.com> Message-ID: On Mon, 23 Jun 2003 20:49:16 +0400 (MSD), Roman Suzi wrote: > 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. > In case of XML I will need something like > > >123456la"lala This, then, is a poor choice for XML. Where XML has the advantage over flat ASCII text, is when the structure is more complex, especially if it's hierarchical (which a heck of a lot of data is). Then a flat ASCII file is too difficult for a human to parse *anyway*, so you might as well take advantage of XML and still have all the advantages of having the data readable in some form. Bleh, that reads terribly. Hope I get the point across -- XML formats don't give any particular advantage over simple, record-based flat ASCII data; they do give advantage once the structure needs to become more complex. -- \ "Computers are useless. They can only give you answers." -- | `\ Pablo Picasso | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From aleax at aleax.it Fri Jun 13 09:10:51 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 13 Jun 2003 13:10:51 GMT Subject: python.dll References: Message-ID: Jacek Potrymaj?o wrote: > Hi, > > My operating system is windows XP. > I'm not a python programmist but I have problem with this. I trye to > install simics simulator that didn't find python.dll > I installed Python2.2.2 and others python programs which allowed to work > under windows. I tryed to find this file in my system but I culdn't. > Should I download this file? I don't know. If somebody could helpo me, I > will be gratefull. I suspect you need old Python 1.5.2 -- in later releases that DLL was named python20.dll, python21.dll and so on, to allow multiple Python versions to easily coexist on the same Windows machine. So, try http://www.python.org/ftp/python/win32/py152.exe . Alex From jon+usenet at unequivocal.co.uk Wed Jun 18 04:38:36 2003 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 18 Jun 2003 08:38:36 GMT Subject: reinventing the web server References: Message-ID: In article , Simon Wittber (Maptek) wrote: > All I want is access to the session, form and querystrings and some > server variables. Personally (and I'm biased ;-) ) I would recommend using jonpy... You can start out using normal CGI for development work and then if you need higher performance you can move to FastCGI or mod_python without needing to change any of your existing code. jonpy comes with templating stuff and so on ("wt") but you don't have to use that part if you don't want to, you can just stick to the Servlet-like CGI interface if you want. http://jonpy.sf.net/ From anton at vredegoor.doge.nl Thu Jun 5 19:15:17 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 06 Jun 2003 01:15:17 +0200 Subject: Loop over list of pairs References: Message-ID: Thomas G?ttler wrote: >What is the prefered way of loop over >a list like this? > mylist=[1, "one", 2, "two", 3, "three"] Python23 style: mylist=[1, "one", 2, "two", 3, "three"] for pair in zip(mylist[::2],mylist[1::2]): print pair Anton From peter at engcorp.com Mon Jun 9 15:01:25 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 09 Jun 2003 15:01:25 -0400 Subject: py2exe and dynamic modules References: Message-ID: <3EE4D985.B091FA88@engcorp.com> "Uwe C. Schroeder" wrote: > > 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__. Have you actually tried doing this? I just made a file that imports another file after dynamically adding a directory to sys.path. Then I ran py2exe on the first script to generate an executable. It rightly complains that it cannot find the second script "The following modules were not found:" but since that's just a warning, it creates the .exe file. Then I run the .exe file and it quietly finds the necessary .py script in the specified directory and imports it. It seems py2exe does a graceful fallback to the usual sort of import processing with sys.path, so I don't think you should have too much trouble with this. -Peter From peter at engcorp.com Mon Jun 9 16:18:36 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 09 Jun 2003 16:18:36 -0400 Subject: py2exe and dynamic modules References: <3EE4D985.B091FA88@engcorp.com> Message-ID: <3EE4EB9C.8533EE25@engcorp.com> "Uwe C. Schroeder" wrote: > > The problem is, that I don't use a normal "import blah" statement, since I > don't know the name yet. AFAIK py2exe actually creates a dict of modules t > load, so if it doesn't find it at compile time, it's still in the dict - > making it possible to do a later import. If the module wasn't specified at > compile time it won't be found. Oops, I saw that part, but just didn't think clearly enough when I replied. Let me try again: File imptest.py, compiled with py2exe as imptest.exe: import sys sys.path.append('c:/temp') filename = sys.argv[1] try: mod = __import__(filename) print mod.test() except: print 'test failed!' File importme.py, stored in c:/temp, containing def test(): return 'test OK!' Run imptest.exe from a directory other than c:/temp: "test OK" results. Looks like it works... (I'm doing this test first... what did I do wrong this time? :-) -Peter From gh at ghaering.de Sun Jun 8 19:52:23 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 09 Jun 2003 01:52:23 +0200 Subject: interpreted In-Reply-To: References: Message-ID: <3EE3CC37.7040801@ghaering.de> An anonymous coward ("Ifman1") wrote: > Python is interpreted, right? Yes. > Is there anyway to make it compiled to > machine code? No, but you can embed everything, including the interpeter in one executable. This is called "freezing". > Will this make it faster? No, only easier to install under certain circumstances. -- Gerhard From peter at engcorp.com Mon Jun 2 07:54:49 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 02 Jun 2003 07:54:49 -0400 Subject: sys.settrace() and stopping the Python interpreter References: <72e160f2.0306020347.2c19ca40@posting.google.com> Message-ID: <3EDB3B09.6A826BA5@engcorp.com> Francis Joanis wrote: > > I am relatively new to Python and I am looking forward to embed it > under a C++ application (gcc/linux) to add scripting capability. > > I've seen various posts about being able or not to stop the execution > of a running Python script based on whatever conditions. > > From what I've seen there is no built-in ways of doing this directly > as a Python feature since it was not designed/implemented. > > On the other hand, I've experimented with the sys.settrace function > (in order to do some condition checking then to raise an exception to > stop the interpreter) but from what I've seen, setting up a trace > function won't take care of Python's built in functions (like > 'print'). > > I'd like to know if there is a way to set a trace function to process > every instructions? settrace() *does* execute for every instruction - every Python bytecode instruction. The problem is that print is *not* a function (even if you unnecessarily use parentheses with it) but rather an actual bytecode instruction. As far as I know, there is no way for you to break print down into any component instructions to trace, because there are none. -Peter From peter at engcorp.com Tue Jun 24 09:42:53 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 24 Jun 2003 09:42:53 -0400 Subject: SocketServer class - basis problem References: <63701d2f.0306231709.7990d916@posting.google.com> <33803989.0306232125.1cd456c2@posting.google.com> Message-ID: <3EF8555D.79425643@engcorp.com> Miki Tebeka wrote: > > Hello, Leonard, > > > data = s.recv(1024) > > s.close() > > print 'Received', data > > > > Why does s.recv() hang the client? It seems like server is not > > handing back "blah", but I'm sure it is..... > I think that the socket buffer is not full (since you are waiting for > 1024 and "blah" is not enough). This is not how the size parameter to recv() is used. It is a *maximum*, meaning any amount of data from zero bytes (if the socket is closed) to that value will be returned, with *no* guarantees how much is actually returned. Often, but absolutely not always, you will get a whole "line" and newbies will be deceived into thinking it's enough just to recv(1024) and carry on, but eventually such code will fail. -Peter From milf at tendoworld.com Thu Jun 26 23:09:30 2003 From: milf at tendoworld.com (MiLF) Date: Fri, 27 Jun 2003 11:09:30 +0800 Subject: Is it possible to write a Audio CD Player by using python only? References: <3EFAFAAA.8D629F66@engcorp.com> <3EFB062B.8642676D@engcorp.com> Message-ID: Thanks you for your information, I'll take a look on the pygame.org. "Peter Hansen" ????? news:3EFB062B.8642676D at engcorp.com... > MiLF wrote: > > > > Well, I just install Python 2.2.3 and Mark Hammond's Python Extensions on my > > w2k, I want to write a cross-plateform audio CD player. Is it enough to > > write a Audio CD player? > > "Mark Hammond's Python Extensions" are actually "Mark Hammond's Win32 > Python Extensions", so if you're looking for "cross-platform" I'm not > sure why you'd be starting with that. > > Anyway, have you look at the link I gave you yet? Go look at the link > I gave you... If that doesn't help, do a few searches using Google and > things like "python audio CD" or whatever... > > -Peter From hyde at math.umn.edu Wed Jun 4 11:49:56 2003 From: hyde at math.umn.edu (McKay Hyde) Date: 4 Jun 2003 08:49:56 -0700 Subject: 64 bit python Message-ID: <701f25e6.0306040749.d649f7f@posting.google.com> I am interested in compiling a 64-bit version of python for use in my electromagnetic scattering code. In particular, we use python for setting up the scattering geometries and for postprocessing and then call C++ code (through SWIG wrappers) to compute the scattered field. I would like to extend the code to make use of the shared memory on an IBM SP (AIX operating system) at my university (through OpenMP calls in the C++ code). However, to address more than 2GB of memory, I need a 64-bit version of my code, including a 64-bit version of python. Can anyone help? From clpy.NOSPAM at russellsalsbury.com Tue Jun 3 22:04:23 2003 From: clpy.NOSPAM at russellsalsbury.com (Russ Salsbury) Date: 3 Jun 2003 19:04:23 -0700 Subject: Possible PEP: Improve classmethod/staticmethod syntax References: <20030603164521903-0400@braeburn.themorgue.org> Message-ID: <4868482a.0306031804.1f791131@posting.google.com> Kevin Smith wrote in message news:<20030603164521903-0400 at braeburn.themorgue.org>... > A new proposed syntax for method modifiers is as follows: > > def classmethod foo(cls): > > > def staticmethod bar(): > > +1 I think it's a great step forward for clarity. The current scheme makes it easy to miss the programmer's intent. Another place that could use a similar improvement is the declaration of properties, where getfoo and setfoo are genereated from def property foo(self, val): """ property doc string """ Also a declarative form of metaclass would be an improvement. Unfortunately the analagous form doesnt give the expected results: class meta foo basefoo: ... This would work metaclass meta: ... class foo basefoo meta: ... Or with less syntactic mayhem: class foo basefoo, metaa metab: ... Anyway, food for thought. -- Russ From khowe at perfnet.ca Thu Jun 26 14:56:16 2003 From: khowe at perfnet.ca (Kevin Howe) Date: Thu, 26 Jun 2003 14:56:16 -0400 Subject: limit module import to only certain symbols? Message-ID: Say I have the following module named "mymodule" import string var1 = 'a' var2 = 'b' And I want to import its symbols into another script: from mymodule import * This will import 3 symbols (string, var1, var2) Is it possible to limit it so that import * will only import specified items? So that: from mymodule import * Would import only var1 and var2? - Kevin From a.schmolck at gmx.net Sun Jun 22 11:24:12 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 22 Jun 2003 16:24:12 +0100 Subject: Getting a list of an object's methods? References: Message-ID: Jeremy Yallop writes: > Freddie wrote: > > I've been having some issues trying to get a list of the methods of a class. > > In 2.2.3, this code gives me all of the object's variables and methods: > > > > for thing in dir(self): > > print 'thing:', thing > > > > In 2.1.3, on several different machines/OSes (Linux and FreeBSD), only the > > variables show up. The same thing happens with __dict__. Is there a way to do > > this that will work on 2.1.x, 2.2.x, and I guess 2.3.x as well? > > self.__class__.__dict__ No, that won't work reliably because not all instances have __class__ and not all types/classes have __dict__s (those with __slots__, e.g and also some C extension). Try >>> import inspect, operator >>> inspect.getmembers(foo, operator.isCallable) for a start (should come pretty close, although it will also give you callables that aren't methods). You'll have to check this for 2.1, but if I remember rightly it ough to work. 'as From dtrahan at cfl.rr.com Wed Jun 11 18:53:24 2003 From: dtrahan at cfl.rr.com (Jack Daniel) Date: Wed, 11 Jun 2003 22:53:24 GMT Subject: How to test if a variable has a natural number? References: Message-ID: Martin P wrote: > > how can I find out if the number of a variable > is a natural number or not? > I'll asume that by "find out if the number of a variable is a natural number or not" you are asking how to determine whether the number a varible is set to is a Natural Number (ie in the set of whole positive numbers; a positive integer). If this is the case here we go: def natural(x): if x >= 1 & x % 1 == 0: print "Varible is set to a NATURAL" else: print "Varible is NOT set to a natural" run this lil snippet with the name of your varible as arg x -- Jack Daniel From jeremy at zope.com Thu Jun 19 12:51:19 2003 From: jeremy at zope.com (Jeremy Hylton) Date: 19 Jun 2003 12:51:19 -0400 Subject: gc questions In-Reply-To: References: Message-ID: <1056041479.24194.12.camel@slothrop.zope.com> On Wed, 2003-06-18 at 20:23, Edward K. Ream wrote: > Many thanks, Jeremy, for these hints. Yes, a dictionary speeds things up a > lot. dict[o] = o won't work for unhashable objects o, so here is the code I > use. It seems reliable and fast: > > global lastObjectsDict > > objects = gc.get_objects() > newObjects = [o for o in objects if not lastObjectsDict.has_key(id(o))] > > lastObjectsDict = {} > for o in objects: > lastObjectsDict[id(o)]=o > > print "%d new, %d total objects" % (len(newObjects),len(objects)) The dict using id() trick is convenient in practice, but it has some problems. It's possible for an address to get re-used, so that two different objects get the same id() on two different invocations of this code. I expect this is pretty likely for objects that are implemented with their own free lists. Whether this is a problem or not depends on what you are trying to do. By the way, here's some code that Tim originally wrote that keeps track of change in number of allocation objects. It's part of the Zope3 test runner. It reports on change in net allocations by type. It sounds like this may be along the lines of what you are trying to do. Jeremy class TrackRefs: """Object to track reference counts across test runs.""" def __init__(self): self.type2count = {} self.type2all = {} def update(self): obs = sys.getobjects(0) type2count = {} type2all = {} for o in obs: all = sys.getrefcount(o) t = type(o) if t in type2count: type2count[t] += 1 type2all[t] += all else: type2count[t] = 1 type2all[t] = all ct = [(type2count[t] - self.type2count.get(t, 0), type2all[t] - self.type2all.get(t, 0), t) for t in type2count.iterkeys()] ct.sort() ct.reverse() for delta1, delta2, t in ct: if delta1 or delta2: print "%-55s %8d %8d" % (t, delta1, delta2) self.type2count = type2count self.type2all = type2all From iko at cd.chalmers.se Fri Jun 27 08:37:17 2003 From: iko at cd.chalmers.se (Anders Hammarquist) Date: 27 Jun 2003 12:37:17 GMT Subject: OFF TOPIC: What did Guido say? References: <20030625002727.20904.qmail@web11402.mail.yahoo.com> <3EF95F29.8050609@riks.nl> Message-ID: In article , Gerrit Holl wrote: >Another one in a way more difficult language: Nah, Dutch is certainly more difficult, with your strange g-sound and all... >hee de her linus torvalds oh ja utallar linux linux ;) and that would really be: Hej, det h?r ?r Linus Torvalds och jag uttalar Linux Linux. /Anders -- -- Of course I'm crazy, but that doesn't mean I'm wrong. Anders Hammarquist | iko at cd.chalmers.se Physics student, Chalmers University of Technology, | Hem: +46 31 88 48 50 G|teborg, Sweden. RADIO: SM6XMM and N2JGL | Mob: +46 707 27 86 87 -- -- Of course I'm crazy, but that doesn't mean I'm wrong. Anders Hammarquist | iko at cd.chalmers.se Physics student, Chalmers University of Technology, | Hem: +46 31 88 48 50 G|teborg, Sweden. RADIO: SM6XMM and N2JGL | Mob: +46 707 27 86 87 From gh at ghaering.de Fri Jun 20 09:52:29 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 20 Jun 2003 15:52:29 +0200 Subject: sourceforge problems In-Reply-To: References: <16115.2851.995073.486228@montanaro.dyndns.org> Message-ID: <3EF3119D.5010503@ghaering.de> Robin Becker wrote: > In message <16115.2851.995073.486228 at montanaro.dyndns.org>, Skip > Montanaro writes > >> 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? > > yes I thought of that, but the idea is too frightening :( Why's that frightening? The projects that are worth it could then find another home, and all the useless ones wouldn't be visible any more :-P Seriously, the SF code was (still is?) Open-Source and there are several sites that have set up SF clones. At least GNU and PostgreSQL have one. Here's the Pg one, for example: http://gborg.postgresql.org/ -- Gerhard From timr at probo.com Wed Jun 11 04:07:33 2003 From: timr at probo.com (Tim Roberts) Date: Wed, 11 Jun 2003 01:07:33 -0700 Subject: Octets calculation? References: <65eFa.634621$Si4.577158@rwcrnsc51.ops.asp.att.net> Message-ID: <0modevgetee4eh0pg2k7s4qhacq7s6bbkm@4ax.com> "Greg Ewing (using news.cis.dfn.de)" wrote: >Tyreal wrote: >> I was reading over the POP3 RFC (RFC 1939) and it states that message sizes must be >> in octets, but that it's different in bytes in that they are nonambigious (ie. >> bytes vary from platform to platform). > >In my experience, this supposed ambiguity about the meaning >of the word "byte" is something that only exists in the >rarified imaginations of standards writers. In the real >world, nobody ever uses it to mean anything other than >8 bits. Today this is true, but remember that POP, like most of the Internet protocols, is very old (in computer years). At the time the early Internet RFCs were written, there were a number of popular mainframe computers that did not use 8-bit character sets. The Control Data 6000s and Cybers used 6-bit characters. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tim at remove_if_not_spam.digitig.cix.co.uk Mon Jun 16 17:58:48 2003 From: tim at remove_if_not_spam.digitig.cix.co.uk (Tim Rowe) Date: Mon, 16 Jun 2003 22:58:48 +0100 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: On Mon, 16 Jun 2003 21:01:42 +0000, Bruno Desthuilliers wrote: >Tim Rowe wrote: >(snip) > >> So if we're going to have meaningless >> polemic, let me try mine :-) >Please be serious. I consider it at least as serious as the post I was replying to, though in my case the exaggeration to the point of comedy was intention (I don't know about successful). No, the compiler and other static testing won't catch all the bugs. But it has been pretty thoroughly shown that dynamic testing won't catch them all either. And the research I've seen indicates that the two techniques catch pretty much non-overlapping sets of bugs. Go back to my parody of Anton's position: which do you think we can do without in our diet? Fibre or vitamins? Ok, now which do you think we can do without in our software assurance? Static testing or dynamic testing? (As an aside, when the project manager comes along and says we have to cut something to meet timescales, do you think it will be compilation or test that's more likely to be cut?) From peter at engcorp.com Mon Jun 9 21:28:02 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 09 Jun 2003 21:28:02 -0400 Subject: Scanning for local servers, getting a broadcast address References: <3ee4ae9b$0$49113$e4fe514c@news.xs4all.nl> <3ee52fdc$0$49111$e4fe514c@news.xs4all.nl> Message-ID: <3EE53422.71BED28B@engcorp.com> Irmen de Jong wrote: > > Noah wrote: > > Ah, yes, of course. But I did not know that you could use > > '' for the bind side. Does that tell it to > > listen on all available interfaces? > > Well, in my opinion, it should. The problem is that certain > OS-ses (windows, mac os X) with certain Python implementations > decide otherwise, and return an error ("cannot assign requested > address" or such). In that case, '' usually *does* work. > Binding on the ip address always works, but you'll only get > broadcast packets that are sent to *that* adapter. Binding on the ip address doesn't even let you get packets that are sent from localhost (127.0.0.1), as far as I know, making some kinds of troubleshooting quite difficult. I believe binding to '' is not just a "usually" working solution, but the _correct_ method of listening on all interfaces. (And listening on fewer than all is perhaps best handled with a firewall, if security is the rationale.) -Peter From peter at engcorp.com Mon Jun 16 10:32:41 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 16 Jun 2003 10:32:41 -0400 Subject: class variable declarations... References: Message-ID: <3EEDD509.890691F5@engcorp.com> Lee John Moore wrote: > > Is using __init__() to force the setting of various class attributes really not > frowned upon? Or is there another way of doing this that's considered more > acceptable? > > 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 > > It just seems against the law to be creating instances of SpeedTouchComm and > accessing class attributes that aren't even referred to outside the __init__() > function. 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. Also, what do you mean by "against the law"? The above example seems 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! :-) -Peter From Tom_Web at gmx.net Wed Jun 25 07:31:11 2003 From: Tom_Web at gmx.net (Thomas Weber) Date: Wed, 25 Jun 2003 13:31:11 +0200 Subject: Newbie: "compiling" scrips (?) In-Reply-To: References: Message-ID: > No, Python is interpreted. There are some tools that make it appear like > it where not, but these are only useful for distributing scripts to > people that don't have Python installed. I think this is what I am looking for! Where can I find these tools? I am still thinking in terms of 'source code' and 'binary', like in C. I have been trying to learn C for some time now, and I now the basics now, but it still feels a litte 'unhandy' and complex. In a book about the open source movement, I read about Python and I liked the idea of a easy-to-learn, object-oriented laguage. Perhaps this is not the right newsgroup to discuss the sense of interpreted laguages, but can you give me a few hints what the advantages are? I must admit, the only interpreted language I know is old Qbasic from the 'good old (Dos) times' ;-) greetings Tom From nskhcarlso at bellsouth.net Mon Jun 9 17:17:03 2003 From: nskhcarlso at bellsouth.net (Kevin Carlson) Date: Mon, 09 Jun 2003 17:17:03 -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: <7E6Fa.40673$DI.12059@fe04.atl2.webusenet.com> Never mind. I don't think the ClientCookie is going to help me here. As someone had eluded earlier in this thread, the cookie is not coming back as a header. I was looking through the headers and couldn't see a Set-Cookie header -- thought I was going crazy. As it turns out, one of the pages in the frameset contains Javascript that creates the cookie. I can parse that for the Cookie and send it back in subsequent requests. Thanks for everyone's help! John J. Lee wrote: > Kevin Carlson writes: > [...] > >>Is there any way to use ClientCookie with httplib rather that urllib >>or urllib2? > > > No reason why not, but IMHO perverse. :-) > > You just have to call extract_cookies and add_cookie_header manually, > which means you need to make a couple of objects that satisfy the > request and response interfaces specified in the docstrings for those > methods (easy enough I guess, though I haven't done it myself): > > from ClientCookie import Cookies > print Cookies.extract_cookies.__doc__ > print Cookies.add_cookie_header.__doc__ > > I just released a 0.4.1a version. Despite the alpha status, I > recommend using that if you're writing new code (or even if you're > not, probably). > > > John From duncan at NOSPAMrcp.co.uk Wed Jun 4 10:16:26 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 4 Jun 2003 14:16:26 +0000 (UTC) Subject: Possible PEP: Improve classmethod/staticmethod syntax References: <20030603164521903-0400@braeburn.themorgue.org> <1ieDa.35049$DV.60225@rwcrnsc52.ops.asp.att.net> Message-ID: Duncan Booth wrote in news:Xns93907DB5984EBduncanrcpcouk at 127.0.0.1: > Lulu of the Lotus-Eaters wrote in > news:mailman.1054701247.26488.python-list at python.org: > >> But you could also write your own function, and use it in a >> metaclass-like way, e.g.: >> >> def fooDoc(f): >> f.__doc__ = "Bob's your uncle." >> return f >> >> class Klass(object): >> def meth(this, that) [fooDoc]: >> pass >> > > Or better: > > def Doc(docstring, **kw): > def fDoc(f): > f.__doc__ = docstring > f.__dict__.update(kw) > return f return fDoc > > class Klass(object): > def meth(this, that) [Doc("Bob's your uncle.", Author="me")]: > pass I hate posting untested code, its always wrong. -- 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 see at my.signature.com Sat Jun 7 20:09:46 2003 From: see at my.signature.com (Andrei) Date: Sun, 08 Jun 2003 00:09:46 +0000 Subject: Html: replacing tags Message-ID: <2972888.1055030986@dbforums.com> 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. Help in clearing up my confusion regarding this matter would be most welcome. -- Contact info (decode with rot13): cebwrpg5 at bcrenznvy.pbz Fcnzserr! Cyrnfr qb abg hfr va choyvp zrffntrf. V ernq gur yvfg, ab arrq gb PP. Posted via http://dbforums.com From mmaru at attcanada.ca Wed Jun 25 21:21:53 2003 From: mmaru at attcanada.ca (Mulugeta Maru) Date: Wed, 25 Jun 2003 20:21:53 -0500 Subject: Python and Jython References: <1056458981.3ef848e5ea620@mcherm.com> Message-ID: <003401c33b81$53fa2bf0$a1639a8e@mulugeta> I must say thank you very much. Very helpful explanation and advice. ----- Original Message ----- From: "Michael Chermside" To: ; Sent: Tuesday, June 24, 2003 7:49 AM Subject: Python and Jython > Mulugeta Maru writes: > > 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. > > Jython and Python are the *same* language. This doesn't mean that they > are identical in all respects... there are several important differences. > But that's a lot like using Netscape's javascript versus Microsoft's... > (back before EMCAscript was standardized) if you stick to the basic things > they'll work the same way in both, but you can find lots of differences lurking > in the corners. > > The most important differences are the truly fundamental ones that motivated > having two different implementations. CPython (the proper name for the C-based > version of Python, although people usually just call it "python") is written in > C. This means that it can be EXTENDED in C, and there are lots of useful > extensions (and some built into the standard distribution) that exist for > CPython which allow OS-specific features like Microsoft com objects and unix > interrupts, or to c libraries (several windowing libraries for instance), or > c's speed (Numeric and libraries for doing scientific computations). Jython has > none of these. > > Meanwhile, Jython runs on the java virtual machine (although that isn't really > an advantage on portability, since CPython is more portable than the JVM). The > most important feature of Jython is that Jython progams can call Java objects, > Java programs can call Jython objects, and the Jython can be compiled into 100% > pure (compiled) Java code! The level of inter-language integration is really > astounding, and makes Jython the perfect choice for scripting Java programs, > interactively examining Java code, and so forth. Also, it means that Jython > programs can take advantage of Java's huge libraries. They have fewer OS- > specific features, but lots of useful things like JDBC, etc. > > The other difference that I've noticed is that a lot more people work on > CPython than are working on Jython. As a result, CPython is a couple of > versions ahead of Jython and keeps adding new features. Hopefully Jython can > attract more volunteers and manage to keep up (because some of the new features > are pretty nice). > > There are, of course, some syntactic differences... the page > http://www.jython.org/docs/differences.html will list some, but it is very > dated since CPython has changed a lot in since version 2.0 -- for instance, it > says that CPython lacks circular garbage collection, but that has since been > added. Nevertheless, it's a useful guide. > > Since what you want to do is mostly to use Python with Java, I'd suggest that > you start out with Jython. You'll find that you can move to CPython anytime, > and that nearly everything you learned in Jython will work perfectly (except > that which depended on Java libraries). > > -- Michael Chermside > > From tjreedy at udel.edu Mon Jun 2 11:54:20 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 2 Jun 2003 11:54:20 -0400 Subject: dictionary issue (and maybe PEP ... depending on the answer) References: <0wBCa.651$ig1.627675@newssrv26.news.prodigy.com> Message-ID: > you want a non-destructive sort. i want a non-destructive sort. last > week someone was wanting to add a non-destructive sort with mapping. > every new user screws up assuming that [].sort is non-destructive. Since all list modification methods work in place, I never made such a special case assumption. I don't quite understand why others would either. A 'non-destructive' .reverse() would make exactly as much sense. It is quite normal for mutable-object methods to mutate the object. The separate issue is whether the methods should return the object so multiple mutations can be chained together, or whether they should return (a) nothing (indicator), as Python does, so people can't forget for too long that the mutation methods do mutate. (But then people do forget that one cannot chain.) > you'd think that someone would add non-destructive sort to python, Some people who want it have done so with their own site setup. def seqsort(seq): tem = list(seq) tem.sort() return tem sef seqrev(seq): tem = list(seq) tem.reverse() return tem or something like that. To be fancier, store input type and convert tem back to that type if possible. Terry J. Reedy From ed at membled.com Sat Jun 7 17:29:11 2003 From: ed at membled.com (Ed Avis) Date: 07 Jun 2003 22:29:11 +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: >>I can think of another rule which is just as simple: allow any >>construct which fits on one line. Simpler to explain, for sure. > >What is the output of > > print a,lambda:print b,c As I mentioned elsewhere in this thread, the lambda definition could be parenthesized where the parse would otherwise be ambiguous. But if parentheses aren't needed they could be left out. >The distinction of statement vs. expression is of purely syntactical >nature. Exactly! My point is, why does this syntactic distinction need to be imposed on anonymous functions. Wouldn't it make more sense for anonymous functions to be able to contain both expressions and statements, just as named functions can? >Expressions nest "naturally", statements nest by indentation, or >don't nest at all. It is the latter case 'don't nest at all' that I am considering with the suggestion that lambda could contain any construct fitting on one line. I agree that the block statements like 'if' and 'while' would be too syntactically awkward to fit inside lambda. Is it a rule of Python's grammar that no construct should ever require parenthesizing just to stop it being ambiguous? If so, I can see why a suggestion to allow map((lambda x: assert x > 0), some_list) would be rejected. But if there is not such a rule, I don't see the problem. Existing programs, those which use only an expression inside lambda, would not be made ambiguous or semantically changed in any way by the proposed extension to the grammar. (At least, I think not, assuming that there is no non-expression statement which could also be parsed as an expression.) -- Ed Avis From jafo-pythonlist at tummy.com Tue Jun 17 12:22:10 2003 From: jafo-pythonlist at tummy.com (Sean Reifschneider) Date: Tue, 17 Jun 2003 10:22:10 -0600 Subject: ANNOUNCE: JOTWeb 1.11, preview of new web application system. Message-ID: <20030617162210.GB5896@tummy.com> 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. While JOTWeb is only about 3 weeks old, it's actually quite useable. There will certainly be changes to the library code, but the base system should remain fairly stable at this point. More information including "why another one", examples, and more is available at: http://jotweb.tummy.com/ Sean -- "The big bad wolf, he learned the rule. You gotta get hot to play real cool." Sean Reifschneider, Inimitably Superfluous tummy.com, ltd. - Linux Consulting since 1995. Qmail, Python, SysAdmin Back off man. I'm a scientist. http://HackingSociety.org/ From gh at ghaering.de Mon Jun 2 06:44:52 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 02 Jun 2003 12:44:52 +0200 Subject: pypgsql installation In-Reply-To: References: Message-ID: <3EDB2AA4.8020600@ghaering.de> jeewee wrote: > after installing postgresql-python.rpm I get this > when I try to run my code: postgresql-python.rpm is something else entirely. Which RPM are you using and which distribution are you using? > [jeewee at shakira blog]$ python pg-test.py > Traceback (most recent call last): > File "getupdates.py", line 5, in ? > from pyPgSQL import PgSQL > File "/usr/lib/python2.2/site-packages/pyPgSQL/PgSQL.py", line 349, in ? > from libpq import * > File "/usr/lib/python2.2/site-packages/pyPgSQL/libpq/__init__.py", line > 23, in ? > from libpq import * > ImportError: /usr/lib/python2.2/site-packages/pyPgSQL/libpq/libpqmodule.so: > undefined symbol: PyUnicodeUCS2_EncodeDecimal > > could someone lead me to the light? The Python installation you're using is incompatible with the one the RPM was built for. I'd recommend that you install pyPgSQL from sources instead. -- Gerhard From mike at bindkey.com Wed Jun 11 13:33:12 2003 From: mike at bindkey.com (Mike Rovner) Date: Wed, 11 Jun 2003 10:33:12 -0700 Subject: feature request: mul References: <2259b0e2.0306110833.24b998cd@posting.google.com> Message-ID: "Michele Simionato" wrote in message news:2259b0e2.0306110833.24b998cd at posting.google.com... > if condition[0] or condition[1] or .... or condition[42]: > dosomething() from predicates import Any, All if Any(condition): > if condition[0] and condition[1] and .... and condition[42]: > dosomething() if All(condition): See Predicates http://py.vaults.ca/apyllo2.py/D857386335 WBR, Mike From alanmk at hotmail.com Wed Jun 18 08:23:47 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 18 Jun 2003 13:23:47 +0100 Subject: urllib2: non-ascii characters in url References: Message-ID: <3EF059D3.10ED7902@hotmail.com> Achim Domma wrote: > I have script which crawls webpages..... But now I > have urls with french characters and get the following traceback: > File "D:\Python23\lib\urlparse.py", line 134, in urlunsplit > url = url + '?' + query > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 13: > ordinal not in range(128) > > As far as I understand these characters are not allowed in urls, so I > wouln't consider this a bug in urllib2, but in reality there are these > characters and I have to handle them. You're right, characters above 128 are not allowed in URLs. They should be escaped as %xx characters, where xx is the hex character code in some character set http://rfc.net/rfc2396.html But the RFC doesn't specify which character set the character codes should be in. Instead, it says that URI schemes, e.g. HTTP, should devise some method of specifying which character encoding is in effect, or specify a default. " For original character sequences that contain non-ASCII characters, however, the situation is more difficult. Internet protocols that transmit octet sequences intended to represent character sequences are expected to provide some way of identifying the charset used, if there might be more than one [RFC2277]. However, there is currently no provision within the generic URI syntax to accomplish this identification. An individual URI scheme may require a single charset, define a default charset, or provide a way to indicate the charset used." As far as I'm aware, there is no default charset for the HTTP scheme, although iso-8859-1 seems to be a good choice. So, if you're receiving URIs with French characters in them, you should escape them to %xx character references, and then pass those to URI retrieval function. The functions urllib.quote and urllib.unquote serve exactly this purpose (assuming that they correctly decide on the encoding of the input):- Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import urlparse >>> import urllib >>> def correcturl(u): ... s, a, p, q, f = urlparse.urlsplit(u) ... p = urllib.quote(p) ... return urlparse.urlunsplit((s, a, p, q, f)) ... >>> correcturl("http://www.co.fr/vous/?tes/ici") 'http://www.co.fr/vous/%88tes/ici' >>> (There is an e-circumflex in the above URL, which may not transport correctly to everyone's email/newsreader). Does that solve the problem? P.S. RFC 2396 is worth a read sometime. It's fairly easy reading, and will help you understand some of the complexities behind URIs, potentially the most commonly used, and thus successful, identifier schemas ever. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From kp at kyborg.dk Wed Jun 25 01:58:38 2003 From: kp at kyborg.dk (Kim Petersen) Date: Wed, 25 Jun 2003 07:58:38 +0200 Subject: "Newbie" questions - "unique" sorting ? In-Reply-To: References: <8da5fvsnidpjtblgfj4484spso2t9e6r95@4ax.com> <3ef80342$0$13176$edfadb0f@dread15.news.tele.dk> <3ef816ff$0$13210$edfadb0f@dread15.news.tele.dk> Message-ID: <3ef93a0e$0$13192$edfadb0f@dread15.news.tele.dk> Bryan wrote: >>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.... > 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. Which is probably correct since that would be equivalent to: not dict_words.has_key(this_word) But if you look at the above code mentioned - it doesn't do that - it calls .keys() [generating a list] and then looks if the string is in it... > > bryan > > -- Med Venlig Hilsen / Regards Kim Petersen - Kyborg A/S (Udvikling) IT - Innovationshuset Havneparken 2 7100 Vejle Tlf. +4576408183 || Fax. +4576408188 From duncan at NOSPAMrcp.co.uk Thu Jun 19 11:52:25 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 19 Jun 2003 15:52:25 +0000 (UTC) Subject: sum(strings) References: Message-ID: Steve McAllister wrote in news:bcsjii$3vf$1 at alto.univ- mlv.fr: > Why does sum reject strings? Is it a matter of efficiency of the > underlying implementation? > It has a specific check to reject strings. If you play games with the starting value, then it will quite happily add up strings: >>> class C: def __add__(self, other): return other >>> sum(["abc", "def", "ghi"], C()) 'abcdefghi' I can see that for adding strings you would be better to use str.join, but the explicit type check seems to be very un-pythonic. Also to add up anything non-numeric, you have to provide a starting value. The implementation is approximately equivalent to: def sum(seq, start=sentinal): iterable = iter(seq) if start is sentinal: result = 0 else: result = start if isinstance(result, basestring): raise TypeError("sum() can't sum strings") for item in iterable: result += item return result I would have thought a simpler implementation would be: def sum(seq, start=sentinal): iterable = iter(seq) if start is sentinal: result = iterable.next() else: result = start for item in iterable: result += item return result which has the advantage that you can sum anything addable without specifying a start value. -- 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 wrbt at email.com Wed Jun 18 11:36:38 2003 From: wrbt at email.com (Larry) Date: 18 Jun 2003 08:36:38 -0700 Subject: Python as a Language Choice References: <2ec1bc1c.0306161417.7f890a66@posting.google.com> Message-ID: <2ec1bc1c.0306180736.35d15099@posting.google.com> "Cousin Stanley" wrote in message news:... > | Hey another Python lover in Phoenix! > | I didn't realize we were such a hotbed! > > Larry ... > > Since Dave B. has also logged in > we are now up to 3 users in a population of 2.5 million ... > > >>> nUsers = 3.0 > >>> population = 2500000 > >>> > >>> percentage = ( nUsers / population ) * 100 > >>> > >>> print '\n %2.6f' % percentage > > 0.000120 > >>> > >>> > > I think we should check with J. Napolitano > for a minority grant ... > I think they just approved the budget, so we're too late for this year. I live in Chandler and work (less than 2 miles away woohoo) at a company in Tempe. I'd say 90% of my work right now is developing web applications with Python, so I'm pretty lucky there. If anyone is up for a "Desert Python Users" beer call say the word. First round is on me. From mickel at csc.fi Mon Jun 30 08:34:42 2003 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Mon, 30 Jun 2003 15:34:42 +0300 (EEST) Subject: Placing entry widgets on a canvas in Tkinter Message-ID: Hi, 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? Or do I have to implement a brand new set() method for the scrollbar-canvas-relationship that not only scrolls the canvas, but also moves the entry widget accordingly? Or put it another way, does anybody have a better idea of how I can get a fixed-size entry hovering over a rectangle object on a canvas than to use the place geometry manager for placing an entry widget in that exact location? (Don't tell me to just use text objects on the canvas as those cannot be really fixed in width *and* height.) Hope you can help. 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 ed at membled.com Sun Jun 8 17:58:40 2003 From: ed at membled.com (Ed Avis) Date: 08 Jun 2003 22:58:40 +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]) > >Note that this does not match your proposed syntax > > lambda_form ::= "lambda" [parameter_list]: simple_stmt You're right of course. I was in the habit of assuming that parens could be added anywhere to disambiguate, since in language courses at university, teaching materials used to say at the beginning 'parens can be used to disambiguate' and then they were not mentioned for the rest of the course. But in the real world a programming language's grammar needs to include ( and ) explicitly. Still, wouldn't it work to parenthesize the whole lambda-expression to avoid ambiguity: swap = (lambda L,i,j: L[i], L[j] = L[j], L[i]) In this case a parse that took the RHS as a 3-tuple would not be possible, since the 'L[j] = L[j]' in the middle would be a statement and statements cannot appear inside tuples. It's likely that similar 'good fortune' applies to other cases where a comma might appear and you might worry about it being parsed as a tuple-forming comma. If the body of lambda is a one-line statement (and not an expression_stmt) then this misparse is not possible. I do, however, need to go back and check this more thoroughly, now that I realize that parenthesizing the whole lambda function body is not possible as a quick fix. >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. Others said that tuple-forming comma binds much more loosely than anything else, which suggests that this is not the case. (Would 'x, 3' be a statement anyway?) >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.) If you are right, then this is a serious objection and a good enough reason to reject the proposal. However - I have been using the grammar at , which seems different to the file you quote (presumably from the Python source code). I think they are different enough to cause confusion, in particular, in grammar.txt a simple_stmt is not a list of statements and cannot contain ';'. Could we continue using that file as reference, unless you believe that it is incorrect wrt the current Python implementation, in which case I will switch to Grammar/Grammar instead. >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). The point I would like to explore is how significant and how problematic these changes really are. You've raised some possible objections to the grammar production I suggested, and I will check it. >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. Maybe. OTOH it is probably easier to give a rationale for; easier to say 'you need bracking here because otherwise...' than to say 'assert cannot be used in a lambda function because it's a statement, and it is because it is'. My feeling is that as long as no existing programs change meaning or become invalid - as long as only those people who want to write anonymous functions of one line of code that happens to be an statement are affected - then the change is worth considering. This desired property of 'it doesn't affect you if you don't use it' is not in itself a reason to add a feature to the language, but it clears the way for consideration of use cases and the principle of least surprise. >A working patch would probably convince me; I'm beginning to think I should write one, I don't know when I will get around to it though. >so probably would a thorough analysis of the syntactical issues. To do that I would need to understand a bit more about how a BNF grammar is interpreted; how the binding tightness of operators is decided, whether parsing at each level is greedy, and so on. -- Ed Avis From aleax at aleax.it Thu Jun 12 04:54:58 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 12 Jun 2003 08:54:58 GMT Subject: feature request: mul References: <2259b0e2.0306110833.24b998cd@posting.google.com> Message-ID: Michele Simionato wrote: > I like the new builtin 'sum', actually I missed it from my very first > Python program (I was doing hystograms at that time). Here is the > question: is there any hope to have a corrisponding 'mul' in the near > future? No, there isn't. Indeed, that one issue was the key point in the python-dev discussion of the sum built-in when I proposed it: would introducing 'sum' start a "slippery slope" continuing with 'product' and ending who knows where? Fortunately, sanity prevailed. 'sum' accounts for maybe 80-90% of the uses of 'reduce' and similar loops, is an absolutely elementary functionality that beginners _expect_ in the language (and indeed get suprised at _not_ finding), and has a perfectly natural and attractive name (not by chance: summing up a set of numbers is the most common arithmetic operation in everyday life, so _of course_ natural languages have good ways to name it!). 'product' (or shold it be 'mul', or ...?) has absolutely none of these advantages and is NOT going to become a Python built-in, ever. > Of course, you could use 'mul' to compute factorials, bu my motivation is > mainly for logical constructs. > At the present, instead of > > if condition[0] or condition[1] or .... or condition[42]: > dosomething() > > I can use (using a comment to make crystal clear what the code is doing) > > if sum(condition): # multi_or > dosomething() Very tricky though -- you have to ensure that each of the items of list 'condition' is 0 or 1, and not some negative value that might erroneously "cancel out" other positive true values. Personally, I prefer to have non-built-in auxiliary functions when I need these kinds of constructs repeatedly: def anyOf(conditions): for c in conditions: if c: return c return False firstTrue = anyOf def allOf(conditions): for c in conditions: if not c: return c return True firstFalse = allOf (I'll use the synonyms firstTrue and firstFalse when I actually care about the exact value of the first true/false item, the names anyOf and allOf when I only care about the truth value of the latter). > Apart for boolean algebra, I think a 'mul' with > the signature > > mul(iterable, start=1) > > would naturally complement 'sum'. Moreover, > the implementation would be trivial and I don't > see why we should not have it. Because its use would be far too rare to warrant a built-in. And encouraging people to multiply (or add) booleans would be a bad side effect, not a good one. Alex From a.schmolck at gmx.net Thu Jun 5 16:58:05 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 05 Jun 2003 21:58:05 +0100 Subject: Loop over list of pairs References: Message-ID: 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 = [] 'as From sismex01 at hebmex.com Wed Jun 18 18:03:43 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 18 Jun 2003 17:03:43 -0500 Subject: Postgresql: plpython may be removed Message-ID: > From: Skip Montanaro [mailto:skip at pobox.com] > Sent: Mi?rcoles, 18 de Junio de 2003 04:58 p.m. > > 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. > > Skip > I suppose plpython is a binding so you can write stored procedures for PostgreSQL in python, and not language bindings to connect to a database instance. -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 cben at techunix.technion.ac.il Wed Jun 11 05:36:43 2003 From: cben at techunix.technion.ac.il (Beni Cherniavsky) Date: Wed, 11 Jun 2003 12:36:43 +0300 (IDT) Subject: Zip imports on python 2.2? Message-ID: 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? -- Beni Cherniavsky From warlock at eskimo.com Sun Jun 15 16:19:56 2003 From: warlock at eskimo.com (Jim Richardson) Date: Sun, 15 Jun 2003 13:19:56 -0700 Subject: getting info out of a list. References: <7tntr-qa9.ln1@grendel.myth> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Sun, 15 Jun 2003 08:55:58 GMT, Alex Martelli wrote: > > > Jim Richardson wrote: > >> I have the following code >> >> for wires in wirelist.keys(): >> bits=wirelist[wires] >> Wire=("GW",wires,bits) >> print Wire >> >> >> Which, depending on the data in wirelist, results in something like, >> >> ('GW', 1, (11, 0, -500, 0, 0, 500, 0, 10)) >> >> >> But what I want is >> >> ('GW', 1, 11, 0, -500, 0, 0, 500, 0, 10) >> >> I want the tuple that is returned from the dict wirelist, to be added as >> individual elements, rather than a tuple of individual elements, to the >> list "bits" >> >> (I hope I have explained this properly) > > Well, not quite -- there seems to be some tuple-vs-lits confusions in > your text vs your code, as well as some confusion as to what gets added > to what else. But I think what you want is, roughly: > I think the confusion is that the data stuffed into the dict earlier, consisted of a tuple. I wasn't clear on that part I think. > Wire = ('GW', wires) + wirelist[wires] > > i.e., you want to CONCATENATE the wirelist[wires] tuple right after > the two-items tuple whose first item is 'GW' and whose second item > is wires. Python does express sequence concatenation as 'adding' > (i.e., it uses the plus sign to indicate it). > > > Alex > Bingo! that was it, thank you very much. I knew I was missing something fundamental. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) iD8DBQE+7NTrd90bcYOAWPYRAmPlAKDMypc5D9PRwoPZJF8XHi0t651k6ACcCibP da79gXGBKq5SfVQUHxR6sK0= =v1lL -----END PGP SIGNATURE----- -- Jim Richardson http://www.eskimo.com/~warlock Linux, because eventually, you grow up enough to be trusted with a fork() From llafba at gmx.net Thu Jun 26 08:33:04 2003 From: llafba at gmx.net (Tom) Date: Thu, 26 Jun 2003 14:33:04 +0200 Subject: boa constructor - run script/output Message-ID: <3EFAE800.6080406@gmx.net> Hi, I am pretty new to BC and python. I just designed a GUI with Boa Constructor. It looks good, but now I have two problems: 1.) I already wrote a script in Python and want to run it in my GUI now. My script is not a class or anything like that. I usually just run it with Ctrl+F5 and it works perfectly. What do I have to tell my event handler in BC to run the script? I don't want to add the whole code (it is pretty long) directly to the code of my wxFrame1.py code. 2.) My second problem is that I don't know how the script returns the output data (I used several print commands). I want to display my messages in another part of my window of my GUI. Right now I see all my messages in the little output Window in BC. Every help would be very much appreciated. I found the Boa Constructor tutorial very helpful, but not very extensive. I also couldn't find anymore help tutorials online. Thank you very much in advance. Tom From belred1 at yahoo.com Sun Jun 22 12:08:55 2003 From: belred1 at yahoo.com (Bryan) Date: Sun, 22 Jun 2003 16:08:55 GMT Subject: xrange Message-ID: 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. timeit -s"from itertools import repeat" "for i in repeat(None, 100): pass" 100000 loops, best of 3: 10.4 usec per loop timeit "for i in xrange(100): pass" 100000 loops, best of 3: 11.6 usec per loop will xrange be obsoleted? what is the best idiom for repeating a loop n times in 2.3 now where you don't care about the index value? thanks, bryan From graham__fawcett at hotmail.com Fri Jun 27 00:13:00 2003 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 26 Jun 2003 21:13:00 -0700 Subject: Exposing object model in Python? References: Message-ID: "MK" wrote in message news:... > Hi all, > > What would be the best way to expose the object model > of a Python application? There's no best way, and there are many very good ones to choose from. I think the best-fit solution depends much on the specifics of your problem. Perhaps you could clarify the nature of the application, the environment in which you intend to deploy it, the intended audience for the app, and some common use-cases in which you would wish to write scripts against your model. > If I package my app with py2exe, can I ship Python > intepreter and access py2exe-cised app through Python > scripts then? The .exe created by py2exe *is* a Python interpreter. The tail-end of the file is ZIP data containing the .pyc files of your application. Practically speaking, the files in the tail-end are intended only for the direct access of the interpreter in the head. So I don't think py2exe is what you're looking for, unless you intend to run a py2exe-based server of some kind which your scripts will connect to. -- Graham From jdhunter at ace.bsd.uchicago.edu Fri Jun 27 13:33:36 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 27 Jun 2003 12:33:36 -0500 Subject: ICA - Independent Component Analysis Message-ID: Has anyone implemented ICA (Independent Component Analysis) in python, or know of a wrapper for a library that does so? I see that the developers of http://pdilib.sourceforge.net/ claim it is coming soon.... My email to them bounced, though, so I couldn't contact them directly. John Hunter From max at alcyone.com Sun Jun 22 19:29:09 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 22 Jun 2003 16:29:09 -0700 Subject: dynamic creating of class References: <948ip0xhyyor.dlg@baczek.net.invalid> Message-ID: <3EF63BC5.B9FEBE0D@alcyone.com> Marek "Baczek" Baczy?ski wrote: > You're calling a string. What you really want is > # the pythonic way > kind = B # bind kind to object under the name B > run = kind() > or > # the ugly way, sometimes the only though > kind = 'B' > run = eval(kind)() If what you think you have is simply a name, it's far better to turn that name into an object by lookup in a dictionary (e.g., globals()) rather than eval'ing it, just on the off-chance that you don't in fact have a simple name after all. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ ... Not merely peace in our time, but peace for all time. \__/ John F. Kennedy From peter at engcorp.com Fri Jun 6 11:35:49 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 06 Jun 2003 11:35:49 -0400 Subject: Postfix/Prefix Operators (++,--) References: <3EE05E36.40DF739F@engcorp.com> Message-ID: <3EE0B4D5.736EE894@engcorp.com> Joshua Marshall wrote: > > Peter Hansen wrote: > ... > > > Secondly, in Python assignment actually *rebinds* a name to a new > > object, so i = i + 1 creates a new object that is one greater than > > the old, and rebinds the name "i" to it (like a pointer). The old > > value, if there are no more references to it, is destroyed. > > > This, combined with the fact that these integer objects are actually > > *immutable* (they cannot be changed!) pretty much prevents any > > possibility of those operators working the way you'd expected. > > ++/-- can be added to Python, and could act in a way that wouldn't > surprise C or Java programmers. There really isn't any conceptual > difference between references to immutabe ints and C/Java primitive > ints. How would the error generated when the C or Java programmer wrote the following code not surprise him or her? c = 1 a = c++ -Peter From jonas at kryfos.com Wed Jun 11 05:39:25 2003 From: jonas at kryfos.com (Jonas Bjering) Date: 11 Jun 2003 02:39:25 -0700 Subject: Extension problem: Is my type object duplicated? Message-ID: <899f71d0.0306110139.72057a5d@posting.google.com> Hello, I am writing a Python Extension in C and have encountered a problem, explicitly created (Explicit as in v = Vector(1, 2, 3)) instances of my object has a ob_type pointer that refers to a different address than the address of my static type object. How can this be? It create trouble for me when objects I create as a result of operations have ob_type set to the address of my static type object (as I expected all objects of my type would have) and when I compare ob_type to check they are of the same type it fails. Specifically in my case the symptom is I get v + v working while v + v + v fails as the result of the first addition has a different ob_type ptr from v. I include my type definition and the relevant functions below. If someone can tell me what I do wrong I would be very appreciated. Thank you Jonas Bjering header.. #ifndef _PYVECTOR_H_ #define _PYVECTOR_H_ #include "Python.h" #include "vector.h" typedef struct { PyObject_HEAD CVector3 _vector; } CVectorObject; int InitVector( CVectorObject* self, PyObject* args, PyObject* kwds ); PyObject* AddVector( CVectorObject* self, PyObject* args ); int CoerceVector( PyObject ** o1, PyObject ** o2 ); PyObject* VectorRichCompare(PyObject* o1, PyObject* o2, int cmpOp); PyObject* VectorRepr( CVectorObject* self ); static PyMethodDef vectorMethods[] = { {NULL, NULL, NULL, NULL} }; static PyNumberMethods vectorAsNumeric = { (binaryfunc) AddVector, // binaryfunc nb_add; 0, // binaryfunc nb_subtract; 0, // binaryfunc nb_multiply; 0, // binaryfunc nb_divide; 0, // binaryfunc nb_remainder; 0, // binaryfunc nb_divmod; 0, // ternaryfunc nb_power; 0, // unaryfunc nb_negative; 0, // unaryfunc nb_positive; 0, // unaryfunc nb_absolute; 0, // inquiry nb_nonzero; 0, // unaryfunc nb_invert; 0, // binaryfunc nb_lshift; 0, // binaryfunc nb_rshift; 0, // binaryfunc nb_and; 0, // binaryfunc nb_xor; 0, // binaryfunc nb_or; (coercion) CoerceVector, // coercion nb_coerce; 0, // unaryfunc nb_int; 0, // unaryfunc nb_long; 0, // unaryfunc nb_float; 0, // unaryfunc nb_oct; 0, // unaryfunc nb_hex; 0, // binaryfunc nb_inplace_add; 0, // binaryfunc nb_inplace_subtract; 0, // binaryfunc nb_inplace_multiply; 0, // binaryfunc nb_inplace_divide; 0, // binaryfunc nb_inplace_remainder; 0, // ternaryfunc nb_inplace_power; 0, // binaryfunc nb_inplace_lshift; 0, // binaryfunc nb_inplace_rshift; 0, // binaryfunc nb_inplace_and; 0, // binaryfunc nb_inplace_xor; 0, // binaryfunc nb_inplace_or; 0, // binaryfunc nb_floor_divide; 0, // binaryfunc nb_true_divide; 0, // binaryfunc nb_inplace_floor_divide; 0 // binaryfunc nb_inplace_true_divide; }; // {"__add__", (PyCFunction) AddVector, METH_VARARGS, "Adds a vector to another and returns the result."}, static PyTypeObject vectorType = { PyObject_HEAD_INIT(NULL) 0, "pyclausewitz.Vector", sizeof(CVectorObject), 0, (destructor) PyObject_Del, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ (reprfunc) VectorRepr, /* tp_repr */ &vectorAsNumeric, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ VectorRichCompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ vectorMethods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc) InitVector, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ 0, //freefunc tp_free; /* Low-level free-memory routine */ 0, //inquiry tp_is_gc; /* For PyObject_IS_GC */ 0, //PyObject *tp_bases; 0, //PyObject *tp_mro; /* method resolution order */ 0, //PyObject *tp_cache; 0, //PyObject *tp_subclasses; 0, //PyObject *tp_weaklist; 0, //destructor tp_del; #ifdef COUNT_ALLOCS ///* these must be last and never explicitly initialized */ 0, //int tp_allocs; 0, //int tp_frees; 0, //int tp_maxalloc; 0, //struct _typeobject *tp_next; #endif }; #endif and the implementation... #include "pyvector.h" #include "text.h" int InitVector( CVectorObject* self, PyObject* args, PyObject* keywordvalues ) { float x; float y; float z; static char *keywords[] = {"x", "y", "z", NULL}; if( !PyArg_ParseTupleAndKeywords(args, keywordvalues, "fff", keywords, &x, &y, &z) ) return -1; self->_vector = CVector3( x, y, z ); return 0; } PyObject* VectorRichCompare(PyObject* o1, PyObject* o2, int cmpOp) { if( !( o1->ob_type == &vectorType && o1->ob_type == &vectorType) ) { CString errorMsg("Cannot compare " + CString( o1->ob_type->tp_name ) + " to " + CString( o2->ob_type->tp_name )); PyErr_SetString( PyExc_NotImplementedError, errorMsg.GetCharPtr() ); return NULL; } CVectorObject* v1 = reinterpret_cast( o1 ); CVectorObject* v2 = reinterpret_cast( o2 ); if( cmpOp == Py_EQ ) { if( v1->_vector == v2->_vector ) { Py_INCREF( Py_True ); return Py_True; } else { Py_INCREF( Py_False ); return Py_False; } } else if( cmpOp == Py_NE ) { if( v1->_vector != v2->_vector ) { Py_INCREF( Py_True ); return Py_True; } else { Py_INCREF( Py_False ); return Py_False; } } else { CString errorMsg("Operation not supported"); PyErr_SetString( PyExc_NotImplementedError, errorMsg.GetCharPtr() ); return NULL; } } int CoerceVector( PyObject ** o1, PyObject ** o2 ) { if( (*o1)->ob_type == &vectorType && (*o1)->ob_type == &vectorType ) { Py_INCREF( *o1 ); Py_INCREF( *o2 ); return 0; } else return 1; } PyObject* AddVector( CVectorObject* self, PyObject* other ) { if( other->ob_type != self->ob_type ) { CString errorMsg("Cannot convert " + CString( other->ob_type->tp_name ) + " to " + CString( self->ob_type->tp_name )); PyErr_SetString( PyExc_TypeError, errorMsg.GetCharPtr() ); return NULL; } CVectorObject* otherAsVector = reinterpret_cast( other ); CVectorObject* result = PyObject_New( CVectorObject, &vectorType ); result->_vector = self->_vector + otherAsVector->_vector; return reinterpret_cast( result ); } PyObject* VectorRepr( CVectorObject* self ) { CString result( "Vector(" ); result = result + CString(self->_vector.x) + ", " + CString(self->_vector.y) + ", " + CString(self->_vector.z) + ")"; return Py_BuildValue( "s", result.GetCharPtr() ); } From a.schmolck at gmx.net Sat Jun 7 10:37:51 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 07 Jun 2003 15:37:51 +0100 Subject: Numeric don't compare arrays correctly References: <3EDFBACD.2090802@wanadoo.es> Message-ID: "Mike C. Fletcher" writes: > >Well, it is only obvious because you (and I) are already used to a rather > >hackish notation. > > > Ah, but what I'm saying is that, if you see this construct: > a < b < c > > then the only non-hackish interpretation is a is less than b which is less > than c, which is taken directly from mathematics. > The hackish (low-level, fiddly) intpretation says "what would the machine > do" and figures out that it's grouping the statements and basically > producing random data ;) . There is of course no straightforward exension of the usual meaning of ``<`` to booleans. However the interpretation that ``<`` is an operator and that operators straighforwardly translate into functions calls (if you know precedence, associativity etc.) , such that ``(a # b # c)`` can be thought of as either ``#(a, #(b, c))`` or ``#(#(a, b), c)`` seems to me certainly much less hackish and fiddly than assuming that, unlike pretty much everything else, ``a < b < c`` really is, say, a single function whose arguments are comparison operator tokens and unevaluated expressions plus an environment. And if you choose something in between, as python does, where '<' is some sort of pseudo-infix operator that can return arbitary (not just boolean) results than you're certainly inviting trouble. > Certainly bad rich-comparisons are a wart, but in the line of cutting it > off, I'd rather have an error raised (syntax error) for a < b < c than have > it work as a built-in random data generator :) . That is, the (current) > common sense behaviour is by far preferable to the (randomising) behaviour > of those unnamed languages, but really, who needs either behaviour so much > that the subtle errors it can introduce are worth the risk? Yes, the symetry > with x == y == z is nice, but again, dropping that construct entirely would > be better than switching to (x == y) == z semantics. I mean x == y and y == > z isn't *that* much harder to type, and neither is (x == y) & (y==z) if you > want the element-wise stuff. Depends on what you mean by "*that* much harder": max([another_func(x) for x in points if a < some_func(x) < b]) becomes res = [] for x in points: func_of_x = some_func(x) if a < func_of_x and func_of_x < b: res.append(another_func(x)) max(res) > Explicit is better, ...yada, yada... refuse to > guess :) . My feeling is that the mistake was not to make rich comparisons explicit (by either introducing new operators (e.g. ~<) or forcing function notation). They just aren't simply some generalization of normal comparisons but something quite different, as their elementwise character doesn't fit in the (necessarily atomic) boolean context within which normal comparisons are (almost always) used. The chaining wart is just a symptom -- my guess would be that almost no code designed for atomic comparisons does something meaningful when handed arrays or other rich-comparing objects. 'as From andrew-usenet at lexical.org.uk Wed Jun 11 19:31:37 2003 From: andrew-usenet at lexical.org.uk (Andrew Walkingshaw) Date: 11 Jun 2003 23:31:37 GMT Subject: PEP 318 - Function Modifier Syntax References: <3EE65444.907E6D87@alcyone.com> <3EE6646E.47555429@alcyone.com> <3EE67C20.941FCA51@alcyone.com> Message-ID: In article , Gerrit Holl wrote: > Andrew Walkingshaw wrote: >> > I think "as" is a perfectly good keyword, and no other suggestion I've >> > seen is better. It reads well and it represents the underlying >> > implementation fairly well. And "as" is already (kind of) a keyword, so >> > all the better. It was an early suggestion, and a good one -- I don't >> > know why people are working it over so much. >> >> Because we haven't anything better to do? :) >> >> Another option which comes to mind, assuming that these function >> decorators work the way I think they do, is "applying": >> >> def f(x,y,z) applying (decorator1, decorator2): > > How about "def f() alteritaccordingto (decorator1, decorator2):" To be honest, as long as the format chosen is relatively easy to remember, type, and relatively clear in its meaning, it doesn't really *matter* what's chosen. I'm in favour, marginally, of the def f(x,y,z) [dec1, dec2]: syntax, but to be honest I'm fairly ambivalent. I suspect that a compromise option such as "using" or "applying" may wind up being a horse-designed-by-committee: a camel, which gives everyone the hump. This is all just idle banter, anyway: I suspect the real action on this issue is over on python-dev! - Andrew -- Andrew Walkingshaw | andrew-usenet at lexical.org.uk From koenig at v-i-t.de Wed Jun 18 08:57:17 2003 From: koenig at v-i-t.de (Mirko Koenig) Date: Wed, 18 Jun 2003 14:57:17 +0200 Subject: preventing creation of instance References: <3EF05E3C.C11192CE@engcorp.com> Message-ID: On Wed, 18 Jun 2003 14:42:36 +0200, Peter Hansen wrote: > Mirko Koenig wrote: >> Is using __new__ a common way in programming python like the contructor >> in c++ or is it seldom used ? > > Perhaps the best answer is that it's *extremely* "new", no pun intended. > It was only just added to the language, and relatively few people have > probably tried using it, let alone figured out how to judge the best > time to use it, and when not to. > > And many of us are still programming with older versions that didn't > have that feature. So perhaps throwing an exception in __init__ is the better way for me? Mirko Koenig From 2002 at weholt.org Tue Jun 24 17:16:11 2003 From: 2002 at weholt.org (Thomas Weholt) Date: Tue, 24 Jun 2003 23:16:11 +0200 Subject: Choosing the right database-system for a small project References: Message-ID: Ok, I'm going to do some more testing on both MetaKit and SQLite, but I'd like to know of any trouble I might run into with concurrent writes or reads to the database. This will be used on a webserver, not with heavy load, but to be sure it would be nice to have at least some simple locking mechanism. Any tips? Thanks so far. Thomas "Thomas Weholt ( PRIVAT )" <2002 at weholt.org> wrote in message news:uAUJa.1825$os2.25697 at news2.e.nsc.no... > 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. ) > > So far I've used MySQL, mainly because I need something that installs easily > on both Linux and Windows. But I don't need a big user-management system, I > need something light, a bit more flexible than shelve, and as I said earlier > I need to lookup data by several key-fields. > > I've also looked at MetaKit and this seems like just my kind of thing. Easy > to use and install. Remember that I've only looked at the docs, not tried > anything for real. Another contender is SQLLite. It's very important that > the system is easy to install. Anything more than "copy these files in this > folder" or run this install-program on Windows is unacceptable, and anything > more than configure/make/make install without lots of other library > dependancies on Linux is also out of the question. > > Can anybody share experiences with these solutions? Speed, flexibility, > installation issues? I intend to use this with Twisted so if there are any > blocking issues I need to consider please let me know. Any other system I > should take a look at ?? > > Thanks a bunch, > Thomas > > From null at null.com Tue Jun 10 06:33:29 2003 From: null at null.com (Iwan van der Kleyn) Date: Tue, 10 Jun 2003 12:33:29 +0200 Subject: Criteria for which Batteries are Included ? Message-ID: <3ee5b419$0$140$e4fe514c@dreader5.news.xs4all.nl> "Batteries Included" is a well-published motto of Python. And it's true, more modules than I would ever need are included in the base distribution. However, I do miss relational database access. Especially the intefaces with MySQL and PostgeSQL. And it would be nice to have modules which interface with mature, and popular (common) protocols as SOAP and Jabber. Of course, if everyone's favourite module would be included, then I suppose the Python distribution wold be unmaintainable. So what are the criteria for the inclusion of a module in Python? User support? Availability on a speciifc number of platforms? Regards, Iwan From aleax at aleax.it Thu Jun 19 16:26:49 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 19 Jun 2003 20:26:49 GMT Subject: sum(strings) References: <7xu1amvu8g.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Alex Martelli writes: >> No, if sum accepted a sequence of strings it WOULD >> have to delegate to ''.join in that case -- and I just couldn't >> find an elegant and totally general way to do that. > > Why can't it just check if all the values are strings, and delegate if > they are? That would require _saving_ all the values (potentially taking up over twice as much memory) in order to allow the argument to be any iterable (including a non-restartable one). I'm not saying it's _impossible_: I'm saying Guido Pronounced against it (or other similar tricks) as being worth the bother. There are IMHO-better tricks: I _could_ have checked just the _first_ item -- if that's an instance of basestring call ''.join with a custom iterator that returns that one checked-item then delegates the rest to the stepped- by-one iterator on the argument -- ''.join will handle the error diagnostics if any of the other items isn't an instance of basestring. It's still complication, not simplicity, elegance and generality. Alex From dwblas at yahoo.com Thu Jun 5 21:05:46 2003 From: dwblas at yahoo.com (DavidW Blaschke) Date: Thu, 5 Jun 2003 18:05:46 -0700 (PDT) Subject: How to reply???? Message-ID: <20030606010546.81652.qmail@web21604.mail.yahoo.com> I'm using a yahoo account --> http://groups.yahoo.com I've tried both Opera and Firebird and get the same result. I belong to other groups, but only have the problem with this group. With an e-mail client does one still use groups.yahoo.com or python-list at python.org? Thanks D.W. > --- In python-list at yahoogroups.com, Paul McNett >

wrote: > > DavidW Blaschke writes: > > > > > When I hit the reply button I get 3 choices: > > > 1. python-list at c... > > > 2. the e-mail address of the person who > posted > > > 3. python-list-owner at yahoogroups.com > > > > > > I think I want to post to python-list at p... > > > Does anyone have a good way to do this without > cutting > > > and pasting the message into compose, and > mailing it > > > as normal e-mail? > > > > What email client are you using? I'm using KMail, > and if I hit > 'reply' (R) > > it will go to the original sender, if I hit > "reply-all" (A) it will > go to > > the original sender as well as python-list at p... If > I hit > > "reply-list" (L) it will just go to > python-list at p... > > > > Are you accessing this list via comp.lang.python > (usenet) or via > > python-list at p... (email)? > > > > -- > > Paul McNett > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From brian_l at yahoo.com Wed Jun 25 01:46:17 2003 From: brian_l at yahoo.com (Brian Lenihan) Date: 24 Jun 2003 22:46:17 -0700 Subject: shebang strange thing... References: <3EF3A07B.A683F94F@alcyone.com> <3EF7A121.7B4C3775@alcyone.com> Message-ID: "Greg Ewing (using news.cis.dfn.de)" wrote in message news:... > Erik Max Francis wrote: > > (Mac gets even fewer points, > > since it chose to do deliberately do smoething even more different.) > > That's debatable. At least the Mac still only uses *one* > character for each end-of-line... That's all fine, but the Mac does exhibit one problem I can't fathom: If you have two or more Python installations, the first one in your path gets invoked no matter what the shebang line says. If the first line of a script is #!/usr/local/bin/python, I expect the interpreter located in /usr/local/bin to execute the script, not the one in /usr/bin, or the one in /sw/bin, but that is what you get if you run the script as an executable. The process list shows why - python is called without a path, e.g. as "python". The same behavior occurs if the shell is bash or tcsh. As far as I know, OS X is the only "modern" Unix to behave this way. This behavior caused me a large amount of angst until I figured out what the problem was. I had to resort to writing a script that renames the pythons in /usr/bin/ and /sw/bin when I don't want them and renames them back if and when I do. I mostly use Python 2.3 from CVS, but I haven't been able to get mod_python working with a Framework build yet, so I need to switch to Fink's python once in a while. From tim.one at comcast.net Sun Jun 1 15:14:08 2003 From: tim.one at comcast.net (Tim Peters) Date: Sun, 01 Jun 2003 15:14:08 -0400 Subject: Defensive programming In-Reply-To: Message-ID: [Robin Becker] > This recently slashdotted paper > > http://www.cs.rice.edu/~scrosby/hash/CrosbyWallach_UsenixSec2003/index.html > > suggests that many common algorithms (including perl hashing) are > open to low input DoS attack. > > I know that the Timbot and other python 'bots are pretty smart, but > are there python algorithms that suffer the same vulnerabilities? 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. If an app can't bear that, then it shouldn't use dicts (or hash tables in Perl, or any similar facility in any other language). This isn't news. What's interesting in the paper is that some apps that should know better were caught doing this. > Regular expression matching seems like a pretty easy target for > some devilish inputs. Absolutely, yes. I've corresponded with Scott Crosby about this, and he's added an example to his web page. A better link than the paper is this link to his page discussing the paper: http://www.cs.rice.edu/~scrosby/hash/ Someone looking to cause trouble should have an easier time exploiting widespread non-defensive regexps. From cnetzer at sonic.net Sun Jun 22 06:14:48 2003 From: cnetzer at sonic.net (Chad Netzer) Date: 22 Jun 2003 03:14:48 -0700 Subject: Tkinter problem In-Reply-To: References: Message-ID: <1056276888.1612.10.camel@adsl-209.204.179.133.sonic.net> > 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 From rganesan at myrealbox.com Tue Jun 3 00:04:30 2003 From: rganesan at myrealbox.com (Ganesan R) Date: 03 Jun 2003 09:34:30 +0530 Subject: Java Class Loading into Jython References: <28cf7c6f.0305280002.4c76564f@posting.google.com> <28cf7c6f.0306020524.6a301509@posting.google.com> Message-ID: >>>>> "Ranjith" == Ranjith Kumar writes: > Thank you very much. > The problem of class not found occurs in the following case. > When I place the class file with the package > com.xxx.yyy.Imported.class under a directory ( which is in the > classpath ) and this directory is not the one in which the jvm is > running. > The same class is loaded when the class is present in the jvm > directory. > / classes / com / xxx / yyy / Imorted - not loaded I am assuming /classes in your classpath. Can you check if the class loads correctly in java. If it loads correctly in java but you can't load it in jython; I'd consider it a bug in jython (unless, you're playing around with the classloader). Ganesan -- Ganesan R (rganesan at debian dot org) | http://www.debian.org/~rganesan/ 1024D/5D8C12EA, fingerprint F361 84F1 8D82 32E7 1832 6798 15E0 02BA 5D8C 12EA From francois at iecholden.com Thu Jun 19 09:56:36 2003 From: francois at iecholden.com (Francois Meehan) Date: Thu, 19 Jun 2003 09:56:36 -0400 Subject: Using ftplib to upload a file to a server.... Message-ID: Hi all, Please excuse my "newbiness", but I can't get python to upload a file using ftplib, basically I don't make sense of the transfercmd. I can connect, return a file listing, but could not find upload example on the net. Could someone provide me an example? Or is there an easier modules to use for FTP file transfer? Francois From ta-meyer at ihug.co.nz Thu Jun 5 02:31:37 2003 From: ta-meyer at ihug.co.nz (Tony Meyer) Date: Thu, 5 Jun 2003 18:31:37 +1200 Subject: Including binary files in a .py file; advice needed In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1301E57EDE@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F13C8CBF0@its-xchg4.massey.ac.nz> > 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. [...] > Anything better ? If I understand what you want to do correctly, then resourcepackage will do this for you. http://resourcepackage.sourceforge.net The standard method is to have a separate .py file that's distributed with the app, but it would be easy enough to embed this into a larger file. =Tony Meyer From fperez528 at yahoo.com Thu Jun 26 23:14:30 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Thu, 26 Jun 2003 21:14:30 -0600 Subject: Activating `-i' from inside a script? References: Message-ID: Fran?ois Pinard wrote: > Hi, Python friends. > > Is there a way for a script to activate the effect of the `-i' option, that > is, to force interactive mode once `__main__' has run? For one application, > I would like that if the application discovers some data discrepancy or > failure (not a Python error) and only then, and if the application was also > started from a tty, it gives the user to interactively explore, using > Python, the context that was built while the run was going. > Fran?ois, you might want to look at ipython's embedding. Since I know you use ipython, there may be a reason why you want something else. I just mention it in case you missed it in the docs. After checking your trigger condition, an ipshell() call will load ipython in the current data context. Best, f From icarroll at pobox.com Thu Jun 12 17:56:18 2003 From: icarroll at pobox.com (W Isaac Carroll) Date: Thu, 12 Jun 2003 14:56:18 -0700 Subject: Twice instanciation References: Message-ID: <3EE8F702.8090103@pobox.com> Salvatore wrote: > W Isaac Carroll wrote: >> What do you mean by "instanciation" and "variable"? >> >> If you are asking whether it's possible to prevent binding the same >> name a second time, then no, it's not possible. > > That's it - excuse my poor English ;-) Your English is fine (instanTiation is the usual spelling by the way). I was just trying to make sure that your concept of variables was compatible with Python's. > As I said to Manual, i'll propose another solution. Probably best. :) TTFN From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Jun 9 16:30:07 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 09 Jun 2003 22:30:07 +0200 Subject: Call a Python file with parameters In-Reply-To: References: Message-ID: <3ee4ee4e$0$49117$e4fe514c@news.xs4all.nl> Jp Calderone wrote: > On Mon, Jun 09, 2003 at 03:10:27PM +0000, martin z wrote: > >>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). What's wrong with : from myModule import myFunction # or even * if you're bold myFunction("blahblah",42) ?? --Irmen From chris.lyon at spritenote.co.uk Mon Jun 9 05:58:30 2003 From: chris.lyon at spritenote.co.uk (Chris Lyon) Date: 9 Jun 2003 02:58:30 -0700 Subject: Scanning for local servers, getting a broadcast address Message-ID: I have a small group of machines both Linux and Windows moving large files around a local network. I wish to know which other machines on the local subnet are running servers. I believe an approach to resolve this is a UDP broadcast and indeed this seems to function acceptably. However since I have to generate the broadcast address, I need to know at least my subnet mask to allow me to derive the Broadcast address. How do I do this in a pythonic fashion without recourse to reading host files which seems very platform dependant? I ask because I have a demo at a client who I know will be running a 255.255.255.240 subnet mask and I would like to be able to scan the servers successfully without any pre-configaration on the software part. Yours in anticipation. Chris Lyon From jdhunter at ace.bsd.uchicago.edu Fri Jun 27 23:22:27 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 27 Jun 2003 22:22:27 -0500 Subject: ICA - Independent Component Analysis In-Reply-To: <1056747980.1169.8.camel@emilio> (Tim Churches's message of "28 Jun 2003 07:06:20 +1000") References: <1056744790.1169.6.camel@emilio> <1056747980.1169.8.camel@emilio> Message-ID: >>>>> "Tim" == Tim Churches writes: Tim> 3) Obtain and install the fastICA library for R (see the Tim> extensive R documentation - R has the slickest fetch and Tim> installation procedures for extensions in the business) Wow, you are right. I had already installed R and rpy before your reply. After reading your post, I read the install guide at http://cran.r-project.org/doc/manuals/R-admin.pdf and all I had to do to install fastICA from within a root R session was: > options(CRAN = "http://cran.us.r-project.org/") > install.packages("fastICA") Then I quit R, fired up python, and could import fastICA w/o rebuilding rpy. Impressive. I suppose I just need to configure my CRAN prefs in a config file so I can install extensions with just one command, instead of the laborious two. Thanks for your advice! John Hunter From rnd at onego.ru Sun Jun 22 12:24:28 2003 From: rnd at onego.ru (Roman Suzi) Date: Sun, 22 Jun 2003 20:24:28 +0400 (MSD) Subject: XML In-Reply-To: <3EF5A4DA.35168B8A@hotmail.com> Message-ID: On Sun, 22 Jun 2003, Alan Kennedy wrote: >4. Semantics vs. format: The OP was concerned with finding good use cases for >XML, where it is a natural fit for the problem at hand. He seemed to be >dissatisfied with XML both as a format, and as a method for building semantic >object models. Well formulated, Alan! This is exactly what I tried to tell. >My thinking is that it is the process of mapping format -> >semantics that is the key issue: The easier that is, the more likely it is to be >usable and to catch on. I think XML will continue to be grow in usage (not >always used appropriately) because the format is trivial for people to >understand (at a minimum requirements level), there is a common data model which >most people can get their heads around, and the mapping from one to the other is >easily dealt with through usage of the plethora of high-quality, standards >compliant XML processing software that is out there. I hope that after, say, 10 years there will be XML tools as stable as D.Knuth's TeX (he promised many dollars to those who find errors in his code). By that date XML will be in much better position than today. Of course, XML standards body need to be stable as well. Plain text also suffered from format problems: we still have thousands of encodings and 3 major variants of line-endings. And, to remain on topic, I hope Python 3 will be ISO and/or ANSI standard ;-) Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From peter at engcorp.com Wed Jun 18 14:13:15 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 18 Jun 2003 14:13:15 -0400 Subject: unit tests with mod_python References: Message-ID: <3EF0ABBB.1D1409D@engcorp.com> emf wrote: > > I am experimenting with test driven development. I'm working with > mod_python, however, and of course you can't import apache from > mod_python outside of actually running within apache. > > Before I reinvent the wheel, has anyone written a mod_python simulacrum It's possible, if you search using the more common term "mock" instead of simulacrum, that you might find something out there already. > for use in unit tests - one that provides, at a minimum, a faux request > object and the other attributes (like apache.OK) needed to run in a > pretend environment? > > Alternately, has anyone set up a way to drive requests from unittest? Searching on the testdrivendevelopment list at Yahoo Groups might be a good idea, in case someone who doesn't frequent this group has actually done that. http://groups.yahoo.com/group/testdrivendevelopment/ -Peter From roman at syxx.de Mon Jun 16 08:43:09 2003 From: roman at syxx.de (Roman Meisl) Date: Mon, 16 Jun 2003 14:43:09 +0200 Subject: Question about Python-Grammar Message-ID: Hello NG, The actual Python Grammar defines following rules: import_stmt: 'import' dotted_as_name (',' dotted_as_name)* | 'from' dotted_name 'import' ('*' | import_as_name (',' import_as_name)*) import_as_name: NAME [NAME NAME] dotted_as_name: dotted_name [NAME NAME] dotted_name: NAME ('.' NAME)* To simplify my question let's take following rules import_stmt: 'import' dotted_as_name dotted_as_name: dotted_name [NAME NAME] dotted_name: NAME ('.' NAME)* which makes following import-statement possible: import NAME NAME NAME What's the sense of this statement? Or is this an error in the grammar? (Even the compiler (2.2.2) claims a syntax error when parsing "import mod1 mod2 mod3" ) I'm sure that the meaning should be different from import NAME, NAME, NAME Thanks in advance! Bye Roman Meisl From Bill.Scherer at verizonwireless.com Wed Jun 4 15:51:13 2003 From: Bill.Scherer at verizonwireless.com (Scherer, Bill) Date: Wed, 4 Jun 2003 15:51:13 -0400 (EDT) Subject: problem with LOB's and DCOracle2 In-Reply-To: <3EDE334A.3C99A22A@yahoo.com> Message-ID: [P&M] On Wed, 4 Jun 2003, Daniel wrote: > I'm trying to create a new LOB to insert into a table, but get an error > when I try to read it back in (in fact, it's a very bad error--a seg > fault). I'm using DCOracle2 1.3b Any suggestions? > > >>> db=DCOracle2.connect('me/pw at db') > >>> clob=db.LobLocator('SQLT_CLOB') > >>> d='insert into foo values(9, XMLTYPE.createXML(:m))' > >>> clob.write('foo') > 10 > >>> db.execute(d, clob) > 4 > >>> c=db.cursor() > >>> c.execute("select * from foo") > 1 > >>> a=c.fetchall() > Segmentation fault IIRC, you may only get a clob with a specifc select and a fetchone, eg: c.execute("select lobFiled from foo") a = c.fetchone() if you want to update that field, do instead: c.execute("select lobFiled from foo for update") HTH - -- Bill.Scherer at Verizon Wireless RHCE 807101044903581 From mcherm at mcherm.com Tue Jun 3 13:54:59 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Tue, 3 Jun 2003 10:54:59 -0700 Subject: sandboxing python code Message-ID: <1054662899.3edce0f36bac2@mcherm.com> Ben writes about executing untrusted code: > 1. Have a pseudo language which I then can render doen to python before > running. But then whats the point of using python? I want to give them all > the power of python where allowed If your pseudo-language is turing complete, then it's still possible for users to write things like infinite loops that you can't tell are infinite (that's the whole point of the "haulting problem"). So you can't solve the untrusted code problem with this approach. > 2. Simply run the code using exec with restricted globals and locals > dictionaries. This can stop people importing dodgy libraries, but cannot > stop people writing infinite loops etc As noted, doesn't really fix it. > 3. Use the parser to generate the AST for the program, and then add checks > inside for loops etc which will cause the program to quit if a certain > counter reaches a maximum. This doesn't solve the memory problem either. Doesn't prevent it from running forever either. That can be done in a single line within python, quite easily. Try, for instance, executing this: x = 1000000000 ** 10000 > 4. Use the c api to run the compiled bytecode a batch at a time, e.g run > for a 100 instructions and the check a condition, bailing out if it fails. > This still doesn't stop people doing something like range(100000000), and > also doesn't seem to have support in the api, so would entail effectively > writing my own python virtual machine. Not really much better. You still haven't gotten at the root cause -- you can't TELL whether some code is going to use more resources than you intended, so there's no way to trap this and stop the offending code. What to do? Well, what you need is a large and complex system for managing resources. It should be responsible for providing nearly all resources -- timeslicing CPU use, allocating memory, mitigating access to disk, network sockets, etc, etc. Such a system is called an "operating system". Okay, forgive me my dramatic phrasing... the truth is that resource restriction is best done by the operating system... and, in fact, pretty much can ONLY be done by the operating system (if you built something to manage resources this well, you'd be creating your own OS). So the REAL solution is to use the OS. Take this untrusted code and run it in a separate process. Run that process with limits on its memory and CPU consumption, or continually monitor the process and kill it if its memory and CPU use get out of hand. Really, this is pretty much the ONLY solution that can truly work (and some operating systems aren't capable of this kind of protection... if yours isn't, I recommend an upgrade). Anything less, and you're just fooling yourself (there are lots of ways to protect against ACCIDENTALLY incorrect code, but if you are facing actual malicious code, then only the OS can help). There are some problems with this approach. For one thing, the overhead can be quite significant. If you're running little 5-line python snippets, launching a whole python interpreter each time, and setting up pipes or files to communicate between processes requires a huge amount of overhead. If you REALLY care about this, you could write a system that launches a separate Python process which talks over a socket to the initiating process and accepts bits of python code to run and returns the results. A separate thread would monitor this separate process and kill it if it starts misbehaving. The currently running code snippet(s) would fail, but then a new "watched process" could be launched. Such a tool would, I think, be superficially very popular. Very popular because reliable sandboxing of untrusted code is a frequent request in this newsgroup, and superficially because I suspect that *in reality* serious programmers (as opposed to armchair speculators) rarely need to execute untrusted code (as evidenced by the lack of an existing library doing this). The only difficult part would be cross-OS portability. -- Michael Chermside From ianb at colorstudy.com Wed Jun 11 16:16:55 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 11 Jun 2003 15:16:55 -0500 Subject: Revised PEP 318 - Function/Method Decorator Syntax In-Reply-To: References: <20030610082514442-0400@braeburn.themorgue.org> <6qwufsn9un.fsf@salmakis.intevation.de> Message-ID: <1055362614.690.935.camel@lothlorien> On Wed, 2003-06-11 at 07:48, Duncan Booth wrote: > > def foo(self) as attributed(my_attr = "bar"): > > pass > > > > with attributed defined as e.g. > > > > def attributed(**kw): > > def add_attrs(f): > > for key, value in kw.items(): > > setattr(f, key, value) > > return add_attrs > > > > I doubt this would have the desired effect. Perhaps we should take this as > a warning: the proposed syntax seems to lead to people writing code > snippets like the one above which would result in foo==None. Accidental Nones happens a lot in Python, I don't think we should try to avoid it. But, it might be nice to say that the decorator is not allowed to return None, so there would be an exception in this case... then at least these bugs will be quickly caught. Ian From hyde at math.umn.edu Thu Jun 5 11:04:57 2003 From: hyde at math.umn.edu (E. McKay Hyde) Date: Thu, 05 Jun 2003 10:04:57 -0500 Subject: 64 bit python In-Reply-To: References: <701f25e6.0306040749.d649f7f@posting.google.com> Message-ID: Martin v. L?wis wrote: > So either LONG_BIT or SIZEOF_LONG is incorrect. Can you tell the > values for either #define? > > Notice that this problem is not generic for 64-bit systems, as there > are actual 64-bit systems which do get their defines right (e.g. Sparc > Solaris 64-bit, or Tru64). So it would be more a problem specific to > your system, or your configuration. For example, which compiler did > you use during configure? > > Regards, > Martin > Sure. The value of LONG_BIT (defined in sys/limits.h on my system) depends on the compiler flags: if I use xlC -q64 (as I did in the configure) LONG_BIT=64, otherwise if one uses xlC alone LONG_BIT=32. SIZEOF_LONG=4, as defined in pyconfig.h; this value appears to be set by the autoconf macro AC_CHECK_SIZEOF(long,4). Does this mean that the configure script expects a size of 4 bytes? Or perhaps the macro is using a different compiler in determining the size? I guess I will try to understand how AC_CHECK_SIZEOF works to see if it is using the correct compiler and compiler flags. Thanks, McKay From kendear at nospam.com Tue Jun 3 14:32:24 2003 From: kendear at nospam.com (Kendear) Date: Tue, 03 Jun 2003 18:32:24 GMT Subject: a = b = 1 just syntactic sugar? References: Message-ID: <3EDCE9C2.5020805@nospam.com> Batista, Facundo wrote: > "b = 1" does not return 1, just returns b. a and b are the same object now > (they are not just equal, they are the very same). if b = 1 returns b, then why can't you say a = (b = 1) ? From m at moshez.org Mon Jun 9 11:00:13 2003 From: m at moshez.org (Moshe Zadka) Date: 9 Jun 2003 15:00:13 -0000 Subject: signal handling oddity In-Reply-To: <20030609143702.B03B326F67@www.fastmail.fm> References: <20030609143702.B03B326F67@www.fastmail.fm>, <20030609134716.915163335D@www.fastmail.fm>, <3H9za.47086$h42.8645@twister.nyc.rr.com> <20030609142215.9399.qmail@green.zadka.com> Message-ID: <20030609150013.10541.qmail@green.zadka.com> On Mon, 09 Jun 2003, "Justin Johnson" wrote: > Yeah, I was using twisted before for this server and it did handle > control-c correctly. I was having problems getting authentication to > work though, so I ended up moving to SimpleXMLRPCServer and adding some > other code to get basic authentication to work. I'm just not familiar > enough with twisted to know what to subclass/override, etc... to get > simple user/password authentication to work. Well, probably in the render() method of your resource, you do the checking of request.headers (there's no problem doing it manually), and if they're ok you call the parent's render() and otherwise you return a 401. -- 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 maurix78_remove_this_ at wanadoo.es Sat Jun 14 18:46:55 2003 From: maurix78_remove_this_ at wanadoo.es (Maurix) Date: Sat, 14 Jun 2003 22:46:55 GMT Subject: comprehending comprehensions References: Message-ID: <3EEBA5C9.3090200@wanadoo.es> Hi, as you are speaking of comprehensions, functional languages and Haskell; i want to propose a game to the group: Let's make some examples to see how long is python compared with Haskell. I've make my try, writing the famous example of qsort in Haskell in a "functional" python: Haskell: qsort [] = [] qsort (x:xs) = qsort elts_lt_x ++ [x] ++ qsort elts_greq_x where elts_lt_x = [y | y <- xs, y < x] elts_greq_x = [y | y <- xs, y >= x] Python: def qsort(list) : if len(list)<=1 : return list x,xs=list[0],list[1:] elts_lt_x=[y for y in xs if y < x] elts_greq_x=[y for y in xs if y >= x] return qsort(elts_lt_x)+[x]+qsort(elts_greq_x) 6 lines vs 5 lines, not bad! Someting can do it better?? I have a question too, there something in haskell that is difficult to "copy" with python? I like haskell for his math-style but have really something more? From op73418 at mail.telepac.pt Wed Jun 18 10:09:09 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 18 Jun 2003 15:09:09 +0100 Subject: destructors, exceptions and the lock guard paradigm References: Message-ID: <19s0fvstohh0juvemrlc7nnoqqbctfr67u@4ax.com> On 17 Jun 2003 19:25:29 -0700, moocat94122 at yahoo.com (Ron Samuel Klatchko) wrote: >I am trying to use the lock guard paradigm in Python. My first >attempt was >this: > >class guard: > def __init__(self, lock): > self.acquired = 0 > self.lock = lock > self.lock.acquire() > self.acquired = 1 > > def __del__(self): > print "releasing lock" > self.release() > > def release(self): > if self.acquired: > self.lock.release() > self.acquired = 1 > >Intended to be used like this: > >class someclass: > def __init__(self): > self.lock = threading.Lock() > > def somefunc(self): > g = guard(self.lock) > # do some work while the lock is held > >The idea was that when somefunc exited, the reference count to g would >drop to 0, the guard would be destructed which would release the lock. > That way, I do not have to manually release the lock for every exit >path. > >While it works for normal returns from the function, the lock is not >released when an exception is thrown. From my research it looks to be >due to how the last traceback is stored and continues to hold a >reference to the guard object. Exactly -- see below. > >Is there a way to get this to work under Python? I realize I can use >try/finally block and put the call to Lock.release() there, I don't >like that as much as the guard method. > You should not rely on __del__ to release external resources. In CPython, __del__ is called as soon as its reference count drops to zero, but that is an implementation detail -- it is not true in Jython for example, where the garbage collector kicks in a non-deterministic fashion. Also, imagine that your object participates in a cycle (a not too uncommon occurence)... So, basically, I guess you are stuck with the common Python idiom -- explicit release of resources via try/finally blocks. >samuel HTH, with my best regards, G. Rodrigues From tjreedy at udel.edu Mon Jun 23 13:29:38 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Jun 2003 13:29:38 -0400 Subject: New to Python...feedback? References: Message-ID: "athe nonrex" wrote in message news:mailman.1056380026.28198.python-list at python.org... > i'm...a...(hang head in shame)...newbie... I recommend you read http://catb.org/~esr/faqs/smart-questions.html TJR From duncan at NOSPAMrcp.co.uk Mon Jun 2 04:42:44 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 2 Jun 2003 08:42:44 +0000 (UTC) Subject: dictionary issue (and maybe PEP ... depending on the answer) References: <0wBCa.651$ig1.627675@newssrv26.news.prodigy.com> Message-ID: Aldo Cortesi wrote in news:mailman.1054538463.26232.python-list at python.org: > 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. > While I agree it's not a good idea to depend on this behaviour, it isn't actually true that the behaviour disappears for large dictionaries. It will however disappear if the dictionary is sparse. If the dictionary isn't sparse, but the keys don't start at a number close to 0 then you can also get the ordering disrupted, for example keys 250..349 will come out in the order 256..349,250..255. -- 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 artur_spruce at yahoo.com Thu Jun 12 10:22:19 2003 From: artur_spruce at yahoo.com (AdSR) Date: 12 Jun 2003 07:22:19 -0700 Subject: PEP 318 - Function Modifier Syntax References: Message-ID: Roman Suzi wrote: > Disclaimer: OOP gurus are free to contact me and remind me why Python needs > all those fancy classmethods, etc. If syncronisation is so important, why not > add a new operator to Python? (I think it is no less important than assert, > for example) I don't know if I'm a guru but I've been doing OOP for last 3 years and I don't think static/class methods are as important in Python as they are in, say, Java where they are used instead of "standalone" functions. Sure you may need them sometimes, like in Python reimplementation of Java DataInputStream/DataOutputStream (don't remember, either on ASPN cookbook or on Useless Python), or in test code for Python libraries. But in those rare (?) cases the two builtin functions that started this thread should be enough. I don't cry after other fancy features either, like the conditional operator for example. True division and "in" operator for strings in 2.3 seem a more important type of improvements for me. AdSR From suresh_vsamy at rediffmail.com Wed Jun 18 13:01:21 2003 From: suresh_vsamy at rediffmail.com (Suresh Kumar) Date: 18 Jun 2003 17:01:21 -0000 Subject: tkSimpleDialog box question............ Message-ID: <20030618170121.6539.qmail@webmail36.rediffmail.com> An HTML attachment was scrubbed... URL: -------------- next part -------------- Hi, Anybody know how to place "tkSimpleDialog" at a given user defined location rather than the default one? I am calling "kSimpleDialog" in my application and it always display near to top-left ( say 100,100). But i want to place at center of the screen or somewhere else. How can i do it? My code is given below. from Tkinter import * import Pmw import tkFont import tkSimpleDialog class Test: def __init__(self,parent): self.myparent = parent self.canvas = Canvasself.myparent,width=500,height=500) self.canvas.bind('', self.showDialog) self.canvas.pack() def showDialog(): radiotype = 0 RadioButtonTest.(sefl.myparent,"Radio Test",radiotype) class RadioButtonTest(tkSimpleDialog.Dialog): def __init__( self, parent,title, filetype) : tkSimpleDialog.Dialog.__init__( self, parent, title) self.group = IntVar() def body(self, master): fType = Frame(master, borderwidth=1, relief=SUNKEN) first = Radiobutton(fType,text = " Test1", ariable=self.group, value=1) first.pack(side=TOP,anchor=W) second = Radiobutton(fType, text = " Test2", variable=self.group, value=2) second.pack(side=TOP, anchor=W) first.select() fType.pack(side="right", padx=3) root = Tk() mytest = Test(root) root.mainloop() From bit_bucket5 at hotmail.com Tue Jun 17 19:46:22 2003 From: bit_bucket5 at hotmail.com (Chris Stromberger) Date: Tue, 17 Jun 2003 23:46:22 GMT Subject: Python 2.3 + mysql? Message-ID: Is there a mysql module that works with Python 2.3? I don't see one listed at sourceforge. Thanks. From NOusenetSPAM at gdargaud.net Fri Jun 20 21:34:32 2003 From: NOusenetSPAM at gdargaud.net (Guillaume Dargaud) Date: Sat, 21 Jun 2003 01:34:32 GMT Subject: Web counter ? Message-ID: Hello all, I'm _very_ new to python and I like to learn by modifying existing code as well as by RTFM (which I'm currently at the first chapters). I tried to find examples of python code for *web counters* but no luck. Could someone point me towards something ? And what's the group's opinion on Paint Shop Pro use of Python for its image scripting ? I saw it after downloading version 8 a few days ago and it looks nice although the code generated was not very obvious. -- Guillaume Dargaud Colorado State University http://www.gdargaud.net/ /* You are not expected to understand this */ From suresh_vsamy at rediffmail.com Wed Jun 11 13:32:22 2003 From: suresh_vsamy at rediffmail.com (Suresh Kumar) Date: 11 Jun 2003 17:32:22 -0000 Subject: Need urgent solution...................... Message-ID: <20030611173222.21827.qmail@webmail27.rediffmail.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From gh at ghaering.de Thu Jun 19 12:23:09 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 19 Jun 2003 18:23:09 +0200 Subject: Problem inserting into Postgres (PgSQL) database In-Reply-To: <200306191119.15704.dreed@capital.edu> References: <3EF195E5.8050909@ghaering.de> <200306191119.15704.dreed@capital.edu> Message-ID: <3EF1E36D.2050503@ghaering.de> Dave Reed wrote: > On Thursday 19 June 2003 06:52, Gerhard H?ring wrote: >>mupeso at arc.sn wrote: >>>[...] >>>sql= "insert into radcheck2 (uid,login,passwd,shell,homedir,domain_name,acc_expired) values ("+str(uid) +",'"+login+"','"+passwd+"','"+shell+"','"+homedir+"','"+dom_name+"','n')" >>[...] >>Second, your style of constructing SQL is a bad one. Use the DB-API way >>of quoting the various datatypes instead: >>[...] >>The way you're constructing your SQL statement now is a security >>vulnerability if any of the fields can come from an untrusted source. > > Could you please elaborate on how your method is more secure? Isn't it > the same result since the %s are replaced with the values from the > variable. A DB-API adapter always does the quoting right, even if there are 'strange' characters in the string. The OP basically always quoted strings using "'%s'" % value Now if value comes from an untrusted source, this opens up the possibility for arbitrary SQL injection. Let's suppose the code in question is this one: sql = "INSERT INTO TEST(FOO) VALUES ('%s')" % value Now an untrusted partie could make value look like this: value = "'); DELETE FROM TEST; --" Which results in this SQL to be executed: INSERT INTO TEST(FOO) VALUES (''); DELETE FROM TEST; --') The comment "--" will make the illegal characters disappear, and appriate use of single quotes and semicolon make it possible to insert an additional SQL statement to be executed. To safely insert strings in SQL statements, you need to at least escape single quotes. pyPgSQL does this already for you. This is PostgreSQL, where this is necessary - other databases, like Oracle can transmit SQL with placeholders and actual values to be inserted seperately and that's what their Python adapters do if you use the DB-API way of quoting. -- Gerhard From sismex01 at hebmex.com Mon Jun 2 15:50:19 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 2 Jun 2003 14:50:19 -0500 Subject: Python get's a mention on University Challenge Message-ID: > > What was the question? > > --Irmen > 42 -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 andrew at acooke.org Sun Jun 8 20:17:33 2003 From: andrew at acooke.org (andrew cooke) Date: 08 Jun 2003 20:17:33 -0400 Subject: Strange problem with notebook computer In-Reply-To: <001401c32e18$9c123e80$afee7b43@homer3cq9tc2v2> References: <001401c32e18$9c123e80$afee7b43@homer3cq9tc2v2> Message-ID: <874r30kste.fsf@acooke.org> is using python the only time you run software that places a heavy load on the computer? it's unlikely to be something special about python itself, but if your computer has a problem that only shows up under load then it may be that python use is triggering it simply because that's what you use when you load the computer. i would suggest playing some cpu-intensive game on it for some time, or doing something else that loads the computer. i expect you'll see the same problem. (i don't want to be rude, but something you learn when you've been using computers for a while is that the mind makes connections before there is enough real evidence - you end up blaming something simply because it's the first thing that comes to mind, and you tend to look for things that support that conclusion and ignore things that don't. it's disturbing how illogical you can be. or maybe it's just me that's mad... ;o) another possibility (i have an old laptop that has a dektop cpu in it because it was faster - this is from many years ago, before there was a big difference between desktop and laptop chips - that has this problem), for example, is that when you're using python you have the computer on your knee, blocking the fan, while otherwise you tend to leave it on a tabletop (in my case, the laptop had legs that kept the fan clear of the table). look for "silly" things like this... good luck, andrew "Homer Ellison" writes: > 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 > -- http://www.acooke.org From duncan at NOSPAMrcp.co.uk Fri Jun 6 10:52:10 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 6 Jun 2003 14:52:10 +0000 (UTC) Subject: Add methods to a class dynamically References: <64fb4467.0306060628.2c51bf09@posting.google.com> Message-ID: tr at jotsite.com (Hoang Do) wrote in news:64fb4467.0306060628.2c51bf09 at posting.google.com: > I am having trouble invoking the created method. The function > addition goes fine but invoking it gives an error. Here is some > simple code: --------------------------------------------------------- > class DynObj: > def __init__(self): > self.methods = ("a", "b", "c") > for method in self.methods: > self. __generateMethod(method) > def __generateMethod(self, methodName): > code = "def %s(self):\n\tprint %s\n" % (methodName, methodName) Try this instead: code = "def %s(self):\n\tprint self.%s\n" % (methodName, methodName) > exec code in globals(), self.__dict__ > > if __name__ == "__main__": > x = DynObj() > print dir(x) > x.a(x) > --------------------------------------------------------- > The Error: > NameError: global name 'a' is not defined > --------------------------------------------------------- > Methods "a", "b", and "c" are callable and in DynObj's __dict__. > However, I can't seem to call it. > > Calling for help from anyone familiar with Python's introspective > features? > Your problem is mainly trying to access the global function 'a' from the print statement. Fix it as shown above. The other problem is that you put a function into the instance so you have to explicitly pass the self parameter when calling it. You probably want to create a bound method instead: def __generateMethod(self, methodName): d = {} code = "def %s(self):\n\tprint self.%s\n" % (methodName, methodName) exec code in globals(), d setattr(self, methodName, d[methodName].__get__(self, self.__class__)) ... >>> x.a() > -- 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 martin at v.loewis.de Sat Jun 21 15:05:14 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 21 Jun 2003 21:05:14 +0200 Subject: Updating to Python 2.2.3 References: Message-ID: Christoph St?hli writes: > I would like to update Python 2.2.2 to the newest version (2.2.3). Do > I have to uninstall the older version first? Do i have to reinstall > all the side-packages (VPython, wxPython etc.)? I'm running Windoze XP. I believe the general advise is that you should uninstall older Python releases before updating. Regards, Martin From achrist at easystreet.com Fri Jun 13 13:47:35 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Fri, 13 Jun 2003 10:47:35 -0700 Subject: Saving Files Under Windows References: <3EE993CB.F2CE7D39@easystreet.com> Message-ID: <3EEA0E37.500BB9D8@easystreet.com> Thanks to all for the advice. To recap: It looks like this is all OS-version-specific. I guess I'd like to just put the data into the application directory on OS's prior to Win2k. If you upgrade a system from Win98 or NT to WinXP is the user screwed by having all their data in the wrong place anyhow? Trying to figure out how to figure out which OS version I'm dealing with, I try: >>> import win32api >>> win32api.GetVersionEx() (4, 0, 1381, 2, 'Service Pack 6') I infer that the major version is the first value in the tuple returned, and that if I see 4 or less, I've got an old system where I can allow or encourage the user to do what I've usually done, ie put data into a sub-folder of the app directory. (File save dialogs start someplace within the application folder). If the major version is 5 or more, I've got 2k or XP or something newer (maybe worse?), and I should look in the registry at 1. For 1-user data HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\ShellFolders\ My choice of registry value names may be "AppData", "Local AppData", and "Personal". I'll probably go with "AppData", if I find it. Any suggestions which is preferred? Anything else to look at on newer Windows versions? 2. If I don't find anything, I try: C:\Documents and Settings\\Application Data\ 3. For data shared among several users: HKLM\Software\Microsoft\Windows\CurrentVersion\Explorer\ShellFolders\ Where I find a value named "Common AppData". Anything else to look at on newer Windows versions? 4. If I don't find anything, I try: C:\Documents and Settings\All Users\Application Data\ File save dialogs for Win2k or newer will start in a subfolder of the folder found by steps 1-4. The python win32api should make all of this duck soup. Any pitfalls? Al From peter at engcorp.com Fri Jun 13 07:21:22 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 13 Jun 2003 07:21:22 -0400 Subject: OnFileOpent(self, event): References: Message-ID: <3EE9B3B2.345CBE67@engcorp.com> MK wrote: > > 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, Presuming you want to call it from within another method of the object in which that method is defined (in other words, assuming you have a "self" in some other method which refers to the object itself) you could possibly do this: self.OnFileOpen(event) Now you may or may not need to specify "event" properly. You could just try with (None), or maybe an empty string '', but that sort of thing probably works only if the method does not actually use the event parameter internally. More information might be needed to help further, but the above at least covers the syntactual aspects. -Peter From edreamleo at charter.net Sat Jun 14 06:58:30 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Sat, 14 Jun 2003 05:58:30 -0500 Subject: You know you're a Pythonista when.. References: Message-ID: > Those that have marked my progress are: 1. I respond to all references to C++, etc. by saying that static languages should be used only if it can be _proved_ that Python does not suffice. Good luck with the proof :-) 2. I create "instant unittests" by copying Python code from copy of Leo to another. I can execute those instant unittests from within Leo itself. These instant unittests are an effortless way of testing code that hardly ever gets executed, like error dialogs. 3. I hardly ever leave the main copy of Leo while developing Leo. "Recompiling" Leo means reloading a separate test outline (containing the instant unittests). The test copy of Leo effortlessly accumulates all the official-unittests-to-be. This change in workflow has approximately tripled my productivity. No kidding. For example, I can correct syntax errors immediately in the main copy of Leo: a) I am already in the correct spot and b) the main copy of Leo is still running and so is unaffected by the botch. All this leave me more free time to enthuse about Python :-) Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From anton at vredegoor.doge.nl Thu Jun 12 10:56:30 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 12 Jun 2003 16:56:30 +0200 Subject: index(x) References: <3EE884B6.3070105@gmx.net> Message-ID: Tom wrote: >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. Probably because there isn't such a command :-) It's a oneliner though, in a recent enough Python: def indices(L,x): return[i for i,y in enumerate(L) if x==y] >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? In open source communities there is the possibility of discussing the source code with the original authors (if they're not too busy making money). Because of this it's possible to help develop the product one is using and for the authors to get specific feedback about the way their product is used. It easy to see that these two aspects must necessarily be linked for maximum effectiveness. So for open source the community is all important. Interact with the fora and search the archives for answers to your questions. If after some reasonable effort no obvious answer is found, write a small as possible a script demonstrating what you want to or can not accomplish, and post it here under a concise and descriptive subject title. You have done well :-) Generations of Python programmers after you will thank you for this. (That is if the subject was not one that has come up a thousand times, which I didn't check, but which seems reasonable) Anton From tzot at sil-tec.gr Mon Jun 23 03:57:54 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 23 Jun 2003 10:57:54 +0300 Subject: random function with strings References: <3ef51a51$0$8029$79c14f64@nan-newsreader-01.noos.net> Message-ID: On Mon, 23 Jun 2003 00:05:05 GMT, rumours say that "Raymond Hettinger" might have written: >"ataraxia2500" >> I have a function that goes through a directory and I would like to remove >> randomly one of the files contained in that directory. >Giving full access rights to a secretary or new programmer >ought to insure an occassional random file deletion ;-) QOTW +1 :) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From a.schmolck at gmx.net Wed Jun 18 16:18:05 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 18 Jun 2003 21:18:05 +0100 Subject: a clean way to define dictionary References: <3EEFEBFD.8090003@nospam.com> Message-ID: Skip Montanaro writes: > >> 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. > OK, I admit this is an overstatement, but ideally you'd like to be able to use a subclass in place of its superclass everywhere, and that includes constructor syntax compatibility (e.g.: ``type(some_dict)(foo=bar)`` to create a new dictionary of the same type as some_dict). 'as From evan at 4-am.com Mon Jun 2 13:51:33 2003 From: evan at 4-am.com (Evan Simpson) Date: Mon, 02 Jun 2003 12:51:33 -0500 Subject: A Python application server? In-Reply-To: References: Message-ID: <3EDB8EA5.5040901@4-am.com> Duncan Smith wrote: > "Java is the only mainstream technology that adds the required level of > safety for code travelling around a network, and the flexibility to invent > our own controls, regardless of the operating system being used." This is one of Zope's core features. Scripts, Documents, Methods, and Templates (the various sorts of programmable object in Zope) are all constrained by Zope's security policies. You can give a totally untrusted user the ability to use Python code, and the worst they can do to your server is deny service. Cheers, Evan @ 4-am From ngterry2000 at yahoo.com.hk Fri Jun 6 23:00:17 2003 From: ngterry2000 at yahoo.com.hk (=?iso-8859-1?q?Terence=20Ng?=) Date: Sat, 7 Jun 2003 11:00:17 +0800 (CST) Subject: Characters in Python In-Reply-To: <23891c90.0306060626.24e6646d@posting.google.com> Message-ID: <20030607030017.64215.qmail@web41101.mail.yahoo.com> In IDLE, you just have to open a module called site (site.py) and find this: # Set the string encoding used by the Unicode implementation. The # default is 'ascii', but if you're willing to experiment, you can # change this. encoding = "utf-8" #modify this details can be found in FAQ --- Paul Boddie wrote: > jansun at home.se (Jan Sundstr?m) wrote in message > news:... > > > > str = '???' > > print str > > > > Python, or perhaps IDLE rather, doesn't seem > toaccept characters with > > codes over 127. > > This reference might be interesting: > > > http://mail.python.org/pipermail/patches/2002-February/007368.html > > However, I see the same problem with IDLE from the > ActiveState Python > 2.2 distribution. Using IDLEfork instead seems to be > a good solution: > > http://idlefork.sourceforge.net > > It turns out that you can do exactly what you wanted > in IDLEfork. > > > Is there a simple way to turn off this obscession > with 7-bit ASCII? > > The above reference would suggest that it isn't a > point of obsession > but an oversight carried over from an earlier time. > Anyway, as a point > of reference it should be noted that ASCII is a 7 > bit standard, if not > officially (but I think it actually is) then for > most intents and > purposes you should consider it to be so. I imagine > that you actually > mean, "Can I work with strings in my own encoding?" > With IDLEfork, the > answer is yes. > > Personally, I think that most people would be better > off working with > Unicode. In IDLEfork you can actually print Unicode > objects directly. > However, in console environments, Python gets rather > upset at the mere > suggestion - see below for a workable approach. > > > And how can one easily change what Python > considers to be > > default character encoding? > > I couldn't find anything about that in the > tutorial. > > To get your default encoding, at least, try this: > > import locale > locale.setlocale(locale.LC_ALL, "") > > Apparently, you should only ever do this once in > your program, and you > shouldn't do it in a library. Then try this: > > encoding = locale.getlocale()[1] > > Sadly, in Windows environments, this may return > something like "1252" > which isn't enough for my next suggestion: to > convert strings to > Unicode, do this: > > u = unicode(s, encoding) # don't use 'str' for > your variable since > # it's a built-in > > On Windows, try this kind of thing instead: > > u = unicode(s, "cp1252") > > To write Unicode out to your console, try this: > > print u.encode(encoding) > > This works on IDLEfork, too, so for success in both > DOS boxes and > IDLEfork I'd suggest explicit encoding of Unicode > objects when > printing stuff out. > > Paul > -- > http://mail.python.org/mailman/listinfo/python-list _______________________________________________________________________ Do You Yahoo!? Get your free @yahoo.com.hk address at http://mail.english.yahoo.com.hk From pifpafpuf at gmx.de Thu Jun 26 08:35:59 2003 From: pifpafpuf at gmx.de (Harald Kirsch) Date: 26 Jun 2003 05:35:59 -0700 Subject: jython type coercion to interface type References: <16990fa4.0306250941.55973aba@posting.google.com> <3ef9f6ab$0$141$e4fe514c@dreader5.news.xs4all.nl> Message-ID: <16990fa4.0306260435.6403a7dd@posting.google.com> Ype Kingma wrote in message news:<3ef9f6ab$0$141$e4fe514c at dreader5.news.xs4all.nl>... > Harald Kirsch wrote: [snip] > > class X { > > public X(CharSequence s) { ... } > > } [snip] > > x = X(CharSequence("bla")) > > > > and got "can't instantiate interface (java.lang.CharSequence)" > Could you try this: > > from java.lang import String > > x = X(String("bla")) > Yes, this worked. Thanks, Harald From dsavitsk at ecpsoftware.com Mon Jun 2 02:09:29 2003 From: dsavitsk at ecpsoftware.com (dsavitsk) Date: Mon, 02 Jun 2003 06:09:29 GMT Subject: dictionary issue (and maybe PEP ... depending on the answer) References: <0wBCa.651$ig1.627675@newssrv26.news.prodigy.com> Message-ID: Dave Harrison wrote: > My quick - ignorant - question is : > > Why dont we get : > > 1, 11, 12, 2, 3, 4, 5, 6, 7, 8, 9 > At the very least because they are integers, so if sorted, they should be sorted correctly. '1', '11', '12', '2', '3', '4', '5', '6', '7', '8', '9' might make sense, however, if the keys were strings. -doug From llafba at gmx.net Mon Jun 9 11:50:37 2003 From: llafba at gmx.net (Tom) Date: Mon, 09 Jun 2003 17:50:37 +0200 Subject: cut off \n Message-ID: <3EE4ACCD.70000@gmx.net> 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]). 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. This is probably a very common problem but I am pretty new to Phython and could find anything useful with google. :-( Thanks, Tom From ais_rajesh at yahoo.com Thu Jun 19 18:40:35 2003 From: ais_rajesh at yahoo.com (Rajesh Sudarsan) Date: Thu, 19 Jun 2003 15:40:35 -0700 (PDT) Subject: Python Mega Widget doubt. Message-ID: <20030619224035.21108.qmail@web41612.mail.yahoo.com> Hi, I am using PMW for creating a GUI. The input is given through XML file. A class parses through the XML file and creates the GUI using the PMW. The GUI consists of EntryWidgets and combo boxes. This is carried out at loading time. Now at runtime, when I change the value of these Entry Fields , how do I read these values? There are multiple XML files and hence multiple windows are created .. Please help.. Regards, Rajesh --------------------------------- Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! -------------- next part -------------- An HTML attachment was scrubbed... URL: From noah at noah.org Mon Jun 9 11:25:27 2003 From: noah at noah.org (Noah) Date: 9 Jun 2003 08:25:27 -0700 Subject: Scanning for local servers, getting a broadcast address References: Message-ID: chris.lyon at spritenote.co.uk (Chris Lyon) wrote in message news:... > ... > However since I have to generate the broadcast address, I need to know > at least my subnet mask to allow me to derive the Broadcast address. > > How do I do this in a pythonic fashion without recourse to reading > host files which seems very platform dependant? > ... > Chris Lyon Do you really need to get the subnet mask? Can you just use the special '' address? The following code (client and server test) demonstrate broadcasting without having to find the subnet mask. Run them on different machines on the same subnet and you should see the server print the packets from the client. --- bclient.py ---------------------------------------------------------------- import time import socket s = socket.socket (socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) s.setsockopt (socket.SOL_SOCKET, socket.SO_BROADCAST, 1) while 1: s.sendto('hello\n', ('', 2003)) time.sleep(1) --- bserver.py ---------------------------------------------------------------- import socket import select import sys s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) s.bind( ('', 2003) ) while 1: (rfd,wfd,efd)=select.select([s],[],[]) if s in rfd: (string, address) = s.recvfrom(100) print 'string: %s' % string print 'from: %s' % str(address) print '--------------------------------' Yours, Noah From kamikaze at kuoi.asui.uidaho.edu Sun Jun 29 04:39:01 2003 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 29 Jun 2003 08:39:01 GMT 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: Thu, 19 Jun 2003 09:56:37 GMT, Alex Martelli : > > David Abrahams wrote: >> the type of c is a container > Rather, "c is a container". Choosing to express "c is a container" > as "the type of c is the type of a container" is just the kind of > useless, redundant boilerplate that negatively impacts productivity. > And in neither C++ nor Java can you express "c is a container", either > directly or indirectly, except in comments That is incorrect for Java, and for most C++ class libraries. List c = new ArrayList(); c.add("foo"); c.add("bar"); System.out.println( c instanceof Collection ); System.out.println( c.size() ); for(Iterator it = c.iterator(); it.hasNext(); ) { System.out.println( it.next() ); } Java classes can have interfaces, which may define methods, or may just be markers for behaviors. You can create your own completely custom class that implements Collection, and it can be used anywhere any of the java.util.* Collections could. In fact, I find it hard to understand how anyone could make such an assertion, unless they were just spouting off without researching it. For me, the value of statically-defined types is that I know that mistyping a method name will show up as an error at compile-time, not at run-time. With __slots__ in the new-style classes, at least now Python can be made to report mistyped field names as errors at run-time instead of silently assigning to them, which was a maddening type of bug to find. I'd prefer to have compile-time checking, but I'm happy enough with Python's other advantages to live with run-time checking for some projects. Python and Java are not diametrically opposed religions that must fight to the death in jihad, despite the existence of loonies favoring exactly that. They solve different problems; sometimes in similar ways, sometimes not. Getting worked up enough about the evils of a type system to post hundreds of lines of poorly-researched screed complete with Stockholm Syndrome references, though... I say this as a friend, there are a lot of decaffeinated brands on the market today that are just as tasty as the real thing. -- Mark Hughes "We remain convinced that this is the best defensive posture to adopt in order to minimize casualties when the Great Old Ones return from beyond the stars to eat our brains." -Charlie Stross, _The Concrete Jungle_ From rganesan at myrealbox.com Sun Jun 1 00:30:19 2003 From: rganesan at myrealbox.com (Ganesan R) Date: 01 Jun 2003 10:00:19 +0530 Subject: Python IO performance? References: Message-ID: >>>>> "Chad" == Chad Netzer writes: > On Sat, 2003-05-31 at 00:26, Ganesan R wrote: >> Python is over 8 times slower! Is the problem with the fileinput >> module or is I/O just slower with python? > Probably a few things. One is that this case really favors Perl because > it has operators for doing these things, and is heavily optimized for > such cases. I agree that this case favors perl. It's just that I am used to writing quick hacks like this for text processing in perl. After learning python I've been resisting my impulse to code them in perl and use python instead. I always had a feeling that my python scripts ran much slower. I decided to so time timing tests to check out my perception and hence the post. > Secondly, you are timing the program startup time plus the loop. Python > has to compile the program before executing it (don't know how Perl does > this, probably the same), then import a module before it does the loop. > This adds a fixed overhead (for small input files, the startup time > could dominate). Note that python doesn't create a pre-compiled > mycat.pyc file when you run a script directly on the command line like > this (it only does it when importing a module, or when explictly told). I made sure that this is not a problem. Doubling the size of the file approximately doubled the time taken. So the overhead is pretty minimal in this case. > Thirdly, the fileinput module itself is not the fastest method. Here is > my quick hack version, that goes quite a bit faster, and uses file > iteration directly: > ==== - mycat2.py > import sys > if len( sys.argv ) < 2: > sys.exit() > f = file( sys.argv[1], "r" ) > for line in f: > print line, > f.close() > ==== I noticed this myself after my post. A similar version that I wrote took < 0.3 secs compared to over 0.7 secs for the version using fileinput. Much better but still about 3.5 times slower than the perl version. > Python 2.3 beta1 has improved the file iteration even more. Here are > those timings: I saw some posts mentioning about 25-30% improvement in performance in general. It's good to know that file iteration is also being addressed. > Now my version is about 2.5 times slower than perl. It is probably not > the case that Python will ever catch up to Perl completely for this > benchmark (again, this benchmark happens to play to Perl's strengths in > using language operators to efficiently handle file IO under the > covers), or even other basic file IO benchmarks. Perl has always > performed better in that area, and is designed to be quick when doing > IO. Interestingly when I tried strace on both the perl and python versions, the actual system calls were virtually identical (4k reads and writes). So, I guess the issue is with the user space libraries like Aahz suggests in his post. I do hope fileinput performance is addressed. It's the a natural choice for writing unix filters and a 2.5 times slow down over a direct coded version is not acceptable. > But as you can see, there have been big improvements made to Python's IO > processing speed, and once the processing of the IO happens, depending > on what is being done, these benchmarks may no longer apply. I'd assume > Perl is still faster for regular expression stuff, for example, but > maybe not by much. Others will know more about this than I (I last used > Perl at version 4). Actually, I first started script using regexps. After some tests I figured out that I/O itself seemed to be bottleneck :-(. I remember Perl using an alternative I/O library called sfio; I don't know if that's the standard in shipping binaries. Any way, let me do some digging with the python 2.3 sources. May be there's more scope for improvement. Ganesan From m at moshez.org Mon Jun 16 21:37:16 2003 From: m at moshez.org (Moshe Zadka) Date: 17 Jun 2003 01:37:16 -0000 Subject: does lack of type declarations make Python unsafe? In-Reply-To: <3EEE1210.3004AB45@engcorp.com> References: <3EEE1210.3004AB45@engcorp.com>, <3EEDDA77.E9246F25@engcorp.com>, <3064b51d.0306151228.22c595e0@posting.google.com> <3EECED65.ACF1A6B7@engcorp.com> Message-ID: <20030617013716.29994.qmail@green.zadka.com> On Mon, 16 Jun 2003, Peter Hansen wrote: > Don't mistake me for the XP community. I'm just me. Your attitude is, however, typical :) > I shortened it from a previous post, in which I continued > "Source code with good unit and acceptance tests is an asset." > > Sounds like you wouldn't agree. Right, I wouldn't. Source code is *always* a liability. Unless you think the unit tests and acceptance tests make it bug-free, I don't see *why* you wouldn't happily delete it the moement it proves to be unnecessarey. > For my company, it's very clear that it's true, however, so I guess > once again (surprise!) I speak only for myself. :-) I doubt it is true, even for your company. Source code is *always* a liability, unit-tests or no unit-tests. It is an *acceptable* liability, sometimes, if you get enough functionality out of it. Insofar as tests measure functionality, they are useful to make sure you have no code which does not give functionality. > I agree. Good thing we don't actually *always* write tests, nor > always write them first. ;-) That sort of makes your methodology from "TDD" to "Sometimes TDD, if it looks like the right thing". So preaching TDD while not practicing it is...well... > Don't mistake strong claims for religion either... I make them > to spur the truly test-less on to consider and investigate and > practice writing tests, because _they_ are the ones who are > writing crappy code, not you, who might understand when to test > and when not to test. It's better to teach people the truth, no? Instead of teaching them about some rosy place which doesn't exist. I feel you are doing unit-testing a disservice: if someone buys into it, and finds that it isn't a win always, he'll just assume that it is worth nothing. In fact, I assumed tests are worth nothing after finding some glaring holes in XP's logic, and it took me a long time to be convinced that they are ever helpful. Assuming there are others like me, it is better to be honest about the limitations of technology first :) -- 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 tjreedy at udel.edu Sun Jun 1 14:43:04 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 1 Jun 2003 14:43:04 -0400 Subject: Defensive programming References: <7xptlxq2yz.fsf@ruckus.brouhaha.com> <2e363c08.0306010923.a08627f@posting.google.com> Message-ID: "Paul Miller" wrote in message news:2e363c08.0306010923.a08627f at posting.google.com... > What in the world are collision resistant hashes? What was meant are hashes for which an attacker cannot feasibly compute a set of colliding keys. For open-source programs, this could mean including a pseudorandom element to the algorithm that privately changes value with each program startup. Terry J. Reedy From goodger at python.org Wed Jun 25 09:46:23 2003 From: goodger at python.org (David Goodger) Date: Wed, 25 Jun 2003 09:46:23 -0400 Subject: Iterating over optparse options In-Reply-To: <33803989.0306250305.77fd046e@posting.google.com> References: <33803989.0306250305.77fd046e@posting.google.com> Message-ID: <3EF9A7AF.8090803@python.org> Miki Tebeka wrote: > Couldn't find it in the manual ... > Is there a way to iterate over the options optparse parser finds? Yes, but that's not using optparse properly. > The rational is that I have a program with many command line > options. Instead of going over all of them I'd like to set my > defaults and change only what is needed. That's what optparse is meant to do, automatically. When you configure the parser, just set appropriate defaults for each option. After parsing, you'll have what you want. parser = OptionParser() parser.add_option("-o", "--option", default="whatever") # ...add more options here... options, args = parser.parse_args() Call the program with "-o something" and "options.option" will contain "something". Call the program with no options and "options.option" will contain "whatever". It may help if you don't think in terms of "options" but use "settings" instead. optparse handles settings, whether or not there's a command-line option associated. > What I like to to is: > ----- > OPTIONS = {} > ... > parser = OptionParser() > ... # Configure parser > options, args = parser.parse_args() If you still want to iterate over the values, you can. "options" is an optparse.Values instance, which contains values in its "__dict__": for opt, value in options.__dict__.items(): OPTIONS[opt] = value -- David Goodger http://starship.python.net/~goodger For hire: http://starship.python.net/~goodger/cv Docutils: http://docutils.sourceforge.net/ (includes reStructuredText: http://docutils.sf.net/rst.html) From junk at aol.com Wed Jun 4 15:56:25 2003 From: junk at aol.com (junk at aol.com) Date: Wed, 04 Jun 2003 14:56:25 -0500 Subject: system event viewer help Message-ID: When I run this script instead of giving me information from my System log it pulls information from my Application log. I'm sure I'm missing something simple but I cant seem to get it to work no matter what I do. import win32evtlog, win32evtlogutil win32evtlog.OpenEventLog(None, "System") win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ print "Event Viewer System log" def CheckRecord(record): if str(record.EventType)=="2": print "Have Warning for %s written at %s" % \ (record.SourceName, record.TimeWritten.Format()) elif str(record.EventType)=="1": print "Have Error for %s written at %s " % \ (record.SourceName, record.TimeWritten.Format()) win32evtlogutil.FeedEventLogRecords(CheckRecord) From alf at fayauffre.org Wed Jun 18 11:44:13 2003 From: alf at fayauffre.org (Alexandre Fayolle) Date: Wed, 18 Jun 2003 15:44:13 +0000 (UTC) Subject: [ANN] pylint-0.1.2 Message-ID: What's new ? ------------ 2003-06-12 -- 0.1.2 * first public release What is pylint ? ------------------------ Pylint is a python tool that checks if a module satisfy a coding standard. Pylint can be seen as another pychecker since nearly all tests you can do with pychecker can also be done with Pylint. But Pylint offers some more features, like checking line-code's length, checking if variable names are well-formed according to your coding standard, or checking if declared interfaces are truly implemented, and much more (see http://www.logilab.org/pylint/ for the complete check list). The big advantage with Pylint is that it is highly configurable, customizable, and you can easily write a small plugin to add a personal feature. The usage it quite simple : $ pylint mypackage.mymodule This command will output all the errors and warnings related to the tested code (here : mypackage.mymodule), will dump a little summary at the end, and will give a mark to the tested code. Pylint is free software distributed under the GNU Public Licence. Home page --------- http://www.logilab.org/pylint/ Download -------- ftp://ftp.logilab.org/pub/pylint/ Mailing list ------------ mailto://python-projects at lists.logilab.org -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org D?veloppement logiciel avanc? - Intelligence Artificielle - Formations From carljohan.rehn at chello.se Thu Jun 5 14:11:05 2003 From: carljohan.rehn at chello.se (carljohan.rehn at chello.se) Date: Thu, 05 Jun 2003 20:11:05 +0200 Subject: Module for quasi-random sequences? Message-ID: <1BLDa.10298$KF1.144776@amstwist00> Does anyone know if there exists a python module for generating quasi-random sequences (Sobol, Halton, Niedereiter, etc)? Carl From peter at engcorp.com Fri Jun 20 06:06:51 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 20 Jun 2003 06:06:51 -0400 Subject: os.path weirdness References: <3EEF41EF.ACF5B0C0@engcorp.com> <3EF1804E.8080300@lmco.com> <87of0th7a9.fsf@pobox.com> Message-ID: <3EF2DCBB.11597E49@engcorp.com> "John J. Lee" wrote: > > Jeff Layton writes: > [...] > > Also, thanks for the comments below. I haven't used the > > debugger at all yet. I'm an old fashioned kind of coder that > > uses lots of "write, printf, print" to debug :) I really do > > need to learn the debugger though. > > I don't think so. print statements are a perfectly good way of > debugging Python code. One of the benefits of an interpreted > language. "print" is fine for debugging, and I've 'ad to work with much less (single LED hooked up to an oscilloscope, toggled in various patterns to indicate state), but there are also times when a few seconds with the debugger will get you farther, faster. One problem with the "print" approach is setup: if it takes a long time to get to the failing code, and it might take several runs before you get the print just right, the pdb.set_trace() approach could mean the difference between finding a problem in a minute and finding it in fifteen minutes. Of course, I could also point out that with TDD you very rarely have to resort to either a debugger *or* print statements, but that's another post. ;-) -Peter From max at alcyone.com Thu Jun 26 22:38:24 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 26 Jun 2003 19:38:24 -0700 Subject: stupid question about os.listdir References: Message-ID: <3EFBAE20.7CA033EB@alcyone.com> Jason Kratz wrote: > oops. almost forgot. if I run interactively in the python > interpreter > it works as I expect. its when doing 'python script.py' from the > command line that it only uses the current directory. Never heard of any such thing. It's likely that your script is not quite doing what you expect it to. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Heaven and Hell / Is on Earth \__/ Salt-n-Pepa From nomail at magicfish.net Mon Jun 23 02:30:34 2003 From: nomail at magicfish.net (Austin Luminais) Date: 22 Jun 2003 23:30:34 -0700 Subject: Windows - getting Tkinter or wxPython window handle? References: Message-ID: "Greg Ewing (using news.cis.dfn.de)" wrote in message news:... > On Windows, is there any chance of getting hold of an > MFC window handle for a Tkinter or wxPython window? > If so, how? In wxPython, wxWindows have a method called GetHandle which will return the HWND of the window. From tchur at optushome.com.au Thu Jun 12 22:07:29 2003 From: tchur at optushome.com.au (Tim Churches) Date: Fri, 13 Jun 2003 12:07:29 +1000 Subject: HL7 servers in Python? Message-ID: <200306130207.h5D27TJ27403@mail019.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From ee01b092 at ee.iitm.ernet.in Sun Jun 8 05:02:32 2003 From: ee01b092 at ee.iitm.ernet.in (Vinoo vasudevan) Date: Sun, 8 Jun 2003 14:32:32 +0530 Subject: the 'in' operator and class instances In-Reply-To: <20030608062201.16011.72647.Mailman@mail.python.org> References: <20030608062201.16011.72647.Mailman@mail.python.org> Message-ID: <20030608085256.M7792@ee.iitm.ernet.in> Hi, I'm an newbie and have been getting to know Python over the past two weeks. One of the things I really liked was the 'in' operator. Statements like "key in dict" or "line in file" are really cool. But this doesn't seem to work for classes. i.e. >>> class a: def f(self): pass >>> 'f' in a Could somebody tell me why class instances don't use in to check for memebership i.e. something like hasattr(..). I read up on "__contains__" in the Language Reference. Couldn't python just define a default version of this for all classes/instances to check for membership. Any class that attaches a special meaning to membership can of course define its own "__contains__". In c++ terminology (my __previous__ language :-) ) : can't "object" define a virtual function "__contains__"? Just a suggestion. Plz let me know if I don't have a clue of I'm talking about. :-) Vinoo From Anish.Mehta at enst-bretagne.fr Tue Jun 3 14:09:04 2003 From: Anish.Mehta at enst-bretagne.fr (Mehta, Anish) Date: Tue, 03 Jun 2003 20:09:04 +0200 Subject: Variable Modifications in a class References: <3EDCDB05.8E12F97@hotmail.com> Message-ID: <3EDCE440.8030009@antares.enst-bretagne.fr> Thanks for the explaination. That point is clear and also one thing more is that when we have the same piece of code in c , and when we do 'c = b' then copy constructor is invoked. So in c with the same(likely) piece of code we have differnt output from python. I would like to know is there any way with which i can write the code in python for the C code like below. I am writing a program in python which is already written in C and in that lot of instances are modifying the variables of the some structure like this: typedef struct ab { int a; int b; }AB; main() { AB b; AB c; b.a = 5; b.b = 10; c = b; c.a = 30; c.b = 40; printf("AB values %d %d\n", b.a, b.b); printf("New values %d %d\n", c.a, c.b); } The output is: AB values 5 10 New values 30 40 >So let's run through your function line by line > > def func(ab): > b = ab() > >This creates a new AB object, the first one. >It also creates the name "b", and binds it to the new AB object. > > c = ab() > >This also creates a new (and different) AB object, the second one. >It also creates the name "c", and binds it to the second AB object. > > b.a = 5 > >Set the "a" member of the AB object *referred to* to by "b" to 5 > > b.b = 10 > >Set the "b" member of the AB object *referred to* to by "b" to 10 > > c = b > >Make the name "c" refer to whatever "b" refers to >(in this case, the *first* AB object). >Note also that you now have no way of getting at the second AB >object, since you have no reference to it. It has fallen into the >garbage heap, and will be recycled eventually. > > c.a = 30 > >Set the "a" member of the AB object referred to by c (i.e. the first AB >object) to 30 > > c.b = 40 > >Set the "b" member of the AB object referred to by c (i.e. the first AB >object) to 40 > >I think you will understand the behaviour better now. > >HTH, > > > From joshway_without_spam at myway.com Fri Jun 6 12:04:17 2003 From: joshway_without_spam at myway.com (Joshua Marshall) Date: Fri, 6 Jun 2003 16:04:17 +0000 (UTC) Subject: Postfix/Prefix Operators (++,--) References: <3EE05E36.40DF739F@engcorp.com> <3EE0B4D5.736EE894@engcorp.com> Message-ID: Peter Hansen wrote: ... >> ++/-- can be added to Python, and could act in a way that wouldn't >> surprise C or Java programmers. There really isn't any conceptual >> difference between references to immutabe ints and C/Java primitive >> ints. > How would the error generated when the C or Java programmer wrote > the following code not surprise him or her? > c = 1 > a = c++ I wouldn't design ++ to error in this case: >>> c = 1 >>> a = c++ >>> a 1 >>> c 2 From troy at gci.net Wed Jun 18 02:48:59 2003 From: troy at gci.net (Troy Melhase) Date: Tue, 17 Jun 2003 22:48:59 -0800 Subject: preventing creation of instance References: Message-ID: Mirko Koenig wrote: > 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. Hi Mirko: I assume that your test class will need to do real work. If that's true, I'd suggest you separate the behaviors of what your class really does and how its instances are created. By separating the two, the class gains a degree of reusability, and the code becomes more clear. For example: class actual_test: def __init__(self, name): self.name = name def test(name, names={}): if name in names: return None names[name] = newone = actual_test(name) return newone adam = test('Adam') eve = test('Adam') assert adam assert eve is None Good luck, troy From dkuhlman at rexx.com Wed Jun 25 17:07:48 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 25 Jun 2003 14:07:48 -0700 Subject: better way than: myPage += 'more html' , ... References: <3EF9CBCB.90305@yahoo.com> Message-ID: Andy Jewell wrote: [snip] > An easy way, which requires little changes tou your code would be > to use a list and join it up into a string in one go at the end: > > -----------8<-------------- > htmlPage=["

\n"] > htmlPage.append("more html\n") > .... > htmlPage.append("more html\n") > .... > htmlPage.append("<\body><\html>\n") > htmlDoc="".join(htmlPage) > -----------8<-------------- If you find that you are explicitly adding a new-line at the end of every string that you append, as a convenience, you might want to consider using the following minor modification: -----------8<-------------- import string ... htmlPage=["
"] htmlPage.append("more html") .... htmlPage.append("more html") .... htmlPage.append("<\body><\html>") # Use string.join() instead of ''.join() to add new-lines. htmlDoc= string.join(htmlPage, '\n') -----------8<-------------- Funny that string.join() supports the optional second parameter, while 'abc'.join() does not. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From andrew-pythonlist at puzzling.org Wed Jun 18 23:44:58 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 19 Jun 2003 13:44:58 +1000 Subject: Setting a class attribute given its name In-Reply-To: References: Message-ID: <20030619034458.GA9923@frobozz> On Wed, Jun 18, 2003 at 11:28:55PM -0400, Edward C. Jones wrote: > The standard way to set a class attribute is > > class X(object): > i = 1 > > Given the string 'i', how do I set the class attribute? The following > doesn't work (Python 2.2.3): > > class X(object): > setattr(X, 'i', 1) That doesn't work because the name 'X' isn't bound yet. This will work, though: class X(object): pass setattr(X, 'i', 1) -Andrew. From g2h5dqi002 at sneakemail.com Mon Jun 16 22:38:36 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 17 Jun 2003 14:38:36 +1200 Subject: does lack of type declarations make Python unsafe? In-Reply-To: References: <3064b51d.0306151228.22c595e0@posting.google.com> <114xq48ewelrf.1xyyacwlxdk1p.dlg@40tude.net> Message-ID: > On Sun, 2003-06-15 at 14:45, Marek "Baczek" Baczy?ski wrote: > >> Searching for a lost colon also takes a lot of time >>*and* tends to happen more often. Don't they all end up down the back of the sofa? >-- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From frobozz_electric at hotmail.com Wed Jun 18 12:27:40 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 18 Jun 2003 16:27:40 GMT Subject: Algorithm help per favore References: <2ec1bc1c.0306180746.159679d6@posting.google.com> Message-ID: "Larry" wrote in message news:2ec1bc1c.0306180746.159679d6 at posting.google.com... > 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] > # Chris Perkins: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204297 def thislist(): """Return a reference to the list object being constructed by the list comprehension from which this function is called. Raises an exception if called from anywhere else. """ import sys d = sys._getframe(1).f_locals nestlevel = 1 while '_[%d]' % nestlevel in d: nestlevel += 1 return d['_[%d]' % (nestlevel - 1)].__self__ def last(sequence): "return the last item in list, or empty list" if sequence: return sequence[-1] else: return sequence sequence = [6,3,3,3,5,7,6,3,4,4,3] filtered = [item for item in sequence if item != last(thislist())] print filtered # OUTPUT #>>> [6, 3, 5, 7, 6, 3, 4, 3] The idea here is to do something like this: lastitem = sequence[0] filtered = [lastitem] for item in sequence[1:]: if item != lastitem: filtered.append(item) lastitem = item But here we make use of Chris Perkins recipe to gain access to the list being contructed by the list comprehension that is filtering our original sequence. From 2002 at weholt.org Sun Jun 22 18:19:24 2003 From: 2002 at weholt.org (Thomas Weholt) Date: Mon, 23 Jun 2003 00:19:24 +0200 Subject: Calling a function, arguments in a dict ?? Message-ID: 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) ??? Best regards, Thomas From mis6 at pitt.edu Wed Jun 11 12:33:33 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 11 Jun 2003 09:33:33 -0700 Subject: feature request: mul Message-ID: <2259b0e2.0306110833.24b998cd@posting.google.com> I like the new builtin 'sum', actually I missed it from my very first Python program (I was doing hystograms at that time). Here is the question: is there any hope to have a corrisponding 'mul' in the near future? Of course, you could use 'mul' to compute factorials, bu my motivation is mainly for logical constructs. At the present, instead of if condition[0] or condition[1] or .... or condition[42]: dosomething() I can use (using a comment to make crystal clear what the code is doing) if sum(condition): # multi_or dosomething() In the same sense, I would like to abbreviate if condition[0] and condition[1] and .... and condition[42]: dosomething() as if mul(condition): # multi_and dosomething() I know I could use 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. Apart for boolean algebra, I think a 'mul' with the signature mul(iterable, start=1) would naturally complement 'sum'. Moreover, the implementation would be trivial and I don't see why we should not have it. P.S. BTW, I like the concept of reduce, but not the syntax, and that is the reason why I *never* use 'reduce' in my programs. A more sensible syntax would have been something like apply('+',iterable) or apply('*',iterable) but of course apply had another meaning. Michele From andrew-pythonlist at puzzling.org Wed Jun 11 08:21:12 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 11 Jun 2003 22:21:12 +1000 Subject: Properties using metaclasses (was: Function/Method Decorator Syntax) In-Reply-To: <20030611110300.GA3350@nl.linux.org> References: <20030610082514442-0400@braeburn.themorgue.org> <20030610142845.4540.qmail@green.zadka.com> <20030611013918.GA2113@frobozz> <20030611085935.GG2113@frobozz> <20030611110300.GA3350@nl.linux.org> Message-ID: <20030611122112.GA3381@frobozz> On Wed, Jun 11, 2003 at 01:03:00PM +0200, Gerrit Holl wrote: > Andrew Bennetts wrote: > [...] > > 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 [...] > > Just a question: Why would this be evil? I think it is explicit, simple, > sparse, readable, practical, unambiguous... The only real anti-zen-behaviour > is that it's nested rather than flat. But for the rest, I don't see the > problem, what is it? Because I'm suspicious of metaclasses in general... although this is a pretty neat solution, and I'm tempted to use it. :) Of course, the metaclass is behind the scenes, and the result is a simple property, so there's no lingering weirdness. The only really nasty thing is that I'm abusing the "class" keyword: when I say "class x(EvilProperty)", x is not a class. *That's* what I consider evil, and why I hesitate to use this in real code. A more extreme example of abusing class was shown to me at PyCon by a fellow Twisted developer (who shall remain nameless so that he won't get mobbed by angry hordes ;) ... it looked something like this: ---- class Adder(type): def __new__(cls, name, bases, dict): return reduce(lambda x,y: x+y, bases, 0) class C(1, 2, 3, 4, 5): __metaclass__ = Adder print C ---- There's some things the class keyword was just never meant to do. -Andrew. From staschuk at telusplanet.net Tue Jun 3 12:22:34 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 3 Jun 2003 10:22:34 -0600 Subject: "for line in fd" twice In-Reply-To: <20030603115347.D1163@localhost.localdomain>; from jack@performancedrivers.com on Tue, Jun 03, 2003 at 11:53:47AM -0400 References: <20030603115347.D1163@localhost.localdomain> Message-ID: <20030603102234.B341@tibia.amotlpaa.bogus> Quoth Jack Diederich: [...] > The part > for (line) in fd: > > will make a temporary list of all the lines in fd before it starts iterating. > so by the time you get to the second for() loop the file has been exhausted. ?! >>> fd = file('python-list') >>> for line in fd: ... break ... >>> fd.readline() # fd not exhausted '=09=09=09 6\n' It reads ahead, certainly, but it doesn't read the whole file. -- Steven Taschuk o- @ staschuk at telusplanet.net 7O ) " ( From alanmk at hotmail.com Wed Jun 11 07:38:07 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 11 Jun 2003 12:38:07 +0100 Subject: File type recognition References: Message-ID: <3EE7149F.B7E9FF61@hotmail.com> Sami Viitanen wrote: > Does anyone know if there is a python script that can recognize the file > type ie. is the file content binary or text. Here is a script that does "magic" stuff, on *nix only. http://www.demonseed.net/~jp/code/magic.py HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From bokr at oz.net Mon Jun 16 15:30:23 2003 From: bokr at oz.net (Bengt Richter) Date: 16 Jun 2003 19:30:23 GMT Subject: raw strings under windows References: <1qeHa.95656$pR3.2051375@news1.tin.it> Message-ID: On Mon, 16 Jun 2003 07:34:21 GMT, Alex Martelli wrote: >Bengt Richter wrote: > ... >>>> 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. > >Noticing, yes; processing, no. That's using the fundamental meaning >of the verb "process" as given e.g. by the American Heritage dictionary: > >To prepare, treat, or convert by subjecting to a special process: [eg] >process ore to obtain minerals. > >In raw string literals, backslashes are not prepared, are not treated, >are not converted, and are not subjected to a special process. Thus, >it makes sense to say they are not processed. You may be favoring a >different nuance of the meaning of the verb "to process" (for example, >"to gain an understanding or acceptance of; come to terms with; [eg] >processed the traumatic event in therapy") but I think the "prepare, >treat or convert" one is primary and a sounder basis for the CS usage. Me too. Does converting raw string source with special backslash semantics into an internal string representation where the string bytes have no special backslash semantics (unless re-interpreted as source of some kind) qualify as processing? I guess it's a nit either way, depending on focus. Sorry I forgot the smiley ;-) > > >>>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. > >To echo you, "so?". The use case for the design of raw string literals >is regular-expression patterns. Why cause ANY problems for whatever >fraction of RE patterns, when the current design choice causes no issue >with any valid RE pattern? Note that a valid RE pattern can never end >with an odd number of backslashes. Admittedly, there aren't any problems that can't be worked around, but on second thought I'm not sure I understand your example of including a single quote character in a single-quoted raw string, except by assuming you are focusing on the regex use case exclusively (where the literal preceding backslash will be a no-op since ['"] are not magic regex characters). IOW you are depending on the destined use of the raw string to ignore the extra backslash which you can't avoid including in your example. I.e., it works, but you are actually generating a character not needed in the regex itself. But then I'm not sure what the example means, since r" ... ' ..." works even better than r' ... \' ...' and I would tend to use triple quotes to avoid escaping if the regex had both. If I had to write a regex to match all legal Python string literals, I guess I would be scratching my head a while (and perhaps wishing for a selectable delimiter ;-) > >>>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). > >Just as obviously, it's even easier to "spell alternatively" a string >constant that ends with an odd number of backslashes. The only issue is, >which use case should be subjected to this minor annoyance (of not being >directly expressible with a raw string literal): the intended one, RE >patterns (for which backslashes can well be actually needed and using >raw string literals thus makes sense), or "DOS filenames" (for which >backslashes can generally be advantageously replaced by plain slashes, >in addition to other "alternative spellings")? > >As I said, this is an EASY design choice to make. And if you can't see >it (I suspect you see it perfectly well and are just taking an opportunity >to start some useless argument) then there isn't much I can do about it: >the art of making the right tradeoffs is exactly that, an art, and the >main quality of Python is that the many design choices that add up to it >have been made consistently, intelligently, and elegantly. > > >> 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. > >You're welcome to dig into the archives to find out exactly when triple >quoting was introducing wrt when raw string literals were introduced. But >even if they were introduced simultaneously, what does that matter? > > >>>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\" > >Then write a PEP proposing it. You know perfectly well that such drastic >changes as additions to Python's syntax don't come about except via the >PEP process. Thus, if you DON'T write a PEP, I will be confirmed in my >working hypothesis that you're not really looking for such a change, but >just looking for arguments for arguments' sake. > Well, I don't enjoy argument per se. I do enjoy batting ideas around, even those where the best strategy in a serious game would be to refrain from swinging and walk. But regarding your hypothesis about my motivations -- isn't it possible that I would propose a non-PEP-able idea for other reasons than argument for argument's sake? E.g., to get a reaction to the idea that might be a better version, and closer to being PEP-worthy? Or to get a better sense of any problematic use cases that other people have bumped into? Or to test an idea in the flames and heat of the c.l.p crucible before investing in a useless PEP effort? Is that not part of the purpose of c.l.p? OTOH, your reaction makes me think that maybe there is a negative aspect to casual discussion of possible alternatives to the current Python design. E.g., if focusing on a small thing that some might think improvable (or even an actual "wart") causes FUD for the language as a whole, that would be unfortunate. Anyway, I'm sorry if I came off as argumentative. I can see that a non-smiley-qualified "So?" could push that button. Sorry if it did. I have posted a number of not-fully-worked-out ideas (to euphemize selfservingly ;-) in the past, and a number of times people have responded with better versions, even though it was recognized that no version could make it through the PEP filter, and in some cases wouldn't even have to, since they were technically legal. I.e., even an exercise in language abuse can have educational value. E.g., I learned something about how exceptions worked when I posted an abuse of exceptions for the purpose of switch/case logic, which I was critiqued into making work, and which then others improved upon. Of course, it may be advisable to label such exercises clearly so newbies won't take such stuff as a model for coding practice ;-) I could probably spend my time better though. Thanks for reminding me ;-) > >>>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. > >I think the whole perlish idea stinks to high heavens, but I look >forwards to reading your PEP carefully detailing this proposal. > I would welcome a hint as to how to achieve an increment in capability without offending your sensibilities ;-) BTW, should little things like this be compounded into a single PEP in order to counter the sense of creeping insignificant featuritis with more collective weight? BTW, note that AFAICS no backward compatibility problem should arise from a new string prefix letter or two, since they would currently be illegal. I don't think it would be a big thing. Regards, Bengt Richter From see at my.signature.com Sun Jun 8 12:29:31 2003 From: see at my.signature.com (Andrei) Date: Sun, 08 Jun 2003 16:29:31 +0000 Subject: Html: replacing tags References: <2972888.1055030986@dbforums.com> Message-ID: <2973944.1055089771@dbforums.com> Originally posted by Fredrik Lundh > Andrei wrote: > > > 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. > > the term "parser" usually refers to a piece of software that reads a > character stream, and turns it into some other data structure. > > if you want to modify a character stream, you have to combine the > parser with code that turns that data structure back to a character > stream. > > the "Using the sgmllib Module to Filter SGML Documents" example in > chapter 5 of my "Python Standard Library" book does exactly that: > > http://www.oreilly.com/catalog/pythonsl/chapter/ch05.html"]- > http://www.oreilly.com/catalog/pythonsl/chapter/ch05.html[/url] > http://www.effbot.org/zone/librarybook-index.htm"]http://ww- > w.effbot.org/zone/librarybook-index.htm[/url] (pdf) > > (you can use a similar approach with HTMLParser, but htmllib is > designed for HTML formatting, not HTML parsing, and is not the > right tool for the task) Thanks, I'll look into sgmllib then (I already have that chapter on my HD :), but it didn't really occur to me to look at sgml). -- Contact info (decode with rot13): cebwrpg5 at bcrenznvy.pbz Fcnzserr! Cyrnfr qb abg hfr va choyvp zrffntrf. V ernq gur yvfg, ab arrq gb PP. Posted via http://dbforums.com From alanmk at hotmail.com Wed Jun 11 05:45:39 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 11 Jun 2003 10:45:39 +0100 Subject: Webhosting with Python support References: Message-ID: <3EE6FA43.6E7ECCA2@hotmail.com> > Can you recommend a good and not very expensive webhosting with Python > support? The definitive list is on a user-updatable page on python.org http://www.python.org/cgi-bin/moinmoin/PythonHosting Check there, and don't forget to update the page with any new data you've found. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From yweng at cs.uoregon.edu Thu Jun 12 21:35:58 2003 From: yweng at cs.uoregon.edu (Yan Weng) Date: Thu, 12 Jun 2003 18:35:58 -0700 Subject: HL7 servers in Python? References: Message-ID: I have implemented a commercial HL7 server using C++ before. (http://www.advancedinfomed.com/eng/product&services/product&services3.htm) >From my knowledge, there is no Python version avaliable. You can find free C++ and java versions somewhere. I guess you can wrap them if you want. To be honest, I don't think writting a HL7 server using python is hard. You already get daemon, service, parser generator, threads, sockets and http servers in python. What you really need to do is putting them together to parse your Hl7 2.3 or 3.0 messages. (for 3.0, you need xml support.) Hope this helps. -- Yan Weng yweng at cs.uoregon.edu http://www.cs.uoregon.edu/~yweng/ From johnroth at ameritech.net Thu Jun 19 13:07:21 2003 From: johnroth at ameritech.net (John Roth) Date: Thu, 19 Jun 2003 13:07:21 -0400 Subject: sum(strings) References: Message-ID: "Raymond Hettinger" wrote in message news:uZlIa.10$38.9 at nwrdny01.gnilink.net... > > "Steve McAllister" wrote in message > news:bcsjii$3vf$1 at alto.univ-mlv.fr... > > Why does sum reject strings? > > Because there is just one right way to do it: > > "".join([str1, str2, str3, ...]) > > Summing involves use of the repeated adds which > is terribly inefficient for strings. But, if you must: > > reduce(str.__add__, [str1, str2, str3, ...], '') > > Besides, it's very nice to be able to specify the join > character or blank. > > > Is it a matter of efficiency of the > > underlying implementation? > > Nope, it's is just a bad idea. I don't think it's a bad idea at all. For me, the killer is the inability to find a good, non-error return for an empty list. John Roth > > > Raymond Hettinger > > From bokr at oz.net Mon Jun 2 17:28:20 2003 From: bokr at oz.net (Bengt Richter) Date: 2 Jun 2003 21:28:20 GMT Subject: Anyone heard of using pyunit to drive security audit? Message-ID: Just had the thought that pyunit could orchestrate a lot of stuff and do a lot of checking, and it might factor in an extensible way. Just a thought. I've often wanted have a script that could give me a report after building a system starting from a formatted disk. Regards, Bengt Richter From martin at v.loewis.de Wed Jun 4 14:54:39 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 04 Jun 2003 20:54:39 +0200 Subject: Tcl isn't installed properly: directory structure wrong References: Message-ID: "Leo" writes: > how can i fix that? Remove your settings of the TCL_LIBRARY environment variable, and the TK_LIBRARY environment variable. Regards, Martin From tireseas at onetel.com Fri Jun 20 13:34:12 2003 From: tireseas at onetel.com (valhalla) Date: Fri, 20 Jun 2003 18:34:12 +0100 Subject: Using OS time In-Reply-To: <20030620160007.7125.87329.Mailman@mail.python.org> References: <20030620160007.7125.87329.Mailman@mail.python.org> Message-ID: <200306201834.12530.tireseas@onetel.com> I wrote: " I suppose a lengthier but more n00bie friendly way of doing this 'countdown' would be to countdown from a given number (e.g. 60) and import time.sleep to sleep for 1 second at each new iteration in the for loop. I think this would do the same thing." -- er, no! Skip this one guys ... I have just answered my own question and eliminated sleep as a solution because while it is sleeping (which would be every second between decrementing counts which accumulates to the majority of the program really) the rest of the program becomes non-functioning - so the player couldn't interact with the game and the program couldn't process input or produce outputs ... i.e. not much of a game really!! Live and learn :-) Back to the signal.alarm() suggestion from Skip. Andy -- ==================== || Reg. Linux User: 313143 || ==================== Sign the Petition: http://www.PetitionOnline.com/endtcpa1/ From suresh_vsamy at rediffmail.com Wed Jun 11 13:31:43 2003 From: suresh_vsamy at rediffmail.com (Suresh Kumar) Date: 11 Jun 2003 17:31:43 -0000 Subject: (no subject) Message-ID: <20030611173143.20968.qmail@webmail27.rediffmail.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From alanmk at hotmail.com Tue Jun 3 13:37:57 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 03 Jun 2003 18:37:57 +0100 Subject: Yield inside try...finally References: <3EDCD703.6FFB8B0D@hotmail.com> Message-ID: <3EDCDCF5.4D317545@hotmail.com> Alan Kennedy wrote: [A vain attempt to get around the try..yield..finally exclusion in python ] D'oh! Of course, the example I wrote doesn't work! It only works when there is no exception, which is the whole point of a finally clause. Sorry about the diversion. Normal service will be resumed as soon as possible :-) regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From rune.hansen at sinsenveien83.com Thu Jun 5 10:04:16 2003 From: rune.hansen at sinsenveien83.com (Rune Hansen) Date: Thu, 05 Jun 2003 16:04:16 +0200 Subject: xmlrpc ssl (slightly embarrassing, long post) In-Reply-To: References: Message-ID: I'm using the OpenSSL library: # Copyright (C) AB Strakt 2001, All rights reserved # # $Id: __init__.py,v 1.1.1.1 2002/06/07 21:13:41 misa Exp $ I'll take a look at M2Crypto Thanks /rune Ng Pheng Siong wrote: > According to Rune Hansen : > >> def __init__(self, server_address, RequestHandlerClass): >> """Constructor. May be extended, do not override.""" >> BaseServer.__init__(self, server_address, RequestHandlerClass) >> #OpenSSL >> ctx = SSL.Context(SSL.SSLv23_METHOD) >> ctx.set_options(SSL.OP_NO_SSLv2) >> ctx.set_verify(SSL.VERIFY_PEER, verify_cb) >> ctx.use_privatekey_file ('key.pem') >> ctx.use_certificate_file('cert.pem') >> self.socket = >>SSL.Connection(ctx,socket.socket(self.address_family,self.socket_type)) > > > Not sure which SSL library you're using, but M2Crypto's works: > > In one window: > > ngps at vista:~/prog/ngps/m2/demo/medusa$ python START_xmlrpc.py > info: Medusa (V1.1) started at Thu Jun 5 21:43:38 2003 > Hostname: vista.netmemetic.com > Port:9080 > > warning: Computing default hostname > info: Medusa (V1.1) started at Thu Jun 5 21:43:38 2003 > Hostname: vista.netmemetic.com > Port:9443 > > M2Crypto HTTPS Server (v0.09) > > In another window: > > ngps at vista:~/prog/ngps/m2/demo/ssl$ python xmlrpc_cli.py > Sure, that works > Sure, that works > > First window says: > > method="Testing" params=(1, 2, 3) > 127.0.0.1:1028 - - [05/Jun/2003:13:44:03 +0800] "POST /RPC2 HTTP/1.0" 200 242 > method="BringOn" params=('SOAP',) > 127.0.0.1:1029 - - [05/Jun/2003:13:44:03 +0800] "POST /RPC2 HTTP/1.0" 200 242 > > There is also a demo server based on TCPServer. > > > From artyprog at wanadoo.fr Thu Jun 12 16:14:35 2003 From: artyprog at wanadoo.fr (Salvatore) Date: Thu, 12 Jun 2003 22:14:35 +0200 Subject: Twice instanciation In-Reply-To: References: Message-ID: vincent wehren wrote: > "Salvatore" schrieb im Newsbeitrag > news:bcakmg$jv7$1 at news-reader14.wanadoo.fr... > >>Hello, >> >>Is it possible to avoid twice instanciation >>of the same variable ? > > > Maybe this helps: > http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52558 > > Regards, > Vincent Wehren In fact that is not exactly what I want. I don't want a unique instance of a class, but i want to avoid a same name of an instance being used twice. Thanks again Vincent From lale at fotonation.com Wed Jun 4 12:48:27 2003 From: lale at fotonation.com (Ilariu Raducan) Date: Wed, 04 Jun 2003 17:48:27 +0100 Subject: PythonWin menu Message-ID: Hi All, Using pythonwin as the framework for an application, at init time I create some menu entries. Every time a document is focused (a MDIChild frame) the menu is replaced with the menu of that document(in my case the standard text document and Tools menu of the PythonWin IDE. How can I display only my menus? Is it possible to have some menus displayed all the time, for each document type? Thank you, Lale From jjl at pobox.com Wed Jun 18 09:07:33 2003 From: jjl at pobox.com (John J. Lee) Date: 18 Jun 2003 14:07:33 +0100 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: <87adcfo7oq.fsf@pobox.com> 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;-). Let me magically conjure into existence a really nice language based on static type inference (let's have it beautifully designed, learning as many lessons from Python as possible, with oodles of good library code, including easy connection to C, C++, Java, COM, .NET, CORBA etc...). Are you going to switch your most frequent first-choice from Python to this statically-typed language? That's *not* a rhetorical question: I don't know the answer. John From zqmkxlwu at xpljwkvs.com Sat Jun 14 21:14:11 2003 From: zqmkxlwu at xpljwkvs.com (Freegift Roger) Date: Sat, 14 Jun 2003 20:14:11 -0500 Subject: Free gifts give away, limited quantity Message-ID: Free laser pointer and free harmonica give away, limited time offer, limited quantity, while supply last http://www.zeroboss.com for details ******************************************************* * http://www.zeroboss.com * ******************************************************* -- Homebase business opportunities, FREE to join -- Quality Jewelry, watches, cookware, toys on Sale at low wholesale price, several wharehouses ******************************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: From g2h5dqi002 at sneakemail.com Thu Jun 12 22:40:42 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Fri, 13 Jun 2003 14:40:42 +1200 Subject: Revised PEP 318 - Function/Method Decorator Syntax In-Reply-To: References: <20030610082514442-0400@braeburn.themorgue.org> <2259b0e2.0306110926.27c4412b@posting.google.com> <2259b0e2.0306120901.2a535e6@posting.google.com> Message-ID: Steven Taschuk wrote: > Quoth Michele Simionato: > > > class C[Traced,Protected]: pass > > I'd be against such a syntax, fwiw. Too easy to mistake for the > normal subclass syntax. Maybe it would help if the base class parentheses were required in that case: class C()[Traced,Protected]: although I think I would tend to write it with a space between: class C() [Traced,Protected]: -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From robin at jessikat.fsnet.co.uk Sat Jun 7 05:59:14 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 7 Jun 2003 10:59:14 +0100 Subject: PIL 1.1.4 and Freetype 2.1.4 Message-ID: Has anyone managed to build PIL with the latest stable FreeType? I'm getting the following linker errors ftinit.obj : error LNK2001: unresolved external symbol _pfr_driver_class ftinit.obj : error LNK2001: unresolved external symbol _t42_driver_class ftinit.obj : error LNK2001: unresolved external symbol _pshinter_module_class ftinit.obj : error LNK2001: unresolved external symbol _bdf_driver_class ftinit.obj : error LNK2001: unresolved external symbol _pcf_driver_class build\lib.win32-2.2\_imagingft.pyd : fatal error LNK1120: 5 unresolved externals I assume this is because FreeType has changed since 2.0 (which PIL assumes). By hacking the setup.py file I am able to get something by using the freetyp214.lib that freetype itself builds. Can I assume that this will work OK? -- Robin Becker From tchur at optushome.com.au Thu Jun 12 17:10:26 2003 From: tchur at optushome.com.au (Tim Churches) Date: 13 Jun 2003 07:10:26 +1000 Subject: HL7 servers in Python? Message-ID: <1055452228.1203.151.camel@emilio> Does anyone know of a Python HL7 socket server/daemon - that is, a daemon which accepts socket connections on a TCP port from an HL7 source, receives an HL7 message via the connection, hands off the message for processing, and then sends back an ACK or NACK H7 message - usually synchronously, via a blocking connection (thus the server needs to be multi-threaded)? HL7 stands for Health Level 7 (where 7 represents the 7th layer of the OSI network stack) and is a widely-used standard for communication of medical information. I'm not looking for HL7 message assembly or parsing libraries, just the socket server bit. Perhaps the SocketServer module in the Python library makes this so trivial that no-one has felt the need to write a specific HL7 server in Python? Anyway, I've looked on Google but can't spot anything obvious. -- 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 andrew at acooke.org Wed Jun 4 18:09:53 2003 From: andrew at acooke.org (andrew cooke) Date: 04 Jun 2003 18:09:53 -0400 Subject: [wanted] Python news threader/archiver In-Reply-To: References: Message-ID: <87k7c1lcjy.fsf@acooke.org> this isn't the solution you're asking for, but it may solve what you really want to do :o) (if not, apologies + please ignore). i get this group by mailing list (there's a group-to-mail gateway at python.org). i then store the articles in a local imap mail server and read them with gnus, which includes an imap-to-nntp converter. so i archive the whole group locally (in a maildir file) and then can either search it directly with my mail client, or read it as threaded news in emacs with gnus. works really well for me, but it requires a unix box and some free time... cheers, andrew "Greg Wilson" writes: > I am looking for Pythonware that will download news items from an NNTP feed > for archival storage, and construct a threaded index page as it does so. > Barry Warsaw has pointed out that I can do this using Mailman, but that > seems like a rather large hammer. If anyone has something that will do > this, please let me know. > > Thanks, > - Greg > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.acooke.org From edcjones at erols.com Sun Jun 1 11:40:54 2003 From: edcjones at erols.com (Edward C. Jones) Date: Sun, 01 Jun 2003 11:40:54 -0400 Subject: Is there a better way of coding this? Message-ID: 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? Perhaps using the "curry" class below? Thanks, Ed Jones ----------------------------------------------------------------- template ="""\ def <@getname@>(self): # Subtle error processing here. self.<@truename@> = self.<@funname@>(self.data) return self.<@truename@> <@attrname@> = property(<@getname@>, None, None) """ def makeget(getname, truename, funnanme, attrname): text = template.replace('<@getname@>', getname) text = text.replace('<@truename@>', truename) text = text.replace('<@funname@>', funnanme) return text.replace('<@attrname@>', attrname) class X(object): exec makeget('geti', '_i', 'Fgeti', 'i') def __init__(self): self.data = 7 def Fgeti(self, i): return 2*i x = X() print x.i print x.__dict__ ----------------------------------------------------------------- # A curry class from the net. class curry: def __init__(self, fun, *args, **kwargs): self.fun = fun self.pending = args[:] self.kwargs = kwargs.copy() def __call__(self, *args, **kwargs): if kwargs and self.kwargs: kw = self.kwargs.copy() kw.update(kwargs) else: kw = kwargs or self.kwargs return self.fun(*(self.pending + args), **kw) From mdavids+py at bantha.org Mon Jun 2 17:49:32 2003 From: mdavids+py at bantha.org (Michael Davidson) Date: Mon, 2 Jun 2003 17:49:32 -0400 Subject: How to make slicing and other methods interact? In-Reply-To: <002601c328fb$07cbe090$a300a8c0@emilio>; from tchur@optushome.com.au on Mon, Jun 02, 2003 at 09:35:07PM +1000 References: <002601c328fb$07cbe090$a300a8c0@emilio> Message-ID: <20030602174932.A79808@bantha.org> On Mon, 02 2003, Tim Churches (tchur at optushome.com.au) wrote: > What is the general pattern for making methods interact? For example, I Try this change: Instead of > def __getslice__(self,low,high): > return self._data[low:high] Do this: > def __getslice__(self,low,high): > return this(self._data[low:high]) The problem is that what you're returning from __getslice__ isn't an instance of your clas. Michael From belred1 at yahoo.com Sun Jun 15 13:38:12 2003 From: belred1 at yahoo.com (Bryan) Date: Sun, 15 Jun 2003 17:38:12 GMT Subject: timeit Message-ID: <8a2Ha.209222$M01.92818@sccrnsc02> i tried timeit for the first time today, pretty darn impressive. i've noticed that postings in this newsgroup use timeit on the command line and with usually just one simple statement or loop. is this the only way to use timeit? can timeit be used within a script? or to execute whole scripts? i guess the obvious anwer that one is: timeit -s"import myscript" "myscript.main()" i'm just curious how other are exploiting timeit. thanks, bryan From dwblas at yahoo.com Sat Jun 21 14:18:04 2003 From: dwblas at yahoo.com (DavidW Blaschke) Date: Sat, 21 Jun 2003 11:18:04 -0700 (PDT) Subject: You know you're a Pythonista when.. Message-ID: <20030621181804.8101.qmail@web21601.mail.yahoo.com> What do you use for this. Something custom? This is an area that I would like to improve. Snipped: > > You start all tasks, no matter how trivial, with > an autogenerated > > project-and-script which is already usable as both > a script and a > > library. __________________________________ Do you Yahoo!? Yahoo! Calendar - Free online calendar with sync to Outlook(TM). http://calendar.yahoo.com From Simon.Wittber at perth.maptek.com.au Mon Jun 16 03:50:33 2003 From: Simon.Wittber at perth.maptek.com.au (Simon Wittber (Maptek)) Date: Mon, 16 Jun 2003 15:50:33 +0800 Subject: DNS/MX Lookup? Message-ID: <10F0E58C0018054484E329DC494C4D7F949144@mexper1> I have to ask... Are you writing a tool to scan for open mail relays? From manuelbastioni at tin.it Sat Jun 21 09:05:29 2003 From: manuelbastioni at tin.it (manuel) Date: Sat, 21 Jun 2003 13:05:29 GMT Subject: os.listdir() References: Message-ID: > This might work: import the nt module (it's built-in), then use nt.listdir. It work fine. :-) And for linux? From theller at python.net Sat Jun 14 17:18:33 2003 From: theller at python.net (Thomas Heller) Date: Sat, 14 Jun 2003 23:18:33 +0200 Subject: pythonCOM with Flash References: <3ee9bfff$0$8301$4d4ebb8e@news.nl.uu.net> <87adckfz28.fsf@pobox.com> Message-ID: Dave Brueck writes: > On Sat, 14 Jun 2003, John J. Lee wrote: > >> Dave Brueck writes: >> >> > On Fri, 13 Jun 2003, wrote: >> > >> > > So, if I understand correctly I cannot use Flash as a GUI without >> > > another GUI to contain the flash object. >> > > >> > > am I right? >> > >> > That is probably the case, but that doesn't mean that the other GUI >> > needs to be a full GUI framework (like wxPython, Tkinter, Qt) - you >> > could use >> [...] >> >> Would that even work? I know Qt has suport for ActiveX controls (or >> whatever you want to call them), but do wx & Tk? > > Can't speak for Tk (althought I'd be willing to bet that it does have > support for ActiveX controls somehow - maybe Pmw?) but wx certainly does. > In fact, the wxPython demo includes two examples. But still, for this case > the most lightweight approach would be ctypes. > Henk Punt's venster library, which is based on ctypes, has an example which embeds the webbrowser ActiveX control. Thomas From m at moshez.org Mon Jun 16 11:00:22 2003 From: m at moshez.org (Moshe Zadka) Date: 16 Jun 2003 15:00:22 -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: <20030616150022.1988.qmail@green.zadka.com> On Mon, 16 Jun 2003, "Terry Reedy" wrote: > If one considers the set of values as part of the type, this amounts > to saying that the type system of most languages is too coarse for > real needs. Many operations need counts [0, 1, 2, ...]. Python does > not have this, C only backhandedly (unsigned int, like calling an int > an unfractionated rational). A few need a count subset: circular > queues need residue classes [0, 1, ..., n-1] with all operation > results taken %n. These are well-defined mathematical sets that > programmers usually have to simulate rather than simply declare. Sure... Some operations need primes (e.g., RSA encryption). Some operation need strings which specify programs which halt (think "exec" :). Of course, if you push too much into the typing system, than the type system becomes undecidable. A language where the compiler only warns about a subset of the typing violations is not much better than a language whose type system is a subset of the real system. -- 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 Thu Jun 19 02:46:50 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Thu, 19 Jun 2003 06:46:50 GMT Subject: Python 2.2.2 win32 build References: Message-ID: On Wed, 18 Jun 2003 22:55:09 -0700, Tim Roberts wrote: > Why would you want to [build Python yourself from source]? There is > already a standard distribution. Why make a non-standard > distribution? I'm just as comfortable knowing that I can count on *A* > Python distribution being *THE* Python distribution. I don't know the OP's reasons for building from source, but since you ask "why", I can give a pretty strong one: Because you want a Python built with options different from the default build. Perhaps you want to enable experimental features, or you want to disable a whole bunch of things that won't be used on the target machine, or you want to test out a new extension yourself. Does that give a better idea of why one might want to do it? -- \ "It is forbidden to steal hotel towels. Please if you are not | `\ person to do such is please not to read notice." -- Hotel | _o__) sign, Kowloon, Hong Kong | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From ph at acdc.fornax Tue Jun 3 10:20:28 2003 From: ph at acdc.fornax (Pierre HANSER) Date: Tue, 3 Jun 2003 14:20:28 +0000 (UTC) Subject: Twisted References: Message-ID: Jason Smith schrieb: > Tahiti is not in Europe! not geographicaly -- Pierre Hanser From peter at engcorp.com Fri Jun 13 14:16:43 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 13 Jun 2003 14:16:43 -0400 Subject: html on Python References: Message-ID: <3EEA150B.85218876@engcorp.com> Luiz Siqueira wrote: > > 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. Please provide (much) more detail about what you are trying to accomplish. There are a dozen ways to work with HTML, but which is best depends entirely on what you are doing. "Work with HTML" is a pretty vague description. -Peter From gherman at darwin.in-berlin.de Wed Jun 4 04:02:00 2003 From: gherman at darwin.in-berlin.de (Dinu Gherman) Date: Wed, 4 Jun 2003 10:02:00 +0200 Subject: Streamlining email archives? Message-ID: Hi, having some trouble with my emailer which gulps at single mail- boxes containing 20,000 messages and more, I'm looking for a more deterministic method of downloading parts of the stocked archives for lists such as this one. Then, I'd be able to pe- riodically download only the recent two months or so into my emailer. I know, there's also Netnews, but that's not an op- tion in this case. Looking at the archives stored e.g. on this page I find that they could lend themselves better to automated processing: http://mail.python.org/pipermail/python-list/ Specifically, I wonder why the full archive is downloadable only as non-compressed 576 MB chunk? Or why the other non- compressed files have an .txt extension while, but not the huge 576 MB one, which has a .mbox extension? Also, it isn't obvious to me which rule is followed for deciding when to have a compressed archive stored there and when to have the uncom- pressed raw mailbox? I assume mailboxes for the last 12 months or so are uncompressed, but this is not exactly true. And it might be different for other lists... And then there is the phenomenon of postings from the future, which would make sense for some of the bots on the list, but they mostly come from nobots. Well, I agree, this is certainly something completely different... but perhaps an interesting issue for Mailman? Hence, is there some common policy behind stocking these ar- chives, and is it specified somewhere? If this is not the case, wouldn't it be useful to do so, if only because then things would be more predictable and people could further automate their processes. Thanks, Dinu -- Dinu C. Gherman ...................................................................... "Consistency is the last refuge of the unimaginative." (Oscar Wilde) From eeide at cs.utah.edu Wed Jun 18 10:39:07 2003 From: eeide at cs.utah.edu (Eric Eide) Date: Wed, 18 Jun 2003 08:39:07 -0600 (MDT) Subject: Definition of Aspect Oriented Programming References: Message-ID: "aeze616" == aeze616 writes: aeze616> What is aspect oriented programming? I read a little bit aeze616> about AspectJ. It seems to me that its like...some kinda, new aeze616> syntax that ain't related to the original Java language. How aeze616> do it work in general? For information about AspectJ, see . For information about aspect-oriented programming (AOP) and aspect-oriented software development (AOSD) in general, see . ObPython: for information about AOP in Python, see . Eric. -- ------------------------------------------------------------------------------- Eric Eide . University of Utah School of Computing http://www.cs.utah.edu/~eeide/ . +1 (801) 585-5512 voice, +1 (801) 581-5843 FAX From jjl at pobox.com Wed Jun 18 20:13:43 2003 From: jjl at pobox.com (John J. Lee) Date: 19 Jun 2003 01:13:43 +0100 Subject: urllib2: non-ascii characters in url References: <3EF059D3.10ED7902@hotmail.com> Message-ID: <87smq6x6tk.fsf@pobox.com> "Achim Domma" writes: [...] > I had to add a > > q = urllib.quote(q,"=&") > > but then it works fine. Thanks! You might well also want to look at this: http://www.python.org/dev/doc/devel/lib/module-encodings.idna.html John From max at cNOvSisiPonAtecMh.com Wed Jun 11 14:05:16 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Wed, 11 Jun 2003 18:05:16 GMT Subject: Go buy _Text Processing in Python_ References: <84fc4588.0306110058.1c019f66@posting.google.com> Message-ID: Well, I have to wait till Amazon delivers the book understand this wisdom I guess :). > But then, if you just take the wisdom of the book to > heart, you can easily write the very same automated conversion of the > ASCII to PDF (via LaTeX; but you could use reportlab or something if you > wanted) that I used to compose the final form. It *is* a book about > text processing, after all. > > Yours, David... > From dsavitsk at ecpsoftware.com Mon Jun 2 13:54:07 2003 From: dsavitsk at ecpsoftware.com (dsavitsk) Date: Mon, 02 Jun 2003 17:54:07 GMT Subject: dictionary issue (and maybe PEP ... depending on the answer) References: <0wBCa.651$ig1.627675@newssrv26.news.prodigy.com> Message-ID: <3bMCa.743$ig1.726886@newssrv26.news.prodigy.com> andrew cooke wrote: > dsavitsk writes: > [...] > > you want a non-destructive sort. i want a non-destructive sort. last > week someone was wanting to add a non-destructive sort with mapping. > every new user screws up assuming that [].sort is non-destructive. > even norvig lists it as the big ugly wart in python (well, maybe not > in those words). > > you'd think that someone would add non-destructive sort to python, > wouldn't you? > > funny old world, eh? > > andrew > Indeed. I've been using this language for going on 6 years and I still screw this up. I was even so assanine as to assume that since, so far as i can tell, the most useful thing for list comprehensions (or rather, the thing that would seemingly justify adding them to the language beyond the coolness factor) seems to be generating a list in place that can be passed to a function all in one line, that at least tacking a .sort() on a list comprehension would be a reasonable sort of thing to expect. Oh well, I don't want to be one of those c.l.py people who argues against decided points and makes everyone here hate them. It does seem, though, that leaving sort() alone and adding .returned_sort() or whatever would not be so terrible. -doug From jepler at unpythonic.net Wed Jun 25 12:48:10 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 25 Jun 2003 11:48:10 -0500 Subject: python hash function In-Reply-To: <5050a341.0306241157.65e08b84@posting.google.com> References: <5050a341.0306241157.65e08b84@posting.google.com> Message-ID: <20030625164807.GA31134@unpythonic.net> On Tue, Jun 24, 2003 at 12:57:09PM -0700, Damien Morton wrote: > static long > string_hash1(register char *p, int size) > { [...] > while (--len >= 0) vs > static long > string_hash3(register char *p, register int size) > { [...] > while (c = *p++) Surely this hash function is incorrect (since it ignores size and assumes p is NUL-terminated. It's probably true that the current hash function is a bad choice for platforms without a fast multiply, but I think the python-dev search will turn up one perceived-as-important property it does have. AFAIR, it seems that strings like 'foo1', 'foo2' and 'foo3' get nice adjacent hash values and are thus less likely to collide. Whether the importance of this property is true in real life is a question that has probably not been answered (Tim Peters often laments the lack of the "average user" when these kinds of discussions are made). A potential problem with this property is that if 'foo' and 'bar' happen to collide, then 'foo1' will collide with 'bar1', etc. This could end up being an unfortunate property. Jeff From fperez528 at yahoo.com Mon Jun 2 16:16:03 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 02 Jun 2003 14:16:03 -0600 Subject: python bibliography manager. Newbie. References: <7b144ff3.0306020655.5e947f58@posting.google.com> Message-ID: Harald Massa wrote: > Bob, > >>can I do this with python:- > >> Take an endnote refer file or other bibliography data (TSV OVID >> Medline etc etc etc) and load the data into a table. > > Yes. > >> Create a GUI for the application. > Yes. > >> ODBC link to other apps. > Yes. > >> create a stand-alone executable. > Depends on your definition of "stand-alone". A stand-alone .exe needs some > .PYD and .DLL, all freely distributable. > > And: > if you google for this application, I think there is a python one out there it's called pybliographer, and it comes with a gui (pybliographic). It knows how to talk to lyx, so the two combined make the perfect document writing system (note that I did NOT say word processor: lyx is not a word processor, it's a far superior system). best, f. From domma at procoders.net Wed Jun 18 07:46:29 2003 From: domma at procoders.net (Achim Domma) Date: Wed, 18 Jun 2003 13:46:29 +0200 Subject: urllib2: non-ascii characters in url Message-ID: Hi, I have script which crawls webpages. The pages are downloaded using urllib2.urlopen and parsed with htmllib.HTMLParser. If I find a link, I make it absolut using urljoin the the original url of the current document. This works fine, as long as all urls contain only ascii charakters. But now I have urls with french characters and get the following traceback: [...] return urljoin(self.url,url) File "D:\Python23\lib\urlparse.py", line 188, in urljoin return urlunparse((scheme, netloc, '/'.join(segments), File "D:\Python23\lib\urlparse.py", line 125, in urlunparse return urlunsplit((scheme, netloc, url, query, fragment)) File "D:\Python23\lib\urlparse.py", line 134, in urlunsplit url = url + '?' + query UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 13: ordinal not in range(128) As far as I understand these characters are not allowed in urls, so I wouln't consider this a bug in urllib2, but in reality there are these characters and I have to handle them. Any idea how to solve this problem? regards, Achim From oren-py-l at hishome.net Mon Jun 16 06:02:55 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Mon, 16 Jun 2003 06:02:55 -0400 Subject: Need some quick help here... In-Reply-To: <200306152153.29188.listbox@cybereal.org> References: <200306152153.29188.listbox@cybereal.org> Message-ID: <20030616100255.GA56022@hishome.net> On Sun, Jun 15, 2003 at 09:53:24PM -0600, Zac Jensen wrote: > I have a bit of an issue in something I'm designing. > > It's a security issue. > > Here's what happens at the point of concern. > > Arbitrary code is accepted to be run through an eval statement that looks like > > eval(a_repr, {'__builtins__':None}) > > Anything could be in a_repr but, in the code that uses the return value of > eval, it will simply raise an exception if it's not a tuple that is returned. > > Also, the string passed to eval will never include a real newline character, > \r and \n are automatically .replace()'d before eval() is called... > > I'm looking for any example that could still cause problems, and optionaly a > suggested solution within the bounds of the problem. Evaluation of this expression, for example, will not finish in a billion years: [0 for a in range(999999) for b in range(999999) for c in range(999999) for d in range(999999) if 0] List and string multiplication can result in excessive memory allocation that will overload the machine's VM and slow everything down to a crawl. There are many other ways for creative mischief with eval. For example, here's how an expression can get a file without access to builtins: [x for x in ''.__class__.__bases__[0].__subclasses__() if x.__name__ == 'file'][0] Using this to fill the disk is left as an exercise to the reader. You can add further preprocessing to the string to prevent these tricks but there will be others. By the time you are done you will find that you have worked much harder than just avoiding eval() altogether and implementing the required functionality some other way. If you want security, never exec() or eval() untrusted data. Oren From Henrik.Weber at sys.aok.de Fri Jun 13 10:46:51 2003 From: Henrik.Weber at sys.aok.de (Henrik Weber) Date: 13 Jun 2003 07:46:51 -0700 Subject: python.dll References: Message-ID: <7e964d1d.0306130646.5f711a82@posting.google.com> Jacek Potrymaj?o wrote in message news:... > Hi, > > My operating system is windows XP. > I'm not a python programmist but I have problem with this. I trye to install > simics simulator that didn't find python.dll > I installed Python2.2.2 and others python programs which allowed to work > under windows. I tryed to find this file in my system but I culdn't. Should > I download this file? I don't know. If somebody could helpo me, I will be > gratefull. > > regards > > Jacek If you installed Python 2.2.2 there should be a python22.dll file in your C:\WINDOWS\system32 directory (or whereever Windows is installed on your machine). Normally the DLL will be found there. Notice however that the version is coded in the file name of the DLL. All Python 2.2.x versions are delivered with a DLL-file called python22.dll. Python 2.1.x had a file called python21.dll. If the application you are trying to run has been built against a version of python different from 2.2.x it will be looking for a python??.dll file with ?? the major and minor version of python for which it was built. You would have to install the required version of python then. Don't try to rename the DLL, your application won't run. Try to find out from the error message or the documentation of your application which version you need and download that from python.org. Hope this helps. Henrik From jjl at pobox.com Sat Jun 21 19:09:03 2003 From: jjl at pobox.com (John J. Lee) Date: 22 Jun 2003 00:09:03 +0100 Subject: Alternatives to Python ? References: <3EF18A03.3050706@netspace.net.au> Message-ID: <87r85nxc34.fsf@pobox.com> andrew cooke writes: [...] > ps i have a list of other free books at > http://www.acooke.org/andrew/writing/free-comp-books.html [...] That's a really good list, thanks Andrew. John From kendear at nospam.com Tue Jun 3 05:27:37 2003 From: kendear at nospam.com (Kendear) Date: Tue, 03 Jun 2003 09:27:37 GMT Subject: a = b = 1 just syntactic sugar? References: Message-ID: <3EDC6A13.5020409@nospam.com> Brian Quinlan wrote: > In C and Perl, assignment is an expression. In Python it is a statement. > This is a deliberate design decision to prevent people from writing code > like this: > > while a = 5: > ... so you mean in Python, = is just like if, for, while... ? From goboborz at yahoo.com Fri Jun 20 10:53:25 2003 From: goboborz at yahoo.com (Gobo Borz) Date: Fri, 20 Jun 2003 09:53:25 -0500 Subject: cgi getlist() problem (my first python program) References: <3EF1CFC0.2010803@yahoo.com> <3EF1DA5E.AC6C4F68@hotmail.com> <3EF216A2.8040508@yahoo.com> <3EF2C694.4060605@mxm.dk> Message-ID: <3EF31FE5.9070100@yahoo.com> Max M wrote: > > A simple way is to render the indexes of every item as a hidden field: > >
> > > > > > > > > > >
> > > results = [] > for idx in cgi['indexes'].value: > name = cgi.get('name%s' % idx, '') > phone = cgi.get('phone%s' % idx, '') > results.append((name, phone)) > This seems like an elegant way to do it. This way, you wouldn't have to have a ROW_COUNT "pseudo-constant" in your program that would have to be changed if the number of rows changed. Thanks! --Greg From gh at ghaering.de Fri Jun 13 19:40:57 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 14 Jun 2003 01:40:57 +0200 Subject: boost python In-Reply-To: <3001490.1055546115@dbforums.com> References: <3001490.1055546115@dbforums.com> Message-ID: <3EEA6109.7040106@ghaering.de> DB_RobertP wrote: > Hello, > I'm hoping there are some boost heads here. [...] There will be some, but the best place for Boost is here: http://python.org/sigs/c++-sig/ -- Gerhard From CousinStanley at hotmail.com Fri Jun 20 21:38:53 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Fri, 20 Jun 2003 18:38:53 -0700 Subject: "Newbie" questions - "unique" sorting ? References: <8da5fvsnidpjtblgfj4484spso2t9e6r95@4ax.com> Message-ID: John ... On the version you have, without changing anything in the program try ... delete word_dups.txt delete word_target.txt rename your_Input_File.txt word_source.txt python word_list.py This single run should produce 2 output files ... word_dups.txt ...... contains ALL words including dups word_target.txt .... contains Unique words excluding dups The newer version I uploaded does the same, only you specify the name of the source input and target output files on the command line and don't have to rename your source input file... python word_list.py xSource.txt xTarget.txt I've only used the names xSource.txt and xTarget.txt as an attempt to try and include a bit of implicit documentation ... For example, with the newer version where file names are specified on the command line we could use a bit of Pythonic alchemy to produce a finished Gold product with no dups from the original Lead input ... python word_list.py Lead.txt Gold.txt -- Cousin Stanley Human Being Phoenix, Arizona From erased*remove_this* at xs4all.nl Thu Jun 19 10:30:39 2003 From: erased*remove_this* at xs4all.nl (rgndrp) Date: 19 Jun 2003 14:30:39 GMT Subject: include files? Message-ID: <3ef1c90f$0$49114$e4fe514c@news.xs4all.nl> 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 :) From shalehperry at attbi.com Wed Jun 18 02:58:38 2003 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 17 Jun 2003 23:58:38 -0700 Subject: a clean way to define dictionary In-Reply-To: <3EEFEBFD.8090003@nospam.com> References: <3EEFEBFD.8090003@nospam.com> Message-ID: <200306172358.38854.shalehperry@attbi.com> On Tuesday 17 June 2003 21:35, Kendear wrote: > > or is there a more common way to define a dictionary > without all the punctuation marks? >>> def make_dict(**kwargs): ... return kwargs ... >>> make_dict(foo=1, bar='sean') {'foo': 1, 'bar': 'sean'} is the most common form I have seen. Not sure if it works for you. From chris.gonnerman at newcenturycomputers.net Tue Jun 10 20:12:59 2003 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Tue, 10 Jun 2003 19:12:59 -0500 Subject: [ANN] GDmodule 0.42 released Message-ID: <001d01c32fae$37b48be0$2100000a@house> Hot on the heels of GDmodule version 0.41, a new version 0.42 has now been released. This new version incorporates a patch from Gregory P. Smith supporting fully generic file-like object I/O, something the GDmodule has never had before. For those not familiar with it, the GDmodule connects the popular GD (graphics drawing) library by Thomas Bouttel with Python. Versions of GD from 1.8.3 on up are supported, but many features require GD 2.0.1 or higher. The original GDmodule was written by Richard Jones at the Bureau of Meteorology Australia; I took over support for the module at version 0.23 with his blessing. GDmodule may be downloaded from my website at http://newcenturycomputers.net/projects/gdmodule.html Thanks to all who have submitted patches and enhancements to this project! Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From jepler at unpythonic.net Wed Jun 4 10:58:09 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 4 Jun 2003 09:58:09 -0500 Subject: Proposed extension to file constructor In-Reply-To: <20030604062225.GB2749@taral.net> References: <20030603182813.GB1366@taral.net> <16092.63916.83822.950537@montanaro.dyndns.org> <20030603194740.GA8136@unpythonic.net> <20030604062225.GB2749@taral.net> Message-ID: <20030604145806.GC8136@unpythonic.net> On Wed, Jun 04, 2003 at 01:22:25AM -0500, Taral wrote: > On Tue, Jun 03, 2003 at 02:47:41PM -0500, Jeff Epler wrote: > > ... but maybe this is the natural interpretation of file(i) when > > isinstance(i, int). > > Yes, I considered this, but there were sufficiently persuasive arguments > against in the sourceforge bug. I'll have to read those arguments. I'll take a look back in the thread for the bug URL. > > > ... and maybe the natural interpretation of file(f) when isinstance(f, > > int) is file(os.dup(f.fileno())) (assuming the above file(i) behavior) > > I think you meant "when isinstance(f, file)". This is possible. Yes. > > > ... and maybe the natural interpretation of file("-") is sys.stdin, and > > file("-", "w") is sys.stdout. > > Yuk. What if I want a file called "-"? .. then you have to call it "./-". Just like at the shell, where you have to type "rm ./-" instead of "rm -". Jeff From artyprog at wanadoo.fr Thu Jun 12 15:35:11 2003 From: artyprog at wanadoo.fr (Salvatore) Date: Thu, 12 Jun 2003 21:35:11 +0200 Subject: Twice instanciation Message-ID: Hello, Is it possible to avoid twice instanciation of the same variable ? class Global: def __init__(self,init=0): self.value = init g = Global() #instanciating one time ok g = Global() #instanciating two times would raise an exception Regards Salvatore From gh at ghaering.de Mon Jun 9 10:42:24 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 09 Jun 2003 16:42:24 +0200 Subject: xmlrpc client on windows + https: error In-Reply-To: <3EE498D4.3080206@is.lg.ua> References: <3EE498D4.3080206@is.lg.ua> Message-ID: <3EE49CCF.10808@ghaering.de> Ruslan Spivak wrote: > Hello, python users! > > I've installed Python-2.2.2 on WinXP and trying to make xmlrp request > with https > > import xmlrpclib > s = xmlrpclib.Server("https://192.168.1.1:81") > s.printRes("test") > > i get an error: > ..... > Your version of httplib doesn't support HTTPS > Can you tell me what to do? How to make it work on windows, cause on my > linux box it's ok with python2.2.2. [...] You can replace _socket.pyd with the one I built with SSL support: http://pypgsql.sourceforge.net/misc/python22-win32-ssl.zip -- Gerhard From jepler at unpythonic.net Sat Jun 7 22:03:05 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 7 Jun 2003 21:03:05 -0500 Subject: finding origin of names In-Reply-To: References: <2259b0e2.0306070843.4ac68402@posting.google.com> Message-ID: <20030608020305.GB18916@unpythonic.net> On Sat, Jun 07, 2003 at 06:28:01PM +0100, Robin Becker wrote: > In article <2259b0e2.0306070843.4ac68402 at posting.google.com>, Michele > Simionato writes > ...... > > > >If I understand correctly you want inspect.getsource or inspect.getmodule > >or inspect.getsourcefile or something like that ... > > > > > > Michele > yes that works for functions and classes containing a method, but not > instances. .. then do something nasty in the instance __init__, such as def __init__(self): self.createdfrom = sys._getframe(1).f_globals['__name__'] that'll store the module name that the calling function was in. It won't tell you want name it was first stored to, there's no way to get that (in fact, it might never be given a name, or might be given a name by the one-level-up caller instead of the direct caller. Jeff From kendear at nospam.com Thu Jun 19 06:38:22 2003 From: kendear at nospam.com (Kendear) Date: Thu, 19 Jun 2003 10:38:22 GMT Subject: thinkings on shallow copy References: <3EF1849E.6060103@nospam.com> Message-ID: <3EF1929E.5040004@nospam.com> Kendear wrote: > i was just looking at docstrings and saw the one > for copy.__doc__ regarding copy.copy(): > > > - A shallow copy constructs a new compound object and then (to the > > extent possible) inserts *the same objects* into in that the > > original contains. > > I wonder if it is actually to insert *the same object references* > into the new compound object... so for the same reason, for deepcopy in the docstring: > - A deep copy constructs a new compound object and then, recursively, > inserts *copies* into it of the objects found in the original. it constructs a new compound object, and set its elements to point to newly created objects (mirroring the source) These newly created objects are created because they are mutable (list, dictionary) or they may contain mutable objects some level down (tuple). It does so recursively. For the absolutely immutable object (immutable any level down), it doesn't have to create new objects for them. (such as numbers, strings, and functions) and can directly point to them. From pinard at iro.umontreal.ca Thu Jun 5 07:48:19 2003 From: pinard at iro.umontreal.ca (Francois Pinard) Date: 05 Jun 2003 07:48:19 -0400 Subject: Python proper on Linux, `.a' vs `.so' In-Reply-To: <20030605044848.17058.qmail@green.zadka.com> References: <20030605044848.17058.qmail@green.zadka.com> Message-ID: [Moshe Zadka] > [Francois Pinard] > > Since the original C programs executables are not so big, less than 100K > > each (relying on installed shared libraries -- of course), I feel that > > the idea of using Python modules from within C applications would "sell" > > better if it was not blatantly bloating the size of executable files. > Many people have already answered on the "how", but I want to concentrate > on the "why". If you are already taking the "Python hit", meaning an > assumption that Python is installed on your target system, would it > not be easier to write the program in Python? If all these programs wer not already written, yes. This set of production programs is legacy code, that we ported over Linux from previous systems (old QNX, in fact). Even if the executables are not so big, the sources use thousands of lines, sometimes a bit intervowen and complex, that I surely do not feel like rewriting if it can be avoided. > In other words, I'm not certain "selling" Python as a C library is > missing an important point -- namely, that it is easier to write Python > code than C code. I absolutely agree with you, and everybody around me as well, nowadays. The point I'm willing to make here, now, is that even if a production program is already written in C, this should not be a compelling reason for extending it with more C code, unless the additions are pretty small. Python still give in faster development and safer maintenance, even there. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From usenet_spam at janc.invalid Wed Jun 25 22:31:25 2003 From: usenet_spam at janc.invalid (JanC) Date: Thu, 26 Jun 2003 02:31:25 GMT Subject: multi-platform python app on cd References: <87he6fb4a5.fsf@pobox.com> Message-ID: Peter Maas schreef: > I have googled this topic before posting and found only some hints > to py2exe that I knew already. As far as Linux/UNIX is concerned I'm > pretty sure that it is possible, perhaps by compiling the executable > with relative default path settings (?) and providing some modules. > The unknown part is Mac. Googling is an art... :-) I found that Python for the Mac comes with a "BuildApplication.py" script that does something similar as py2exe on Windows: """Create a standalone application from a Python script. This puts up a dialog asking for a Python source file ('TEXT'). The output is a file with the same name but its ".py" suffix dropped. It is created by copying an applet template, all used shared libs and then adding 'PYC ' resources containing compiled versions of all used modules written in Python and the main script itself, as __main__. """ -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From bdesth.nospam at removeme.free.fr Fri Jun 27 08:56:08 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Fri, 27 Jun 2003 12:56:08 +0000 Subject: Python executables? References: <3EFAFB13.1090506@removeme.free.fr> Message-ID: <3EFC3EE8.7070901@removeme.free.fr> Aur?lien G?ron wrote: > 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). (snip) > > Bruno wrote: (snip) >>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? This point out that binarie compilation does not enforce licence and copyright... A simple solution is to make the code open-source !-) > So why not simply compile your code and make it *harder* (although not > impossible) to decypher: Compiling also means loosing quite a great part of interpreted languages power. > 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. You can choose to only deliver bytecode (.pyc) files. But you have to be sure the user has the right interpreter version... And like Java, there is a simple way to decompyle... > 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. Doesn't this affect bytecode quality ? > 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. I guess there is none. All you can do is hack the binary code. But some people are pretty good at this. (snip) >>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 !-) > > I don't see small footprint and fast execution speed as antagonist at all, > quite the contrary. This seems to be a quite common observation that programs can be optimized for speed or for size, but not both (the program being correctly written, of course...). > In fact, assembly code produces the fastest and > smallest programs. I was talking about the same program written with the same language... BTW, I'm not sure a human programmer can beat a good compiler, unless the code is to be 'optimized' for one specific processor, which I don't call optimization !-) Bruno From bh at intevation.de Wed Jun 18 10:16:23 2003 From: bh at intevation.de (Bernhard Herzog) Date: 18 Jun 2003 16:16:23 +0200 Subject: How to recognize a generator function? References: Message-ID: <6q65n3pj2g.fsf@salmakis.intevation.de> Gon?alo Rodrigues writes: > On Wed, 18 Jun 2003 03:21:35 -0700, Oscar Rambla > wrote: [...] > >How to recognize if a function is a generator function before calling it? Why do you need to recognize that? > Let us see... > > >>> from __future__ import generators > >>> def testfunc(): > ... return None > ... > >>> testfunc > >>> testfunc.func_code.co_flags 4099 > >>> def testfunc(): > ... yield None > ... > >>> testfunc > > >>> >>> testfunc.func_code.co_flags 4131 So it's possible to distinguish the two, but I don't see why anyone would care (except in some very special circumstances such as a debugger, maybe). Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From paoloinvernizzi at dmsware.com Fri Jun 27 08:26:33 2003 From: paoloinvernizzi at dmsware.com (Paolo Invernizzi) Date: Fri, 27 Jun 2003 14:26:33 +0200 Subject: filedescriptor out of range in select() In-Reply-To: References: <3EFABC5E.329613C6@alcyone.com> Message-ID: 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') [/usr/local/lib/python2.2/asyncore.py|poll3|184] [/usr/local/lib/python2.2/asyncore.py|handle_read_event|391] [/usr/local/lib/python2.2/site-packages/spambayes/Dibbler.py|handle_accept|280] [/usr/local/bin/pop3proxy.py|__init__|337] [/usr/local/bin/pop3proxy.py|__init__|180] [/usr/local/bin/pop3proxy.py|__init__|134] [/usr/local/lib/python2.2/asyncore.py|create_socket|260]) error: uncaptured python exception, closing channel <__main__.BayesProxy connected 192.168.0.2:63485 at 0x84d8aac> (exceptions.AttributeError:'_socket.socket' object has no attribute 'isClosed' [/usr/local/lib/python2.2/asyncore.py|poll3|184] [/usr/local/lib/python2.2/asyncore.py|handle_read_event|397] [/usr/local/lib/python2.2/asynchat.py|handle_read|82] [/usr/local/bin/pop3proxy.py|recv|360] [/usr/local/lib/python2.2/asyncore.py|recv|353] [/usr/local/lib/python2.2/asynchat.py|handle_close|149] [/usr/local/bin/pop3proxy.py|close|368] [/usr/local/lib/python2.2/asyncore.py|__getattr__|372]) 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' From tjreedy at udel.edu Wed Jun 18 11:53:07 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 18 Jun 2003 11:53:07 -0400 Subject: Python Cannot be Killed References: <0B-dnTU7p53bx3KjXTWJiA@comcast.com> <5g5vevsu4c5rr5d5scks4tfjqe5mpn1h4j@4ax.com> Message-ID: "Tim Rowe" wrote in message news:5g5vevsu4c5rr5d5scks4tfjqe5mpn1h4j at 4ax.com... > On Tue, 17 Jun 2003 14:13:25 -0400, "Terry Reedy" > wrote: > > >Every few months, someone asks for tips on convincing 'management' > >that Python is as safe a business bet as closed-source, proprietary > >products. Here's a point that is sometimes overlooked: unlike the > >latter, > > > >Python cannot be killed. > > If Python were perceived as a threat to Microsoft I would expect them > to produce a "Visual Python" with a snazzy interface, some fairly neat > proprietary web tools and subtle incompatibilities with the > GPL-compatible one we know and love, and integrated with MSIE. > Unfortunately Sun is struggling to stop them doing this with Java, and > the Python community would, AFAICS, have real trouble finding the > money to mount an effective opposition. > > I think a false sense of security can be very dangerous. Your scenario is quite different from Microsoft (or anyone else) 'buying' the CPython codebase and then prohibiting us from using it after current 1-year licenses expire, which is the analog of what they reportedly plan to do with RAVAntiVirus. That they cannot do, (unless they spent billions to buy off every Python programmer in the world). I think your scenario would worst effect Pythoneers with managers who insisted on switching from real Python to Microsoft's version. I believe Sun's problem is that they specifically authorized Microsoft to produce and distribute a Windows Java version -- which Sun wanted MS to do to 'validate' Java as a standard run-anywhere language. They got some of the benefit they wanted, but having stepped into the ring with a bulldog, they have to deal with the downside. So now they have to argue in court that Microsoft stepped over a somewhat blurry technical line in the contract. If it has not done so, the PSF should probably trademark 'Python' as computer language name. With trademark rights, PSF could avoid Sun's 'problem' by refusing to license Python to Microsoft -- even if asked -- and forgo it 'impremature'. We are arguably doing well enough without it now. Or it could try to write a better contract. Perhaps sufficient would be specifying that anything bearing the Python name, with some version number, must pass the corresponding test suite, just like CPython. If a licensed version had avoidable and unwanted (by PSF) incompatibilities, add more unit tests for the next version to catch them. Terry J. Reedy From oren-py-l at hishome.net Tue Jun 3 13:23:12 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Tue, 3 Jun 2003 13:23:12 -0400 Subject: "for line in fd" twice In-Reply-To: References: Message-ID: <20030603172312.GA40534@hishome.net> On Tue, Jun 03, 2003 at 05:24:16PM +0200, Thomas G?ttler wrote: > Hi! > > the following does not work: > > """ > fd=open(file) > for line in fd: > if line.startswith("mymark"): > break > for line in fd: > #Read lines after "mymark" > .... > fd.close() > """ > > The second loop misses some lines. "for line in fd" internally invokes iter(fd). In python 2.2.x this returns an xreadlines object. This object has an internal readahead buffer that is lost when the iteration is stopped with the break statement and the xreadlines object is deallocated. The second for loop skips some arbitrary number of lines ahead. In 2.3 the readahead buffer has been moved into the file object itself and file objects are iterators instead of having an iterator. > It works with the old way: > > """ > while 1: > line=fd.readline() > if not line: > break > """ Yes, it works and it is fully compatible with seeks, mixing read() and readline() etc. But it's also slower because it does not do readahead buffering. Oren From max at alcyone.com Sun Jun 8 07:22:46 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 08 Jun 2003 04:22:46 -0700 Subject: a = b = 1 just syntactic sugar? References: <2259b0e2.0306070837.789f2a9f@posting.google.com> Message-ID: <3EE31C86.1D205A84@alcyone.com> Ed Avis wrote: > Oh. I thought someone said on this newsgroup only a few days ago that > they did not, when I mentioned that > > cond and x or y > > is a well-known substitute for a conditional operator like C's > (cond ? x : y) or Haskell's (if cond then x else y). Someone said > that it wouldn't work, because x and y would be evaluated in either > case. No, the problem with it is that it won't work if x is false. Think about it. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ God is love, but get it in writing. \__/ Gypsy Rose Lee From scrow at gladstone.uoregon.edu Fri Jun 27 13:01:37 2003 From: scrow at gladstone.uoregon.edu (Sam Crow) Date: 27 Jun 2003 10:01:37 -0700 Subject: Error importing cgi module Message-ID: <2fd0d25a.0306270901.c82972a@posting.google.com> Hello, having a little problem loading python modules.. here is the output from the interactive environment notice import sys worked correctly. when I do a search in the lib driectory for cgi i can find the modules there as well >>> import sys >>> import cgi Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.2/cgi.py", line 39, in ? import urllib File "/usr/local/lib/python2.2/urllib.py", line 26, in ? import socket File "/usr/local/lib/python2.2/socket.py", line 41, in ? from _socket import * ImportError: ld.so.1: python: fatal: relocation error: file /usr/local/lib/libcrypto.so.0: symbol __eprintf: referenced symbol not found any thoughts? Thank you, Sam Crow From creedy at mitretek.org Fri Jun 27 10:39:38 2003 From: creedy at mitretek.org (Chris Reedy) Date: Fri, 27 Jun 2003 10:39:38 -0400 Subject: How to memoize functions? In-Reply-To: References: <3efb54b3$1_2@corp-news.newsgroups.com> Message-ID: <3EFC572A.1030706@mitretek.org> Jeff Epler wrote: > The argument tuple is only "materialized" for a moment (it disappears > after the called function returns, if it was taken by *args, or else > before the first line of the function if it was taken by named args). > It will disappear from a weakkeydict immediately as a result. Yeah. I'd already recognized that problem. > The common memoize, written here using nested scopes, never trims old > values from the dictionary: > def memoize(f): > d = {} > def g(*args): > if not d.has_key(args): > d[args] = f(*args) > return d[args] > return g Nice. I tried it and it also appears to work for methods, e.g.: class foo: def f(...): ... f = memoize(f) > You could make d be a cache of limited size with code like > if not d.has_key(args): > if len(d) > 1000: > d.pop() # XXX > d[args] = f(*args) > the XXX line removes "some key" from the dictionary. The actual item is > not specified, but turns out to have some relationship to the hash value > of args. This may or may not be acceptable to you. Otherwise, you might > implement a true pseudorandom replacement algorithm, or the standard LRU, > or LFU. These may require that you maintain a heap or other auxiliary > list (corresponding to the keys) to achieve O(1) for the "remove an old > memoized value" code. The more I think about this, the more I like it. It solves another problem I was having, which is that re-computation for the same set of arguments is most likely for recent computations. > I just think weakrefs are not the solution to this problem... Just out of curiosity, what's the problem with weak refs. Are they too new to depend on or are they carrying some other baggage that's not obvious from the documentation. Chris -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 80,000 Newsgroups - 16 Different Servers! =----- From amk at amk.ca Fri Jun 13 08:19:36 2003 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 13 Jun 2003 07:19:36 -0500 Subject: Rudeness with names (was Re: interpreted) References: <3EE5BF67.2040201@ghaering.de> <7h3d6hjmpbw.fsf@pc150.maths.bris.ac.uk> <7h37k7qkxtp.fsf@pc150.maths.bris.ac.uk> Message-ID: <_AGdnTCc3q7FXHSjXTWcqg@speakeasy.net> On Fri, 13 Jun 2003 11:47:15 GMT, Michael Hudson wrote: > Wasn't Sam Rushing at eGroups? Perhaps I should have researched that > post... You're correct. I don't know if Medusa was initially written for egroups, but they certainly employed Sam Rushing for a time; the egroups web server was a Medusa application. --amk From staschuk at telusplanet.net Tue Jun 24 14:24:29 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 24 Jun 2003 12:24:29 -0600 Subject: division In-Reply-To: ; from frobozz_electric@hotmail.com on Tue, Jun 24, 2003 at 12:31:24AM +0000 References: Message-ID: <20030624122429.A907@tibia.amotlpaa.bogus> Quoth Sean Ross: [...] > > >>> txt = pattern.sub(replaceint, "((4 * 5) -2) / 5 ") [...] > > it doesnt raise an exception even though im dividing > > 18 / 5 which doesnt go evenly . > > Adding the following method to the myint class solves this issue: > > def __rdiv__(self, other): > return self.__div__(other) Now what if the denominator is computed as well? ((4*5) - 2)/(4+1) You need the values produced by + etc. to be myints as well; merely inheriting the arithmetic methods from int is inadequate, since these methods return ints. So you need to extend __add__, __sub__, __radd__, ... Expressions are pretty easy to parse and evaluate, btw; it seems to me simpler to write your own parser/evaluator, rather than using eval. -- 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 sross at connectmail.carleton.ca Sun Jun 22 23:19:56 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sun, 22 Jun 2003 23:19:56 -0400 Subject: division References: Message-ID: > > > The problem is division, I would like it that only exact division was > > > aloud, I mean no remainders. > > > 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. I'm not going to ask why you want this behaviour, I'm just going to offer a quick, dirty, and possibly buggy solution. This code relies on the following assumptions: [1] You want to ensure that *only* exact division can occur [2] The only numbers your users can *ever* enter are integers, i.e. '2.0 + 3.14' will raise an exception. So, for this to work, you'll need to somehow ensure [2]. A more reliable solution would be to make your own simple interpreter. I would recommend checking out SPARK. There are examples available with the software that you could extend to fit your problem domain. Anyway, here's some code. I won't guarantee its robustness, I'll just say it appears to work. import re class ExactDivisionError(Exception): pass class myint(int): def __div__(self, other): "does exact division only" quotient, remainder = divmod(self, other) if remainder: raise ExactDivisionError, "exact division only" return quotient def replaceint(match): "substitues 'myint(integer)' for each matched integer" return 'myint(%s)'% match.string[match.start():match.end()] # some testing... pattern = re.compile(r'\d+') # matches integers txt = '2 + 22/5' txt = pattern.sub(replaceint, txt) print txt # 'myint(2) + myint(22)/myint(5)' try: result = eval(txt) # this will raise an exception for 'txt' print result except ExactDivisionError: print "ExactDivisionError" Hope that's helpful, Sean From tim.fuehner at t-online.de Mon Jun 23 05:47:37 2003 From: tim.fuehner at t-online.de (Tim Fuehner) Date: Mon, 23 Jun 2003 11:47:37 +0200 Subject: importing swig generated modules in C program Message-ID: Hi, I'm pretty new to Python, and I have the following problem: I extended Python (version 2.2.1 GCC 3.2) by wrapping a C module using SWIG: C file: /* File : example.c */ double My_variable = 3.0; /* Compute factorial of n */ int fact(int n) { if (n <= 1) return 1; else return n*fact(n-1); } /* Compute n mod m */ int my_mod(int n, int m) { return(n % m); } SWIG file: /* File : example.i */ %module example %{ /* Put headers and other declarations here */ %} extern double My_variable; extern int fact(int); extern int my_mod(int n, int m); running ``swig -python example.i'' (version 1.3.19) and using ``gcc -shared example.o example_wrap.o -o _example.so \ -L/usr/lib/python2.2/config -lpython2.2'' I obtained the files ``_example.so'' and ``example.py''. Using these files interactively works fine: #>>> import example #>>> example.fact(5) #120 However, when I try to call this module from within a C program it fails: #include static PyObject *my_callback = NULL; int main(int argc, char **argv) { Py_Initialize(); PyRun_SimpleString("import example"); return 0; } yielding: Fatal Python error: Interpreter not initialized (version mismatch?) Aborted the program was linked as follows: gcc -o pyc pyc.o -lm -lpthread -ldl -lutil \ -L/usr/lib/python2.2/config -lpython2.2 When I import native Python modules everything works fine. Anybody have a clue? -- TIM FUEHNER mailto: tim.fuehner at t-online.de From cben at techunix.technion.ac.il Tue Jun 10 07:03:25 2003 From: cben at techunix.technion.ac.il (Beni Cherniavsky) Date: Tue, 10 Jun 2003 14:03:25 +0300 (IDT) Subject: ANN: Set-like methods on dicts In-Reply-To: <874r2y7qui.fsf@pobox.com> References: <874r2y7qui.fsf@pobox.com> Message-ID: John J. Lee wrote on 2003-06-10: > Beni Cherniavsky writes: > > > Dictionary users of the Python world, unite (or intersect)! > [...] > > They already did: > > http://www.python.org/doc/2.3b1/whatsnew/node2.html > No, they did not - not with values: >>> from dsets import * >>> s = DSet({1: 'one', 2: 'two'}) >>> s.intersection([1, 5], collision=first) DSet({1: 'one'}) >>> s.union_update({2: 'TWO', 3: 'THREE'}, collision=second) >>> s DSet({1: 'one', 2: 'TWO', 3: 'THREE'}) >>> s.intersection({1: 'one', 2: 'QuuX', 3: 'three'}, collision=str.__eq__) DSet({1: True, 2: False, 3: False}) How do you do this with sets? The keys will behave the same with sets but the values won't be tracked. -- Beni Cherniavsky From pythonguy at Hotpop.com Wed Jun 11 04:58:29 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 11 Jun 2003 01:58:29 -0700 Subject: Go buy _Text Processing in Python_ References: Message-ID: <84fc4588.0306110058.1c019f66@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 m at moshez.org Wed Jun 18 14:01:26 2003 From: m at moshez.org (Moshe Zadka) Date: 18 Jun 2003 18:01:26 -0000 Subject: How to permanently remove __import__? In-Reply-To: References: , <3EEF8C0C.23E93E18@engcorp.com> <3EEF970C.4630A21@engcorp.com> Message-ID: <20030618180126.20453.qmail@green.zadka.com> On Wed, 18 Jun 2003, "martin z" wrote: > This is what I meant by "too much". I have no ambiguous concept of > "potentially dangerous code" - I just don't want > the user getting at the files. Then use your operating system's capabilities for restricted execution. Alternatively, look at the code Oren Tirosh posted a few days ago to show how it's fairly easy to break this type of restrictions. Importing is your *last* problem. (For starters, you want to make sure you properly disable open() and file() and execfile(), right? And trust all builtin modules to be fairly nice...and trust the Python coders to make sure no untrusted paths exist...) -- 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 p-abel at t-online.de Fri Jun 27 08:55:31 2003 From: p-abel at t-online.de (Peter Abel) Date: 27 Jun 2003 05:55:31 -0700 Subject: Namespacedifference reading - writing ?? Message-ID: <13a533e8.0306270455.431d3cfd@posting.google.com> Can anybody tell me if the following 2 examples are OK as shown below? In my opinion it is **not**. 1) >>> def outer(): ... x=1 ... def inner(): ... print 'x in inner =',x ... #x=100 ... #print 'x set in inner=',x ... inner() ... print 'x in outer =',x ... >>> outer() x in inner = 1 x in outer = 1 2) >>> def outer(): ... x=1 ... def inner(): ... print 'x in inner =',x ... x=100 ... print 'x set in inner=',x ... inner() ... print 'x in outer =',x ... >>> outer() x in inner =Traceback (most recent call last): File "", line 1, in ? File "", line 7, in outer File "", line 4, in inner UnboundLocalError: local variable 'x' referenced before assignment Is there really a difference in namespacehandling depending on writing or reading variables? Regards Peter From peter at engcorp.com Thu Jun 26 17:32:13 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 26 Jun 2003 17:32:13 -0400 Subject: XML References: <3EF6E9A1.74E45E69@hotmail.com> Message-ID: <3EFB665D.180C7934@engcorp.com> Mel Wilson wrote: > > And there isn't much to XML. [snip summary of XML] > Many people seem to be confused about XML because there > is less there than they think there should be. It's amazing how many books have been written which spend several chapters and many, many pages without managing even to say everything you said in those four short paragraphs! -Peter From aleax at aleax.it Tue Jun 17 12:00:58 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 17 Jun 2003 16:00:58 GMT Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> <3EECED65.ACF1A6B7@engcorp.com> Message-ID: <_WGHa.192340$g92.3890412@news2.tin.it> Moshe Zadka wrote: > 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 the salaries for gardeners and the expenses for fertilizer do *not* mean that a garden owned by a corporation is a liability of that corporation -- it's still an asset. It's quite normal that there may be expenses connected to maintenance of an asset (and different fiscal regimes define ordinary and extraordinary maintenance in slightly different ways, as well as, in some cases, 'required' versus 'optional' maintenance), but those, of course, do not change its asset-nature. > to accounting-lingo? How come we weren't sued for malpractice when my > bosses authorized me to delete heaping gobs of code? Just because If you didn't keep an archival trace of the previous versions (e.g. with CVS, subversion, or the like), then I guess you're lucky you have friendly and accomodating stockholders and/or auditors. Disposal of some assets is a normal procedure, of course, but you don't just take them to the middle of the sea in the night and dump them there -- you need an audit trail for that (partly depending on your local jurisdiction's inventory regulations, of course). Consider for example a restaurant which at the start of a given business day has in its inventory 3 Kg of truffles: these are assets ("stock in trade" is the common term). At the end of the day, it's possible that, say, 1 Kg of the truffles has been used in preparing various delicious dishes for the restaurant's customers. On closing for the night, the restaurant's stocks are subject to routine inspection and it turns out that 0.5 Kg of the remaining truffles have spoiled and should be disposed of. No problem: quite an ordinary operation. But still, an entry must be made in the books recording the disposal of such and such an amount of goods due to spoilage. And if you think that the possibility of spoilage (and thus of needing disposal), or the need for maintenance (e.g. cleaning superficial warts that may develop on the truffles' surface, to avoid some more of them spoiling and needing disposal) means the truffles owned by the restaurant are "a liability", rather than an asset of the firm, then we're not dealing with a lack of understanding of "accounting lingo": we're dealing with something way deeper! Stock-in-trade has cost money and/or effort to acquire; unless it spoils and needs to be disposed of, it may be used (possibly with further expenditure of work &c) to generate income for the firm (e.g. to prepare goods or services for sale to customers); thus, it's an asset of the firm. The possible need for maintenance and risk of spoilage do not change this situation one bit! > translating from sane-speak to accountant-lingo is non-trivial does > not mean source code is not a liability] It's not an issue of "lingo" vs alleged "sane-speak". It's a matter of common sense, ordinary microeconomics, and somebody trying to be funny without, it appears, the slightest grasp of the subject. A liability of a firm is a financial obligation, responsibility, or debt. If the firm owns an asset on which it is legally mandated to provide ordinary maintenance, then that legal mandate (an obligation which imposes costs) is a liability (it can generally be shown as such in your balance sheet, depending on the exact accounting rules that may apply in your jurisdiction), but that does not change the nature of the asset as such (it may offset its _value_, but that's another issue). When the maintenance is not mandatory by law, then it's quite iffy to consider it a liability -- "ordinary operating expense" is the only classification that makes _sense_, although it may be possible to play (perhaps-legal) tricks to doctor the balance sheet anyway (e.g., hive off the asset into a legally separate firm and undertake to provide the maintenance by entering a binding contract with that firm -- that _might_ let you hide some or all of the asset's value and perhaps even show a net notional liability, depending on how you may be required to consolidate balance sheets and how fast-and-loose you're willing to play with the spirit vs the letter of accounting principles and rules). But, tricks apart, an asset which requires maintenance is NOT a liability! Alex From paul at boddie.net Wed Jun 25 09:37:17 2003 From: paul at boddie.net (Paul Boddie) Date: 25 Jun 2003 06:37:17 -0700 Subject: Check your Wikis References: <6a351$3ef6f993$516049d2$22156@nf1.news-service.com> Message-ID: <23891c90.0306250537.565529a8@posting.google.com> Duncan Grisby wrote in message news:<6a351$3ef6f993$516049d2$22156 at nf1.news-service.com>... > I just noticed an "interesting" addition to the omniORB Wiki. There's > a small page about Python on the Wiki, and someone added a link to > www.python info.com (without the space). If you go to that site, you > find a collection of old information about Python, that I've seen > somewhere before. Interspersed throughout the text are various links > to porn sites. [...] > I assume this is an attempt to get the porn sites indexed, which is > why I've broken the URL above. Is this the same thing, then...? http://www.python.org/cgi-bin/moinmoin/Du Pont (Space added for anti-indexing effect.) I know that it's "against the Wiki way" or , but is it really that intrusive to insist that people register to edit Wikis containing useful and important information? Although it has been quite dormant, the Webware Wiki managed to secure contributions from motivated people whilst insisting on registration, for example. Besides, the supposed "Wiki way" really does contradict some of the most basic security precautions for the running of Internet sites - denial of service can become a serious concern. Paul From martin at v.loewis.de Wed Jun 18 15:29:33 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 18 Jun 2003 21:29:33 +0200 Subject: Displaying IPA characters in Tkinter References: Message-ID: Mickel Gr?nroos writes: > So there is no way of conduct for mapping a regular keyboard to IPA > characters, is there? You can certainly do that in the application, by means of Tk bind operations. It's not simple, though, as you would have to implement key repeat, insertion into insertion point, etc. all yourself. There might be also a way to define a new keyboard layout in your operating system. That would be outside of Tk and Python. Regards, Martin From news at manuelmgarcia.com Fri Jun 13 18:43:22 2003 From: news at manuelmgarcia.com (Manuel Garcia) Date: Fri, 13 Jun 2003 22:43:22 GMT Subject: why 'lambda' and 'reduce'? References: <84fc4588.0306112339.10a4012b@posting.google.com> Message-ID: I had a few people email me, asking how many of the 5000 digits of Pi are accurate, and being surprised that all 5000 are correct. I can explain how it works as best I can (I am not a professional mathematician). The limits of how many digits it can compute are only the limits of Python's long integer implementation, and the limits of the computer's memory. 1,000,000 digits, probably, if you don't mind the wait. 1,000,000,000 digits, don't think so. It is hardly the most efficient way to calculate Pi, but it also is not grotesquely inefficient. In fact, it runs surprisingly fast in Python 2.3 for 5000 digits. The code contains absolutely no 'obfuscation', except the use of '+' for string concatenation. All the 'lambda's and 'reduce' and whatnot actually have to be there for the efficiency of the algorithm; to make the code run as fast as a straightforward implementation. The whole of the obfuscation is that Python's built-in functions and long integers make coding the algorithm unusually 'clean' (if that mess can be called 'clean'). The code uses a 'quadratic iteration', referring to the speed with which correct digits are produced. With each iteration the number of correct digits is doubled. Modern computers of massive numbers of digits of Pi (many billions) use such iterations. (There are newer techniques for computing just a specific digit of Pi, without having to compute the digits before, but if you wanted the unbroken list of digits, you would use an iteration algorithm.) A helpful webpage is: http://numbers.computation.free.fr/Constants/Pi/iterativePi.html (The iteration I used is #1.2.1, found in 1976 independently by Eugene Salamin and Richard Brent) An article in Scientific American (I haven't read it, but a couple of different websites said it was fun and easy to understand): Borwein, Jonathan M., and Peter B. Borwein. RAMANUJAN AND PI; February 1988, page 66 If you wish to download a massive number of digits of Pi, to confirm all this: http://www.geocities.com/thestarman3/math/pi/picalcs.htm Geometrical or calculus based algorithms for computing Pi typically add a fixed number of correct digits with each 'step' (either a single compass and ruler construction in an infinite construction or a single term in an infinite sum or product). These newer techniques are based on pretty 'heavy-duty' number theory, increase the number of correct digits times 2, times 3, times 4, times 5, etc. (I think I saw the construction of an iteration that increased times 16) The Japanese group who hold the record on computing digits of Pi (51 billion digits) used a 'times 4' (quartic) iteration, optimized for binary computers. Their iteration actually computes the reciprocal of Pi, making it hard to inspect the digits while you are creating them. I picked the simplest quadratic iteration, because for 5000 digits it hardly makes any difference. The '13' in the code is the number of iterations needed. For 10000 digits, you would use 14 iterations, etc. To maintain accuracy to 5000 digits, I could not use Python floating point. I had no choice but to use long integers, much like Tim Peters' 'FixedPoint'. The integers are huge (around 10**5000 to 10**10000 in size), but Python has no limits on the size of long integers. (Python 2.3 uses the Karatsuba algorithm to multiply long ints, much faster than 2.2. I don't think division was speeded up). To allow use of longs instead of decimals, I had to scale up all calculations by 10**5010 (I needed 10 extra decimal places to guarantee the accuracy of the 5000 digits, because I haven't eliminated rounding errors, but I only need 10 (maybe less, I didn't really try) because the iteration is pretty numerically stable) What looked like 'geometrical mean' was actually my having to implement a square root function with Newton's method, because Python's built in pow() converts to floating point with fractional exponents, and 10**5000 is too large for the built in floating point. The number '15' is the number of iterations Newton's method needs (it is also quadratic, I threw a couple of extra iterations in there to keep the Pi iteration happy). If you go through the expression step by step, you will see no 'lambda' or 'reduce' can be removed, unless you sacrifice speed or accuracy. So it is true it is hardly obfuscated, because my hands were tied almost every step of the way. 'lambda' took the place of variable assignment, and my bizarre 'reduce' expressions were used for looping. Anyway, here is the code. I measured x*x as running faster than x**2 or pow(x,2) using 2.3's 'timeit' module, but it really doesn't make any difference, as the running time is swamped by the long integer division and multiplication. 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),_:((x+y)//2L, S((x*y)//F),2L*t, (a-(t*(((x+y)//2L)**2- (S((x*y)//F))**2))//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]) Manuel From CousinStanley at hotmail.com Sat Jun 21 05:13:48 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Sat, 21 Jun 2003 02:13:48 -0700 Subject: "Newbie" questions - "unique" sorting ? References: <8da5fvsnidpjtblgfj4484spso2t9e6r95@4ax.com> Message-ID: | ... | It didn't seem to work | so I have obviously done something wrong. | ... John ... I don't think you did anything wrong, but I think I did and the problem didn't show up until I tested with larger files ... After re-reading your post again I did more testing on larger input files with more words, but still found duplicates in the end result ... 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 Processing a 40 KB input file runs in about 8 Seconds on the 250 MHz Win98 system that I use ... Total Words .... 5927 Unique Words .... 1704 -- Cousin Stanley Human Being Phoenix, Arizona From skip at pobox.com Thu Jun 19 12:22:54 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 19 Jun 2003 11:22:54 -0500 Subject: error loading files containing nullbytes w/ urllib? In-Reply-To: References: Message-ID: <16113.58206.661442.224182@montanaro.dyndns.org> Luther> f = open('gwb.jpg','w') Luther> What am I doing wrong??? Are you using Windows or Mac OS 9? If so, open your output file with mode = 'wb'. Skip From mis6 at pitt.edu Wed Jun 4 17:03:17 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 4 Jun 2003 14:03:17 -0700 Subject: reStructured Text - suitable for non-documentation? References: <2259b0e2.0306020703.3db3a717@posting.google.com> <3EDB6B80.7090608@mxm.dk> <2259b0e2.0306021308.2413a0da@posting.google.com> Message-ID: <2259b0e2.0306041303.14992fee@posting.google.com> "Raymond Hettinger" wrote in message news:... > "Michele Simionato" wrote in message > > Hey, literate programming is great!! > > > > But if it was invented in 1984, why is it so little > > widespread ? I hardly heard about it before today > > (except for Leo, the literate programming editor, > > which however I never tried). > > It is still around and has many incarnations such as CWEB, > Leo, etc. There a few issues limiting its popularity. > > One of the core ideas is write a piece of documentation that > is a cross between a well written essay and concrete detail > documentation. The problem here is that not that many > people write well enough to achieve even the essay and > even fewer can effectively combine that with detail docs. > The writing skills need to augmented by knowledge of > the markup language (usually TeX). And the writer needs > to know the programming language being used. And the > programmer needs to be skillful enough to write a program > in disconnected fragments that still makes sense and can > be debugged after re-assembly. > > Donald Knuth is one person who has all of these skills > and can apply them all at the same time. In contrast, > the average Joe is lucky to have even a few of the > skills, much less being able to apply them all at the > same time. It is rarer still to find teams where all of > the programmers can read and write in a literate style. > As some of the python developers can attest, it takes > a while just to get the LaTeX markup correct. > > Even if all of the pieces fall into place, there is still a > sense that it takes a lot of work. So, eventhough there > is a certain pleasure to writing literate code, it is something > you tend to save for that special program and then find that > most tasks are too mundane to warrant using your heavy gun. > I see all of your points and I fully agree. Actually, I think literate programming is beatiful if you are writing a book on programming, but it is an heavy weight for any other purpose ;) > Also, I find that the process of writing literately collides with > the Test Driven Development process. I'm sure it's possible > to do both at the same time, they just don't seem to fit together > naturally. > > > > BTW, I have in mind an integration of documentation+test suite, > > not documentation+program (a la Knuth). > > +1 > > > Raymond Hettinger I see you are already converted, but for sake of programmers still dubious on the virtues of rst and similar tools, I will add few sentences. I don't want to document all of my code, as literally programming would aspire to, it is too much an effort. My idea is to document only the user interface, by giving examples of usage automatically tested by doctest. This integrate the documentation of the public interface (i.e. the user manual) with its testing. The documentation of the internals and their testing is a different subject and a much bigger work :-( For instance, I recently took the habit of writing all or my posts to c.l.p. in reStructuredText. One advantage is that I have a simple script based on doctest that tests the code before I post it ;) a second advantage is that I can cut and paste from my postings and collect them in larger documents. Then, it is trivial to convert them in html for web publishing or even in latex for printing purposes. I am really really happy with rst+doctest ;) Michele From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Jun 9 07:25:24 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 09 Jun 2003 13:25:24 +0200 Subject: Why is lambda so slow? In-Reply-To: References: Message-ID: <3ee46ea2$0$49115$e4fe514c@news.xs4all.nl> anson wrote: > What's the reason of lambda being so slow? In what code do you find this to be slow? Have you timed it? Anyway, invoking a lambda is calling a function and AFAIK calling functions in Python is relatively slow. --Irmen From johnroth at ameritech.net Sat Jun 7 07:02:12 2003 From: johnroth at ameritech.net (John Roth) Date: Sat, 7 Jun 2003 07:02:12 -0400 Subject: Postfix/Prefix Operators (++,--) References: <3EE05E36.40DF739F@engcorp.com> <3EE0B4D5.736EE894@engcorp.com> <3EE0D19C.7D7FFCA0@engcorp.com> <3EE149EF.73C7373F@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3EE149EF.73C7373F at 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... But setattr() is used in expressions! However, I agree with you in general, setattr() is an exceptional case. John Roth > > -Peter From martin at v.loewis.de Tue Jun 24 15:42:00 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Jun 2003 21:42:00 +0200 Subject: cvs checkout question In-Reply-To: References: Message-ID: <3EF8A988.90405@v.loewis.de> Russell E. Owen wrote: > % 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: You should leave the password empty. > cvs [login aborted]: recv() from server cvs.python.sourceforge.net: > Connection reset by peer In that case, SF has rejected you because it is overloaded. Just retry immediately. Regards, Martin From simonb at webone.com.au Tue Jun 17 16:14:29 2003 From: simonb at webone.com.au (Simon Burton) Date: Wed, 18 Jun 2003 06:14:29 +1000 Subject: installing PIL on OSX References: Message-ID: On Mon, 16 Jun 2003 18:12:03 -0700, Chris Fonnesbeck wrote: > I am trying to install PIL on OSX using python2.3b, but am having some > problems, apparently related to tcl/tk. Here are the errors: > I didn't get far either; have you tried the python "kitchen sink" (look on macpython list) Simon. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sun Jun 29 06:44:26 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sun, 29 Jun 2003 12:44:26 +0200 Subject: Fast CGI Vs Java Application Servers In-Reply-To: References: Message-ID: <3efec309$0$49100$e4fe514c@news.xs4all.nl> Charles Handy wrote: > > How does FastCGI compare against java Apps running in java app servers > like TomCat, Sun One, WebLogic and WebSphere? A (fast)CGI program compared to the actual Java program may not be much of a difference, depending on the program of course. What is a *huge* difference is that the Java app is running inside an *application server*. A (J2EE) Application Server provides a rich environment on which to base your scalable enterprise applications: - security - connectivity - scalability (performance, clustering) - maintainability / managability - error reporting/logging - component based (EJBs) - database connectivity and object persistence - transactions - ... All of these are standardized in some way (as part of J2EE). In theory you can move your J2EE application to a different environment running on a different vendor's app server without much sweat. You don't have any of this readily available when writing (fast)CGI applications; you have to implement all of these yourself. --Irmen de Jong From manuelbastioniNOSPAM at tin.it Fri Jun 13 19:29:35 2003 From: manuelbastioniNOSPAM at tin.it (Manuel) Date: Fri, 13 Jun 2003 23:29:35 GMT Subject: getFoo1() vs. class.foo1 Message-ID: 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. Because this mean many many lines added, I want ask the difference between two methods. The simple class above begin: class VerySimple: __foo1 = 1 __foo2 = 2 __foo3 = 3 def getFoo1(self): return __foo1 def getFoo2(self): return __foo2 def getFoo3(self): return __foo3 setFoo1(self,val): __foo1 = val setFoo2(self,val): __foo2 = val setFoo3(self,val): __foo3 = val I've add a lot of line. It' necessary in all cases? thx, Manuel From messageboardfan1 at yahoo.com Mon Jun 2 20:34:08 2003 From: messageboardfan1 at yahoo.com (ataraxia2500) Date: Tue, 03 Jun 2003 02:34:08 +0200 Subject: reading files in folder Message-ID: <3edbece3$0$8343$79c14f64@nan-newsreader-02.noos.net> I would like to make a function that do something to all the text files that are in a folder and if that folder contains other folders with text files the functions would also modify those text files. is there a simple function that do that? thanx in advance From tjreedy at udel.edu Sat Jun 7 20:51:26 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 7 Jun 2003 20:51:26 -0400 Subject: a = b = 1 just syntactic sugar? References: Message-ID: "Ed Avis" wrote in message news:l1wufxh9g8.fsf at budvar.future-i.net... > Steven Taschuk writes: > > >We already have closures, don't we? > > > > >>> def f(x): > > ... def g(y): > > ... return x + y > > ... return g > > ... > > >>> q = f(3) > > >>> q(4) > > 7 > > Which Python version does this require? 2.1 with future statement, 2.2 without > (The machine to hand has only 1.5.2, although normally I use 2.2 or so.) Upgrade if you can. > I mean things like > > def make_adder(): > x = 0 > def incr(): > x += 1 > return x > return incr > > f = make_adder() > g = make_adder() > print f(), f(), g(), g() # 1 2 1 2 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 Terry J. Reedy From peter at engcorp.com Fri Jun 6 05:26:14 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 06 Jun 2003 05:26:14 -0400 Subject: Postfix/Prefix Operators (++,--) References: Message-ID: <3EE05E36.40DF739F@engcorp.com> hostmaster wrote: > > Python doesn't seems to support postfix/prefix operators (e.g. i++, > --i). Why? See Jp's and Chad's answer, and add to that all the *many* past discussions on the same point (it's not like you've asked an original question... the archives would almost certainly have helped you), plus the following: Python statements are not expressions. They do *not* return values as they do in Java and C. That pretty much removes any possible purpose in having those operators. Secondly, in Python assignment actually *rebinds* a name to a new object, so i = i + 1 creates a new object that is one greater than the old, and rebinds the name "i" to it (like a pointer). The old value, if there are no more references to it, is destroyed. This, combined with the fact that these integer objects are actually *immutable* (they cannot be changed!) pretty much prevents any possibility of those operators working the way you'd expected. End result: no chance of having it, and no reason to have it... -Peter From aeze616 at cse.unsw.edu.au Mon Jun 16 20:46:58 2003 From: aeze616 at cse.unsw.edu.au (anson) Date: 16 Jun 2003 17:46:58 -0700 Subject: can someone find me the canvas.py file? Message-ID: Dear people, I've been trying to look for the canvas.py file that demostrates how to use the QCanvas in python but I can't find it. I thought it would be in the demostration documentations but it isn't. Does anyone know where it is? Or can anyone give me a working .py example that shows how to use the QCanvas? Thanks. zeallous From gradha at titanium.sabren.com Wed Jun 4 05:50:03 2003 From: gradha at titanium.sabren.com (Grzegorz Adam Hankiewicz) Date: Wed, 4 Jun 2003 11:50:03 +0200 Subject: How do I obtain the filenames' encoding after os.listdir? Message-ID: <20030604095003.GA8459@pedos.es> Hi. I'm using os.listdir() to read a directory. The function returns a list of string objects: In [3]: l = os.listdir(".") In [7]: l[6] Out[7]: 'm\xfasica.mid' In [8]: l[6].decode("latin1") Out[8]: u'm\xfasica.mid' I want to transform the strings to unicode objects so I can use them with pygtk, and the current process works ok for my machine. The question is how do I know the encoding of the filenames? Currently I'm presuming latin1, but if somebody else uses a different encoding, how do I know which one? The documentation says string.decode can use as parameter "ignore" or "replace", but using them only raises LookupErrors. -- Please don't send me private copies of your public answers. Thanks. From p at ulmcnett.com Thu Jun 5 12:51:07 2003 From: p at ulmcnett.com (Paul McNett) Date: Thu, 5 Jun 2003 09:51:07 -0700 Subject: Tk vs wxPython ? In-Reply-To: <1054830721.2139.13.camel@software1.logiplex.internal> References: <200306050920.17729.p@ulmcnett.com> <1054830721.2139.13.camel@software1.logiplex.internal> Message-ID: <200306050951.07037.p@ulmcnett.com> Cliff Wells writes: > There is little doubt in my mind that Qt is a great toolkit. There is > less doubt in my mind that bundling a toolkit with Python that requires > users to pay a licensing fee will never happen. Whether that fee is > $1000 or $10 is irrelevant. Wait. Unless I'm seriously misunderstanding the Qt licensing, the only people that need to pay the Qt licensing fees are the developers of the commercial apps (1 license per platform per developer). IOW, I as the developer of some great commercial PyQt app need to somehow get licenses from Trolltech that allow me to do the development and distribute the Qt runtime libraries. How I pass this cost on to the users of my product is completely up to me. Neither the users of my product, nor I, owe anything additional to Trolltech beyond the developer licensing fees. Anyone please correct me if I've misread any of this, as it will definitely have a bearing on my GUI toolkit decision. -- Paul McNett From tebeka at cs.bgu.ac.il Wed Jun 25 07:05:28 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 25 Jun 2003 04:05:28 -0700 Subject: Iterating over optparse options Message-ID: <33803989.0306250305.77fd046e@posting.google.com> Hello All, Couldn't find it in the manual ... Is there a way to iterate over the options optparse parser finds? What I like to to is: ----- OPTIONS = {} ... parser = OptionParser() ... # Configure parser options, args = parser.parse_args() for opt, value in options: OPTIONS[opt] = value ----- The rational is that I have a program with many command line options. Instead of going over all of them I'd like to set my defaults and change only what is needed. Thanks. Miki From mis6 at pitt.edu Mon Jun 2 17:08:23 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 2 Jun 2003 14:08:23 -0700 Subject: reStructured Text - suitable for non-documentation? References: <2259b0e2.0306020703.3db3a717@posting.google.com> <3EDB6B80.7090608@mxm.dk> Message-ID: <2259b0e2.0306021308.2413a0da@posting.google.com> Max M wrote in message news:<3EDB6B80.7090608 at mxm.dk>... > Michele Simionato wrote: > > > Recently, I have found a nice application for rst in the context of > > DDD (Documentation Driven Development, dunno if the acronym already > > exists ;) > > and I thinks it may be of interest to people here (if not to the OP). > > > Knuth beat you to it. Google for "litterate programming" Hey, literate programming is great!! But if it was invented in 1984, why is it so little widespread ? I hardly heard about it before today (except for Leo, the literate programming editor, which however I never tried). BTW, I have in mind an integration of documentation+test suite, not documentation+program (a la Knuth). Bye, -- Michele From sholden at holdenweb.com Wed Jun 25 07:47:53 2003 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 25 Jun 2003 11:47:53 GMT Subject: Newbie: "compiling" scrips (?) References: Message-ID: "Troels Therkelsen" wrote in message news:slrnbfj02u.dk.t_therkelsen at abattoir.2-10.org... [how to "compile" Python] > > I don't know if this answers your question, but in order for a Python script > (or any script, really) to be executable under Linux (and all UNIX-like > systems), you need to do two things: > > 1) Make sure that the file has the executable bit set. This can be done > with the chmod command, for example 'chmod +x my_file.py'. Be sure to > read the man page for chmod, if you aren't already familiar with this > command. > > 2) At the very first line of your script file you must have a so-called > shebang line. This line tells your shell how to execute the file. The > Python tutorial recommends this shebang: > > #! /usr/bin/env python > > (No spaces before the # and the newline *must* be '\n'. If you use > '\r\n' it won't work and the error message isn't very helpful) > > Alternatively, if you don't wish to do all this, you can also execute your > script by typing 'python my_file.py'. Regardless of which approach you take, > however, python must be in your $PATH for either of them to work. If python > has been properly installed on your system, it will be. > Of course, if the shebang line explicitly names the Python executable then there is no need for it to be on the user's PATH. On Red Hat 8.0, for example: [sholden at munger sholden]$ cat test.py #!/usr/bin/python print "So, Python need not be on the path!" [sholden at munger sholden]$ export PATH=`pwd` # don't try this at home ... [sholden at munger sholden]$ echo $PATH /home/sholden [sholden at munger sholden]$ test.py So, Python need not be on the path! regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From ed at membled.com Sat Jun 7 07:12:01 2003 From: ed at membled.com (Ed Avis) Date: 07 Jun 2003 12:12:01 +0100 Subject: a = b = 1 just syntactic sugar? References: Message-ID: Sean Legassick writes: >> def f: >> print 'hello' >> x = f >> >>f is an expression, yet it 'contains' a statement. >f might well be an expression, but surely the 'def f:' is a statement >with an accompanying suite. It's a kind of assignment statement. Yes... what we are talking about here, of course, is purely syntax. Semantically there doesn't seem much difference between defining f that contains a print statement, and defining an anonymous function that has the same. If a clear and simple syntax can be worked out to let expressions appear in lambda-defined functions, just as they can in ordinary functions, there doesn't seem to be any other reason to prohibit it. I think that the rule of 'anything that fits on one line' is such a simple rule; just as simple as 'any expression, but not a statement' and more powerful. -- Ed Avis From rnd at onego.ru Sun Jun 29 04:36:31 2003 From: rnd at onego.ru (Roman Suzi) Date: Sun, 29 Jun 2003 12:36:31 +0400 (MSD) Subject: XML In-Reply-To: <64A8663A-A9E9-11D7-8B63-000A95A06FC6@shangri-la.dropbear.id.au> Message-ID: On Sun, 29 Jun 2003, Stuart Bishop wrote: >On Tuesday, June 24, 2003, at 02:49 AM, Roman Suzi wrote: >> ------------------ >> foo = "123" >> bar = "456" >> zoo = "la\"lala" >> ------------------ >> >> And it's not very hard to parse that. >> 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. > >Are you just assuming this? The following works happily under >both Python2.1.3 and Python2.2.3, and probably every version >since minidom appeared. Yes, these were simple examples. But if I were into weird things I were in trouble. >XML gets pretty hairy, generally when you are trying to *do* something >hairy. If you can program Python, you probably have no need for XSLT. >DTD's and schemas are only needed if you need to validate your data. >The advantage is, that these tools and many more are available if you >*do* need them. I agree. >XML can also be dead easy if you don't get carried away. >Using a better interface than the DOM (Elementree or pyRXP) >makes it even easier, since you end up with nice pythonic >lists'n'stuff to deal with instead of having to lookup method >names like getElementsByTagName or wholeText. Currently I found a good piece of software I searched for for my document needs: docutils. It's ability to convert plain (well-reStructured) text to xhtml, latex, xml is amasing. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From cms103 at owlfish.com Mon Jun 16 19:22:55 2003 From: cms103 at owlfish.com (Colin Stewart) Date: 16 Jun 2003 16:22:55 -0700 Subject: [ANN] PubTal Version 1.0 Message-ID: <38bccbba.0306161522.242cf57e@posting.google.com> I'm pleased to announce the first release of PubTal. PubTal is a template-driven web site publisher suitable for small web sites. It uses text files as content, templates are written in TAL, and it produces static HTML files. PubTal is freely available under a BSD Style license from: http://www.owlfish.com/software/PubTal/ Colin Stewart. From ryjek at findmeifyou.can Tue Jun 24 16:51:58 2003 From: ryjek at findmeifyou.can (Ryjek) Date: Tue, 24 Jun 2003 16:51:58 -0400 Subject: Thread State and the Global Interpreter Lock In-Reply-To: <3EE15007.4DDD5B8F@engcorp.com> References: <53u1evk5jmdcgma5e8eupbe3tn45js302i@4ax.com> <7812evshjqmgm6oa14jibn9t3lc8ht5qu4@4ax.com> <3EE15007.4DDD5B8F@engcorp.com> Message-ID: <3ef8b9b2$1@news.hks.com> Peter Hansen wrote: > Afanasiy wrote: > >>On Fri, 6 Jun 2003 15:40:25 -0500, Skip Montanaro wrote: >> >> >>> >> Are there plans to make the Python interpreter "fully thread safe" in >>> >> a future version? >>> >>>In what way is it not "fully thread safe" today? >> >>http://www.python.org/doc/current/api/threads.html > > > I suspect Skip meant to elicite from you the answer to this > question: What problems have *you* encountered as a result of > the "not fully thread-safe" issue you are concerned about? I was looking for an answer to the same question and came accross this thread. Our application currently consists of two processes: one is a database and one is a windowing program with a user interface. Both embed a Python interpreter for customization purposes (i.e. you can write your own GUI extensions, and your own database procedures). I would like to merge both processes into one process with two threads (mostly for performance purposes), but keep both threads' data separated the same way as they are now. Python practically does not allow me to do it because it insists that only one thread can execute Python bytecodes at a time. I would like to be able to run both interpreters in completely separate environments, where no state and no objects are shared. I believe the restriction of "one thread at a time" is too strict in such cases. What is the purpose of Py_NewInterpreter() if you cannot run it concurrently ..? I understand that making Python completely thread safe w.respect to native threads may not be appropriate, but it shouldn't be that difficult to allow for real concurrent execution in isolated environments. At least, this is what they did in Perl: http://www.icewalkers.com/Perl/5.8.0/lib/threads.html r From duncan at NOSPAMrcp.co.uk Fri Jun 6 10:27:47 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 6 Jun 2003 14:27:47 +0000 (UTC) Subject: id(a) == id(b) and a is not b --> bug? References: Message-ID: Steve McAllister wrote in news:bbq5df$9nm$1 at alto.univ- mlv.fr: > 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? String literals are immutable. If an object is immutable there is no benefit to creating a new one each time, so the compiler may decide just to reuse an existing object. The rules for when the compiler creates a new object or just reuses an existing one are complex and vary with different versions of Python, so the only things you can safely depend on are: if two immutable objects are the same, they could have the same id. if two objects are different and have overlapping lifetimes they cannot have the same id. In particular here is an example of a situation where the actual contents of the string determine whether a new string is created or one is reused: >>> a = 'foo' >>> a is 'foo' 1 >>> a = 'foo bar' >>> a is 'foo bar' 0 >>> -- 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 tim.one at comcast.net Mon Jun 16 20:13:28 2003 From: tim.one at comcast.net (Tim Peters) Date: Mon, 16 Jun 2003 20:13:28 -0400 Subject: Possible bug in setting Windows file permissions? (os.chmod() not working properly?) In-Reply-To: <8C50918F08A109479D62BAE0F1AB9546D64640@lionking.HANA> Message-ID: [Matthew Shomphe] > Bloody hell, you're right! I didn't think that UNIX file > permission descriptions would work in Windows, but they do. Sometimes they do, and provided you stick to things that also make sense on Windows (e.g., the "execute" bit doesn't mean beans on Windows, or, in the other direction, the Windows "hidden" bit has no spelling via chmod). > Can someone make this clearer in the documentation? You're elected <0.5 wink>. Start by doing a google search on _chmod msdn The top hit will take you to MS's docs for MS's implementation of chmod (which Python calls). > It's interesting to note that '666' maps into '33206' in the > Windows file permission description. So you can (apparently), use > both values to make a file readable & writeable. One of many undocumented mysteries. This one isn't too surprising: >>> oct(33206) '0100666' >>> From adalke at mindspring.com Thu Jun 12 22:32:23 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 12 Jun 2003 20:32:23 -0600 Subject: long-term release schedule? References: <5654fff9.0306112203.6aa1ef99@posting.google.com> <5654fff9.0306121555.4c214e92@posting.google.com> Message-ID: Yan Weng > Because scientific > computing seems a strong area of python, I have this speed improvement > suggestion just to make python even stronger in this area. Just think about > reseach and applications for "online" image processing and pattern > recognition. Speed is always an important issue. Speaking as one who does scientific computing, the high-performance code is usually a small part of the code and, if needed, can easily be rewritten in C/C++/Fortran, which is quite easy given the wrapper generators available for those languages. Improving Python's performance would be nice, but it'll be a lot of work to make it comparable to any of those three languages. Andrew dalke at dalkescientific.com From duncan-news at grisby.org Sun Jun 29 15:06:17 2003 From: duncan-news at grisby.org (Duncan Grisby) Date: Sun, 29 Jun 2003 19:06:17 +0000 Subject: EuroPython Photos Message-ID: The European Python Conference was held last week. I took quite a lot of photos, which I've put on my web site here: http://www.grisby.org/Photos/140/ I've tried to label them to say who they are pictures of, but there are lots of people I don't know. If you know the names of anyone I haven't labelled, please let me know. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From max at alcyone.com Tue Jun 10 17:59:01 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 10 Jun 2003 14:59:01 -0700 Subject: Revised PEP 318 - Function/Method Decorator Syntax References: <20030610082514442-0400@braeburn.themorgue.org> Message-ID: <3EE654A5.1F158A91@alcyone.com> Chris Liechti wrote: > what's with the [] syntax discussed here a week ago? > it was something like: > > def foo(self) [synchronized(lock), classmethod]: To me it says, "Hi, I'm a list!" when listness does not seem warranted. Yes, we're talking about a sequence of properties, but the square brackets just look wrong there to me. > or merging with yours: > > def foo(self) as [synchronized(lock), classmethod]: Doubling up the syntaxes seems unnecessary. > i think the use of [] is quite logic. it's a _list_ of function > decorators. > and it helps readability, at least the variants should be listed as > alternatives in the PEP. It's a sequence. And, if you want to get technical, it's more likely to be handled as a tuple internally, anyway. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I'm spreading my wings and I fly / I'm still as the night \__/ Chante Moore From Chris.Rennert at mdi-oshkosh.com Wed Jun 25 14:12:02 2003 From: Chris.Rennert at mdi-oshkosh.com (Chris Rennert) Date: Wed, 25 Jun 2003 13:12:02 -0500 Subject: SSL in Python References: <3ef9cc58$0$837$39cecf19@news.twtelecom.net> Message-ID: <3ef9e5ac$0$838$39cecf19@news.twtelecom.net> Thanks, I am on my way there now. Again thank you for the quick reply Chris "Jp Calderone" wrote in message news:mailman.1056561529.27235.python-list at python.org... > On Wed, Jun 25, 2003 at 11:23:57AM -0500, Chris Rennert wrote: > > I noticed in the documentation that they have ssl() in Python, but it says > > only if configured. I just can't find info on how to configure SSL in > > Python. My goal is to write a simple p-2-p chat, but have all info > > encrypted between clients. Any help you could give me would be greatly > > appreciated! > > Python's built-in SSL support only works for clients, not servers. > Several third party modules exist to provide server support, PyOpenSSL my > personal favorite. The gory details of this (and other networking issues) > are dealt with by Twisted: http://www.twistedmatrix.com/. > > 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 jdhunter at ace.bsd.uchicago.edu Wed Jun 18 23:41:12 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 18 Jun 2003 22:41:12 -0500 Subject: parsing complex web pages In-Reply-To: <873ci7x80p.fsf@pobox.com> (jjl@pobox.com's message of "19 Jun 2003 00:47:50 +0100") References: <873ci7x80p.fsf@pobox.com> Message-ID: >>>>> "John" == John J Lee writes: John> If it works well for you, why not stick with it? It does work well -- today I parsed about 1000 tickers worth of pages w/o error. The main reason I was interested in a python solution is if I ever decide to release my Yahoo.Finance modules. I have done several of yahoo's pages now (research, profile, historical) and I figure others may find this useful someday. I would rather send them out as pure python than as 'requires lynx'. This isn't too big a deal, though, since lynx runs on a lot of platforms. 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. John Hunter From leo.broska at NOSPAM.isys.com.au Mon Jun 2 19:43:09 2003 From: leo.broska at NOSPAM.isys.com.au (Leo) Date: Tue, 3 Jun 2003 09:43:09 +1000 Subject: python IDLE on win2000 doesn't startup References: <3edb6252$0$54846$a726171b@news.hal-pc.org> Message-ID: "Joe Gwozdecki" wrote in message news:3edb6252$0$54846$a726171b at news.hal-pc.org... > > "Leo" wrote in message news:bbf7r6$27sm$1 at otis.netspace.net.au... > ... > > i have downloaded python 2.2.2 for win. > > > > now i try to start the idle. it doesn't work: no screen, no > > msg. :-( > > Go to Start, then programs, then python 2.2. You will see > python 2.2 IDLE gui. Put your cursor on it and click right > button and send it to your desktop. Go to desktop and > double click on it. It will start right up. You could also > double click on it, right where you found it. sorry does not work! after doubleclicken i get an hourglass for a sec then i'm back in the desktop without any newly started application. a bit desperate, leooo From guettler at thomas-guettler.de Mon Jun 16 10:55:21 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Mon, 16 Jun 2003 16:55:21 +0200 Subject: Big dictionary manipulation References: Message-ID: Pawel Lewicki wrote: > Hello, > I have a question about the strategy of manipulating of big dictionaries. > I build the tree-type dynamic structure of dictionaries. Something like > dict={k_1:{k_11:[l_11, l_12]}, k_12:[l_21, l_22], k2:...} > Until now I was converting it to the list [k_1, [k_11, [l_11,l_12]]...] to > set and keep the sequence. > The final amount of data sometimes is really big and deep so I guess that > conversion is unnecessary waste of time. Maybe I should just add indexes - > lists of keys to iterate. > My question is if there is any kind of bottleneck in passing that > structure? Is it a reference so no additional memory is consumed? > That data would be passed from Zope product to ZPT page if it has any > meaning. Hi Pawel! Objects are passed by reference in python. You only get problems if your structure is bigger than your physical memory. If that's the case, you can have a look at BTrees. Unfortunately it is not clear for me why you convert the dictionary to a list. thomas From richardd at hmgcc.gov.uk Mon Jun 2 06:01:55 2003 From: richardd at hmgcc.gov.uk (Richard) Date: Mon, 2 Jun 2003 11:01:55 +0100 Subject: Listing only directories? Message-ID: <3edb2094$1@mail.hmgcc.gov.uk> Hi, I am using os.listdir(root) to get a file and directory listing of the 'root' directory. However I am trying to filter out only the directories in this listing. I have tried the following (after reading up in the manual): def listDirectories(root): [f for f in os.listdir(root) if os.path.isdir(f)] return f but this doesn't seem to do what I want it to, only seeming to return the name of one of the directories it finds. Can anyone tell me what I am doing wrong, and if I'm barking up completely the wrong tree? Cheers Richard D From sross at connectmail.carleton.ca Sat Jun 28 22:54:39 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sat, 28 Jun 2003 22:54:39 -0400 Subject: code suite as first class object ? References: Message-ID: I've been thinking about something like this (though not exactly) for the last few weeks. I did a post ("PEP318 - property as decoration"), where (amongst other things) I suggested it would be possible to define properties cleanly using blocks and/or thunks. This idea was based on a discussion from python-dev in January/February ("Extended Function Syntax"). Blocks and thunks (as I saw them) seemed powerful. The way I was thinking about them, it looked like it might be possible to define anonymous functions, and even anonymous classes. From there, I began toying with a language design that focused on trying to use only namespaces, bindings, generators, blocks and thunks (oh, and numbers and strings and lists, etc). I haven't quite worked out the kinks, but it looks something like Smalltalk with bits and pieces of Icon, Ruby, and Python thrown in. The idea I was trying to work out was "If Python were to add thunks (as I pictured them), how could that affect the language? What sorts of things could I expect to see people trying with their code?". In other words, "How bad could it get?". Here's an example: MyClass = object with: "MyClass = object(thunk), where object returns a class defined using thunk" __init__ = method with self, foo: "__init__ = method(thunk), where method returns a method defined using thunk" self._foo = foo foo = property with: "property foo's docstring" fget = with self: return self._foo fset = with self, value: self._foo = value bar = static, method with: "bar = static(method(thunk))" 1.upto(10) do with i: print "upto() yeilds %d which is passed to the thunk. The thunk is passed to do (do(thunk)) ", \ "where it gets executed, and so you see this!" % i So, the language I was working out was not Python as it is now, but as it might become should something like blocks and thunks be added. I don't find the language terrible, but I also don't find it to be Python - and that's my point, I suppose. I like the idea of blocks and thunks and anonymous functions, classes, etc., but I don't like the idea that there could be more than one way to define a function, method, or class. If you read the python-dev discussions, the ideas presented for thunks appear to enable macro programming as well. For instance, using Guido's definition of thunks he was able to construct a switch statement, but not like yours, like this: [Guido] > > switch(expr): > > case(val1): > > block1 > > case(val2): > > block2 > > default: > > block3 > > To which he added: > > This actually makes me worry -- I didn't plan thunks to be the answer > > to all problems. A new idea that could cause a paradigm landslide is > > not necessarily right. A statement I'd have to say I agree with. From lale at fotonation.com Thu Jun 5 05:59:47 2003 From: lale at fotonation.com (Ilariu Raducan) Date: Thu, 05 Jun 2003 10:59:47 +0100 Subject: PythonWin menu In-Reply-To: References: Message-ID: I found the tool menu of PythonWin IDE in a very unusual place: pywin.mfc.docview.DocTemplate._SetupSharedMenu_ It seems to work if I overwrite that method for every document template Thank you, Lale Mark Hammond wrote: > Ilariu Raducan wrote: > >> Hi All, >> >> Using pythonwin as the framework for an application, at init time I >> create some menu entries. >> Every time a document is focused (a MDIChild frame) the menu is >> replaced with the menu of that document(in my case the standard text >> document and Tools menu of the PythonWin IDE. >> >> How can I display only my menus? >> Is it possible to have some menus displayed all the time, for each >> document type? > > > You are really going to need to dig into the Pythonwin sources to track > this down, and see what is available. All this functionality should be > in .py files in the pywin tree. A number of products have created > applications with completely custom frames and menus, so it can be done. > > Mark. > From MatthewS at HeyAnita.com Thu Jun 19 11:40:53 2003 From: MatthewS at HeyAnita.com (Matt Shomphe) Date: 19 Jun 2003 08:40:53 -0700 Subject: Algorithm help per favore References: <2ec1bc1c.0306180746.159679d6@posting.google.com> <5ab0af73.0306181828.512d5b00@posting.google.com> <3EF12866.CE8C3913@alcyone.com> Message-ID: <5ab0af73.0306190740.49202cb3@posting.google.com> Erik Max Francis wrote in message news:<3EF12866.CE8C3913 at alcyone.com>... [snip] > > This contains a particularly subtle bug lurking for user-defined > sequence types which don't support the negative indices protocol. A > much more solid solution, in my opinion, would be to test the index > _first_ and then test the subscripted value second: That's something I did not consider (although in my defense, the original poster was talking about iterating over a list:-) ). > > >>> l = [6, 3, 3, 3, 5, 7, 6, 3, 4, 4, 3] > >>> [x for i, x in enumerate(l) if i == 0 or l[i - 1] != x] > [6, 3, 5, 7, 6, 3, 4, 3] > [snip] > > In general practices, it's a good idea to test the more stringent > condition first, before the second one, when you have short circuiting > logical operators like you do in Python (and most other modern > languages). I agree, and would have done short-circuting except that I didn't think that Python had this feature. A quick test showed me that I was wrong. I wanted to change the solution anyway, since not everyone has enumerate(). Although for this solution, the iterable object needs to have __len__ defined: >>> l = [6,3,3,4,5,6,7,7,7,8,8,9] >>> [l[i] for i in xrange(len(l)) if i == 0 or l[i] != l[i-1]] [6, 3, 4, 5, 6, 7, 8, 9] Then, modifying your Range class: >>> class Range: def __init__(self, n): self.n = n def __getitem__(self, i): if 0 <= i < self.n: return i else: raise IndexError def __len__(self): return(self.n) >>> l = Range(10) >>> [l[i] for i in xrange(len(l)) if i == 0 or l[i] != l[i-1]] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] I think this may be faster than calling enumerate() repeatedly. From mike at bindkey.com Wed Jun 11 19:31:29 2003 From: mike at bindkey.com (Mike Rovner) Date: Wed, 11 Jun 2003 16:31:29 -0700 Subject: vector subscripts in Python? References: <3064b51d.0306111512.7701dbbc@posting.google.com> Message-ID: wrote in message > Does Python have the equivalent of "vector subscripts" of Fortran 95? Not directly. > ii = [0,2] > xx = [1,4,9] > print subscript(xx,ii) # returns [1, 9]; in F95, "print*,xx(ii)" is analogous print [x[i] for i in ii] WBR, Mike From http Mon Jun 2 09:35:21 2003 From: http (Paul Rubin) Date: 02 Jun 2003 06:35:21 -0700 Subject: CGI question: safe passwords possible? References: <7xwug82ag0.fsf@ruckus.brouhaha.com> <3EDB4CC2.B34F910C@engcorp.com> Message-ID: <7xhe784n6u.fsf@ruckus.brouhaha.com> Peter Hansen writes: > Doesn't this implementation also suffer from requiring the server > side to store the password somewhere effectively in the clear? Yes. > (Paul, I don't understand why you did a double hash above, since it > doesn't seem to add any extra value over a single one, in this case.) It's similar to HMAC, it avoids some possible attacks on the hash function. Probably not needed in this case. > 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... From guettler at thomas-guettler.de Fri Jun 6 10:19:02 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Fri, 06 Jun 2003 16:19:02 +0200 Subject: diff --brief Message-ID: Hi! I need a method like diff --brief which tells my wether two files differ. I looked at filecmp.cmp(), but this does not seem to do what I want. I did it like this, but I would prefere to use a function from the library (if there is such a function) def diff(file1, file2): """ returns 1 if the content of both files are different returns 0 if all bytes are equal. """ fd1=open(file1) fd2=open(file2) while 1: chunk1=fd1.read(1024) chunk2=fd2.read(1024) if not chunk1: if chunk2: return 1 else: break if chunk1!=chunk2: return 1 return 0 From domma at procoders.net Fri Jun 20 03:44:15 2003 From: domma at procoders.net (Achim Domma) Date: Fri, 20 Jun 2003 09:44:15 +0200 Subject: bug in urllib2/python23 ? Message-ID: Hi, the following lines import urllib2 urllib2.urlopen('http://fr.allafrica.com/health/newswire') produce the following backtrace on my computer: File "D:\Python23\lib\urllib2.py", line 136, in urlopen return _opener.open(url, data) File "D:\Python23\lib\urllib2.py", line 330, in open '_open', req) File "D:\Python23\lib\urllib2.py", line 309, in _call_chain result = func(*args) File "D:\Python23\lib\urllib2.py", line 824, in http_open return self.do_open(httplib.HTTP, req) File "D:\Python23\lib\urllib2.py", line 818, in do_open return self.parent.error('http', req, fp, code, msg, hdrs) File "D:\Python23\lib\urllib2.py", line 350, in error result = self._call_chain(*args) File "D:\Python23\lib\urllib2.py", line 309, in _call_chain result = func(*args) File "D:\Python23\lib\urllib2.py", line 447, in http_error_302 new = self.redirect_request(req, fp, code, msg, headers) File "D:\Python23\lib\urllib2.py", line 421, in redirect_request if (code in (301, 302, 303, 307) and req.method() in ("GET", "HEAD") or File "D:\Python23\lib\urllib2.py", line 208, in __getattr__ raise AttributeError, attr AttributeError: method If I add a trailing slash to the url, everything works fine. Looks like a bug to me!? Or is there a reason for this behaviour? If yes, how could I decide wether I have to add a slash or not? regards, Achim From daniel.neugebauer at gmx.de Fri Jun 6 19:03:52 2003 From: daniel.neugebauer at gmx.de (Daniel Neugebauer) Date: Sat, 07 Jun 2003 01:03:52 +0200 Subject: popen with linux: permission denied Message-ID: Hi! I don't actually know if this is the right group to ask in but I was writing on a brief python script when the following error occured: I execute my script using Apache, so it can give me a HTML site in a browser. This worked just fine until I tried to popen another Python script. No matter which user owns that file or has privileges to access/execute it on the shell, I am unable to launch it from my script. If I enter another command it works fine - it just seems to dislike my script. As I'm a newbie to Python it would be great if someone were able to give some advice. Thanks, Daniel From pxtl at hotmail.com Wed Jun 18 11:30:37 2003 From: pxtl at hotmail.com (martin z) Date: Wed, 18 Jun 2003 15:30:37 GMT Subject: How to permanently remove __import__? References: <3EEF8C0C.23E93E18@engcorp.com> <3EEF970C.4630A21@engcorp.com> <3EF08043.F5692E2F@engcorp.com> Message-ID: > If you do the custom interpreter you might be able to make fewer > changes, and be confident of much greater security, than if you > try to put all the restrictions in from a higher level. Just a > thought... A custom interpreter would be ideal if it weren't for three things: first, I've looked at the code for Python's filesystem functions. They were not meant to be human-readable except possibly to Guido himself. Playing with them would be less than fun. Second, when newer versions of Python become available I don't want to have to recode the whole anti-filesystem component. Third: it would just be nicer if I could work within the existing Python framework. I don't suppose there's a compiler variable for "no filesystem" eh? From staschuk at telusplanet.net Wed Jun 11 13:53:44 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 11 Jun 2003 11:53:44 -0600 Subject: unittest: Dynamically creating tests In-Reply-To: ; from jerf@jerf.org on Wed, Jun 11, 2003 at 03:37:42AM +0000 References: Message-ID: <20030611115344.E1157@tibia.amotlpaa.bogus> Quoth Jeremy Bowers: [...] > 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? It's possible to arrange your test classes in such a way that unittest.main would pick them up, but it might be more informative to see how such test classes could be created and used "by hand": import unittest def testcasefor(i): class MyTest(unittest.TestCase): def testMultiplication(self): self.assertEquals(3*i, i+i+i) def testNegation(self): self.assertEquals(0, i + -i) return MyTest def testsuite(): suite = unittest.TestSuite() for i in range(5) + ['foo']: testcase = testcasefor(i) tests = unittest.defaultTestLoader.loadTestsFromTestCase(testcase) suite.addTest(tests) return suite if __name__ == '__main__': runner = unittest.TextTestRunner() runner.run(testsuite()) Note the call to loadTestsFromTestCase. This creates a suite containing two instances of MyTest, one for testMultiplication and one for testNegation. (Which test method is used in a given instance is specified by passing its name to TestCase.__init__. Your exception above is due to instantiating a TestCase yourself without that argument.) Note also how to run a TestSuite object "by hand" by using a TestRunner. Normally you don't have to worry about any of this, because unittest.main does all of it for you. One problem with the above code (as you'll see if you run it and look at the test failure) is that the error message is less than adequate -- it doesn't say which value of i was being used in the test which failed. One possible remedy is to extend TestCase.__str__(): class MyTest(unittest.TestCase): # ... def __str__(self): return '%s (i = %r)' % (unittest.TestCase.__str__(self), i) A similar thing could be done in shortDescription instead, or in addition. > (On a side note, is there a way to programmatically add something to the > *current* module, while it's being created? [...] The module object already exists by the time the code is executed; you just have to get ahold of it. One method: import sys setattr(sys.modules[__name__], 'foo', 'bar') Or, if you don't mind hardcoding the name of your module, import mymodule setattr(mymodule, 'foo', 'bar') (Recursive import doesn't recurse infinitely.) There's also globals()['foo'] = 'bar' and, of course, exec. [...] -- Steven Taschuk o- @ staschuk at telusplanet.net 7O ) " ( From afriere at yahoo.co.uk Mon Jun 2 01:47:51 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 1 Jun 2003 22:47:51 -0700 Subject: Python IO performance? References: Message-ID: <38ec68a6.0306012147.1ae26ac5@posting.google.com> Ganesan R wrote in message news:... > I agree that this case favors perl. It's just that I am used to writing > quick hacks like this for text processing in perl. After learning python > I've been resisting my impulse to code them in perl and use python > instead. Why?! For quick hacks and simple text processing I still reach for Perl, especially if the task involves regexps. This is where Perl shines, after all. On the other hand if the problem suggests an OO solution, or even the use slightly complex data structures, Perl doesn't get a look in. Hell I've even used Perl to generate some repetitive Python code! I think this Perl vs Python loyalty bit is just a little silly, you know horses for courses and all. Besides, it doesn't hurt to do just a little bit of coding in some of the other languages within your repetoire so that you don't find yourself thinking, (as I have done on occasion), hmm now does the tilde come before the equals sign or after it ... From theller at python.net Tue Jun 3 11:04:04 2003 From: theller at python.net (Thomas Heller) Date: 03 Jun 2003 17:04:04 +0200 Subject: pychecker checks files by executing them ?? References: <3EDCB6BF.1090909@molgen.mpg.de> Message-ID: Axel Kowald writes: > Hi, > > I got pychecker and installed it on my w2k machine as described. It > also seems to work, but when I do: > > pychecker myFile.py it actually "executes" myFile.py, while > checking it. Is this the correct behaviour?? > > Obviously I would like to check my scripts without executing them. Any > idea what's going on ? > pychecker imports them, not executes them. Protect the main function or what it is in your case by the usual 'if __name__ == "__main__":' idiom (which you should do anyway IMO), and you are fine. Thomas From alienoid at is.lg.ua Tue Jun 3 06:18:01 2003 From: alienoid at is.lg.ua (Ruslan Spivak) Date: Tue, 03 Jun 2003 13:18:01 +0300 Subject: os.system question Message-ID: <3EDC75D9.4060409@is.lg.ua> Hello, python users! I need to get result from 'ping' command(in manpage they are 0, 1, 2), but when i execute the following lines i i get strange results: import os res = os.system("ping -w 3 192.168.1.1") print res This gives 256 or another numbers, what am i doing wrong? Your help is very, very appreciated. Best regards, Ruslan From mertz at gnosis.cx Sat Jun 7 13:58:59 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sat, 07 Jun 2003 13:58:59 -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: |David> I tend towards polysyllabic--sometimes even |David> polyglottal--neologistic agglutinations. Dave Cole wrote previously: |A more accurate word might be "sesquipedalia". :-) I think you need one more letter: sesquipedalian. But I think that lovely word slightly misses the part about neologistic agglutination. The words aren't just long, they're novel in predicatable ways too. -- 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 milf at tendoworld.com Thu Jun 26 10:37:29 2003 From: milf at tendoworld.com (MiLF) Date: Thu, 26 Jun 2003 22:37:29 +0800 Subject: Is it possible to write a Audio CD Player by using python only? References: <3EFAFAAA.8D629F66@engcorp.com> Message-ID: Well, I just install Python 2.2.3 and Mark Hammond's Python Extensions on my w2k, I want to write a cross-plateform audio CD player. Is it enough to write a Audio CD player? "Peter Hansen" ????? news:3EFAFAAA.8D629F66 at engcorp.com... > MiLF wrote: > > > > Is it possible to write a Audio CD Player by using python only? > > Do you mean using pure Python code, or do you mean using libraries > which have Python wrappers, such that any code *you* write is indeed > Python? > > There are various libraries, perhaps most importantly http://pygame.org/ > which allow you to access various multimedia capabilities. > > You may also want to look for existing solutions, and if you need > to ask more, at least specify your platform... > > -Peter From staschuk at telusplanet.net Thu Jun 12 19:18:00 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 12 Jun 2003 17:18:00 -0600 Subject: Revised PEP 318 - Function/Method Decorator Syntax In-Reply-To: <2259b0e2.0306120901.2a535e6@posting.google.com>; from mis6@pitt.edu on Thu, Jun 12, 2003 at 10:01:17AM -0700 References: <20030610082514442-0400@braeburn.themorgue.org> <2259b0e2.0306110926.27c4412b@posting.google.com> <2259b0e2.0306120901.2a535e6@posting.google.com> Message-ID: <20030612171800.A2488@tibia.amotlpaa.bogus> Quoth Michele Simionato: > Steven Taschuk wrote: [...] > > What if we thought of these > > things as descriptor decorators instead of function decorators? [...] > I see your point. Still, multiple inheritance would seem more consistent > to me, [...] ... achieving the chaining with a cooperative __get__? You're right, that seems quite natural. > [...] and also would be more natural when extending the notation to classes > i.e. > > class C[Traced,Protected]: pass > > would have a metaclass inherited from Traced and Protected. I'd be against such a syntax, fwiw. Too easy to mistake for the normal subclass syntax. (Wouldn't be a big deal if one were trained to notice the difference by frequent use of metaclasses; but few users would be.) -- 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 joconnor at nets.com Wed Jun 4 10:45:44 2003 From: joconnor at nets.com (Jay O'Connor) Date: Wed, 04 Jun 2003 07:45:44 -0700 Subject: Not getting all keys in FieldStorage (Multipart form data) References: <3EDDDF00.3070104@mxm.dk> <3EDDF63D.88366C54@hotmail.com> Message-ID: <20030604.074543.1789366143.30733@nets.com> In article <3EDDF63D.88366C54 at hotmail.com>, "Alan Kennedy" wrote: > Max M wrote: > >> Here you are mixing stuff: >> >> action="%s/admin/additem.py?bookid=%s&image=yes" >> >> you should not pass parameters as part of the action. Do it as a hidden >> field instead. > >> I think it is undefined what happens in this case. Most likely the >> browser ignores the parameteres in your action, and just add those from >> the form itself. >> >> Anyway it isn't legal. > > I don't think the specs specify either legality or illegality. On > reading the (supposedly) definitive section of the HTML 4.01 spec on > form submission, > > http://www.w3.org/TR/html401/interact/forms.html#submit-format > > it says: > > "The action attribute may take two values: > > o get: With the HTTP "get" method, the form data set is appended to the > URI > specified by the action attribute (with a question-mark ("?") as > separator) and this new URI is sent to the processing agent. > o post: With the HTTP "post" method, the form data set is included in > the body > of the form and sent to the processing agent." FWIW, I've seen problems that web servers sometimes have a limit on the length of the URL they will accept. I found this out accidentally when I left "method=POST" off of a form so it tried to send it as a GET and there was too much data on the line. -- Jay O'Connor http://www.r4h-music.com "God Himself plays the bass strings first, when He tunes the soul" From achrist at easystreet.com Sun Jun 15 00:31:00 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Sat, 14 Jun 2003 21:31:00 -0700 Subject: Saving Files Under Windows References: <3EE993CB.F2CE7D39@easystreet.com> <8360efcd.0306130530.281ff230@posting.google.com> Message-ID: <3EEBF684.8C09F4B7@easystreet.com> I've got similar trouble with my WinNT machine, which is why I won't default to put data into the folders that MS sets up on C: if the OS is old. My drive is aN ibm 20 Gb, but the BIOS can't handle a partition bigger than 8 Gb, so it's divided into drives C:, D:, I:, and J:, using special software from IBM. This special software will make the C: drive any size that you want, as long as you want it to be exactly 2 Gb. Since MS automatically puts all kinds of things useful and otherwise on C:, I don't have space there for anything that I can put anywhere else. I guess that with new systems you are supposed to be happy with huge folders of programs and data on C:. IDK. Al Dennis Lee Bieber wrote: > > Tim Golden fed this fish to the penguins on Friday 13 June 2003 06:30 > am: > > > > > Not necessarily a complete answer. I don't believe there are any > > "rules", in Python or otherwise. However, Microsoft would rather like > > you to save things in "My Documents", "My Pictures", "My Rubbish Bin" > > and so on, and the easiest way to find them is discussed in the above > > thread (and a few others if you care to Google back through this > > newsgroup). > > > Which I consider a pain -- It wouldn't be so bad if M$ had the > foresight to mandate that those (what I consider "dynamic" directories) > were automatically placed on a separate PARTITION, so that run-away > data files don't kill what I consider a "system software" (static) > partition. > > I'm still configuring my new laptop -- doing a full backup with 3rd > party installed software first, THEN I'm going to risk Partition Magic > on it to create my "data" partition. Will still take some time to get > all the applications configured. Is there some easy way to define M$'s > "My " to use a separate partition? From gus.tabares at verizon.net Sat Jun 14 00:24:29 2003 From: gus.tabares at verizon.net (Gus Tabares) Date: Sat, 14 Jun 2003 00:24:29 -0400 Subject: why does python execute line bye line as im coding????????? In-Reply-To: <20030613235210.11559.00000446@mb-m13.aol.com> Message-ID: Unless you have some sort of name function you are not showing, this will never work. Try something like this: name = raw_input("What's your name? ") print "Hello", name HTH, Gus -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org]On Behalf Of L48R4T Sent: Friday, June 13, 2003 11:52 PM To: python-list at python.org Subject: why does python execute line bye line as im coding????????? 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 simon -- http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Thu Jun 26 13:27:51 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 26 Jun 2003 13:27:51 -0400 Subject: Something strange with python 2.2.1 under RedHat 8.0 References: Message-ID: <3EFB2D17.AEFF206F@engcorp.com> Richard Kuhns wrote: > > Python 2.2.1 (#1, Aug 30 2002, 12:15:30) > [GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import os > >>> for k in os.environ: > ... print k > ... > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/UserDict.py", line 14, in __getitem__ > def __getitem__(self, key): return self.data[key] > KeyError: 0 Judging by the error message, os.environ is *not* a dict, but a UserDict. If it were to be subclassed from IterableUserDict instead, it would work okay I guess. Checking Python 2.2.2, I find it *is* now subclassed from IterableUserDict, so you're reporting a bug that is fixed in a later release. Please upgrade. I'd check the bug tracker on SourceForge, but I am rarely able to use that pathetic piece of crap successfully to search for already-reported bugs, so I'll just skip it... :-) -Peter From paul at fxtech.com Thu Jun 19 15:47:22 2003 From: paul at fxtech.com (Paul Miller) Date: Thu, 19 Jun 2003 14:47:22 -0500 Subject: Python database integration with FileMaker on Macintosh? Message-ID: Anyone gotten this to work? Have any pointers? From alf at fayauffre.org Wed Jun 18 11:35:55 2003 From: alf at fayauffre.org (Alexandre Fayolle) Date: Wed, 18 Jun 2003 15:35:55 +0000 (UTC) Subject: [ANN] AOP package aspects-0.1.2 Message-ID: What's new? ------------ 2003-06-18 -- 0.1.2 * first public release What is logilab.aspects? ------------------------ logilab.aspects is a python package that enables Aspect Oriented Programming in Python. For now, it provides a set of ready-to-use aspects, and an easy way to create your own aspects. The current possibilities are still a bit limited, but it will soon provide a more exhaustive way to define and use more complex aspects. The aspects module contains some useful aspects such as: * LoggerAspect: trace all method calls. * ContractAspect: contracts can be seen as a sub-part of aspects, and this particular aspect will allow you to use contracts in Python. We have choosen to consider contracts definitions as a part of documentation. The conditions are thus specified in method and modules docstrings. * ProfilerAspect: simple method profiler * DispatcherAspect: enable multimethods * ConfirmationAspect: ask confirmation before an operation * ObserverAspect: aspect implementation of the Observer Design Pattern Home page --------- http://www.logilab.org/aspects/ Download -------- ftp://ftp.logilab.org/pub/aspects/ Mailing list ------------ mailto://python-projects at lists.logilab.org (you'll need to subscribe first on http://lists.logilab.org/mailman/listinfo/python-projects) -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org D?veloppement logiciel avanc? - Intelligence Artificielle - Formations From brian_l at yahoo.com Thu Jun 26 05:34:09 2003 From: brian_l at yahoo.com (Brian Lenihan) Date: 26 Jun 2003 02:34:09 -0700 Subject: shebang strange thing... References: <3EF3A07B.A683F94F@alcyone.com> <3EF7A121.7B4C3775@alcyone.com> <85el1hpz0c.fsf@stowers-institute.org> Message-ID: Michael Coleman wrote in message news:<85el1hpz0c.fsf at stowers-institute.org>... > brian_l at yahoo.com (Brian Lenihan) writes: > > If you have two or more Python installations, the first one in > > your path gets invoked no matter what the shebang line says. > > > > If the first line of a script is #!/usr/local/bin/python, I expect the > > interpreter located in /usr/local/bin to execute the script, not the > > one in /usr/bin, or the one in /sw/bin, but that is what you get if > > you run the script as an executable. > > > > The process list shows why - python is called without a path, e.g. as > > "python". The same behavior occurs if the shell is bash or tcsh. > > As far as I know, OS X is the only "modern" Unix to behave this way. > > Tru64 (5.1) also shows this behavior (which recently bit me too), but > it's arguably a bug in Python rather than in the OS. If you look > carefully, I think you'll find that the correct binary (e.g., > /usr/local/bin/python) is in fact being invoked, but that that binary > then uses the libraries associated with the first python in your PATH. > The reason this is happening is that python determines where all of > its libraries live by examining argv[0], if a more suitable method is > not available. If this gives the full path, everything is fine, but > if only the basename is given ("python"), then the startup code walks > to the PATH to guess. As you've noticed, in some cases, this guess is > wrong. I never use True64, but my company does, so I'm glad you identified the same problem on that platform. argv[0] should contain the full path to the interpreter and it does not, which makes me believe this is an OS error, not a Python error, except you could argue that relying on argv is not a platform independent way to find the correct path. If I could get the Panther install CD to boot on my PowerBook, I could see if this is still going to be a problem in the future. From wrbt at email.com Wed Jun 18 11:46:05 2003 From: wrbt at email.com (Larry) Date: 18 Jun 2003 08:46:05 -0700 Subject: Algorithm help per favore Message-ID: <2ec1bc1c.0306180746.159679d6@posting.google.com> 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. From skip at pobox.com Tue Jun 3 11:19:29 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 3 Jun 2003 10:19:29 -0500 Subject: Buid error on Python 2.1.3 for Solaris 8 In-Reply-To: References: Message-ID: <16092.48257.276750.103274@montanaro.dyndns.org> Francis> After ./configure and make there is an error Francis> rm -f libpython2.1.a Francis> ar cr libpython2.1.a Modules/getbuildinfo.o Francis> sh ar: not found Francis> *** Error code 1 Francis> make: Fatal error: Command failed for target 'libpython2.1.a' Francis> What's wrong? Make sure /usr/ccs/bin is in your PATH. That's where Sun keeps auxiliary programming tools like ar. Skip From kowald at molgen.mpg.de Tue Jun 3 10:54:55 2003 From: kowald at molgen.mpg.de (Axel Kowald) Date: Tue, 03 Jun 2003 16:54:55 +0200 Subject: pychecker checks files by executing them ?? Message-ID: <3EDCB6BF.1090909@molgen.mpg.de> Hi, I got pychecker and installed it on my w2k machine as described. It also seems to work, but when I do: pychecker myFile.py it actually "executes" myFile.py, while checking it. Is this the correct behaviour?? Obviously I would like to check my scripts without executing them. Any idea what's going on ? Many thanks, Axel From evan at 4-am.com Mon Jun 16 16:16:03 2003 From: evan at 4-am.com (Evan Simpson) Date: Mon, 16 Jun 2003 15:16:03 -0500 Subject: Looking for a (very) small http proxy in Python In-Reply-To: <3eee1c7b$0$5407$626a54ce@news.free.fr> References: <3eee1c7b$0$5407$626a54ce@news.free.fr> Message-ID: <3EEE2583.2070800@4-am.com> adfgvx wrote: > I am looking for a little script in Python that acts as a proxy. I only need > to write in a file all the headers of the http requests and of the answers. http://hathaway.freezope.org/Software/TCPWatch Cheers, Evan @ 4-am From dtrahan at cfl.rr.com Thu Jun 5 00:55:41 2003 From: dtrahan at cfl.rr.com (Jack Daniel) Date: Thu, 05 Jun 2003 04:55:41 GMT Subject: girl scout badge References: Message-ID: http://www.python.org and start reading... From zephyr01 at alltel.net Fri Jun 20 19:02:37 2003 From: zephyr01 at alltel.net (Hans Nowak) Date: Fri, 20 Jun 2003 19:02:37 -0400 Subject: os.listdir() In-Reply-To: References: Message-ID: <3EF3928D.7050002@alltel.net> manuel wrote: >>If you can't "import os" in Blender, something is wrong... > > > I can, but I have full python installed. > Many users have only Blender and Python22.dll; > this mean they don't have the os.py... :-( > > A simple listdir in python isn't possible? This might work: import the nt module (it's built-in), then use nt.listdir. From tjreedy at udel.edu Fri Jun 20 12:04:32 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 20 Jun 2003 12:04:32 -0400 Subject: Multiple string.replace in one run References: Message-ID: <7wadnTKgcusNrW6jXTWJjg@comcast.com> "Thomas G?ttler" wrote in message news:bcuqfh$nbvnm$1 at ID-63505.news.dfncis.de... > How can I replace several variables at once? I remember there being a substantial thread on this question within the past year. Perhaps Google can help. TJR From theller at python.net Fri Jun 20 11:02:16 2003 From: theller at python.net (Thomas Heller) Date: Fri, 20 Jun 2003 17:02:16 +0200 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> Message-ID: David Abrahams writes: > Has someone really straightened out the situation with Python > debuggers? Last time I looked there was no JIT debugging, You can install an except hook which throws you into a debugger when an uncatched exception is raised, see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65287 > and no way > to set a conditional breakpoint in a long-running test without waiting > forever as Python calls the debugger hook on every instruction (or > statement, I forget). Hm, you can simply insert 'import pdb; pdb.set_trace()' into the code. No overhead. Thomas From jarausch at skynet.be Sun Jun 8 16:48:00 2003 From: jarausch at skynet.be (Helmut Jarausch) Date: Sun, 08 Jun 2003 22:48:00 +0200 Subject: compile cvs version with icc - howto Message-ID: <3ee3a100$0$279$ba620e4c@reader0.news.skynet.be> Hi, has anybody successfully compiled the current cvs version with Intel's icc compiler? I had no lock with the following configure statement CC=icc CPP=icc CFLAGS='-O3 -march=pentiumiii -tpp6 -axiMK -ip' \ CXXFLAGS='-O3 -march=pentiumiii -tpp6 -axiMK -ip' \ configure --prefix=/usr/local \ --with-cxx=icc --without-gcc --with-signal-modules --with-threads \ --with-pymalloc --with-fpectl since some tests within configure do not work with icc e.g. icc -v For my book site (http://gnosis.cx/TPiP/), I used a Perl script that my host happened to have installed to let readers contribute suggestions, post errata, etc. (Matt Wright's WWWBoard). However, now that the book is out, I think I can clear out the earlier comments (I'll save them somewhere, but they are less relevant). And this also seems like a good time to move to a Python solution (it -is- after all attached to a book about Python). My main goal here is that I want to think about administering the discussion board AS LITTLE AS POSSIBLE. I don't really care about elaborate configurability, or multiple forums, or complex sorting on criteria. Just something where viewers can post simple comments, and see what other wrote.... Oh, and something where it is really easy to remove the posts from spammers who occassionally find the board and post weird ads (I always seem to mess up the formatting when I delete them from the HTML file in vim; but partially because of the slightly cluttered HTML format used [lots of comments indicating where insertions go]). I know I could write something that showed off fabulous Python programming principles. But I don't want to do that now... I'd like my whole effort to consist of: % wget ftp://some.path.to/fooboard.tgz % tar xvfz fooboard.tgz % python2.3 setup.py install Beyond that, I have to start thinking... yeack! It does, however, have to be able to work with plain CGI, no custom Twisted or Zope server, nor even fast_cgi (actually, that might be on the host, but I haven't looked into it).. -- 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 gumuz at looze.net Thu Jun 19 05:33:26 2003 From: gumuz at looze.net (Guyon Morée) Date: Thu, 19 Jun 2003 11:33:26 +0200 Subject: Anyone using Venster? Message-ID: <3ef182ca$0$13798$4d4ebb8e@news.nl.uu.net> Recently I discovered the 'Venster' package at http://venster.sf.net/ I really like the idea of using this instead of the pywin/mfc stuff. The only problem is that there is almost no documentation and I can not find anything on the web/newsgroup about it. So i was wondering if anyone's using this and likes to share some code. cheers, guyon From r.shaffer9 at verizon.net Sun Jun 15 19:59:10 2003 From: r.shaffer9 at verizon.net (Robert S Shaffer) Date: Sun, 15 Jun 2003 23:59:10 GMT Subject: Large File Parsing Message-ID: I have upto a 3 million record file to parse, remove duplicates and sort by size then numeric value. Is this the best way to do this in python. The key is the first column and the ,xx needs removed. 1234567,12 123456789012,12 import os import string def filesort( input1,input2 ): if (len (input1) > len( input2 )): return 1 if (len (input1) < len( input2 )): return -1 return cmp(input1,input2) def run(): lines = open('input.dat').readlines() oufile = open ( 'output.dat' , 'w') dictfile = {} for eachline in lines: splitline = string.splitfields(eachline, ',') #add \n so that I can use writlines filekey = splitline[0] + '\n' dictfile[filekey] = eachline filekeys = dictfile.keys() filekeys.sort(filesort) oufile.writelines( filekeys) oufile.close() if __name__ == '__main__': run() From frobozz_electric at hotmail.com Tue Jun 10 13:58:41 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 10 Jun 2003 17:58:41 GMT Subject: PEP318: property as decoration Message-ID: I think that function/method decoration does not apply easily to properties. Defining a property like so: def foo(self, value=None) as property: def fget(): return self._foo def fset(): self._foo = value or like so: def foo() as property(fget=fget, fset=fset): def fget(self): ... ... or however it's meant to be done, seems problematic. For one thing, a property is not strictly a method, and probably should not be defined as such. It *uses* methods, but it is not itself a method. Or that's my understanding (I may be way off base). Regardless, there are other issues. The decorator syntax is meant to replace the current idiom: def bar(): pass bar = staticmethod(bar) with def bar() as staticmethod: pass where "bar" is defined as a method; that method is passed to "staticmethod"; and "bar" is then re-bound to the resulting transformed method. And for multiple decorators, the idea is to compose a series of transformations before re-binding "bar", like so: def bar() as staticmethod, otherdecorator: pass bar = staticmethod(otherdecorator(bar)) # or, bar = otherdecorator(staticmethod(bar)), whichever the case may be... The issue here is that each of these decorators takes one and only one argument. When you wish to use a decorator that takes more than one argument you begin to run into trouble. For instance: Suppose we wish to make a contract decorator, in order to facilitate the creation of eiffel-like methods. We could say: # [1] def eiffel() as contract: def fpre(): ... def fpost(): ... or perhaps: # [2] def eiffel() as contract(fpre=fpre, fpost=fpost): def fpre(): ... ... which would be equivalent to something like the following: def fpre(): ... def fpost(): ... def eiffel(): ... eiffel = contract(eiffel, fpre, fpost) The problem is, how do we pass fpre, and fpost into contract using our new decorator syntax? For [1], we could say, well the interpreter will create the function eiffel, extract the fpre and fpost nested methods somehow, and pass those methods, along with eiffel itself, to contract for transformation. OK, but what about when you use multiple decorators? def eiffel() as staticmethod, contract: def fpre(): ... ... How will the interpreter decide which methods need to be pulled out of eiffel's definition, and to which decorator those methods need to be passed? If we choose [2], we a somewhat better off, but we are left with the issue of resolving what it means to say contract(fpre, fpost). Is this called as-is? Is it called as contract(eiffel, fpre, fpost)? Probably the latter is what's intended. Will there be conflicts if there exists an fpre or fpost method that has been defined outside of eiffel's scope? e.g.: def fpre(): ... def eiffel() as contract(fpre, fpost): def fpre(): ... ... If so, perhaps it would be better to do something like this: # [3] def eiffel() as contract(eiffel.fpre, eiffel.fpost): def fpre(): ... ... Where we create the method eiffel, which has nested methods fpre, and fpost which are accessible as attributes (something which cannot currently be done), and then contract is interpreted using eiffel, eiffel.fpre, and eiffel.fpost as arguments: contract(eiffel, eiffel.fpre, eiffel.fpost) The results of which are then bound to eiffel. Something like this could possibly work. But you'd have to allow access to a functions nested functions. What issues does that raise? Anyway, moving back to properties. For property to be used cleanly as a decorator in the way people seem to be hoping for, you would likely need to be able to do something like [2], or [3]. So a property definition would be something like this: def foo() as property(foo.fget, foo.fset): def fget(self): ... ... Plus you would need to change property so that it could take a functor as its first argument, e.g., property(foo, foo.get, foo.set) so that it could be used in the same manner as all other decorator methods. Personally, the current way to define a property doesn't bother me much. The only issue I have with it is that it clutters the class/instance scope with expendable methods getfoo, setfoo. They are expendable in that they are not called directly by instances of the class (although they could be!), instead the property is used. Other than that, I'm ok with it. It's explicit and it's pretty clear and simple to use. def getfoo(self): return self._foo def setfoo(self, value): self._foo = value foo = property(getfoo, setfoo) Still, it might be nice to take advantage of something like blocks. In this way, you could define get/set methods for each property, using the same name ("get", "set") each time, without conflict or clutter because the defined methods would be local to the block. For example, the following is a hypothetical property definition using something like a Ruby block: def once(): yield None foo = once() do *args: def get(self): return self._foo def set(self, value): self._foo = value return property(get, set) I'm not overly familiar with Ruby blocks, so I've no idea if something like this would work in that langauge. But, the idea here is that the block is associated with a generator function (as I believe they are in Ruby). When the generator yields None, the value is passed as an argument to the associated block, which then executes. This block has its own scope, inside of which we define our get/set methods and return a property using those methods. The returned property is assigned to foo. Here I'm trying to stay as close to the idea of Ruby blocks (as I understand them) as possible, so the generator function association is required. You could not for instance do the following: foo = do: def get(self): return self._foo def set(self, value): self._foo = value return property(get, set) which, to my mind, would mean that you'd assigned an anonymous function, taking zero arguments and returning a property, to foo. Although you *could* do this: foo = foo() afterwards and, now, foo *would* be a property. One issue that immediately springs to mind with this approach is that it introduces a second way to define functions/methods. I like that "there's preferably only one way to do things" in this language, so I'm NOT overly fond of this idea. Another tactic, would be to introduce "thunks", as have been discussed on Python-Dev. I can't really go much into detail describing thunks, as I'm not certain I've fully understood them myself. Regardless, I will try to describe them in the terms that I mean for them to be used. My idea of a thunk is something like the following: variablename = functionname with [[arg,]*, [*args]?, [**kwds]?]?: suite or, more simply: var = func with x, y, z=None: #do stuff with x, y, z Here "with x, y, z=None: ..." declares a thunk, call it T. This thunk is passed to func as an argument, i.e. func(T). So the result of this construct is equivalent to: var = func(T) where T is the thunk. Inside of func, T can be called in the same way that any other first class function would be. Taking this idea, and applying it to the definition of properties, we could do the following: foo = property with: def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo fdoc = "foo" return fget, fset, fdel, fdoc This would be equivalent to the following: foo = property(thunk) where thunk is the anonymous function defined after "with:" that returns a get,set,and del method, as well as a doc string. The method "property" could be changed to accept a function as an argument. It could then evaluate that function, retrieve the get,set, del methods and doc string, and construct a property with which to bind foo. Something like this: def myproperty(thunk): fget, fset, fdel, fdoc = thunk() return property(fget, fset, fdel, fdoc) def propertythunk(): def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo fdoc = "foo" return fget, fset, fdel, fdoc class MyClass(object): def __init__(self): self._foo = "foo" foo = myproperty(propertythunk) x = MyClass() print x.foo # "foo" x.foo = "changed" print x.foo # "changed" # BTW, the above code works, if you'd care to try it out... I find thunk syntax appealing. Saying foo = property with: suite reads like "make 'foo' a property with the following suite", which is what it does. Moreover, thunks have a wider utility than just for making properties. For instance, thunks could be used in file processing situations to ensure that the file is closed after it is used...there's a longer, better reasoned, discussion of this idea on Python-Dev (January/February 2003). Anyway, these are just some ideas. Both thunks and blocks require adding new keywords to the language, and both also add powerful, but sometimes confusing, abilities. For the most part, I'm just fine having neither. But, I'd probably not regret having them either, except when people start defining there methods like so: params = do include=[], exclude=[]: "returns a dictionary of parameter names and values" import inspect args, varargs, varkw, defaults = inspect.getargvalues(inspect.stack()[1][0]) if not include: include = args[:] ...etc... From tjreedy at udel.edu Thu Jun 5 20:48:46 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 5 Jun 2003 20:48:46 -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> <3EDFC47D.27B3331@alcyone.com> Message-ID: <9M-cnTRuXdR-eUKjXTWcog@comcast.com> "Erik Max Francis" wrote in message news:3EDFC47D.27B3331 at alcyone.com... > Jack Diederich wrote: > > > so if you want to be a grammar nazi it was Pollyannaish, or Pollyannish (final a elided). which I prefer, especially if adding -ness. But, to my surprise, the former gets more Google hits. TJR From vze4rx4y at verizon.net Mon Jun 2 18:09:52 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Mon, 02 Jun 2003 22:09:52 GMT Subject: Descriptor Writeup Message-ID: For those interested in learning about Python's descriptors, here is a write-up on what they are, how they work, and how to use them: http://users.rcn.com/python/download/Descriptor.htm Raymond Hettinger From kyle at lakeofburningfire.org Thu Jun 19 10:03:53 2003 From: kyle at lakeofburningfire.org (Kyle Yancey) Date: Thu, 19 Jun 2003 14:03:53 GMT Subject: Definition of Aspect Oriented Programming References: Message-ID: In any program there will be small recurrent tasks that are spread out over your entire code base. These tasks can't be modularized in the current programming paradigm. The typical examples are logging or user authentication. Although you can obviously create classes for these tasks and place them in modules, they will be used throughout your entire code base. You might say that they are sandwiched into your code. Any change to this code will leave you doing a hunt through your entire code base. Aspect Oriented Programming allows you to write modules specifying where these tasks need to be sandwiched in and performs this "weaving" at compile time. This is my simple explanation, but I hope that it has helped. For those who are interested, aspect oriented programming is available in python through the use of metaclasses. Pythius contains an Aspect Oriented module with a similar interface to aspectj. I personally find this much better than transwarps. http://pythius.sourceforge.net/ If I've not been clear enough, I apologize. I'm rather new to this concept myself. On 17 Jun 2003 19:54:42 -0700, aeze616 at cse.unsw.edu.au (anson) wrote: >Dear sir, > > What is aspect oriented programming? I read a little bit about >AspectJ. It seems to me that its like...some kinda, new syntax that >ain't related to the original Java language. How do it work in >general? > >regards, > >zeallous From gradha at titanium.sabren.com Wed Jun 4 07:02:39 2003 From: gradha at titanium.sabren.com (Grzegorz Adam Hankiewicz) Date: Wed, 4 Jun 2003 13:02:39 +0200 Subject: How to write a constructor accepting initialization and file persistence? Message-ID: <20030604110239.GA9875@pedos.es> Since Python doesn't have function overloading, I don't know very well what's the best way to write the constructor of an object which should accept initialization parameters or an xml.dom.minidom node storing it's data. My aproximation: class something(parent): def __init__(self, one, two, three, file_data = None) super(something, self).__init__(one, three, file_data) if file_data: init_extra_attributes_from_file_data() else: init_extra_attributes_from_parameters(one, two, thre) Maybe I could use **keywords, but this forces the caller to always name the parameters. Is there any other way? -- Please don't send me private copies of your public answers. Thanks. From lonetwin at yahoo.com Mon Jun 23 11:36:32 2003 From: lonetwin at yahoo.com (Steve) Date: Mon, 23 Jun 2003 21:06:32 +0530 Subject: curses on linux Message-ID: Hi, I plan to write a little app. on linux that uses the curses module. Here's what I'd like to do: a) Start up my application. (ie: all the initscr & stuff) b) Open *another* curses based application "embedded" within mine (actually I'm planning to fire-up the 'links' browser). By embedded I mean either it is displayed in one sub-window/pad on the screen, or it is displayed as it normally should with a key binding that'll allow me to switch between the embedded app and mine. c) I should be able to move between these two apps. However, I can't figure out how to do this. I tried using curses.def_[prog|shell]_mode, and curses.reset_[prog|shell]_mode, but that doesn't seem to work. From the Ncurses faq I learnt [ http://dickey.his.com/ncurses/ncurses.faq.html#handle_piping ] --------------------------------------------- Redirecting I/O to/from a Curses application In principle, you should be able to pipe to/from a curses application. However, there are caveats: * Some (very old) curses implementations did not allow redirection of the screen. Ncurses, like Solaris curses, consistently writes all output to the standard output. You can pipe the output to a file, or use tee to show the output while redirecting. * Ncurses obtains the screen size by first using the environment variables LINES and COLS (unless you have disabled it with the use_env call), then trying to query the output file pointer, and then (finally) the terminal description. If you are redirecting output, then a query based on the file pointer will always fail, resulting in the terminal description's size. * Similarly, you can redirect input to an ncurses application. However, I have observed that the use of setvbuf (for better output buffering) interferes with the use of stream I/O on GNU/Linux (and possibly other platforms). Invoking setvbuf may (depending on the implementation) cause buffered stream input to be discarded. Ncurses does not use buffered input, however you may have an application that mixes buffered input with a curses session. --------------------------------------------- How do I translate that to python ?? Right now, I've cooked up something ugly using the pty module (pty.spawn() function). However, it's far from what I'd like to do. I'd post the code if anyone is interested, I didn't do it here, 'cos it's kinda big. any suggestions ?? Peace Steve -- An idealist is one who helps the other fellow to make a profit. -- Henry Ford From gerrit at nl.linux.org Tue Jun 10 05:32:05 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 10 Jun 2003 11:32:05 +0200 Subject: PEP 317: Eliminate Implicit Exception Instantiation In-Reply-To: <20030609001830.A1089@tibia.amotlpaa.bogus> References: <20030609001830.A1089@tibia.amotlpaa.bogus> Message-ID: <20030610093205.GA2609@nl.linux.org> Steven Taschuk wrote: > raise MyError() Just curious: am I the only one who always does this and is accustomed to this style? 11:30:26:4:gerrit at stopcontact:~/cvs/brian$ grep "raise " *.py basesprites.py: def next(self): raise StopIteration() basesprites.py: raise errors.UndefinedAttributeError(self.__class__, *missing) basesprites.py: raise errors.SingleCollision(self, sprite) basesprites.py: raise errors.OutsideArea(w, self.rect) basesprites.py: raise errors.DataError("image", self) basesprites.py: raise errors.UndefinedMethodError(self.__class__, 'getbullet') basesprites.py: raise errors.UnableShooting(self) basesprites.py: raise errors.ShootingReload(self, cf=self.frame, \ basesprites.py: raise errors.UnexspectedCollision(self, item, "I'm in a wall") basesprites.py: raise TypeError("Bullet constructor takes 2-3 args") brian.py:## raise SystemExit() brian.py: raise errors.EndGame() brian.py: raise NotImplementedError("please wait ;)") brian.py: raise errors.EndGame() DataServer.py: raise AttributeError(msg) errors.py: raise UsageError("at least one attribute must be given") level.py: raise errors.GivenUpSpritePlacement(spr, counter) level.py: raise errors.SpriteTooLarge(self.world.size, (w, h)) level.py: raise errors.GivenUpSpritePlacement(wall, counter) screen.py: raise NotImplementedError("only tiled mode supported, mode is", self.bgmode) screen.py: raise errors.UsageError("mode must be one of %s" % self.modes) util.py: ordering, and if list(s).sort() doesn't raise TypeError it's util.py: raise Exception() yours, Gerrit. -- 50. If he give a cultivated corn-field or a cultivated sesame-field, the corn or sesame in the field shall belong to the owner of the field, and he shall return the money to the merchant as rent. -- 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 tr at jotsite.com Fri Jun 6 13:25:14 2003 From: tr at jotsite.com (Hoang Do) Date: 6 Jun 2003 10:25:14 -0700 Subject: Add methods to a class dynamically References: <64fb4467.0306060628.2c51bf09@posting.google.com> Message-ID: <64fb4467.0306060925.4f3b91dd@posting.google.com> Thank you for the reply. That was the answer. I forgot to quote my print statement and the error message from the interpreter was misleading. I'm also posting from Google so my response might be slow. Damien Metzler wrote in message news:... > Hoang Do wrote: > > I am having trouble invoking the created method. The function addition goes > > fine but invoking it gives an error. Here is some simple code: > > --------------------------------------------------------- > > class DynObj: > > def __init__(self): > > self.methods = ("a", "b", "c") > > for method in self.methods: > > self. __generateMethod(method) > > def __generateMethod(self, methodName): > > code = "def %s(self):\n\tprint %s\n" % (methodName, methodName) > > exec code in globals(), self.__dict__ > > > > if __name__ == "__main__": > > x = DynObj() > > print dir(x) > > x.a(x) > > --------------------------------------------------------- > > The Error: > > NameError: global name 'a' is not defined > > --------------------------------------------------------- > > Methods "a", "b", and "c" are callable and in DynObj's __dict__. However, I > > can't seem to call it. > > > > Calling for help from anyone familiar with Python's introspective features? > > > > code = "def %s(self):\n\tprint '%s'\n" % (methodName, methodName) > > you forgot the ' so your looking to print the variable a wich is not > defined as a global variable From theller at python.net Tue Jun 24 09:12:27 2003 From: theller at python.net (Thomas Heller) Date: Tue, 24 Jun 2003 15:12:27 +0200 Subject: py2exe and dynamic service installation ? References: <3ci0syqd.fsf@vfa.com> Message-ID: "Harald Schneider" writes: > Thomas, > > do I need to prepare my Python app for the use with WISE, when I want to > install it as a service? Does it need to provide a certain service API or > some special response codes ? No, you create your service with py2exe as always, and Wise does the rest - create a windows installer, install the files on the target machine and register the serice there. The registration is done from the installer, not from the service. I'll try to attach a screenshot of the dialogbox that the wise program displays (at build time), so you can see the options which are available. Hm, doesn't work in the newsgroup - will send by private mail. Thomas From v.wehren at home.nl Thu Jun 12 15:47:47 2003 From: v.wehren at home.nl (vincent wehren) Date: Thu, 12 Jun 2003 21:47:47 +0200 Subject: Twice instanciation References: Message-ID: "Salvatore" schrieb im Newsbeitrag news:bcakmg$jv7$1 at news-reader14.wanadoo.fr... > Hello, > > Is it possible to avoid twice instanciation > of the same variable ? Maybe this helps: http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52558 Regards, Vincent Wehren > class Global: > def __init__(self,init=0): > self.value = init > > g = Global() #instanciating one time ok > g = Global() #instanciating two times would raise an exception > > > Regards > > Salvatore > From bignose-hates-spam at and-zip-does-too.com.au Sun Jun 22 00:16:59 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Sun, 22 Jun 2003 04:16:59 GMT Subject: XML References: <3EF471BA.EE4F056@hotmail.com> Message-ID: On Sat, 21 Jun 2003 16:03:43 -0400, Markus Wankus wrote: > LOL. I think the point was - your .html files are 7-bit ASCII plain > text.... They are (often) encoded in 7-bit ASCII, but not always (frequently they are 8-bit iso8859-1, or utf-8, or other more-than-7-bit encodings). However, regardless of character encoding, HTML documents aren't "plain text" because they're marked up. The actual data the format holds is wrapped up in document formatting (HTML markup), not left "plain". -- \ "We demand rigidly defined areas of doubt and uncertainty!" -- | `\ Vroomfondel, _The Hitch-Hiker's Guide To The Galaxy_, Douglas | _o__) Adams | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From mertz at gnosis.cx Mon Jun 9 15:56:28 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Mon, 09 Jun 2003 15:56:28 -0400 Subject: pickling from C References: Message-ID: "Max Khesin" wrote previously: |I am exploring a possibility of having a c++ module write files in pickle |format to be later processed with python. How difficult is this to do? |(let's say all I need to write are some string-to-in-list dictionaries). Is |there a project to do this somewhere? Probably not outrageously hard... but I imagine it would be even easier to use YAML as a format. If you use the Syck C library (which has a Python binding), you can even do the reading and writing quite quickly. And the intermediate format is quite a bit more readable than are pickles (which may not be necessary, but cannot hurt). To an extent, I could recommend gnosis.xml.pickle for the same reasons. But other than for XML buzzword-compliance, YAML is almost always better (smaller data files, faster, etc). -- ---[ 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 ellisonh at prodigy.net Tue Jun 10 03:16:38 2003 From: ellisonh at prodigy.net (Homer Ellison) Date: Tue, 10 Jun 2003 00:16:38 -0700 Subject: Strange problem with notebook computer In-Reply-To: <874r30kste.fsf@acooke.org> Message-ID: <000601c32f20$3c306790$f5e57b43@homer3cq9tc2v2> Thank you to those of you who responded. It seems the fan stopped working (I hadn't previously noticed because it's a laptop computer with a quiet fan). I don't know why the overheating problem seems to be at its worst when I'm troubleshooting Python code, but I'm convinced that replacing the fan will solve the problem. Thanks again, Homer -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org] On Behalf Of andrew cooke Sent: Sunday, June 08, 2003 5:18 PM To: Homer Ellison Cc: Python List Subject: Re: Strange problem with notebook computer is using python the only time you run software that places a heavy load on the computer? it's unlikely to be something special about python itself, but if your computer has a problem that only shows up under load then it may be that python use is triggering it simply because that's what you use when you load the computer. i would suggest playing some cpu-intensive game on it for some time, or doing something else that loads the computer. i expect you'll see the same problem. (i don't want to be rude, but something you learn when you've been using computers for a while is that the mind makes connections before there is enough real evidence - you end up blaming something simply because it's the first thing that comes to mind, and you tend to look for things that support that conclusion and ignore things that don't. it's disturbing how illogical you can be. or maybe it's just me that's mad... ;o) another possibility (i have an old laptop that has a dektop cpu in it because it was faster - this is from many years ago, before there was a big difference between desktop and laptop chips - that has this problem), for example, is that when you're using python you have the computer on your knee, blocking the fan, while otherwise you tend to leave it on a tabletop (in my case, the laptop had legs that kept the fan clear of the table). look for "silly" things like this... good luck, andrew "Homer Ellison" writes: > 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 > -- http://www.acooke.org From alanmk at hotmail.com Thu Jun 26 12:45:34 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 26 Jun 2003 17:45:34 +0100 Subject: catch non-blocking socket exceptions References: <3EFB0E6E.1DEF9B20@engcorp.com> Message-ID: <3EFB232E.C64F5BD3@hotmail.com> Axel Bock wrote: > hm. twisted. yeah. > I tried it for the udp approach for the same problem, and ended up > writing > the stuff by myself - the udp thing in twisted is rather ... twisted :-) > (and I do not consider the documentation/howtos/examples to be useful for > beginners in any way). > > for tcp it might be worth a try ... although its really a quite simple > problem and twisted a rather large solution :-) Perhaps something like Spread is closer to what you need? http://www.python.org/other/spread/ *Very* easy to get up and running, built for working with UDP, easy to configure ..... Just an alternative suggestion. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From edreamleo at charter.net Thu Jun 12 08:35:43 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Thu, 12 Jun 2003 07:35:43 -0500 Subject: Use __del__ methods to improve gc? Message-ID: 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? Thanks, Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From mwilson at the-wire.com Wed Jun 11 17:10:48 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 11 Jun 2003 17:10:48 -0400 Subject: Looking for the greatest negative float value References: Message-ID: In article , "Gilles Lenfant" wrote: >Hi, > >I need the same as... > >import sys >negmaxint = - sys.maxint -1 > >... but for float data > >any hint ? I'm not completely sure this is right, but.. v, w, x = -1.0, 0.0, 0.0 i = 0 while v < w and i < 2000: x, w, v = w, v, v*2.0 i += 1 print i print x, w, v d = -x / 2.0 y = x while x > w: y, x = x, x-d d /= 2.0 print repr (y) winds up printing 1025 -8.98846567431e+307 -1.#INF -1.#INF -1.7976931348623157e+308 and that last number seems credible. Regards. Mel. From babith_cj at yahoo.co.in Mon Jun 2 14:56:21 2003 From: babith_cj at yahoo.co.in (=?iso-8859-1?q?Babith=20C.J?=) Date: Mon, 2 Jun 2003 19:56:21 +0100 (BST) Subject: query Message-ID: <20030602185622.16543.qmail@web8207.mail.in.yahoo.com> Im working on python script in an organisation. I've to generate html reports and take print outs.. pagination is a problem for that.Can anyone tell me a solution for generating printer freindly reports ? regards Babith ________________________________________________________________________ Missed your favourite TV serial last night? Try the new, Yahoo! TV. visit http://in.tv.yahoo.com From contact at alanlittle.org Wed Jun 25 17:46:32 2003 From: contact at alanlittle.org (Alan Little) Date: 25 Jun 2003 14:46:32 -0700 Subject: can't import MySQldb on OS X Message-ID: <4ef0f3a4.0306251346.14df9f93@posting.google.com> I can't import MySQLdb on OS X 10.2.6 Downloaded the package from sourceforge, got it to build after some messing about with setup.py, and now I have _mysql.so and all its little friends in /usr/lib/python2.2/site-packages But still I get: >>> import MySQLdb Traceback (most recent call last): File "", line 1, in ? ImportError: No module named MySQLdb ... is there some python path variable I need to set? Or should python look in site-packages by default? Ah. After further investigation I realise I have two pythons installed, 2.2 and MacPython 2.3a2. But neither of them can see the MySQLdb module. From news at 92tr.freeserve.co.uk Tue Jun 17 08:12:27 2003 From: news at 92tr.freeserve.co.uk (ddoc) Date: Tue, 17 Jun 2003 12:12:27 +0000 Subject: popen3 child_stdin References: Message-ID: It was brainfade. The function returns a tuple, of course. It works, and solves one Linux task I had been contemplating for a while, but doesn't of itself accomplish a job I want to do in Windows I should be able to automate a DOS program - or rather seize its interface and control what goes in as from a keyboard, and catch what comes out as if to the screen, thus programattically determining what gets typed to it and what gets shown to a notional user, but I suspect I need to use pipes rather than the popen setup. Does anyone know an example of this being done (to a DOS/console program) that is available for inspection? -- A From peter at engcorp.com Thu Jun 26 11:17:02 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 26 Jun 2003 11:17:02 -0400 Subject: catch non-blocking socket exceptions References: Message-ID: <3EFB0E6E.1DEF9B20@engcorp.com> Axel Bock wrote: > > I try to connect to several hosts at once to verify whether a certain > service is running. Now it's quite stupid to connect to one after another, > cause if I do this I'll wait forever if some hosts don't respond (at least > until TCP timeout). > > But if I connect to several hosts in parallel and use polling objects I'm > stuck - I don't know how to handle exceptions: are they raised as normal? > If yes, how do I get the correspondig socket object - or file number? > If no, how do I know if a socket timed out, or refused connection, or > something similar? Check out these pages for some background (especially page four on non-blocking sockets): http://www.mcmillan-inc.com/sock1.html But consider just using Twisted and letting all this stuff be handled for you... no sense reinventing the wheel in an area that is notoriously difficult to do right. -Peter From sismex01 at hebmex.com Tue Jun 17 16:45:23 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 17 Jun 2003 15:45:23 -0500 Subject: You know you're a Pythonista when.. Message-ID: > From: cer1969 at hotmail.com [mailto:cer1969 at hotmail.com] > Sent: Martes, 17 de Junio de 2003 03:40 p.m. > > 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 > 7.a) You finish writing a simple script, and realize it's going to be an excellent library, and redo it again in a library form, which is called by a separate script. (*GUILTY*) -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 m at moshez.org Thu Jun 5 12:28:50 2003 From: m at moshez.org (Moshe Zadka) Date: 5 Jun 2003 16:28:50 -0000 Subject: PythonD: 4Suite or Twisted? In-Reply-To: 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: <20030605162850.7519.qmail@green.zadka.com> On 05 Jun 2003, David Bolen wrote: > 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). In 1.0, UDP support was marked "unstable" for a reason -- the developers had misgivings about the API. We have since changed it :) > 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. 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". > 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 I'm sorry, converting from TCP to UDP doesn't make much sense to me. The protocols have completely different characteristics. > 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. Stability only changes before minor (not patch) releases. Specifically, I predict that UDP will be stable by the time 1.1 rolls out, and with roughly the same API. In other words, I consider the UDP stable enough to develop against. > 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. Um, it's not as much that UDP "feels" like the odd man out, but it is the odd man out. SSL and UNIX domain sockets are reliable stream transports. UDP is not. > 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. This is correct. However, for any protocol *except* echo, this actually makes sense. "datagramReceived" implies that the data packet has semantic meaning, while "dataReceived" implies that the data packet is a part of a stream, and may contain half the end of a previous message and half the beginning of the next one. This is a profound semantic difference, which cannot, and should not, be blurred by Twisted. > I think my conclusions at the time were that the Protocol class was > really a StreamProtocol class in disguise Correct. Protocol is StreamProtcol. > and there was probably no > top level "protocol" abstraction in the system. Also correct. However, I'm not sure I see the need for such an abstraction. > 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. I disagree. If Perspective Broker (say) was to support UDP, it would need an implementation of reliability on top of that. That is a whole 'nother level of support. > 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. Nothing works in both cases. I think that's pretty clear. We have a HOWTO explaining how to write UDP code. > 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. 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. -- 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 sameersahani at yahoo.com Mon Jun 30 07:43:34 2003 From: sameersahani at yahoo.com (sameer) Date: 30 Jun 2003 04:43:34 -0700 Subject: how can i retrieve a single row from JTable using jython Message-ID: <1812cd68.0306300343.44f99be6@posting.google.com> hi guys, plzz give ur valuable suggestion for the following problem..... my objective is to retrieve a row from jtable using jython scripting.so i started from jython where i mentioned connection and with the help ofcursor ,retrieve records from table. then import(let mytable.class)class file into jython. from this i get all the data from table.means the whole table i get from database.now when i will click a row ,i have to get the whole data of that row.for that i wrote listselectionlistener,but when the program is running only it gives the first row and after that when i clicked any other row i didn;'t get anything.means by default,when the constructor is called it is fired only once and after that it is not executed. plzz help me how can i get any row when i will clicked .is there any other listener or ..any thing it's urgent.. best regards, sameer From rnd at onego.ru Sun Jun 22 12:34:20 2003 From: rnd at onego.ru (Roman Suzi) Date: Sun, 22 Jun 2003 20:34:20 +0400 (MSD) Subject: xrange In-Reply-To: Message-ID: On Sun, 22 Jun 2003, 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. > >timeit -s"from itertools import repeat" "for i in repeat(None, 100): pass" >100000 loops, best of 3: 10.4 usec per loop > >timeit "for i in xrange(100): pass" >100000 loops, best of 3: 11.6 usec per loop > >will xrange be obsoleted? what is the best idiom for repeating a loop n >times in 2.3 now where you don't care about the index value? Interesting, what prevents from making xrange-object an iterator? Then there will be obvious backward compatibility and no need to change idioms. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From light at soton.ac.uk Tue Jun 10 08:43:02 2003 From: light at soton.ac.uk (Mark Light) Date: Tue, 10 Jun 2003 13:43:02 +0100 Subject: Changing properties of a class instance widget Message-ID: Hi, I have a class (after some help from this newsgoup) that generates an array of buttons that I can select and deselect via left clicks etc(done using bind). What I would like to be able to do is to have a button that when clicked will select all in a particular coulmn of buttons. So I need to be able to referebce the separate instances. A few snippets of the code! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #Class to generate sample buttons - including sample list population and data entry #CCC> class MyButton(Button): ##< def __init__(self, parent, buttonNb, **options): self.__buttonNb = buttonNb apply(Button.__init__, (self, parent), options) self.configure( width=10) self.bind('', self.onLeftClick) self.bind('', self.onMiddleClick) self.bind('', self.onRightClick) self.bind('', self.onDoubleClick) ##> #Define middleclick ##< def onMiddleClick(self, event): self.config(None, bg=('green'), relief=SUNKEN) print "MiddleClick on Sample" + `self.__buttonNb` ##> #generate buttons from a list (called Layout - e.g. [(frame3b2, 1), (frame3b2, 2),....]) for frame, sample in Layout: b = MyButton(frame, sample, text="Sample %s" % sample) b.pack(side=LEFT) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ How can I refer to a particular instance of MyButton to change it's widget properties. Many Thanks, Mark. From roy at panix.com Sat Jun 14 13:52:17 2003 From: roy at panix.com (Roy Smith) Date: Sat, 14 Jun 2003 13:52:17 -0400 Subject: comprehending comprehensions Message-ID: 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? From icarroll at pobox.com Thu Jun 12 16:15:23 2003 From: icarroll at pobox.com (W Isaac Carroll) Date: Thu, 12 Jun 2003 13:15:23 -0700 Subject: Twice instanciation References: Message-ID: <3EE8DF5B.1040609@pobox.com> Salvatore wrote: > Hello, > > Is it possible to avoid twice instanciation > of the same variable ? > > class Global: > def __init__(self,init=0): > self.value = init > > g = Global() #instanciating one time ok > g = Global() #instanciating two times would raise an exception What do you mean by "instanciation" and "variable"? If you are asking whether it's possible to prevent binding the same name a second time, then no, it's not possible. If you're asking whether it's possible to raise an exception the second time a class constructor is called, then yes, it is. (Although raising an exception is not the usual way to handle this. Search for the Highlander (Singleton) or Borg (Monostate) pattern for more information.) TTFN From MatthewS at HeyAnita.com Mon Jun 16 14:41:10 2003 From: MatthewS at HeyAnita.com (Matt Shomphe) Date: 16 Jun 2003 11:41:10 -0700 Subject: Possible install bug in Python 2.3b1? (Python 2.2 still in the registry) Message-ID: <5ab0af73.0306161041.203f6378@posting.google.com> I installed Python 2.3b1 on my machine (Win2k, sp3, 384 MB ram, 500mHz pentium III). After installing, I noticed that in the registry (regedit), there were still entries containing the old Python 2.2 records. For example: HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Applications\python.exe\shell\open\command HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Applications\pythonw.exe\shell\open\command HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment (It's still in the %PATH%) HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Control\Session Manager\Environment (It's still in the %PATH%) HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment (It's still in the %PATH%) all have the path C:\Python22\. This does not seem to affect the behavior of the latest install. (I noticed the error only when I tried to install eGenix.com's mx extensions. It requires Python 2.2 and I noticed a garbage entry when it was about to install.) Is this a bug that should be reported? From eppstein at ics.uci.edu Wed Jun 18 14:56:27 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 18 Jun 2003 11:56:27 -0700 Subject: Algorithm help per favore References: <2ec1bc1c.0306180746.159679d6@posting.google.com> <3EF0AAFB.DDA5F555@engcorp.com> Message-ID: In article <3EF0AAFB.DDA5F555 at engcorp.com>, Peter Hansen wrote: > > >>> L = [6,3,3,3,5,7,6,3,4,4,3] > > >>> [x for x, y in zip(L, [L]+L) if x != y] > > [6, 3, 5, 7, 6, 3, 4, 3] > > But this won't work if L contains a reference to L! :-) :-) Ok, what's the quickest way to build a new object that's guaranteed unequal to any previous object? E.g. [x for x, y in zip(L, [lambda x:x]+L) if x != y] There must be a better way to do this than with a lambda. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From alanmk at hotmail.com Mon Jun 23 04:09:15 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 23 Jun 2003 09:09:15 +0100 Subject: XML References: Message-ID: <3EF6B5AB.24D8AC3C@hotmail.com> Alan Kennedy wrote: >> Semantics vs. format: The OP was concerned with finding good use cases >> for XML, where it is a natural fit for the problem at hand. He seemed >> to be dissatisfied with XML both as a format, and as a method for >> building semantic object models. Roman Suzi wrote: > Well formulated, Alan! This is exactly what I tried to tell. OK, so we've figured out what you don't like about XML. Now all we have to figure out is why you don't like it ;-) regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From achrist at easystreet.com Fri Jun 20 14:05:42 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Fri, 20 Jun 2003 11:05:42 -0700 Subject: Saving Files Under Windows -- Py2Exe and Installer References: <3EEDEF93.1629EB53@easystreet.com> Message-ID: <3EF34CF6.8DE52B99@easystreet.com> OK. Here's the next level conundum of this maze of what goes where and who can do what under Windows. If I distribute an app as a one file distro using py2exe or the McMillan installer, when it runs IIRC it wants to explode itself back into multiple pieces that are deleted at the end of the run. I'm guessing that this means that the user must have privileges to create files in the program's directory. Is that so? If Windows is promoting or enforcing a policy of "programs here" and "files there", with administrator privileges required to create a file or write to the program files folder, isn't this going to be a problem? Best solution if so? Al From bit_bucket5 at hotmail.com Wed Jun 18 07:51:23 2003 From: bit_bucket5 at hotmail.com (Chris Stromberger) Date: Wed, 18 Jun 2003 11:51:23 GMT Subject: Python 2.3 + mysql? References: Message-ID: On Wed, 18 Jun 2003 02:18:14 +0200, Gerhard H?ring wrote: >Chris Stromberger wrote: >> Is there a mysql module that works with Python 2.3? I don't see one >> listed at sourceforge. > >There's only one MySQL module worth talking about: MySQLdb. How come you >think it cannot be compiled against Python 2.3? > >(If this is indeed about Windoze binaries for Python 2.3, I'll build >them and have them uploaded by Andy *after* Python 2.3 final is released.) > >-- Gerhard Oh yeah, I guess I should have mentioned that I'm looking for the binary. Thanks for the info. If someone decides to build a binary in the meantime, please let me know at usenet at strombergers.com ! :-) From ian-news at upright.net Fri Jun 6 12:54:21 2003 From: ian-news at upright.net (Ian Upright) Date: Fri, 06 Jun 2003 16:54:21 GMT Subject: LANGUAGE QUESTION??? References: <8dcf2300.0306040159.118c24e8@posting.google.com> Message-ID: <1ch1evgo3g93g2219l4tfv9so3bi80rlrm@4ax.com> philh at cabalamat.org (phil hunt) wrote: >A hammer. > >A hammer is the best tool by far, we should use it for everything, >and throw away all our screwdrivers. For exteme construction, one should use extreme tools. A jackhammer always gets it done quicker but great care must be taken in it's use. Additional attatchments are often needed such as a few different sizes of square and circular nail plates. Once time is taken to master the skill, it is highly successful at bringing incredibly rapid results. As one construction worker put it, "why nail one at a time when I can nail ten??" Case closed. The jackhammer is THE tool. Ian --- http://www.upright.net/ian/ From moocat94122 at yahoo.com Tue Jun 17 22:25:29 2003 From: moocat94122 at yahoo.com (Ron Samuel Klatchko) Date: 17 Jun 2003 19:25:29 -0700 Subject: destructors, exceptions and the lock guard paradigm Message-ID: I am trying to use the lock guard paradigm in Python. My first attempt was this: class guard: def __init__(self, lock): self.acquired = 0 self.lock = lock self.lock.acquire() self.acquired = 1 def __del__(self): print "releasing lock" self.release() def release(self): if self.acquired: self.lock.release() self.acquired = 1 Intended to be used like this: class someclass: def __init__(self): self.lock = threading.Lock() def somefunc(self): g = guard(self.lock) # do some work while the lock is held The idea was that when somefunc exited, the reference count to g would drop to 0, the guard would be destructed which would release the lock. That way, I do not have to manually release the lock for every exit path. While it works for normal returns from the function, the lock is not released when an exception is thrown. From my research it looks to be due to how the last traceback is stored and continues to hold a reference to the guard object. Is there a way to get this to work under Python? I realize I can use try/finally block and put the call to Lock.release() there, I don't like that as much as the guard method. samuel From fperez528 at yahoo.com Fri Jun 13 18:26:43 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 13 Jun 2003 16:26:43 -0600 Subject: subclassing unittest.TestCase? References: Message-ID: Chris Curvey wrote: > Hi all, > > I'm trying to subclass unittest.TestCase and add to the constructor. > But whenever I try to run my tests, I get > > ValueError: no such test method in HtmlTestCase.HtmlTestCase: runTest > > there must be something simple that I'm missing. The subclass looks like: > > class HtmlTestCase(unittest.TestCase): > def __init__(self): > unittest.TestCase.__init__(self) > # create a random string to use as the test identifier > self.testId = random.randint(1,10000000) > self.tags = [] > > Any ideas? you're not passing the arguments through: class HtmlTestCase(unittest.TestCase): def __init__(self,*args): unittest.TestCase.__init__(self,*args) # create a random string to use as the test identifier self.testId = random.randint(1,10000000) self.tags = [] best, f From artyprog at wanadoo.fr Thu Jun 12 16:45:09 2003 From: artyprog at wanadoo.fr (Salvatore) Date: Thu, 12 Jun 2003 22:45:09 +0200 Subject: Twice instanciation In-Reply-To: References: Message-ID: <3EE8E655.6000502@wanadoo.fr> Manuel Garcia wrote: > On Thu, 12 Jun 2003 22:14:35 +0200, Salvatore > wrote: > > You may have to use a 'try' statement. > > print "1st time, create name 'G'" > > try: > G > except NameError: > G = 'whatever' > else: > print "name 'G' already in use" > > print "2nd time, recognize already using 'G'" > > try: > G > except NameError: > G = 'whatever' > else: > print "name 'G' already in use" > > If you want this behavior as part of your class, you will have to do > some very tricky programming with 'sys._getframe()' and 'inspect' in > your '__init__'. 'sys._getframe(1).f_locals' and > 'sys._getframe(1).f_globals' so you can see the names already in use, > to see if perhaps any are an instance of your class, and then > 'inspect' to take a peek at the line of code with the assignment. > If, in fact, this is what you want, may I ask what the exact purpose > is? This what I wanted indeed, and it's no as simple as I imagined ;-) What are you trying to avoid, and why is it important to avoid > it? The problem araise when I was asked from a friend how to manage global variables, and among other examples I said he could wrote a class named Global and instanciate object from this class, being assured a same name would not be used twice The code for the procedure very roughly sketched out in the > preceeding paragraph would be difficult to write, and very difficult > to be made robust. I will use another solution :-) Thanks Manuel From jjl at pobox.com Wed Jun 18 12:00:20 2003 From: jjl at pobox.com (John J. Lee) Date: 18 Jun 2003 17:00:20 +0100 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> Message-ID: <87ptlbml4b.fsf@pobox.com> Steven Taschuk writes: > Quoth John J. Lee: > [...] > > I agree with this. I don't know what all the fuss is about with the > > interactive prompt. I certainly do use it, quite frequently, but [...] > > Maybe only me and David make lots of mistakes at the interactive > > prompt ;-) > > I'm a big fan of the interactive prompt, but certainly not for > coding -- I too make too many mistakes for that to be practical, > and I prefer my text editor anyway. Of course!! > 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. It's still convenient, but can be replaced quite easily with a good IDE, I think. John From mlh at furu.idi.ntnu.no Thu Jun 5 07:55:01 2003 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Thu, 5 Jun 2003 11:55:01 +0000 (UTC) Subject: Efficient data flow between orthogonal C extensions? References: <87el29rpmv.fsf@smtp.gsi.de> Message-ID: In article <87el29rpmv.fsf at smtp.gsi.de>, Pierre Schnizer wrote: >mlh at furu.idi.ntnu.no (Magnus Lie Hetland) writes: > [snip] >If you are using callbacks, That was, at least, my original idea, although a more centralized version would also be possible. >you can wrap the callbacks with swig. Sounds good.... >While swig will not generate helpers to call python functions from C, >you can pass pointers to C functions. >http://www.swig.org/Doc1.3/SWIG.html#n30 Hm. I don't quite get this... This piece of documentation does seem to work with Python-implemented callbacks... And the name-based approach strikes me as a bit impractical. A callback has to have a given name to be applicable -- or am I misunderstanding? Even though this doesn't mean that the extensions need to know about each other, conceptually, the would need to know what the methods of the other extensions are called... It would be nice to be able to supply the extension with an arbitrary object (e.g. a PyCObject) and have it cast it and use it itself. Of course, assigning a function to a variable with the correct name (if that would work) isn't too much of a nuisance. Any input on this? Am I misunderstanding the functionality? And... I suppose the declared callbacks would be in the namespace of the extension module? (Otherwise, how would it be imported?) In that case, wouldn't it be necessary to assign a function pointer to it anyway? Hm... I guess I'll have to look into whether this is the way to go (and perhaps actually try it before speculating too much ;). Thanks for the input. >Pierre -- Magnus Lie Hetland "In this house we obey the laws of http://hetland.org thermodynamics!" Homer Simpson From wobh at helium.barsoom.invalid Mon Jun 2 13:39:23 2003 From: wobh at helium.barsoom.invalid (William Clifford) Date: 2 Jun 2003 17:39:23 GMT Subject: Perl HTML::Element in Python Message-ID: I've started. I have something that is very weakly functional. I've made a page with all the code on it here: http://wobh.home.mindspring.com/test/element.py.html This is intended and a personal learning project but if anyone has any suggestions/insights/criticisms, just post them here. Thanks. -- William Clifford wobh at yahoo.com http://wobh.home.mindspring.com From martin at v.loewis.de Tue Jun 3 14:40:53 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 03 Jun 2003 20:40:53 +0200 Subject: GIL and uniprocessor machines References: <20d6d41f.0306030415.18f4c093@posting.google.com> Message-ID: aahz at pythoncraft.com (Aahz) writes: > >So the > >GIL should actually not be a restriction at all in that case? > > You're half-right. However, even on a single-CPU machine, handling > multiple I/O requests concurrently does give a speed boost, which is why > Python has a mechanism for releasing the GIL in C extensions -- and all > the reentrant-capable I/O calls in the standard library release the GIL. More generally, in a single processor machine, the system may be able to switch threads at a time it considers appropriate. With the GIL, the system's choice of alternative new threads is reduced to non-Python threads, unless the active Python thread has released the GIL. Regards, Martin From fredrik at pythonware.com Thu Jun 26 07:33:49 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Jun 2003 13:33:49 +0200 Subject: filedescriptor out of range in select() References: <3EFABC5E.329613C6@alcyone.com> Message-ID: Erik Max Francis wrote: > I strongly suspect it means that the file descriptor (or the result of > calling the .fileno method of a socket-like object) passed in one of the > objects is way out of range for being a valid file descriptor number. as you can see if you look at the source code, all it means is that the file descriptor is larger than FD_SETSIZE, which is a compile-time constant. 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... 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. From http Fri Jun 20 14:05:34 2003 From: http (Paul Rubin) Date: 20 Jun 2003 11:05:34 -0700 Subject: sum(strings) References: Message-ID: <7xn0gchbf5.fsf@ruckus.brouhaha.com> mwilson at the-wire.com (Mel Wilson) writes: > Interesting point arose the other day.. using '+' to concatenate > strings is wrong, because concatenation isn't commutative. No biggie, lots of matrix packages use * for matrix multiplication and that isn't commutative either. > 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. That would be a buggy optimizer. If + isn't necessarily commutative, the optimizer shouldn't assume that it is commutative. From listbox at cybereal.org Mon Jun 16 06:29:32 2003 From: listbox at cybereal.org (Zac Jensen) Date: Mon, 16 Jun 2003 04:29:32 -0600 Subject: Need some quick help here... In-Reply-To: <200306152153.29188.listbox@cybereal.org> References: <200306152153.29188.listbox@cybereal.org> Message-ID: <200306160429.34287.listbox@cybereal.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Sunday 15 June 2003 09:53 pm, Zac Jensen wrote: > I have a bit of an issue in something I'm designing. > > It's a security issue. apparently this is an old issue with a lot of papers on the topic so, I'll just go from there thanks for the input those who responded :) - -Zac -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) iD8DBQE+7ZwOV3L7YsSif1URAt+CAJ9og52VaTWUNu7o7Pvl3tvO1d2YOQCfeWOi cjLT0rwZrHv3lzjLQfih2Y0= =AXIZ -----END PGP SIGNATURE----- From glauco at sferacarta.com Tue Jun 17 10:46:02 2003 From: glauco at sferacarta.com (Glauco) Date: Tue, 17 Jun 2003 14:46:02 GMT 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? > > Lars seq = ( 'a' , 'c' , 'g' , 't' ) for x1 in seq: for x2 in seq: for x3 in seq: forx4 in seq: print "%s%s%s%s" % (x1, x2, x3, x4 ) something like this ? Glauco From just at xs4all.nl Wed Jun 4 03:54:52 2003 From: just at xs4all.nl (Just) Date: Wed, 04 Jun 2003 09:54:52 +0200 Subject: pychecker checks files by executing them ?? References: <3EDCB6BF.1090909@molgen.mpg.de> Message-ID: In article , bokr at oz.net (Bengt Richter) wrote: > >True. Yet it would be far better if PyChecker would analyze the compiled > >byte code instead of executing it. The same goes for pydoc btw. > > Bad news. I would want a documenter to be a safe way to get a first look > at something untrusted. Sheesh. Thanks for the wakeup ;-/ Just the other day I came across http://happydoc.sourceforge.net/, which says it uses the parse tree to extract documentation. Just From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Jun 9 06:38:37 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 09 Jun 2003 12:38:37 +0200 Subject: pickle vs cPickle: error is not raised at unpickle / windows vs linux (!) (repost) In-Reply-To: References: Message-ID: <3ee463ab$0$49113$e4fe514c@news.xs4all.nl> Tim Peters wrote: > This is why bug reports don't belong on comp.lang.python: the context is > lost, and I don't have time to go searching for it. When you don't get a > reply to a repeated question about dubious behavior, it's probably because > nobody reading c.l.py knows the answer. In this case, there are maybe two > people on Earth who understand all the pickle changes going into 2.3, and > Guido (the one who knows best) rarely has time to read c.l.py anymore. Yes, well, then please tell me why it's not best to first ask around and see if anybody else has seen the same problem or even knows a solution, before submitting an unfounded bug report in sourceforge? Which *will* take time and resources of those involved to look at it. Would you be happier if I submit all 'dubious behavior' as bug reports on SF, even those that are obviously my mistake, which probably can be pointed out quickly by several knowledgeable people here on c.l.python? At least I had the patience to first ask around and wait a while to see if anything interesting comes up. It didn't. What's wrong with that? > So, if you think this is an important question, please gather all the pieces > and open a single coherent bug report on SourceForge. Or, if it's an idle > question, feel encouraged to keep replying to yourself about it on c.l.py > . It certainly is not an idle question. How on earth could I know in advance that nobody would reply to it? But, to please you, and myself, I will submit a bug report on SF now. --Irmen From mertz at gnosis.cx Mon Jun 30 21:33:20 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Mon, 30 Jun 2003 21:33:20 -0400 Subject: Howto: extract a 'column' from a list of lists into a new list? References: Message-ID: "Greg Brunet" wrote previously: |>>> tbl.Fields() |[('STOCKNO', 'C', 8, 0), ('DACC', 'C', 5, 0), ('DEALERACCE', 'C', 30, |0), ('D-ACCRTL', 'C', 9, 0), ('D-ACCCST', 'C', 9, 0)] NAME,TYPE,LEN,DEC = range(4) names = [row[NAME] for row in tbl.Fields()] -- 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 news at manuelmgarcia.com Thu Jun 12 18:15:55 2003 From: news at manuelmgarcia.com (Manuel Garcia) Date: Thu, 12 Jun 2003 22:15:55 GMT Subject: why 'lambda' and 'reduce'? References: <3ee8e465$0$49115$e4fe514c@news.xs4all.nl> Message-ID: <0rthev82lo9obv6fj7a7rea8ra2ihnl5r6@4ax.com> On Thu, 12 Jun 2003 22:36:52 +0200, Irmen de Jong wrote: >Anyway it ran quite fast indeed... somehow I don't expect >this kind of unreadable and horribly nested code to run >fast too. Never mind. :-) Thank heavens it doesn't take as much time to run as it did to write! Actually 10000 digits wouldn't be much longer. I am using a quadratic iteration, so the number of valid digits is doubled with each step! (It is amazing to me there are algorithms that can do this). There are other iterations that increase the number of valid digits times 3, times 4, times 5, but they cannot be as cleanly implemented. http://numbers.computation.free.fr/Constants/Pi/iterativePi.html The '13' in the progam is the number of iterations needed for 5000 valid digits. 10000 digits would require 14 iterations, etc. As horrible as it looks, after I added the last 'lambda', it runs just as fast as a straightforward implementation. The only inefficient part is using '+' to concatenate strings, and I do that just to make the string processing a little harder to spot. Manuel From tjreedy at udel.edu Sat Jun 14 18:04:29 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 14 Jun 2003 18:04:29 -0400 Subject: Reading from a FIFO, burning CPU References: Message-ID: "Elmar W. Hoefner" wrote in message news:bcg2m8$iqmme$1 at ID-113469.news.dfncis.de... > Hi there! > > I tried to continuously stream a FIFO into my python script. > I was successful so far, but the performance is not acceptable: In a sense, the performance is too good. and that is why ... > If I start the script, it eats 99% of my CPU cycles. Like you told it to do. Unless you have some other work to interleave with this process, this is no more wasteful than the CPU's or OS's own idle loop > Can anyone give me a hint how to change this? Simplest: try sleeping between readline() calls to free up CPU time for other processes, or have your program go off and do something else useful while waiting for more fifo data. > I did it this way: > > 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 Terry J. Reedy From no_replies at fake_email_address.invalid Tue Jun 10 13:03:01 2003 From: no_replies at fake_email_address.invalid (Robert Oschler) Date: Tue, 10 Jun 2003 17:03:01 GMT Subject: Access "slot" field dynamically? References: Message-ID: <9boFa.674$Hw.872301@news2.news.adelphia.net> Steven 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. thx -- Robert Oschler, Android Technologies, Inc. http://www.androidtechnologies.com - The home of Off-Book! (tm) The scene memorization tool for Actors and Actresses! "Steven Taschuk" wrote in message news:mailman.1055258590.26664.python-list at python.org... > 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 maxm at mxm.dk Mon Jun 30 07:44:02 2003 From: maxm at mxm.dk (Max M) Date: Mon, 30 Jun 2003 13:44:02 +0200 Subject: Idiomatic way of repeating items in a sequence. In-Reply-To: References: Message-ID: <3F002282.6090506@mxm.dk> alr wrote: > I need to repeat each item in a list n times, like this function does: > > def repeatitems(sequence, repetitions): > newlist = [] > for item in sequence: > for i in range(repetitions): > newlist.append(item) > return newlist I would make just a minor change: def repeatitems(sequence, repetitions): newlist = [] for item in sequence: newlist += repetitions*[item] return newlist regards Max M From shlomme at gmx.net Sun Jun 1 13:18:16 2003 From: shlomme at gmx.net (Torsten Marek) Date: Sun, 01 Jun 2003 19:18:16 +0200 Subject: PyModule for ID3 v2.2+ In-Reply-To: References: Message-ID: Andreas Jung schrieb: > Is there a module that can read ID3 tags from MP3 files where the ID3 tags > are of version 2.2 (produced by iTunes)? > > -aj > I wrote a C++ library with Python bindings (libtagedit) for most likely that purpose. You are able to read/write the most interesting fields in ogg and mp3 (ID3v2.x) tags without notice of the file type. The fields are: Artist, Title, Album, Year, Comment, Genre and Track. To use it, you will need sip (from www.riverbankcomputing.co.uk), the C++ library and Python bindings are at www.sourceforge.net/projects/libtagedit. I use those library myself heavily with large portions of mp3/ogg files, the only bug by now I know of is sometimes wrong detection of mp3 file length and bitrate, but I did not have the time to get into this. The mp3 plugin can read ID3v1 tags, but converts them to ID3v2 tags on writing. If you do not like using sip and you need only and full access to ID3v2.x tags, I'll could give you a standalone C++ library, for which you could generate Python bindings. Refering to former postings, I do not claim to be standards compliant, but Xmms, Xine and Winamp (2.xx and 3) are able to read them flawlessly, or, at least, I did not hear complains... greetings Torsten From mickel at csc.fi Tue Jun 10 05:19:59 2003 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Tue, 10 Jun 2003 12:19:59 +0300 (EEST) Subject: Setting allowed size of text object on canvas in Tkinter In-Reply-To: Message-ID: On Tue, 10 Jun 2003, Eric Brunel wrote: > Mickel Gr?nroos wrote: > > Hi everybody! > > > > How do I force a text object to be of a required size on a canvas in > > Tkinter? > > > > [...] > > Is this what you want? > > --------------------------------- > from Tkinter import * > > root = Tk() > c = Canvas(root) > c.pack() > c.create_text(100, 100, text='spam spam spam spam spam', width=75) > root.mainloop() > --------------------------------- No, the text is still wrapping. I would like to be able to se a "height" option too, so that only the text that fits in the area defined by "width" and "height" would be visible (and the rest simply not shown at all). Do you know how to ackomplish that? (Currently, I use bbox() to get the coordinates of the rectangle and the text, then I chop of characters from the end of my string in a loop until the bbox of the text is fully overlapped by the rectangle -- ugly and possibly slow.) /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 jack at performancedrivers.com Mon Jun 2 22:14:06 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 2 Jun 2003 22:14:06 -0400 Subject: Python get's a mention on University Challenge In-Reply-To: ; from g2h5dqi002@sneakemail.com on Tue, Jun 03, 2003 at 01:54:32PM +1200 References: <2vNCa.733$Bp6.118@news-binary.blueyonder.co.uk> <3edbaa7a$0$49106$e4fe514c@news.xs4all.nl> Message-ID: <20030602221406.A1163@localhost.localdomain> On Tue, Jun 03, 2003 at 01:54:32PM +1200, Greg Ewing (using news.cis.dfn.de) wrote: > Phil Thompson wrote: > > Maybe prayer should be added as a transport to Twisted? > > Should be simple enough: > > def pray(text): > open("/dev/god", "w").write(text) Your program makes some assumptions, other programmers might prefer these to fit their personal style. def atheistic_pray(text): os.system('mknod /dev/god') # we have to do this ourselves open('/dev/god', 'w').write(text) def agnostic_pray(text): try: open('/dev/god', 'w').write(text) except: pass def believer_pray(text): """this function always succeeds""" open('/dev/god', 'w').write(text) -jack From news at manuelmgarcia.com Fri Jun 13 22:53:29 2003 From: news at manuelmgarcia.com (Manuel Garcia) Date: Sat, 14 Jun 2003 02:53:29 GMT Subject: why 'lambda' and 'reduce'? References: <84fc4588.0306112339.10a4012b@posting.google.com> Message-ID: On Fri, 13 Jun 2003 19:35:11 -0600, Steven Taschuk wrote: >I think the expression > (S((x*y)//F))**2 >is a bit obfuscated. Modulo rounding error, it's equivalent to >x*y, nyet? I made the change, ran the program, had Python compare the digits to the digits I downloaded, and you are right. If you use the version with the extra 'lambda' to set x1 and y1, you will see the reason for my mistake. In the correct version, I need to know S((x*y)//F) to keep the iteration happy, so I set x1, and x1*x1 is just another way of saying x*y, and no more expensive to compute. Before I put in the final 'lambda', I made a thoughtless cut-and-paste. I would be lying if I said I understood the iteration more than just to copy it ;-) (hmm, if I put an _another_ lambda to store the result of x*y, I might be able to make it faster...) This weekend I will be trying to have Python figure out 1,000,000 digits, and I will keep your observation in mind, because I will need every last bit of speed. >This is the point which still puzzles me -- I see no obvious >reason for the rounding error not to propagate. My experiments >with the code haven't turned up a case with more than about five >wrong digits, but I'd expect a proof of stability to be quite >involved. Compare it to Newton's method for finding the square root. (I had to implement this in my code, to get the square roots for these massive numbers). Newton's method is also an iteration, and it is also quadratic, so the number of correct digits doubles with each step. You can draw the geometry behind the calculus, and you will see each step gives the iteration a much better chance to leap closer to the true value. With Newton's method, it is not mysterious. All these guys have done is find a way of computing Pi that works just as well as Newton's method finds the square root. The error never gets a chance to propagate, in fact a large percentage is sliced off each step, in fact the percentage grows with each step. (How is that for hand waving? ;-) >> What looked like 'geometrical mean' was actually my having to >> implement a square root function with Newton's method, [...] > >Geometric mean is a specific case of square root -- the gm of two >numbers is the square root of their product. Note, incidentally, >that this is the multiplicative equivalent of the arithmetic mean: I was just trying to figure out what you thought I was 'obfuscating'. My code consists of Newton's method for the square root, and a copied quadratic iteration for finding Pi, and nothing else (except a cute trick with 'reduce' ;-) Christopher Craig and Tim Peters supplied the efficient long integer implimentation. BTW, please except my apology for my being a butthead earlier. Manuel From mis6 at pitt.edu Sun Jun 8 09:19:37 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 8 Jun 2003 06:19:37 -0700 Subject: Thoughts on cooperative methods References: Message-ID: <2259b0e2.0306080519.1f432e68@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. I suggest you to google in the newsgroup for "super". There have been discussions about many of the points you mention (especially Bjorn Pettersen was strongly criticing the current behaviour of super, you can look at his postings too). Michele From aleax at aleax.it Wed Jun 18 04:40:11 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 18 Jun 2003 08:40:11 GMT Subject: a clean way to define dictionary References: <3EEFEBFD.8090003@nospam.com> Message-ID: 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'] If you could rely on the newlines, lst = [ x.split() for x in lst.split('\n') if not x.isspace() ] would give you [['a', '1'], ['foo', '3'], ['bar', '234'], ['joe', '321']] , meaning that dict(lst) would immediately return the dictionary you want (except that the values still need to be run through 'eval', which you could do separately). Just pointing out that you may have flattened lst too much with that single split call, so you later need to recover some structure (originally indicated by the newlines) that you have just thrown away -- you might choose to NOT throw it away in the first place. Also, as already mentioned elsewhere on the thread, avoid using dict as your own variable name, since that stops you from calling Python's own built-in 'dict' and severely restricts your options! So I'll call the name of the dictionary you're building 'adict' in the following. With lst made into a list of lists (split by \n first, and only line by line split on generic whitespace), the loop equivalent to your following: > i want to do something like > > dict = {} > for key, value in lst: > dict[key] = eval(value) would indeed work just perfectly -- the reason it doesn't work after the single call to lst.split is that you've flattened away the structure. Still, if you're given an already-flattened list by an evil godmother, bunching it up again isn't beyond human ingenuity (just some amount of wasted effort if you could have avoided the original flattening;-). [ [lst[i],list[i+1]] for i in range(0,len(lst),2) ] would be a typical, simple list comprehension to do this bunching-up, for example -- so you could loop for key, value in [ [lst[i],list[i+1]] for i in range(0,len(lst),2) ]: or, as others have indicated, in Python 2.3 you could slice lst[::2] and lst[1::2] to get the even and odd items and zip them up again: for key, value in zip(lst[::2], lst[1::2]): but that doesn't work in 2.2 (you need 2.3 for that) -- same for itertools.islice which might be used to construct similar functionality. > or is there a more common way to define a dictionary > without all the punctuation marks? What 'punctuation marks' are you referring to? Those in the normal literal form of dictionaries? Those are just braces around the lot, colons to separate key and value, commas to separate the items, i.e. {1:2, 3:4} but apparently in your case some of the values are meant to be ints and others are meant to be strings, so that would require some more punctuation quite independently from the fact that those values are then meant to become keys and values in a dictionary. If you have metaknowledge such as "all keys are strings, all values ints" then you need to encode that somehow -- might as well be in your code that builds the dictionary. Alex From exarkun at intarweb.us Sun Jun 8 02:01:40 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sun, 8 Jun 2003 02:01:40 -0400 Subject: Twisted - howto transport megabytes? In-Reply-To: References: Message-ID: <20030608060140.GA24472@meson.dyndns.org> On Sun, Jun 08, 2003 at 01:01:18AM -0400, Ed Young wrote: > I am exploring Twisted for use as the basis for an > application to application data transporter (queueing). > > When receiving large messages (multiple megabytes), I can > use the dataReceived method to get the messages piecemeal. > Since file writes can be blocking, how can I write the > received pieces to a file in a non-blocking fashion? > > When sending large messages (multiple megabytes), well, > I haven't figured that out yet. Does the transport > method accept a filehandle from which it will feed as > it needs to? > > The Twisted documentation is twisting my mind . > All hints appreciated... You very likely want to make your protocol a producer, then register it with a consumer (eg, your transport). An example of doing this can be found in twisted.protocols.smtp -- SMTPClient is a producer, so as to gracefully handle arbitrarily large emails. Not that I want to discourage questions on c.l.py, but there is also a mailing list dedicated to twisted - twisted-python at twistedmatrix.com - where most developers are paying attention, and where more complex questions may meet with a response. Hope this helps, Jp From joshway_without_spam at myway.com Fri Jun 6 09:51:15 2003 From: joshway_without_spam at myway.com (Joshua Marshall) Date: Fri, 6 Jun 2003 13:51:15 +0000 (UTC) Subject: id(a) == id(b) and a is not b --> bug? References: Message-ID: 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. From fredrik at pythonware.com Wed Jun 25 05:56:01 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 25 Jun 2003 11:56:01 +0200 Subject: newbie: good reasons for learning Python? References: <3ef37a28$0$306$ba620e4c@reader0.news.skynet.be> <3ef95a8d$0$97270$edfadb0f@dread12.news.tele.dk> Message-ID: Max M wrote: > Actually I find both that and frederiks version of the code overly > complex. many years ago, I stumbled upon the 99 bottle page, and found a C-written-in-Python-syntax example, so I sent the page maintainer a nice new Pythonic example, without all those extra characters... unfortunately, I couldn't keep myself from adding a much more obscure example as a postscript. guess the "pythonic edition" look too bland, or something. > This is a bit longer but should be more "pythonic" and far easier to > understand: well, you're still using the locals() hack. From bignose-hates-spam at and-zip-does-too.com.au Thu Jun 26 21:15:18 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 27 Jun 2003 11:05:18 +0950 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: > "Ben Finney" wrote in message > news:slrnbfn2eb.rbb.bignose-hates-spam at iris.polar.local... >> 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. Further highlighting the foolishness of keeping them as separate operations. If they interacted in this non-intuitive and damaging way, the "go to the start of the next line" should have been a single transaction for the user, with the implementation deciding how to carry it out. -- \ "I spent all my money on a FAX machine. Now I can only FAX | `\ collect." -- Steven Wright | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From peter at engcorp.com Mon Jun 16 14:53:04 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 16 Jun 2003 14:53:04 -0400 Subject: does lack of type declarations make Python unsafe? References: <3EEDDA77.E9246F25@engcorp.com>, <3064b51d.0306151228.22c595e0@posting.google.com> <3EECED65.ACF1A6B7@engcorp.com> Message-ID: <3EEE1210.3004AB45@engcorp.com> Moshe Zadka wrote: > > I have always been slightly at odds with the XP community, and I > think your post shows why acutely: Don't mistake me for the XP community. I'm just me. > On Mon, 16 Jun 2003, Peter Hansen wrote: > > > Without tests, source code is a liability, not an asset. > > That's, of course, correct but terribly misleading. Source code, > with or without tests, is always a liability. I shortened it from a previous post, in which I continued "Source code with good unit and acceptance tests is an asset." Sounds like you wouldn't agree. For my company, it's very clear that it's true, however, so I guess once again (surprise!) I speak only for myself. :-) > Sure, tests sometimes reduce bugs. And sometimes not. And sometimes > they reduce bugs, but less than what you would have accomplished > if you did something else. Sometimes, of course, tests are the > best way to fix bugs. The important thing to realize is "not always". [snip] > I tend to write code, and then write tests if and when I get to them. > Sometimes, I only write tests before a big refactor. Sometimes, > I do the big refactor and just check several command-line options > manually to check it hasn't broken. Following a religion, like "always > write tests first", has always looked silly to me. Sorry :) I agree. Good thing we don't actually *always* write tests, nor always write them first. ;-) Don't mistake strong claims for religion either... I make them to spur the truly test-less on to consider and investigate and practice writing tests, because _they_ are the ones who are writing crappy code, not you, who might understand when to test and when not to test. -Peter From mvs2 at linuxmail.org Wed Jun 11 10:43:27 2003 From: mvs2 at linuxmail.org (marcus) Date: 11 Jun 2003 07:43:27 -0700 Subject: Iteration through a text file. References: Message-ID: <1f9c7669.0306110643.3cc34cd7@posting.google.com> David's code was exactly what I was looking for. I've changed the print statements to write out to a .csv file, and everything works great. Thanks to all who replied, and thanks to David for the kind examples. I'll be going through it again line by line as to gain an understanding of how this was constructed. I've seen it work, now I want to see how it works. :) Thanks again, all. From suresh_vsamy at rediffmail.com Tue Jun 10 08:23:50 2003 From: suresh_vsamy at rediffmail.com (Suresh Kumar) Date: 10 Jun 2003 12:23:50 -0000 Subject: Partially solved Pmw.ScrolledCanvas issues..... Message-ID: <20030610122350.20635.qmail@webmail27.rediffmail.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From mgerrans at mindspring.com Wed Jun 18 02:13:03 2003 From: mgerrans at mindspring.com (Matt Gerrans) Date: Tue, 17 Jun 2003 23:13:03 -0700 Subject: a clean way to define dictionary References: <3EEFEBFD.8090003@nospam.com> <3EEFEF90.4000703@nospam.com> Message-ID: I just had a very similar task today; I would build your dictionary like this: items = {} for pair in [line.split() for line in lst.split('\n')]: if len(pair) == 2: key,value = pair items[key] = int(value) # (or long, if necessary) (I'm not into the real cryptic one-liners, I don't want to discourage potential newcomers to Python who may stumble across my code). Also, you may want some exception handling if your input can't be trusted to always be in the format shown. By the way, the problem I was dealing with was a work around for a bug in the Microsoft Visual Studio .Net has a strange bug that causes custom controls to keep on automatically getting bigger every time you open a module. I created a list file containing modules I'm working on and the controls that Visual Studio keeps on hosing up, along with their desired sizes, like so: d:\path\module1.cs userControl1 100 200 d:\path\module1.cs userControl2 130 230 d:\path\module2.cs userControlA 200 300 userControlA 200 300 d:\path\module3.cs userControlA 400 500 (in the case where no file is specified, it is assumed to be the one from the last line where one was.) I read this into a dictionary then run through all the files in the dictionary's keys and repair their controls' sizes right before a build. From andrew-pythonlist at puzzling.org Sun Jun 15 09:47:19 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Sun, 15 Jun 2003 23:47:19 +1000 Subject: Use __del__ methods to improve gc? In-Reply-To: References: Message-ID: <20030615134719.GA23784@frobozz> On Fri, Jun 13, 2003 at 11:27:45AM -0500, Edward K. Ream wrote: > > I suspect the paragraph you mean might be...: [snip] > > That's the one. Thanks Alex. It is now up on my wall :-) > > BTW, I'm chuckling a little less now. Executing: > > print len(gc.garbage), len(gc.get_objects()) > > periodically shows that my app is steadily eating memory. len(gc.garbage) > remains zero while len(gc.get_objects()) steadily increases. And I thought > I was recycling all bindings :-( > > You wouldn't know of something similar to timeit for storage allocation, > would you? Something that's might help a little is: import gc, sys, types def mostRefs(n=30): d = {} for obj in gc.get_objects(): if type(obj) in (types.ClassType, types.TypeType): d[obj] = sys.getrefcount(obj) counts = [(x[1],x[0]) for x in d.items()] counts.sort() counts = counts[-n:] counts.reverse() return counts Which is a rather nasty way to find out what the classes and types have the most instances alive (because each instance has a reference to its class, a class's ref count is roughly equal to the number of instances). -Andrew. From fuka at fuxoft.cz Thu Jun 5 04:54:45 2003 From: fuka at fuxoft.cz (Frantisek Fuka) Date: Thu, 05 Jun 2003 10:54:45 +0200 Subject: JavaScript parser in Python In-Reply-To: <3EDDEF4D.CEB99B24@engcorp.com> References: <3EDDEF4D.CEB99B24@engcorp.com> Message-ID: >>And what about Python script that could disassemble the compiled Java >>file into the primitive "Java-assembler" instructions? (i.e. not Java >>source) > > Just to clarify, in case you weren't aware "Frantisek": Java is *not* > related to Javascript. The two are very different beasts and have next > to nothing in common. Oops, shame on me... From regnivon at netscape.net Tue Jun 17 13:10:33 2003 From: regnivon at netscape.net (scn) Date: 17 Jun 2003 10:10:33 -0700 Subject: user authentication interface in python References: <3cf72d52.0306130501.6acb9984@posting.google.com> Message-ID: <3cf72d52.0306170910.dc711fb@posting.google.com> Gerhard H?ring wrote in message news:... > 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. thanks for responding. what i wanted to achieve was keeping the database access information in a separate file, similar to the convention i've seen used in php. the db connection, username and password information was typically stored in an 'configure.inc' file and included in the main script using the 'include' statement. i suspect i need to learn a little more about building web applications in python and try to think 'python' rather than 'php'? i'll think my questions through a little better next time. thank you. scn From jepler at unpythonic.net Wed Jun 25 22:24:26 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 25 Jun 2003 21:24:26 -0500 Subject: [ANN] Partial.py: convenient notation for partial application/currying In-Reply-To: References: Message-ID: <20030626022426.GB26038@unpythonic.net> Hm, interesting. > >>> mapcall(_.upper, ["list", "of", "strings"]) So you are forced to use 'mapcall' instead of 'map' for some reason? It seems like you could define _ in such a way that this was not necessary (this may not fit in with your whole module, though---also, performance of my approach is untested and uncompared with mapcall(_., ...). class MethodCaller: def __init__(self, method_name): self.method_name = method_name def __call__(self, obj, *args, **kw): method = getattr(obj, self.method_name) return method(*args, **kw) class UnderscoreMaker: def __init__(self): pass def __getattr__(self, m): return MethodCaller(m) _ = UnderscoreMaker() >>> map(_.upper, "abc") ['A', 'B', 'C'] Here's an api idea (no implementation) for currying: def f(x, y, z): print x, y, z class C: f = f # _[] gives a curryable, and curryable[] curries. _ when currying leaves # the arg open. If this was integrated in the language, f[_, ...] would # mean the same thing as _[f][...] >>> g = _[f][_, _, 'a'] >>> g(1, 2) 1 2 a # Might as well allow this shorthand >>> g = _[f, _, 'a'] >>> g(1, 2) 1 a 2 >>> c = C() # A MethodCaller is also curryable[]. _ means the same thing >>> g = _.f['a'] >>> g(c, 1) <__main__.C instance at 0xdeadbeef> a 1 Of course, there are always those who already have a use for _: the interactive prompt, gettext-style i18n, and god knows what else... Also, the triple-use of _ seems a bit dirty. Another thing that would be cool is if Python could perform constant propagation when currying, possibly giving a better/more efficient function instead of a slower one with more indirection. Jeff PS What? You mean you already had this thread twice this year? Why wasn't I invited? From andrew at acooke.org Sat Jun 7 18:31:07 2003 From: andrew at acooke.org (andrew cooke) Date: 07 Jun 2003 18:31:07 -0400 Subject: Help with Lazy Evaluation In-Reply-To: <3EE24DBA.8020204@geekabytes.net> References: <3EE24DBA.8020204@geekabytes.net> Message-ID: <87d6hplduc.fsf@acooke.org> you can use generators as a way of generating lazy lists: http://www.python.org/doc/current/ref/yield.html otherwise you can use closures: def stream(x): return lambda : (x, stream(x+1)) x = stream(10) for i in range(5): (n, x) = x() print n 10 11 12 13 14 andrew junk writes: > Information Please? > > Hi. I've looked throught the Python-list archives and I couldn't find > what I'm looking for. > > Has anyone written a module that supports infinite sets and/or lazy > evaluation? If so, could you please let me know? [...] -- http://www.acooke.org From Ludger.Humbert at cs.uni-dortmund.de Mon Jun 16 06:11:49 2003 From: Ludger.Humbert at cs.uni-dortmund.de (Ludger.Humbert) Date: Mon, 16 Jun 2003 12:11:49 +0200 Subject: One Problem -- how to implement in three programming paradigms in Python Message-ID: <3EED97E5.1080100@cs.uni-dortmund.de> Hi, in our introduction course "didactics of informatics" for students we want to show that it is possible to realize one problem *clean* in several programming paradigms. We want to use Python as programming language to implement the solutions. The problem is shown at http://in.hagen.de/~humbert/vortraege/F.Grundkonzepte_html/22.html knowledge based solution ======================== A possible solution in Prolog http://in.hagen.de/~humbert/vortraege/F.Grundkonzepte_html/23.html If one uses holmes [from Mark Lutz, Programming Python, pp 1039--1040] the solution can be expressed as ("nach" -- german for "to"): rules (filename labyrinth3.kb): ~~~~~ rule f01 if true then weg rein nach 28. ... rule f20 if true then weg 41 nach raus. rule r1 if weg ?a nach ?b, weg ?b nach ?c then tour ?a nach ?c. rule r2 if weg ?a nach ?b, tour ?b nach ?c then tour ?a nach ?c. the dialog in holmes: -Holmes2 inference engine- holmes> @= ../labyrinth3.kb holmes> ?- tour rein nach raus ... yes: (no variables) show proof ? y "tour rein nach raus" by rule r2 "weg rein nach 28" by rule f01 ... Now we are looking for other soultions, we can express in Python. functional solution? ==================== ?? objectoriented solution? ======================== ?? TNX Ludger Humbert From mcfletch at rogers.com Mon Jun 16 14:44:06 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 16 Jun 2003 14:44:06 -0400 Subject: Rational Rose ".ptl" file parsing? In-Reply-To: References: Message-ID: <3EEE0FF6.1070408@rogers.com> Well, the "lisp.py" example from simpleparse seems to parse it fine, but all you get out is a set of "name", "string", "list" and "number" records (in a tree) (i.e. the parser's just giving you what lisp structures were found). You'd have to interpret the results yourself regarding what each name is *meaning*. The grammar is pretty simple from what you've shown, you could probably hand-code it as easily as using a parser. Enjoy yourself, Mike Here's what you get on a small sample string (note that everything below "float" is ignorable in most cases): success '(object Design "Logical View"\n is_unit \tTRUE\n is_loaded \t(test this 2.3456))' 86 'list' : '(object Design "Logical View"\n is_unit \tTRUE\n i... (0, 86) | 'name' : 'object' (1, 7) | 'name' : 'Design' (8, 14) | 'string_double_quote... : '"Logical View"' (15, 29) | | 'char_no_quote' : 'Logical View' (16, 28) | 'name' : 'is_unit' (34, 41) | 'name' : 'TRUE' (46, 50) | 'name' : 'is_loaded' (55, 64) | 'list' : '(test this 2.3456)' (67, 85) | | 'name' : 'test' (68, 72) | | 'name' : 'this' (73, 77) | | 'number_expr' : '2.3456' (78, 84) | | | 'number' : '2.3456' (78, 84) | | | | 'float' : '2.3456' (78, 84) | | | | | 'explicit_base' : '2.3456' (78, 84) | | | | | | 'int_unsigned' : '2' (78, 79) | | | | | | 'decimal_fraction' : '.3456' (79, 84) | | | | | | | 'int_unsigned' : '3456' (80, 84) Harry George wrote: >Anyone have a handy parser for the RatRose .ptl file format? Want to >get it into an object tree reasonable naming convetions. Iwas going >to do this with shlex, but I'd go with anything already working. It >occurs to me that this is fairly lispish, so "readlisp.py" is another >candidate. > > ... _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From peter at engcorp.com Mon Jun 2 19:45:16 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 02 Jun 2003 19:45:16 -0400 Subject: PySerial rereads its own data References: Message-ID: <3EDBE18C.2C58B42E@engcorp.com> Cliff Wells wrote: > > I'm trying to write an app that talks to a bit of hardware on the serial > port. As a test setup, I've got a null modem cable linking /dev/ttyS0 > and /dev/ttyS1 on the same PC. [snip] > 'hello' correctly appears on the console running 'cat /dev/ttyS1'. > > My question is this: why do I get back the data I just wrote? More to > the point, how do I stop it? Maybe check (or post?) the output of "stty" for /dev/ttyS0 on the sending machine? Echoing? -Peter From tismer at tismer.com Mon Jun 30 20:32:26 2003 From: tismer at tismer.com (Christian Tismer) Date: Tue, 01 Jul 2003 02:32:26 +0200 Subject: Newbie: "compiling" scrips (?) In-Reply-To: <20030630155721.A6906@prim.han.de> References: <3EF9CBD8.F3AFF856@hotmail.com> <20030630155721.A6906@prim.han.de> Message-ID: <3F00D69A.8050901@tismer.com> holger krekel wrote: > 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). Continuations, in the full sense of Stackless 1.0, are probably not necessary, as they are not needed for CPython. > 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. To give you an update after the conversations on the sprint, this is just one idea out of at least three. I am going to study and implement them all. PyPy gives us this opportunity. The bare chance to just modify the code generator is tempting, but pruning certain paths in the tree of possible solutions too early is not in the sense of PyPy. Besides the code generator, there are both the Stackless 1.0 and 2.0 approaches, which are valid solutions which can and should be implemented for PyPy. There is much more to it, to be discussed elsewhere. > Doing this manually at the C-level (or Python-level for that matter) is > tedious and error-prone. Interesting. It seems that some people have more experience with this stuff than I expected. I'd be glad to learn more... - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From db3l at fitlinxx.com Wed Jun 25 16:58:17 2003 From: db3l at fitlinxx.com (David Bolen) Date: 25 Jun 2003 16:58:17 -0400 Subject: [ANN] pylint-0.1.2 References: <6q1xxrpcu0.fsf@salmakis.intevation.de> <6qsmq7ntwd.fsf@salmakis.intevation.de> <3EF9FAD4.7B98ECBC@easystreet.com> Message-ID: achrist at easystreet.com writes: > I just hit an unfixable (for now) problem with pychecker, too. > Ran out of memory. My machine is WinNT 4.0 + 128 MB, and running > pychecker on a program (40k LOC + wxPython + a few other library > packages) runs me out of memory with nothing else running. > (I've got an old machine for which it is very hard to find memory > upgrade) How about some more disk? And what's your virtual memory set to? It may stink in terms of performance, depending on what the real working set size is, but just giving yourself some more virtual memory (aka disk or upping the defined swap) should take care of the out of memory error. That is unless the code is actually tickling some sort of bug in PyChecker that causes it to burn memory unnecessarily. -- David From max at cNOvSisiPonAtecMh.com Tue Jun 17 10:05:19 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Tue, 17 Jun 2003 14:05:19 GMT Subject: The beauty of Python References: Message-ID: Another thing to look at is python 'snippets', which I think I saw on sourceforge.net (but can no longer find). Also try some articles that concentrate on features that make Python very appealing, such as the 'charming python' column. max. -- ======================================== Max Khesin, software developer - max at cNvOiSsPiAoMntech.com [check out our image compression software at www.cvisiontech.com, JBIG2-PDF compression @ www.cvisiontech.com/cvistapdf.html] "Thomas Weholt ( PRIVAT )" <2002 at weholt.org> wrote in message news:R5FHa.7104$Hb.128118 at news4.e.nsc.no... > 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 andrew at acooke.org Wed Jun 4 08:56:36 2003 From: andrew at acooke.org (andrew cooke) Date: 04 Jun 2003 08:56:36 -0400 Subject: Yield inside try...finally In-Reply-To: References: <3EDCEC1F.96CB0766@hotmail.com> Message-ID: <87wug2knln.fsf@acooke.org> Michael Sparks writes: [...] > This wheel re-invention is designed to see if using a generator based > (or rather co-routine) approach produces clearer, more readable, more > maintainable code, with significantly less fragility. It might not pan > out, but then again, it might. (After all state machines and generators > are functionally equivalent.) [...] i've been sitting her thinking and staring out of the window and i can't see how you can make finally play nicely with continuations (stating the obvious: exceptions and coroutines can be unified with continuations, but "finally" involves an extra guarantee that i can't see how to enforce). but what are you doing here? aren't co-routines just a way of simulating a separate thread? ok, not quite - they give you certain ways of sychronizing the program that would be much uglier if you had two threads. but if you're higher level code is supposed to be guaranteeing that the coroutine is repeatedly called to completion, then it's more like a separate thread... in that case, maybe you should use a separate thread?! i don't know anything about threads in python, so maybe this is just silly. but if it's not, how would you do it? it looks like your yield is there to carry information back to the caller routine about progress - couldn't this be done by sending messages on a channel back to the main caller thread? ideally the channel would be a buffer that doesn't block, so that the worker thread can run to completion (making the finally clause work as expected). the caller thread can then check the channel, popping the progress reports off the stack and acting accordingly. the big advantage of this approach is that finally works as expected because the worker thread must (given the non-blocking channel) run to conclusion (either via an exception or on sucess). disadvantages are: - if the main thread needs to controll the worker thread (in which case you're back with the same problem - you have to rely on your top level code to not freeze the worker thread, just as now you have to rely on it to call the coroutine through to completion) - if support for concurrent code in python is poor don't know if that helps, probably too far removed from what you want... cheers, andrew -- http://www.acooke.org From bgailer at alum.rpi.edu Mon Jun 30 13:16:42 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 30 Jun 2003 11:16:42 -0600 Subject: Idiomatic way of repeating items in a sequence. In-Reply-To: <5.2.1.1.0.20030630103828.025a57d0@66.28.54.253> References: Message-ID: <5.2.1.1.0.20030630111404.025aef78@66.28.54.253> At 10:47 AM 6/30/2003 -0600, Bob Gailer wrote: >At 04:26 AM 6/30/2003 -0700, alr wrote: > >>I need to repeat each item in a list n times, like this function does: >> >> def repeatitems(sequence, repetitions): >> newlist = [] >> for item in sequence: >> for i in range(repetitions): >> newlist.append(item) >> return newlist >> >>Output: >> >> >>> repeatitems(['a', 'b', 'c'], 3) >> ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'] >> >>Clear and simple. But i wonder if there is a more idiomatic way. Surely >>not this: >> >> def repeatitems(sequence, repetitions): >> return reduce(lambda l, i: l + i, [[item] * repetitions for item >> in sequence]) > > >>> sequence = ['a', 'b', 'c'] > >>> repetitions = 3 > >>> newlist = [] > >>> map(newlist.extend,apply(zip,[sequence]*repetitions)) > >>> newlist >['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'] Then I noticed John Hunter's IMHO more elegant solution >>> newlist = [x for x in sequence for i in range(len(sequence))] but would adjust it to >>> newlist = [x for x in sequence for i in range(repetitions)] to meet the requirements. 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 owen at nojunk.invalid Wed Jun 25 15:01:00 2003 From: owen at nojunk.invalid (Russell E. Owen) Date: Wed, 25 Jun 2003 12:01:00 -0700 Subject: cvs checkout question References: <3EF8A988.90405@v.loewis.de> Message-ID: Thanks for the helpful replies! I did eventually get in and got what looked like most of the files (including the two I really cared about). It eventually hung and after about an hour of nothing happening I killed it. -- Russell From kavi_ranjith at yahoo.com Mon Jun 2 09:24:47 2003 From: kavi_ranjith at yahoo.com (Ranjith Kumar) Date: 2 Jun 2003 06:24:47 -0700 Subject: Java Class Loading into Jython References: <28cf7c6f.0305280002.4c76564f@posting.google.com> Message-ID: <28cf7c6f.0306020524.6a301509@posting.google.com> Thank you very much. The problem of class not found occurs in the following case. When I place the class file with the package com.xxx.yyy.Imported.class under a directory ( which is in the classpath ) and this directory is not the one in which the jvm is running. The same class is loaded when the class is present in the jvm directory. / classes / com / xxx / yyy / Imorted - not loaded / com / xxx / yyy / Imorted - loaded perfectly I would like to know on what criteria the byte files loaded into the jvm. ranjith Ganesan R wrote in message news:... > >>>>> "Ranjith" == Ranjith Kumar writes: > > > Hi there , > > I am running an java application which uses jython interpreter. My aim > > is to import my custom java class files into my jython scripts. These > > class files are not placed inside any of the jars residing in the > > classpath. Where should i place the class files. > > Any class files in your classpath can be loaded in jython. If those > classes are accessible from your java application you are already set. > > Ganesan From missive at frontiernet.net Sat Jun 21 16:18:44 2003 From: missive at frontiernet.net (Lee Harr) Date: Sat, 21 Jun 2003 20:18:44 GMT Subject: XML References: <3EF471BA.EE4F056@hotmail.com> Message-ID: In article , Martin v. L?wis wrote: > Ben Finney writes: > > [In response to Alan Kennedy claiming that HTML is the most widely > used [electronic] document format in human history?] >> It isn't. That award would go to 7-bit ASCII plain text. >> >> Facetious? No. > > Do you have numbers to prove that? Looking at my disk: > > martin at mira:~> locate .html|wc > 41104 41104 2425699 > martin at mira:~> locate .txt|wc > 7958 7963 389013 > > So I do have way more .html files than .txt files. I haven't counted > source code files, here, obviously, but I'm not sure whether those > would qualify as '7-bit ASCII plain text'. > How about email? From kylotan at hotmail.com Mon Jun 9 11:52:08 2003 From: kylotan at hotmail.com (Kylotan) Date: 9 Jun 2003 08:52:08 -0700 Subject: File reading using delimiters Message-ID: <153fa67.0306090752.218d23b1@posting.google.com> All the examples of reading files in Python seem to concern reading a line at a time. But this is not much good to me as I want to be able to read up to arbitrary delimiters without worrying about how many lines I'm spanning. With my rudimentary Python knowledge I'm having to read in multiple lines, concatenate them, search for the delimiter, split the result if necessary, and carry forward whatever was after the delimiter to the next operation. Is there a better way of reading until a certain character is encountered, and no more? From mleeds at mlp.com Thu Jun 5 19:12:05 2003 From: mleeds at mlp.com (Leeds, Mark) Date: Thu, 5 Jun 2003 19:12:05 -0400 Subject: FW: (no subject) Message-ID: I have another date question : Now I have dates that are of the form 2/14/1980 so I tried to read them in using Temptime = time.strptime(filedate,"%m" + "//" + "%d" + "//" + "%Y") But I get some weird error like format mismatch. Could it be because the date is 2/14 instead of 02/14 ? This will be my last question about dates. mark -----Original Message----- From: Skip Montanaro [mailto:skip at pobox.com] Sent: Thursday, June 05, 2003 3:08 PM To: Leeds, Mark Cc: python-list at python.org Subject: Re: (no subject) Mark> i have a date, say as a string 26Nov2002 and i want to convert it Mark> to a string 20021126. Python has a time module with strptime (parse) and strftime (format) functions. >>> import time >>> t = time.strptime("26Nov2002", "%d%b%Y") >>> t (2002, 11, 26, 0, 0, 0, 1, 330, -1) >>> time.strftime("%Y%m%d", t) '20021126' Skip From ed at membled.com Mon Jun 9 16:29:28 2003 From: ed at membled.com (Ed Avis) Date: 09 Jun 2003 21:29:28 +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: >>>For example, what is the meaning of >>> >>>a = lambda b : return b > 0 >Why not the same as > >def fresh(b): > return b >a = fresh > 0 Hmm, I see what you mean. Other articles on this thread have also demonstrated ambiguous parses. It does look like the only way to have a simple_stmt inside a lambda is to have some kind of bracketing, and that is inconsistent with the rest of the language (which uses indentation and newline) and in particular with ordinary function definitions. -- Ed Avis From http Mon Jun 2 23:19:53 2003 From: http (Paul Rubin) Date: 02 Jun 2003 20:19:53 -0700 Subject: Toss your cookies (Mozilla cookie file filter) Message-ID: <7xisrn4zl2.fsf@ruckus.brouhaha.com> I threw together a simple Python script to remove unwanted cookies from my Mozilla cookie file. Mozilla has some built-in cookie filtering preferences but they're not that useful. Some better preferences will probably be in a later version (there's a very active CR in Bugzilla on the subject) so this script will become obsolete when that happens, but for now I find it handy enough that I thought I'd post it here. ================================================================ #!/usr/bin/python # clean mozilla cookie file by removing unwanted cookies # # Copyright 2003 by Paul Rubin, written May 2003 # Copying permissions: GNU General Public License version 2, www.gnu.org # # Uses two files, "whitelist" and "blacklist" # file format: # blank lines and lines starting with '#' are ignored # hostname.domain.tld # matches all cookies from that domain # .domain.tld # matches all cookies from that domain or any subdomain # hostname.domain.tld:cookie1,cookie2,... # matches only cookies whose names appear in the list # # The script reads the whitelist and discards any cookies that don't # match some line in it. Then it reads the blacklist and discards # any cookies that match it, that have fallen through the whitelist. class ruledict: def __init__(self): self.rules = {} def add(self, rule): rule = rule.split(':') domain = rule[0] if self.rules.get(domain,0) == 1: # already accepting all cookies for this domain return if len(rule) == 1: # accept all cookies for this domain self.rules[domain] = 1 return cookie_names = [a.strip() for a in rule[1].split(',')] if domain not in self.rules: self.rules[domain] = {} self.rules[domain].update(dict([(a,1) for a in cookie_names])) def match(self, cookie): import re domain = cookie[0] cookie_name = cookie[5] found = 1 while found: if domain in self.rules: d = self.rules[domain] if d == 1 or cookie_name in d: return 1 if not domain.startswith('.'): domain, found = '.' + domain, 1 else: domain, found = re.subn('^(.[^.]*)\.', '.', domain) return 0 def read_ruledict(filename): val = ruledict() for line in open(filename): if line[0] == '#' or line == '\n': continue val.add(line.strip()) return val vv = read_ruledict('whitelist') import re,tempfile,os cookie_filename = "cookies.txt" global whitelist,blacklist def backupfile(filename): # generate backup filename from filename and current time from time import time # return filename + '.' + hex(int(time()))[2:] + "~" # don't make so many backups return filename + "~" def good_cookie(cookie): return whitelist.match(cookie) and not blacklist.match(cookie) def main(): global whitelist, blacklist whitelist = read_ruledict("whitelist") blacklist = read_ruledict("blacklist") f = open(cookie_filename) tempname = tempfile.mktemp() out = open(tempname, "w") killed = {} for line in f: cookie = line.split('\t') if len(cookie) == 1 or line[0] == '#' or good_cookie(cookie): out.write(line) else: origin = cookie[0] killed[origin] = 1 + killed.get(origin, 0) if killed: print 'Killed:' ko = killed.keys() ko.sort() for k in ko: print '%s (%d)'% (k, killed[k]) os.rename(cookie_filename, backupfile(cookie_filename)) os.rename(tempname, cookie_filename) main() From ed at membled.com Mon Jun 9 16:07:10 2003 From: ed at membled.com (Ed Avis) Date: 09 Jun 2003 21:07:10 +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]) >The problem with this plan is the amount of lookahead required for >the parser to decide among possible parse trees. You're right. Since LL(1)-ness is a good property to have, my suggestion of putting simple_stmt directly inside lambda will not work. I don't plan to get into a tar-pit of proposing ever more complex and baroque grammar changes, each one in turn being shot down by someone finding an unparseable or ambiguous or counterintuitive code sample. But I would like to have a second attempt. >I actually think parentheses directly around the statement is a >more promising approach. I was just about to post that when I thought I should read the rest of your reply first ;-). Hmm, so maybe there would have to be two cases, one containing an expression as at present, and a second case lambda_form ::= "lambda" [parameter_list]: "(" simple_stmt ")" This would, I believe, fix the with 'the rest of the language' such as the is-it-a-tuple-or-not example you cite. But there is the problem that the two different productions for lambda overlap, after all, an expression can be wrapped in ( ) and so '(e)' might be the expression (e) or the expression_stmt e. With the idea of inserting an implicit 'return' before expression_stmts inside lambda functions, the semantics of the two would be the same so it might not matter. Or maybe the bracketing could be used to avoid the 'implicit return' peculiarity altogether. The meaning of lambda x: expr could be defined to be the same as a named function containing 'return expr'. While the meaning of lambda x: (simple_stmt) would be defined to be like a named function containing simple_stmt. If we arrange that the first grammar rule always matches in preference to the second, then existing constructs like 'lambda x: (3)' would not change in meaning. I hope this makes some sense. (I'm tempted to say that if starting from scratch I would allow only one-line statements inside lambdas, and require explicit 'return'. Or else I would not require 'return' inside named functions but return the value of the last expression_stmt evaluated. Either way I'd want to make lambda function bodies and named function bodies act the same way as far as possible. Anyway, starting from scratch is not an option here.) The trouble with bracketing is that the code you write is no longer so obvious. -- What, I have to put () round the body of my lambda function? I don't do that for ordinary function bodies. I have to put () around 'print' but not around 'sys.exit()' - why? And so on. So if putting brackets round the body of the anonymous function is the only way to make it work, I might say that it is too surprising and inconsistent with ordinary function definitions, exactly the same complaints I had against the status quo. Yes, life would be easier if all lambda functions currently had 'return expr' rather than just 'expr' as their body. But if only expressions are allowed, this is just syntactic salt and in any case not backwards compatible. >In the grammar, precedence is implicit in the nesting of productions, >e.g., 'not' has a higher precedence than 'and' just because not_test >occurs in expansions of and_test and not (directly) vice versa. Right, that clarifies things. -- Ed Avis From domma at procoders.net Wed Jun 18 10:10:35 2003 From: domma at procoders.net (Achim Domma) Date: Wed, 18 Jun 2003 16:10:35 +0200 Subject: urllib2: non-ascii characters in url References: <3EF059D3.10ED7902@hotmail.com> Message-ID: "Alan Kennedy" wrote in message news:3EF059D3.10ED7902 at hotmail.com... > Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import urlparse > >>> import urllib > >>> def correcturl(u): > ... s, a, p, q, f = urlparse.urlsplit(u) > ... p = urllib.quote(p) > ... return urlparse.urlunsplit((s, a, p, q, f)) I had to add a q = urllib.quote(q,"=&") but then it works fine. Thanks! Achim From a at b.c Tue Jun 17 12:40:19 2003 From: a at b.c (Patrick Useldinger) Date: Tue, 17 Jun 2003 18:40:19 +0200 Subject: Observer Pattern (if you got some spare time) In-Reply-To: References: <3eee0283$1_1@news.vo.lu> Message-ID: <3eef42a0_2@news.vo.lu> Tim Rowe wrote: > I'm interested in the comment on class PubSub: "you should only need > one instance of this class". You can, as Troy points out, have as many instances of the PubSub class as you wish; I just can't see *why* you would like to do that. > The approach in Gamma et al > looks to be to be far easier to manage: make each subject handle its > own message queue rather than have a centralised despatcher. Is there > a reason you didn't go that route, given that Python supports the > necessary multiple inheritance? Yes, serveral: -1- I prefer to avoid multiple inheritance, because this potentially raises a few problems and puts constraints on the classes that inherit, and therefore limits reusability. -2- Imagine you have a general-purpose class Tool with methods m1, m2, m3, which are supposed to be broadly reusable. In this solution, an instance of Tool will just attach itself to subjects "Tool.m1", "Tool.m2" and "Tool.m3". Any class who wants to use these methods will just publish those "well-known" subjects, and no objects ends up knowing that the other object exists. They all just know about the central dispatcher. This approach decouples classes even more, and also allows for more reusability. -3- I wanted to have "multi-messages", a kind of broadcasting medium where everyone is allowed to publish information on the same subject. I cannot see how to do this easily with the standard pattern. With a central instance, you just agree on a common subject, that's all. -Patrick -- Real e-mail address is 'cHVAdm8ubHU=\n'.decode('base64') Visit my Homepage at http://www.homepages.lu/pu/ From scott_list at mischko.com Wed Jun 18 18:36:14 2003 From: scott_list at mischko.com (Scott Chapman) Date: Wed, 18 Jun 2003 15:36:14 -0700 Subject: Postgresql: plpython may be removed In-Reply-To: <16112.57458.12166.525214@montanaro.dyndns.org> References: <200306181436.21252.scott_list@mischko.com> <16112.57458.12166.525214@montanaro.dyndns.org> Message-ID: <200306181536.14899.scott_list@mischko.com> On Wednesday 18 June 2003 14:58, Skip Montanaro wrote: > 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. This is not about using PostgreSQL from Python. It's about using Python from PostgreSQL. - Scott From clifford.wells at attbi.com Sun Jun 15 17:57:22 2003 From: clifford.wells at attbi.com (Cliff Wells) Date: 15 Jun 2003 14:57:22 -0700 Subject: does lack of type declarations make Python unsafe? In-Reply-To: <114xq48ewelrf.1xyyacwlxdk1p.dlg@40tude.net> References: <3064b51d.0306151228.22c595e0@posting.google.com> <114xq48ewelrf.1xyyacwlxdk1p.dlg@40tude.net> Message-ID: <1055714242.6232.1.camel@devilbox.homelinux.net> On Sun, 2003-06-15 at 14:45, Marek "Baczek" Baczy?ski wrote: > Searching for a lost colon also takes a lot of time > *and* tends to happen more often. -- Cliff Wells From bleach at apple.com Wed Jun 18 13:46:57 2003 From: bleach at apple.com (Brett Leach) Date: Wed, 18 Jun 2003 12:46:57 -0500 Subject: Python Cannot be Killed References: Message-ID: in article mailman.1055875654.5426.python-list at python.org, Michael Chermside at mcherm at mcherm.com wrote on 6/17/03 1:45 PM: > Terry Reedy wrote: >> Python cannot be killed. > > Gerhard suggested: >> Try stop feeding your Python and just wait a few months. > > "Few" may be more than you think. From > http://animaldiversity.ummz.umich.edu/accounts/python/p._reticulatus > >> Reticulated pythons, like all reptiles, have a low metabolic rate >> allowing them to go without food for long periods of time. In 1926, >> a captive specimen at Regent's Park refused food for 23 months, after >> which it accepted a meal and continued to feed normally (Murphy and >> Henderson 1997). > > If you do this I would be *very* cautious about approaching said python. You might end up as the meal. From pythonguy at Hotpop.com Wed Jun 11 05:01:58 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 11 Jun 2003 02:01:58 -0700 Subject: Factorials References: <3ee1e6f1@shknews01> <84fc4588.0306100413.1125d1ee@posting.google.com> Message-ID: <84fc4588.0306110101.4a63666e@posting.google.com> Thank you. I did not know that lambda was in fact slower than operator methods, but now I do. I encountered lambda's in lisp first, where they are preferred over direct function calls. Looks like python's lambda is somewhat different. Perhaps the language developers should re-implement it in C. Thanks Anand Pillai "Terry Reedy" wrote in message news:... > "Anand Pillai" wrote in message > news:84fc4588.0306100413.1125d1ee at posting.google.com... > > Here is a version that will make the "functional programmers" > > happy. It is iterative rather than recursive. > > That will make some "functional programmers" unhappy, but let each > speak for his/herself. > > > def fac1(x): > > nums=range(x+1) > > return reduce(lambda x, y: x*y, nums[1:]) > .. > > def fac1(x): return reduce(lambda x, y: x*y, (range(x+1))[1:]) > > No reasons to construct two lists: range(x+1)[1:] == range(1,x+1) > No reason for lambda either: import operator, then operator.mul is C > coded multiplier which should be noticably faster that Python coded > lambda > Also, reduce croaks on empty list, so if you want fact(0) == 1, [as > needed, for instance in C(n,k) = n!/((n-k)!k!) ], you need starter > value 1, in which case, initial 1 in list is not needed. These all > give > > import operator > def fac1(x): return reduce(operator.add, range(2,x+1), 1) > > This will, however, not raise exception for negative x but return 1 > instead. Also range allows but truncates float args, so that > fact1(float) = fac1(int(float)) rather than raising exception or > returning float version from gamma function. So, giving up one-line > fetish, we might write > > def fac1(n): > if n < 0 or int(n) != n: raise ValueError("arg %g is not nonnegative > int" % n) > else: return reduce(operator.add, range(2,x+1), 1) > > Terry J. Reedy From staschuk at telusplanet.net Tue Jun 3 13:53:53 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 3 Jun 2003 11:53:53 -0600 Subject: Variable Modifications in a class In-Reply-To: <3EDCDB05.8E12F97@hotmail.com>; from alanmk@hotmail.com on Tue, Jun 03, 2003 at 06:29:41PM +0100 References: <3EDCDB05.8E12F97@hotmail.com> Message-ID: <20030603115352.C1162@tibia.amotlpaa.bogus> Quoth Alan Kennedy: > "Mehta, Anish" wrote: [...] > > c = b > ^^^^^ > > This is where you are misunderstanding python. > > "b" and "c" are not variables, they are references. They are simply a name, > which is "bound" to something, so the name "refers to" the something. Nitpicking: 'b' and 'c' *are* variables. It's just that what the word 'variable' means in Python is different than what it means in some other languages; in particular assignment is name-binding, not value-copying, as you make clear. -- 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 jack at performancedrivers.com Wed Jun 11 15:24:07 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 11 Jun 2003 15:24:07 -0400 Subject: __past__ (Was: Re: PEP-317) In-Reply-To: <20030611191633.GC5575@nl.linux.org>; from gerrit@nl.linux.org on Wed, Jun 11, 2003 at 09:16:33PM +0200 References: <1055255402.3ee5eb6ae09ee@mcherm.com> <1055312155.157424@yasure> <20030611191633.GC5575@nl.linux.org> Message-ID: <20030611152407.J1069@localhost.localdomain> On Wed, Jun 11, 2003 at 09:16:33PM +0200, Gerrit Holl wrote: > Roy Smith wrote: > > "Donn Cave" wrote: > > > "Never" would be a reasonable schedule, hope that's constructive. > > > The reasons advanced for breaking currently valid "raise" statements > > > would be excellent for a newly introduced feature, but those same > > > excellent sentiments add up to "gratuitous" here. Break things > > > only when necessary, not just for the sake of tidiness. > > > > I have to agree with that. I'm all for making stuff better, but if it > > means breaking something that currently works, it's a bad idea. I'd > > much rather live with a few "historical warts" in the language than have > > to put up with working code breaking. > > 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 makes letting something work again a *lot* easier. It is easy > to automate this if the interpreter it was written for is known. > Hmm... Python could have a --past commandline argument that tries > to run code, and when it fails, tries to find out whether it is > because of backwards incompatibility or not; if it is, it can (at > the users wish, of course) add these lines to the code. This would > more or less enforces new users to use new-style code. The point of __future__ is to give people a chance at using upcoming standard features. The __future__ enhancements are actively maintained working code. __past__ would mean maintaining both the old and the new standards. Putting switches in the code to handle it right both ways and doubling the maintenance workload. An easier way to implement __past__ is documentation. "If you want to do it the old way, download an old tarball" -jackdied From p at ulmcnett.com Thu Jun 5 19:40:55 2003 From: p at ulmcnett.com (Paul McNett) Date: Thu, 5 Jun 2003 16:40:55 -0700 Subject: How to reply???? In-Reply-To: <20030605201919.53918.qmail@web21604.mail.yahoo.com> References: <20030605201919.53918.qmail@web21604.mail.yahoo.com> Message-ID: <200306051640.55885.p@ulmcnett.com> DavidW Blaschke writes: > When I hit the reply button I get 3 choices: > 1. python-list at cwi.ni > 2. the e-mail address of the person who posted > 3. python-list-owner at yahoogroups.com > > I think I want to post to python-list at python.org. > Does anyone have a good way to do this without cutting > and pasting the message into compose, and mailing it > as normal e-mail? What email client are you using? I'm using KMail, and if I hit 'reply' (R) it will go to the original sender, if I hit "reply-all" (A) it will go to the original sender as well as python-list at python.org. If I hit "reply-list" (L) it will just go to python-list at python.org. Are you accessing this list via comp.lang.python (usenet) or via python-list at python.org (email)? -- Paul McNett From jjl at pobox.com Wed Jun 25 19:31:59 2003 From: jjl at pobox.com (John J. Lee) Date: 26 Jun 2003 00:31:59 +0100 Subject: Advice for developing in python with Microsoft Office? References: Message-ID: <871xxhvimo.fsf@pobox.com> claird at lairds.com (Cameron Laird) writes: [...] > Attempts to program Office frustrate many people. 'Fact, > it's hard to falsify the proposition that some of the > documentation has been managed in order to maximize > frustration. Microsoft seems to enjoy 'death by documentation'. It's not that the huge quantity of it is a bad thing per se, or that the individual bits of documentation are bad, so much as the fact that the various bits often don't seem to know of each others' existence. Perhaps that's achieved by the same people whose job it is to rename everything every few months? John From terry at wayforward.net Sun Jun 8 20:58:57 2003 From: terry at wayforward.net (Terence Way) Date: Sun, 08 Jun 2003 20:58:57 -0400 Subject: Hardware take on software testing. References: <2ae25c6b.0306060450.78e988f9@posting.google.com> Message-ID: On Fri, 06 Jun 2003 09:50:41 -0400, Paddy McCarthy wrote: > If software were tested like hardware... > What you're describing sounds a lot like IBM's Cleanroom: which as I recall had two broad principles: 1. Specify everything and hammer out flaws in review meetings; and 2. Rigorously track bugs (counted from the first time a file is compiled!), using random test data that matches the expected usage. If followed rigorously, then your S curve showed up, and the MTTF (Mean Time To Failure) could be calculated for a piece of software. I've used Cleanroom, and I have to honestly say I didn't have the discipline to carry it through -- which my team picked up on. The project we worked on didn't fail, but in the end bugs were found and stamped out the old-fashioned way. Cleanroom, and much of the software development methodologies, insist that bugs get more expensive as time goes on, so it's cost-effective to spend time up-front to remove all bugs. XP refutes that, and says bugs cost the same no matter what: it's only software, just change it when you find a bug. Despite this, I wonder if the two can be combined: XP with cleanroom testing, resulting in peer-reviewed well-specified software with a MTTF quality metric. Hrmm. From pythonguy at Hotpop.com Fri Jun 27 14:36:26 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 27 Jun 2003 11:36:26 -0700 Subject: wxPython Filedialog question Message-ID: <84fc4588.0306271036.52b98626@posting.google.com> Hi I am using wxPython version 2.4.0.1. When using wxFileDialog to save files, the filename returned is *always* the extension of the first entry in the wildcard. That is if my wildcard string is as "Bitmap files|*.bmp|JPEG files|*.jpg|GIF files|*.gif", the filename returned is always , even if I select "JPEG files" or "GIF files" in the "Save as type" combo of the file selection box. Is this a bug with wxPython ? Thanks Anand Pillai From mcfletch at rogers.com Wed Jun 11 13:20:26 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 11 Jun 2003 13:20:26 -0400 Subject: Looking for the greatest negative float value In-Reply-To: References: Message-ID: <3EE764DA.60708@rogers.com> The maximum negative float is probably somewhere close to: -1.79769313e+308 but it could be different on other platforms (I'm on a Win2K machine). HTH, Mike Gilles Lenfant wrote: >Hi, > >I need the same as... > >import sys >negmaxint = - sys.maxint -1 > >... but for float data > >any hint ? > >Thanks in advance. > >--Gilles > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From jjl at pobox.com Sat Jun 14 16:48:04 2003 From: jjl at pobox.com (John J. Lee) Date: 14 Jun 2003 21:48:04 +0100 Subject: pythonCOM with Flash References: <3ee9bfff$0$8301$4d4ebb8e@news.nl.uu.net> <87adckfz28.fsf@pobox.com> Message-ID: <87y904gzcr.fsf@pobox.com> Dave Brueck writes: > On Sat, 14 Jun 2003, John J. Lee wrote: [...] > > Or use IE as the control container. I think Alex Martelli has posted > > here about this (probably at length ;-) in the past. > > I don't think this would do what the OP wants, though. The point (as I > understood it) was to be able to use Python for the underlying app logic > and Flash as the UI. Yep, I understood that. > If you put the Flash control inside IE you're really > not that much closer to the goal and you've created more work for yourself > since you have to fiddle with both Python <--> IE as well as IE <--> Flash > control. Not according to Alex. See the first message here: http://www.google.com/groups?q=control+container+Martelli+IE+group:comp.lang.python Admittedly, I haven't tried it myself. John From jjl at pobox.com Thu Jun 19 21:29:40 2003 From: jjl at pobox.com (John J. Lee) Date: 20 Jun 2003 02:29:40 +0100 Subject: thinkings on shallow copy References: <3EF1849E.6060103@nospam.com> <3EF225AA.1000909@nospam.com> Message-ID: <87k7bhh6yj.fsf@pobox.com> Kendear writes: > Steven Taschuk wrote: > > Quoth Kendear: [...] > >>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. > essentially, "same object references" are the same as > "references to the same objects"... just as > "character pointer" is the same as "pointer to character" > in C. No, the two aren't analogous at all. It's what the 'same' refers to that's confusing us, not the relative order of 'object' and 'reference' per se. John From ed at membled.com Mon Jun 9 16:45:52 2003 From: ed at membled.com (Ed Avis) Date: 09 Jun 2003 21:45:52 +0100 Subject: a = b = 1 just syntactic sugar? References: Message-ID: Michael Chermside writes: >> cond and x or y >It looks like you somehow managed to overlook the most vigorous >discussion ever to grace this newsgroup. Hmm, most likely it was before my time, or I just ignored it. Anyway this above conditional was just a side topic in some larger thread, and I will now do my best to resist venturing further down that side road. Thanks for the tip, -- Ed Avis From mis6 at pitt.edu Mon Jun 16 09:00:14 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 16 Jun 2003 06:00:14 -0700 Subject: timeit References: <8a2Ha.209222$M01.92818@sccrnsc02> Message-ID: <2259b0e2.0306160500.7d25ca69@posting.google.com> "Bryan" wrote in message news:<8a2Ha.209222$M01.92818 at sccrnsc02>... > i tried timeit for the first time today, pretty darn impressive. i've > noticed that postings in this newsgroup use timeit on the command line and > with usually just one simple statement or loop. is this the only way to use > timeit? can timeit be used within a script? or to execute whole scripts? i > guess the obvious anwer that one is: > > timeit -s"import myscript" "myscript.main()" > > i'm just curious how other are exploiting timeit. > > thanks, > > bryan I have added timeit to the module containing my personal utility functions: # import timeit,__main__,warnings warnings.filterwarnings('ignore', 'import \* only allowed at module level',SyntaxWarning) def timeit_(stmt,setup='from __main__ import *',n=1000): t=timeit.Timer(stmt,setup) try: print t.repeat(number=n) except: t.print_exc() # Here is an example of usage (to measure the function call overhead): >>> from util import timeit_ >>> def f(): pass ... >>> timeit_('f()',n=1000000) [1.9124521017074585, 1.9128650426864624, 1.9139430522918701] More or less 2 seconds for a million of calls. HTH, Michele From mhammond at skippinet.com.au Tue Jun 3 19:16:15 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 03 Jun 2003 23:16:15 GMT Subject: easily immobilize PythonWin In-Reply-To: <3EDC6F0F.2010409@nospam.com> References: <3EDC6F0F.2010409@nospam.com> Message-ID: <3%9Da.4070$7E.46945@news-server.bigpond.net.au> Kendear wrote: > 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 IDLE runs programs in their own process. For Pythonwin, right-click on the taskbar icon, and select "Break into running code" Mark. From jkn at nicorp.f9.co.uk Tue Jun 17 12:54:38 2003 From: jkn at nicorp.f9.co.uk (Jon Nicoll) Date: 17 Jun 2003 09:54:38 -0700 Subject: "Structure and Interpretation of Computer Programs" in Python? References: Message-ID: <8351bb33.0306170854.51f8d39@posting.google.com> Hi Peter pcolsen at comcast.net (Peter Olsen) wrote in message news:... > Has anyone translated some of the programs in Abelson and Sussman's > "Structure and Interpretation of Computer Programs" from Scheme into > Python. > I think Sam Rushing has done just that. Have a look at his web pages: http://www.nightmare.com/software.html Sorry, I can't send you a direct email via google. Jon Nicoll > Python has replace Scheme as my favorite language, but I doubt that > anything will ever replace SICP as my favorite CS book. I'd like to > see the two melded, but probably I will ever have the time to do it > myself. > > (If you respond, please send a copy to me directly. Thanks!) > > Peter Olsen > pcolsen (at) comcast (dot) net > > Engineering is the art of using a professional knowledge of > mathematics and the physical sciences to improve the quality of life. From junk at geekabytes.net Mon Jun 9 10:13:42 2003 From: junk at geekabytes.net (Nielson Family) Date: Mon, 09 Jun 2003 08:13:42 -0600 Subject: Prolog-style unification? In-Reply-To: References: Message-ID: <3EE49616.3030304@geekabytes.net> Simon, See comments in line, 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() >> >> > >too verbose for me. howbout just Var ? > This logic code is currently _very_ experimental and the pseudo-syntax is still very fluid. Expect many changes to come. However, I should point out that I chose verbose names so that anyone looking at the code could read immediately what the logic code was. For example, suppose we chose your syntax and called the logic variables 'var'. That works okay using an import statment, but what if you use from logic import *? X = var() Y = var() That doesn't seam as clear to me as X = LogicalVariable(). I suppose it coulod be shortened to X = LogicVar() > > > >>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? > I am considering implementing iterators, but I _am_ trying to adhere to a prolog syntax as much as possible. My thesis work is in multiparadigm design patterns; in my current research, I have come to the conclusion that when attempting to make a language multiparadigm, it is often helpful to have each individual paradigm close to the most popular language of that paradigm rather than inventing 'new' syntax. On the other hand, I am also looking at multiparadigm syntax. I think that the iterators you suggest above are a good example of that (combining imperative and logical into a single construct). I am considering providing multiple syntax to perform the same functions. One syntax would be highly python-esque while the other would be more like Prolog (for example, I worked really hard to come up with a way to define inferences without creating them as a function; I did this so that it would look like Prolog but also that a reader would know instantly that it's not a function, its an inference; however, I think that in the end, I'll provide _both_ syntax as acceptable options). > > > >>print "--------------" >> >>Grandfather = logic.Fact() >>Grandfather(Grandfather.Grandfather, Grandfather.Grandson) ( >> Father(Grandfather.Grandfather, Grandfather.Son) >> Father(Grandfather.Son, Grandfather.Grandson)) >> >> > >does this use __getattr__ hooks? otherwise where does the attributes of >Grandfather come from? > Yes, this is using the __getattr__ hooks. There are all sorts of crazy things going on behind the scenes to get the constructs to work right. > > > >>while Grandfather(X,Y): >> print X,Y >> >> >>The output of this is: >> >>James Seth >>Seth Alex >>------------------ >>James Alex >> >>I'm still tracking down bugs all the time, but it's getting pretty good. >> >>Would you PLEASE let me know what you think? >> >>-- Seth James Nielson >> >> > > >Excellent; i'd like to see more logic for python stuff. >Please post your code! > >Simon Burton. > > > > > As I said, my code is very very experimental. I want to get it just a little more stable before posting. I'm hoping to post within a week or two (between working on my thesis proposal and working 30 hours a week, my time is kinda short ;) Thanks for your input! You're very helpful! -- Seth From mvs2 at linuxmail.org Thu Jun 5 13:47:12 2003 From: mvs2 at linuxmail.org (marcus) Date: 5 Jun 2003 10:47:12 -0700 Subject: Iteration through a text file. References: <1f9c7669.0306041001.e5b72ea@posting.google.com> <3EDE34AA.C8247DA0@engcorp.com> <1f9c7669.0306050624.11721703@posting.google.com> Message-ID: <1f9c7669.0306050947.1b4e811b@posting.google.com> Sorry, cut off the rest of that: Server, PRODUCTION2270 Uptime Report for: \\10.xxx.xxx.xxx OS: Windows NT 4.0 (Build 1381), Service Pack 6, Multiprocessor Free. Time Zone: Pacific Standard Time System Events as of 3/31/2003 10:06:40 AM: Date: Time: Event: Comment: ---------- ----------- ------------------- ----------------------------------- Current System Uptime: 40 day(s), 16 hour(s), 28 minute(s), 15 second(s) The system event log is empty. UPTIME is unable to calculate the system's availability. From wooooee at yahoo.com Thu Jun 12 15:17:23 2003 From: wooooee at yahoo.com (Curly Joe) Date: Thu, 12 Jun 2003 12:17:23 -0700 (PDT) Subject: index(x) Message-ID: <20030612191723.18361.qmail@web41804.mail.yahoo.com> Here are 2 links about lists that probably tell you more than you want to know http://www.faqts.com/knowledge_base/index.phtml/fid/534 http://www.faqts.com/knowledge_base/view.phtml/aid/18151/fid/1099 You can also sort the list first, then find the first occurance of whatever you are looking for, and then step through the list from that point forwards until you no longer find that value. Best of luck. __________________________________ Do you Yahoo!? Yahoo! Calendar - Free online calendar with sync to Outlook(TM). http://calendar.yahoo.com From jepler at unpythonic.net Wed Jun 4 11:59:50 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 4 Jun 2003 10:59:50 -0500 Subject: Possible PEP: Improve classmethod/staticmethod syntax In-Reply-To: <16094.3683.298847.221012@montanaro.dyndns.org> References: <16094.3683.298847.221012@montanaro.dyndns.org> Message-ID: <20030604155950.GD8136@unpythonic.net> On Wed, Jun 04, 2003 at 10:21:07AM -0500, Skip Montanaro wrote: > > gca> Since decorators are in a dictionary, in what order should they be > gca> applied? I though item extraction from a dictionary was, basically, > gca> unordered. > > Correct. The advantage of a dictionary is that the individual elements can > be more complex. For the pre- and post-condition stuff this works well. To > use lists there you have to extend list constructor syntax somehow, as I > used in my original message: > > def foo(...) [pre=foo_pre, post=foo_post]: > > > You could also use strings: > > def foo(...) ['pre=foo_pre', 'post=foo_post']: > > > The compiler would presumably split them at the '=' and eval() the right > hand side where necessary to get at the actual value. Why not use def foo(...) [pre(foo_pre), post(foo_post)] where pre(x) returns a callable that will add the x precondition to its argument? For instance, class pre: def __init__(self, precondition): self.precondition = precondition def __call__(self, f): return add_precondition(f, self.precondition) as far as I understand the proposed syntax, the items inside the [...] are Python expressions (which must evaluate to callable objects), not just identifiers. One other message in the thread asked, "what if you want to turn off pre/postcondition checking" (paraphrase). I don't see why you wouldn't be able to change 'pre's behavior before the 'def foo' block, since it's just any callable. Something like if do_preconditions: from preconditions import pre, post except: pre = post = lambda x: x Jeff From jafo-pythonlist at tummy.com Thu Jun 19 19:43:28 2003 From: jafo-pythonlist at tummy.com (Sean Reifschneider) Date: Thu, 19 Jun 2003 17:43:28 -0600 Subject: ANNOUNCE: JOTWeb 1.11, preview of new web application system. In-Reply-To: References: <20030617162210.GB5896@tummy.com> <1055884182.1169.11.camel@emilio> <20030619102215.GC23876@tummy.com> Message-ID: <20030619234328.GK20521@tummy.com> On Thu, Jun 19, 2003 at 09:27:59PM +1000, Dave Cole wrote: >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. That is certainly true... >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. Sure. Along those lines, I'm adding to JOTWeb a way to set up per-site startup scripts (probably of both HTML/TAL and Python varieties, so that you can use whichever one is more comfortable). I'm tempted to add per-page "configuration" because it would be easy, but it seems that it can be handled directly in the HTML/TAL (tal:define) or in the normal python modules. >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() I don't really think that it makes sense to have the user have to build up the namespaceto say what "currenttime" is. It just makes sense to me that if you ask for the "currenttime" attribute of the "code" entity, and you have a module called "code" which contains a function "currenttime", that you (as an application framework) can go ahead and call that for the user, instead of making the user go through the extra step of creating a context, importing the module, and setting up a name in the name-space... >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. Big Deal or not, it seems to me that like 90% or more of the time when you have a template and somebody references it, you want to provide a name-space and render it. I put a template there for a reason -- to be rendered to the browser. I really believe that if that is such a common case, that the user shouldn't have to do anything special to make it happen. It's no big deal to specify time.localtime(time.time()) as the argument to strftime(), but I definitely think that making that the default was a good thing... >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. That's what it boils down to... It seems to me, now, that you could do the same thing with Albatross, using a default handler with mod_python and overriding the context. >When you make something implicit you remove some flexibility from the >application developer. I imagine you wondered from time to time when I'm not sure that I agree that making something implicit prevents it from being overridden. So far, in the development I've done with JOTWeb, I haven't really run into a case where I wanted to change the default behavior in a way that required me to override the default rendering code, yet still have it do template rendering. Sean -- Hell hath no fury, like a file-system scorned. -- Sean Reifschneider, 1998 Sean Reifschneider, Member of Technical Staff tummy.com, ltd. - Linux Consulting since 1995. Qmail, Python, SysAdmin Back off man. I'm a scientist. http://HackingSociety.org/ From jacek.generowicz at cern.ch Fri Jun 13 08:32:28 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 13 Jun 2003 14:32:28 +0200 Subject: You know you're a Pythonista when.. References: <7h3he6vmpfd.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson writes: > I guess I'm not the only person to have typed "import sys" into a bash > prompt on a system with ImageMagick installed? Been there, done that ... got the T-shirt. From MatthewS at HeyAnita.com Mon Jun 16 19:17:41 2003 From: MatthewS at HeyAnita.com (Matt Shomphe) Date: 16 Jun 2003 16:17:41 -0700 Subject: Possible bug in setting Windows file permissions? (os.chmod() not working properly?) Message-ID: <5ab0af73.0306161517.43dbb96b@posting.google.com> 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@ From niklas_dont_spam_me at grin.se Tue Jun 3 10:05:24 2003 From: niklas_dont_spam_me at grin.se (Niklas Frykholm) Date: 3 Jun 2003 14:05:24 GMT Subject: reStructured Text - suitable for non-documentation? References: Message-ID: > Who is using reStructured Text actively? I am, both at home and at work. At home I use it for everything that does not have to be heavily structured (XML) or heavily formatted (raw HTML, LaTeX, Quark), such as letters, notes, works of fiction, etc. At work we use a reST-based Wiki for all our internal documentation (which is not Python-related). > Am I insane for even thinking of such a thing? Certainly not. If I were to rewrite my web pages today I would write most of it in reST (using Leo :). I would only write the front page and the graphics intense pages in HTML. > Are there better alternatives (i.e. ones specifically designed for > marking up web page content in plain text)? It all depends on what you want to do and what you mean by better. If the formatting options provided by reST (headlines, lists, footnotes, etc..) covers your needs, then I think you will have a hard time finding a better markup. If reST provides _almost_ everything you might still want to use it and try one of the following options - pre- or post-process your document to add your own markup - implement your own custom reST directives - use the .. raw directive to include raw HTML where needed // Niklas From jmdeschamps at cvm.qc.ca Wed Jun 4 16:07:10 2003 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 4 Jun 2003 13:07:10 -0700 Subject: Accented cahrs in PythonWin Message-ID: <3d06fae9.0306041207.5d4213a4@posting.google.com> Python 2.2.2 PythonWin build 152 in the interactive window: >>> toto = "?t? >>> # accepted string assignment but can't see the last quote >>> print toto ?t >>> # where is the last quote ??? >>> toto '\xe9t\xe9' >>> # here are 3 chars BUT pasted here as: >>> toto = "?t?" >>> # accepted string assignment but can't see the last quote >>> print toto ?t? >>> # where is the last quote ??? >>> toto '\xe9t\xe9' >>> # here are 3 chars The disapearring quote and acute e are back ??? Is something wrong??? Thanks for any cue on the subject! JM From br272 at msn.com Mon Jun 16 11:51:25 2003 From: br272 at msn.com (Brandon) Date: 16 Jun 2003 08:51:25 -0700 Subject: Using ctime to use the last two digits of time? Message-ID: <89c84d18.0306160751.648a14f0@posting.google.com> In reference to the Exercise on the bottom of this page; http://www.honors.montana.edu/~jjc/easytut/easytut/node14.html#SECTION001410000000000000000 "use the last two digits of time at that moment to be the 'random' number. " Now, I'm assuming that you need to use ctime to do this - but I have absolutely no idea how to modify the ctime statement in order for it to produce the last two digits (the seconds, respectively). I've searched the newsgroups and Python.org with no success, so if anyone could point me in the right direction - I'd appreciate it. I'll keep searching in the meanwhile. I've noticed that some sites seem to say that ctime(seconds) would be the right thing to do, but that never seems to work. Thanks! Brandon From mertz at gnosis.cx Sat Jun 14 16:54:36 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sat, 14 Jun 2003 16:54:36 -0400 Subject: comprehending comprehensions References: Message-ID: |Roy Smith wrote: |> Why are list comprehensions called what they are? Sean 'Shaleh' Perry wrote |it came from the functional programing world via ML (or was it Haskell). Perry's answer is correct, as far as it goes. But the Haskell/ML usage itself derives from Zermelo-Frankel axiomatic set theory. In particular, the Axiom of Comprehension states: given a set A and a predicate P, there uniquely exists a set B that contains only elements of A that fulfill P. Now backtracking a little, why such an odd axiom? This is because of Russell's paradox. Back in the old days, mathematicians thought that sets were simply the extensionality of intention predicates. In other words, given any predicate, sui generis, there is a set of things fulfilling the predicate. Russell asked, What about the set of all things that are not members of themselves? (It is a member of itself if-and-only-if it is not a member of itself). Russell had this awkward solution involving type hierarchies that is best forgotten. The more elegant solution is ZFC axiomatization. In particular, you avoid the paradox if you need to start with a prior set A, and only check the predicate against its members. So what does this have to do with list comprehensions. Well, recall how you would write the set B in math notation. Subject to the limits of my keyboard, something like: B = {x | x <- A s.t. P(x)} I try to draw the "member of" symbol as "<-" in ASCII. Now suppose we turn the usual squiggly set brackets into angle brackets, and replace "s.t." (such that) with a simple comma: [x | x <- A, P(x)] Viola... Haskell. Now suppose we use the word "in" instead of the ASCII attempt at the member symbol. And we use the word "if" instead of "s.t.". And also, the conditionality mark "|" is expanded to the word "for": [x for x in A if P(x)] And that's Python. Yours, Lulu... -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad ---[ Postmodern Enterprises ]-------------------------- From skip at pobox.com Tue Jun 3 23:53:57 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 3 Jun 2003 22:53:57 -0500 Subject: Possible PEP: Improve classmethod/staticmethod syntax In-Reply-To: <4868482a.0306031804.1f791131@posting.google.com> References: <20030603164521903-0400@braeburn.themorgue.org> <4868482a.0306031804.1f791131@posting.google.com> Message-ID: <16093.27989.801780.408444@montanaro.dyndns.org> Russ> Kevin Smith wrote: >> A new proposed syntax for method modifiers is as follows: >> >> def classmethod foo(cls): >> >> >> def staticmethod bar(): >> >> Russ> +1 Russ> I think it's a great step forward for clarity. I don't believe Guido ever expected the current implementation of class and static methods to be the final solution. It's just that there were enough possibile syntaxes that it wasn't immediately obvious which was the best. >From time-to-time a more general function annotation syntax has been proposed which would make the above unnecessary. An optional list of modifiers could be placed between the argument list and colon like so: def foo(cls) [class]: def bar() [static]: That list could of course contain more than one element. I don't see a PEP for the proposal, but I know it's come up a couple times. You might try searching the python-dev archives for something like "function modifiers". Skip From haris.bogdanovic at zg.hinet.hr Sun Jun 15 18:47:48 2003 From: haris.bogdanovic at zg.hinet.hr (Haris Bogdanovic) Date: Mon, 16 Jun 2003 00:47:48 +0200 Subject: Cannot build Tk under RedHat Message-ID: <3EECF794.3030700@zg.hinet.hr> 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 From mlh at furu.idi.ntnu.no Thu Jun 5 08:03:24 2003 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Thu, 5 Jun 2003 12:03:24 +0000 (UTC) Subject: Efficient data flow between orthogonal C extensions? References: <87el29rpmv.fsf@smtp.gsi.de> <6qfzmokc1t.fsf@salmakis.intevation.de> Message-ID: In article <6qfzmokc1t.fsf at salmakis.intevation.de>, Bernhard Herzog wrote: [snip] >I'm not sure how similar it is to what Magnus wants to do, but at least >the C-API handling might be an example. Indeed. >The basic approach taken to communicate a C-API from one dynamically >loaded module to another is that the streamfilter module as an attribute >called Filter_Functions which holds a PyCObject containing a pointer to >a struct with function pointers. The pstokenize module imports the >streamfilter module, extracts the struct and then calls the functions. Somewhat similar to the approach in the standard docs, then, except that you don't #include the .h-file of each extension...? (I'll look into the source.) >The approach is basically the same as in cStringIO in the Python sources >(see Include/cStringIO.h and Modules/cStringIO.c. Yeah, but this is more or less what I started out with (I think?) -- your C code needs to contain #import statements and call to macros to initialize the imported C code (such as PycString_IMPORT in this case)... The components themselves can't do this, since I want them to be orthogonal, and I don't see how the coordinating framework can either, since I want the components to be dynamically available/loadable (i.e. orthogonal of the framework, basically). Maybe I'm missing an important part of the functionality here... Is it possible to only keep a generic version of these declarations, and to store the specific implementations as PyCObjects? Is that what you do in Sketch? Basically, what I would like to do is have all C components totally ignorant of each other and only receive info about the "outside world" from the Python interpreter (probably in the form of PyCObjects). I would also like to make Python components and C components polymorphically equivalent, but that shouldn't be hard with some added Python magic on top of things ;) >PyGTK also does somethng like this. OK. Thanks. > Bernhard -- Magnus Lie Hetland "In this house we obey the laws of http://hetland.org thermodynamics!" Homer Simpson From jdhunter at ace.bsd.uchicago.edu Wed Jun 4 12:07:24 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 04 Jun 2003 11:07:24 -0500 Subject: Store python list in MySQL In-Reply-To: ("John Bradbury"'s message of "Wed, 4 Jun 2003 15:59:02 +0000 (UTC)") References: Message-ID: >>>>> "John" == John Bradbury writes: John> I can convert the list to a string and it works, but I don't John> want to do that. Is there a way of storing Python Lists/ John> Dictionaries etc as binary using MySQLdb & then to be able John> to reload them as Lists etc? I'm assuming that when you say you can convert the list to a string, you mean something like str(seq). If so, there's a better way using pickle. import pickle s = pickle.dumps([1,2,'Hi', (1,2)]) s is now a string. Store it in the mysql BLOB, and you can get the list back by seq = pickle.loads(s) print seq John Hunter From mwilson at the-wire.com Tue Jun 24 10:45:15 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Tue, 24 Jun 2003 10:45:15 -0400 Subject: shebang strange thing... References: <3EF3A07B.A683F94F@alcyone.com> <3EF7A121.7B4C3775@alcyone.com> Message-ID: <7PG++ks/KrDI089yn@the-wire.com> In article <3EF7A121.7B4C3775 at alcyone.com>, Erik Max Francis wrote: >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. 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. Regards. Mel. From bokr at oz.net Fri Jun 20 20:34:14 2003 From: bokr at oz.net (Bengt Richter) Date: 21 Jun 2003 00:34:14 GMT Subject: Weird 'and' result... References: Message-ID: On Fri, 20 Jun 2003 23:22:46 +0000 (UTC), "Artur M. Piwko" wrote: >pipen at demon:/tmp/ekg-1.1rc1$ python >Python 2.2.3 (#1, Jun 4 2003, 02:54:59) >[GCC 3.3 (Debian)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> "%08x" % (0xea7ee5ccea7 & 0xffffffff) >'ea7ee5ccea7' >>>> > >And it should be 'ee5ccea7'. Am I missing something? > >>> 0xea7ee5ccea7 16114421386919L >>> 0xffffffff -1 >>> 0xffffffff +0L -1L >>> 0xffffffffL 4294967295L >>> "%08x" % (0xea7ee5ccea7 & 0xffffffffL) 'ee5ccea7' It's a problem with the traditional hex literal representation of int numbers, which are usually 32 bits, and so wind up signed if the 0x80000000 bit is set. When an operation with a long causes promotion of the int to long, the sign bit gets logically extended, so it's as if you had all f's still. You can append an L as above to get the 0-sign-extended mask. Btw, a literal format of 1x... for 1s and 0x... 0s as sign extensions has been proposed, which I like much better than putting a '-' in front of the hex for the absolute value. IOW, I'd rather write 1xa than -0x6, which doesn't show me the bits I'm used to. >>> hex(-0x6) '0xfffffffa' >>> hex(-0x6L) '-0x6L' The bits are there, you just don't get to see them 'normally' in the hex representation of negative longs. >>> hex(-0x6L & 0xffff) '0xFFFAL' whereas you could with the 1xa == 1xfa == 1xffffffa format. Regards, Bengt Richter From gerrit at nl.linux.org Sun Jun 1 17:27:32 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 1 Jun 2003 23:27:32 +0200 Subject: repr on a string In-Reply-To: References: Message-ID: <20030601212732.GA4826@nl.linux.org> David Shochat schreef op zondag 1 juni om 22:21:17 +0000: > The Library Reference says this about built-in repr(): > Return a string containing a printable representation of an object. > > While studying Programming Python, 2nd Ed. Example 2-18, p. 84, I was > wondering what the point was of applying repr to a component (dir) of > sys.path. Isn't it after all, already a printable string? Ok, so > what does it mean to take repr of a printable string, and why does > the author want to here? Are we worried that the path contains an > unprintable directory name or something? > > I tried this: > >>> str = 'dog' > >>> str > 'dog' > >>> repr(str) > "'dog'" > > We now seem to have a string with quote characters as its first > and last components. I would have thought that the operation of > making a printable representation of something that is already > printable would be the identify function. Could someone > explain precisely what is going on here? 'repr' creates a reprentation that can be eval()ed, if possible. That's why the quotes are necessary. When you type the name of an object in the active interpreter, it also does a repr. When you type "print object" it doesn't: 8 >>> s = 'dog' 9 >>> s 'dog' 10 >>> print s dog 11 >>> repr(s) "'dog'" 12 >>> print repr(s) 'dog' 13 >>> print repr(repr(repr(repr(s)))) '\'"\\\'dog\\\'"\'' 14 >>> eval(repr(s)) 'dog' 15 >>> print eval(repr(s)) dog 18 >>> print repr(s)[0] ' 20 >>> repr({}) '{}' 21 >>> repr(0) '0' 22 >>> repr(repr) '' Hope this helps! yours, Gerrit. -- If a father give a present to his daughter -- either marriageable or a prostitute (unmarriageable) -- and then die, then she is to receive a portion as a child from the paternal estate, and enjoy its usufruct so long as she lives. Her estate belongs to her brothers. -- 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 robin at jessikat.fsnet.co.uk Thu Jun 5 03:55:58 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 5 Jun 2003 08:55:58 +0100 Subject: Efficient data flow between orthogonal C extensions? References: <87el29rpmv.fsf@smtp.gsi.de> Message-ID: In article <87el29rpmv.fsf at smtp.gsi.de>, Pierre Schnizer writes >mlh at furu.idi.ntnu.no (Magnus Lie Hetland) writes: > >> 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. >> >If you are using callbacks, you can wrap the callbacks with swig. While swig >will not generate helpers to call python functions from C, you can pass >pointers to C functions. >http://www.swig.org/Doc1.3/SWIG.html#n30 > > >Pierre I believe Bernhard Herzog's Sketch drawing editor does stream like transfers between extensions. -- Robin Becker From fperez528 at yahoo.com Mon Jun 9 19:31:45 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 09 Jun 2003 17:31:45 -0600 Subject: Recall last result References: <3ee4577d$0$25096$91cee783@newsreader01.highway.telekom.at> Message-ID: Erich Neuwirth wrote: > Is there a standard way of recalling the last result? > Following situation: > 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? > Now i want to count the number of elements in > the solution list. > Can i access the result of the last computation in a goboal vaiable? > > History recall does not help me, since that would reproduce my input, > but I need the output. > > I tried to find the answer in the docs, but could not find it. > Is there a FAQ dealing with questions like this one? Try ipython (http://ipython.scipy.org). It's an interactive shell which remembers all output in variables named _NNN, where NNN is a numeric identifier which increases with each new prompt. You are likely to be familiar with mathematica, so you should feel right at home: ipython's prompt system is inspired by mathematica's use of %, %%, %NNN for recalling previous results. Best, f. ps. ipython has many other features intended to make interactive use much more efficient than with the default interpreter. From peter at engcorp.com Sun Jun 8 15:31:38 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 08 Jun 2003 15:31:38 -0400 Subject: program path References: <3EE28ABC.7D6DB511@engcorp.com> <3EE2AD6E.933C6ED7@engcorp.com> <3EE36B46.343D8774@engcorp.com> <3EE36E0D.3050604@ghaering.de> Message-ID: <3EE38F1A.6B4CDEE@engcorp.com> Steven Taschuk wrote: > > Quoth Gerhard H?ring: > [...sys.argv[0] test in WinXP...] > > C:\>tmp\x.py > > C:\tmp\x.py > > What happens if %PATH% includes c:\tmp, and you invoke it simply > as 'x.py', from some other directory? See Mike's reply... it works fine. So basically os.path.abspath(sys.argv[0]) should be the idiomatic way to find the full path where the __main__ script lives. (I did try searching the archives for past discussions on this but couldn't find a reference after a minute so I gave up.) -Peter From bbeck at NOSPAM.austin.rr.com Wed Jun 18 17:30:01 2003 From: bbeck at NOSPAM.austin.rr.com (Brandon Beck) Date: Wed, 18 Jun 2003 21:30:01 GMT Subject: How to recognize a generator function? References: Message-ID: This isn't perfect, and you should probably constrain the exception handlers and consider what happens if the function or generator throws an exception itself, but it should suffice to illustrate one possible direction for you to take. There is also some potentially awkward behavior that could come about if you pass in a function that has a function named next on it. def call(obj): try: obj() return except: # Wasn't a generator function pass try: obj.next() return except: pass # Try anything any other ways you want to "call" here... raise Exception("I don't know how to handle: %s" % (obj,)) Brandon > I'll try to explain me better. Supose : > > # a generator-function > def f(): > a = 1 > yield a > > # a kind of callback > def call( object ) > if isGeneratorfunction( object): > g = object() > elif Type(object) is GeneratorType: > object.next() > > call( f ) From jdhunter at ace.bsd.uchicago.edu Fri Jun 20 08:51:47 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 20 Jun 2003 07:51:47 -0500 Subject: Run a linux program through python In-Reply-To: (Gunnar Staff's message of "Fri, 20 Jun 2003 09:29:37 +0200") References: Message-ID: >>>>> "Gunnar" == Gunnar Staff writes: Gunnar> I would like ti run a linux program through a python Gunnar> script. Do enyone know the syntax for running a OS program Gunnar> from python? If you want control of the process's standard input and output, take a look at os.popen, os.popen2 and friends. John Hunter From exarkun at intarweb.us Fri Jun 6 02:15:57 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 6 Jun 2003 02:15:57 -0400 Subject: Postfix/Prefix Operators (++,--) In-Reply-To: <1054878539.22405.4.camel@mylinuxsite.com> References: <1054878539.22405.4.camel@mylinuxsite.com> Message-ID: <20030606061557.GB17460@meson.dyndns.org> On Fri, Jun 06, 2003 at 01:49:00PM +0800, hostmaster wrote: > Hi, > > Python doesn't seems to support postfix/prefix operators (e.g. i++, > --i). Why? Because i = i + 1 i = i - 1 and because >>> import this ... There should be one-- and preferably only one --obvious way to do it. ... and because Python is not C or Java, it is Python. Jp From tim.golden at viacom-outdoor.co.uk Tue Jun 17 07:18:29 2003 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 17 Jun 2003 04:18:29 -0700 Subject: Saving Files Under Windows References: Message-ID: <8360efcd.0306170318.1e1202a1@posting.google.com> Tim Golden wrote in message news:... > achrist at easystreet.com> This looks to be exactly what I need, if I can get > it to work ... > achrist at easystreet.com> Are these not portable to WinNT? On NT 4.0 SP6, I > get: > > [snip error messages] > > Ahh. I rather thought that the win32 shell stuff was universal (on win32, at > least). I don't have an NT4 box here, so I'll have to try it when I get > home. Can anyone else confirm, or cast light on this? > > TJG Answering myself... WinNT (and maybe Win95) don't support SHGetSpecialFolderPath directly; instead, you have to use SHGetSpecialFolderLocation and then SHGetPathFromIDList. If you wish, have a butchers at my winshell module (http://tgolden.sc.sabren.com/python/winshell.html), a convenience wrapper round these sort of things. If nothing else, you can look at the code and see what I'm talking about. Since Win2K (and maybe Win98) also support the two-level SHGet..., I've recoded my module to use that rather than try to do platform-specific juggling, which smacks of browser-sniffing a little too much for my liking. TJG From johnroth at ameritech.net Sun Jun 8 13:43:01 2003 From: johnroth at ameritech.net (John Roth) Date: Sun, 8 Jun 2003 13:43:01 -0400 Subject: the 'in' operator and class instances References: <20030608062201.16011.72647.Mailman@mail.python.org> Message-ID: "Vinoo vasudevan" wrote in message news:mailman.1055063152.22684.python-list at python.org... > Hi, > I'm an newbie and have been getting to know Python over the past two weeks. > One of the things I really liked was the 'in' operator. Statements like "key > in dict" or "line in file" are really cool. But this doesn't seem to work for > classes. i.e. > > >>> class a: > def f(self): > pass > > >>> 'f' in a > > > Could somebody tell me why class instances don't use in to check for > memebership i.e. something like hasattr(..). I read up on "__contains__" in > the Language Reference. Couldn't python just define a default version of this > for all classes/instances to check for membership. Any class that attaches a > special meaning to membership can of course define its own "__contains__". In > c++ terminology (my __previous__ language :-) ) : can't "object" define a > virtual function "__contains__"? Just a suggestion. Plz let me know if I don't > have a clue of I'm talking about. :-) The standard method of implementing the "in" operator depends on the class implementing enough of the sequence protocol so that the interpreter can iterate through it to find (or not find) the requested item. See topic 3.3 in the Python Reference Manual (2.2.2 version.) It can also implement the __contains__() method if it doesn't want to look like a sequence. John Roth > > > Vinoo > > From max at alcyone.com Mon Jun 9 18:57:20 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 09 Jun 2003 15:57:20 -0700 Subject: Recall last result References: <3ee4577d$0$25096$91cee783@newsreader01.highway.telekom.at> <3EE45AED.8A20FD8E@hotmail.com> <3EE45F0A.750D7AB3@alcyone.com> <3EE46986.53EFF8EC@hotmail.com> Message-ID: <3EE510D0.DBD3CF5D@alcyone.com> Alan Kennedy wrote: > Just in case he wasn't, then perhaps you can enlighten us on how to > solve the > problem in the general case? I'm not aware of any way to solve it in the general case. -- 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 andrew-pythonlist at puzzling.org Mon Jun 2 22:29:56 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 3 Jun 2003 12:29:56 +1000 Subject: Extension without sub-classing? In-Reply-To: <3EDB61A1.3050203@magma.ca> References: <3EDB61A1.3050203@magma.ca> Message-ID: <20030603022956.GA11968@frobozz> On Tue, Jun 03, 2003 at 02:17:35AM +0000, Martin d'Anjou wrote: > Is it possible to extend a python class without sub-classing? > > For example, in file1.py > > class car: > def start_engine(self): > print "Started" > > And in file2.py, continue the declaration of the car class, without > specializing it: > > extend car: > def apply_breaks(self): > print "You have stopped" > > I know the "extend" syntax is wrong, but I want to extend "car" without > sub-classing. Is this possible and how? You can't directly, but you can do: from file1 import car def apply_breaks(self): print "You have stopped" car.apply_breaks = apply_breaks Or, perhaps more conveniently, you could extend this to: from file1 import Car class CarContinued: def apply_breaks(self): print "You have stopped" # ...etc... Car.__dict__.update(CarContinued.__dict__) -Andrew. From jwsacksteder at ramprecision.com Fri Jun 20 14:11:41 2003 From: jwsacksteder at ramprecision.com (jwsacksteder at ramprecision.com) Date: Fri, 20 Jun 2003 14:11:41 -0400 Subject: Newbie on importing Message-ID: <71650A6F73F1D411BE8000805F65E3CB3B33A9@SRV-03> 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 *'? From michaels at rd.bbc.co.uk Wed Jun 4 04:48:11 2003 From: michaels at rd.bbc.co.uk (Michael Sparks) Date: Wed, 04 Jun 2003 09:48:11 +0100 Subject: Yield inside try...finally References: <3EDCEC1F.96CB0766@hotmail.com> Message-ID: Thanks to all who responded. I'll group my replies here... Peter Hansen wrote: > Twisted does "deliberate wheel reinvention" already, in many > different areas. Why reinvent reinventing the wheel when others > already do it so well? ;-) Twisted is, AFAICT, essentially a state machine/reactor based approach which has been done multiple times in multiple languages, each time with a different "twist". (sorry...) In the past I've worked as part of a large team supporting and helping maintain a million line piece high performance network code written in C++ that was entire state machine based. The system was elegant, worked very efficiently, but was _fragile_ to change, and needed a high skill level to debug due to this fragilty. The complaints may not apply to Twisted, but in most statemachine / reactor based systems I've come across, sooner or later things become either ugly, fragile or inefficient. (pick any one :) This wheel re-invention is designed to see if using a generator based (or rather co-routine) approach produces clearer, more readable, more maintainable code, with significantly less fragility. It might not pan out, but then again, it might. (After all state machines and generators are functionally equivalent.) Steven Taschuk wrote: > What if the caller of your code calls .next for a while, then > discards the iterator and does something else? Then the finally > block will not be executed. The system I've written that this code will live in forms a component system that uses generators as communicating lightweight threads or microprocesses. If the scheduler doesn't re-call next() - and hence re-activate - this component, this would be deemed as catastrophic failure of the system as a whole. Much like with state machine based concurrency if a particular state machine gets stuck in a location and doesn't return control to (say) a reactor pattern would be deemed a catastrophic failure. Alan Kennedy wrote: > [ solultion ] So the general form would be: class Finality(Exception): pass try: thing = getThing() try: # .. try, again while thing.doMoreThingsThatMightBreak(): yield thing raise Finality except Exception, x: # Where you want nested "finally"s thing.necessaryShutdownFollowingFirstBreakable() raise x except Finality: # Where you would want the last "finally" pass except NastyExceptionThrowableByAllThoseMethods, e: print "Whinge, Moan, Complain", e I'm not convinced that I _like_ this version, but it's definitely an interesting alternative. (The thing I don't like is the "raise" in this casestrikes me as an abuse of what raise is for. I'll have a think. Very many thanks to all who responded - esp Alan! Regards, Michael -- Michael.Sparks at rd.bbc.co.uk British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From Mike.Prager at noaa.gov Tue Jun 3 18:24:08 2003 From: Mike.Prager at noaa.gov (Michael Prager) Date: Tue, 03 Jun 2003 18:24:08 -0400 Subject: smtplib and SSL Message-ID: 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.") I am trying to write a simple Python script to log into an ESMTP server and send email. However the statement server.starttls() leads to an error message, as in this incomplete screen dump: send: 'STARTTLS\r\n' reply: '220 Ready to start TLS\r\n' reply: retcode (220); Msg: Ready to start TLS Traceback (most recent call last): File "E:\MHPutil\sendmsg\send2.py", line 40, in ? serv.starttls() File "D:\python22\lib\smtplib.py", line 560, in starttls sslobj = socket.ssl(self.sock, keyfile, certfile) AttributeError: 'module' object has no attribute 'ssl' Is there a precompiled version of Python available with SSL support in the library? If so, where? I'm not sure from the Python.org web page whether this might work with the beta of 2.3. Or is that not the problem? -- Mike Prager NOAA, Beaufort, NC * Opinions expressed are personal and not represented otherwise. * Any use of tradenames does not constitute a NOAA endorsement. From gh at ghaering.de Thu Jun 5 19:03:38 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 06 Jun 2003 01:03:38 +0200 Subject: data base In-Reply-To: <20030605194905.12276.qmail@web21606.mail.yahoo.com> References: <20030605194905.12276.qmail@web21606.mail.yahoo.com> Message-ID: <3EDFCC4A.4060901@ghaering.de> DavidW Blaschke wrote: > I prefer metakit over SQLLite. As I understand it, > SQLLite is an interface to gdbm. Your understanding is outdated. SQLite 1.x was using gdbm. But since SQLite 2 (Oct. 2001), this is no longer true. > Metakit is a step up > but is still easy to use. If you don't need a relational database, there are a lot more options. For embedded SQL databases, there are three options AFAIK (PySQLite, Gadfy and some wrapper upon Metakit). > But it is personal > preference, of course. Search for database on > freshmeat and you'll probably find several options. > [broken quoting snipped] Here are the resources I recommend prior to going to Freshmeat: http://python.org/topics/database/ http://dmoz.org/Computers/Programming/Languages/Python/Modules/Databases_and_Persistence/ I try personally to keep the dmoz one up-to-date. -- Gerhard From psimmo60 at hotmail.com Fri Jun 20 05:24:28 2003 From: psimmo60 at hotmail.com (Paul Simmonds) Date: 20 Jun 2003 02:24:28 -0700 Subject: Btrieve/C-extension question References: <94974e1a.0306190653.3a829cb6@posting.google.com> Message-ID: <94974e1a.0306200124.4dee6542@posting.google.com> "vincent wehren" wrote in message news:... > "Paul Simmonds" schrieb im Newsbeitrag > news:94974e1a.0306190653.3a829cb6 at posting.google.com... > > "vincent wehren" wrote in message > news:... > > > > > Is it sensible to pass such a block of memory to Python and back? > > > If so, what is the best way to go about this, I.O.W, how do I pass such > a > > > block of memory > > > to Python and back (unchanged). > > > > I think you need a PyCObject. > > Thanks > Yes, that was my guess too... > So I did someting along the lines of: > > pos = PyCObject_FromVoidPtr(pos_blk; NULL) ; > return Py_BuildValue("N", pos); > > Passing is back in where I was getting trouble: > ( passed back in via PyArg_ParseTuple(args, "O", pos) ) > pos_blk = PyCObjectAsVoidPtr(pos); > doesn't seem to work... > > I think I need to check to C side of things once more. > Maybe there's some other Btrieve mystery that needs unravelling! It looks like there might be a simpler problem. If you have declared pos as a pointer to a PyObject, ParseTuple takes the addresses of the pointers. For example (untested): PyObject *VoidPtr_ParseMe(PyObject *self, PyObject *args) { int flag; PyObject *file; if(!PyArg_ParseTuple(args,"Oi",&file,&flag)) return NULL; /* This could be your problem /\ * Then this should work...*/ your_function(PyCObject_AsVoidPtr(file), flag); etc... } Of course, if the mistake in your ParseTuple line was just a typo, maybe you should take a look at exactly what gets put into the CObject. HTH, Paul > > Vincent Wehren > From pje at telecommunity.com Sat Jun 7 18:11:13 2003 From: pje at telecommunity.com (Phillip J. Eby) Date: Sat, 07 Jun 2003 18:11:13 -0400 Subject: PyProtocols 0.9 Message-ID: <5.1.0.14.0.20030607180620.02418c50@mail.telecommunity.com> Do you hate having to write lots of if-then logic to test what type something is? Wouldn't it be nice if you could just declare "I want this object to have this behavior" and magically convert whatever value you have, to the type you need? PyProtocols lets you do just that, cleanly, quickly, and robustly -- even with built-in types or other people's classes. PyProtocols extends the PEP 246 adapt() function with a new "declaration API" that lets you easily define your own interfaces and adapters, and declare what adapters should be used to adapt what types, objects, or interfaces. In addition to its own Interface type, PyProtocols can also use Twisted and Zope X3's Interface types. (Of course, since Twisted and Zope interfaces aren't as flexible, only a subset of the PyProtocols API works with them. Specific limitations are listed in the documentation.) If you're familiar with Interface objects in Zope, Twisted, or PEAK, the Interface objects in PyProtocols are very similar. But, they can also do many things that no other Python interface types can do. For example, PyProtocols supports "subsetting" of interfaces, where you can declare that one interface is a subset of another existing interface. This is like declaring that somebody else's existing interface is actually a subclass of the new interface. Twisted and Zope don't allow this, which makes them very hard to use if you're trying to define interfaces like "Read-only Mapping" as a subset of "Mapping Object". Unlike Zope and Twisted, PyProtocols also doesn't force you to use a particular interface coding style or even a specific interface type. You can use its built-in interface types, or define your own. If there's another Python package out there with interface types that you'd like to use (CORBA? COM?), you can even create your own adapters to make them work with the PyProtocols API. PyProtocols is also the only interface package that supports automatic "transitive adaptation". That is, if you define an adapter from interface A to interface B, and another from B to C, PyProtocols automatically creates and registers a new adapter from A to C for you. If you later declare an explicit adapter from A to C, it silently replaces the automatically created one. PyProtocols may be used, modified, and distributed under the same terms and conditions as Python or Zope. PyProtocols resources include: * Release notes, installation instructions, and browsable API docs: http://peak.telecommunity.com/protocol_api/ * Source and Binary Releases: http://peak.telecommunity.com/dist/ * Reference Manual (HTML): http://peak.telecommunity.com/protocol_ref/module-protocols.html * Reference Manual (PDF): http://peak.telecommunity.com/protocol_ref.pdf * Browsable CVS Repository: http://cvs.eby-sarna.com/PyProtocols/ Version 0.9 of PyProtocols is a complete, working release, so you can download it now and try it out. But, the exact spellings of the API and other interfaces may be subject to change in the future. We would like feedback from the community on the current API, as some API names may not be clear or obvious yet. Please contact the author with your input. From maurix78_remove_this_ at wanadoo.es Sat Jun 14 06:36:11 2003 From: maurix78_remove_this_ at wanadoo.es (Maurix) Date: Sat, 14 Jun 2003 10:36:11 GMT Subject: Execute a process as a specific user (OT) References: <3EE9E547.9040209@wanadoo.es> <3EEAEBE1.3010800@wanadoo.es> Message-ID: <3EEAFA82.1020000@wanadoo.es> Hi, thanks a lot, I solved the problem in a little different form: The problem is not that root is not authorized but that can't find .Xauthority file for the user's server, the solucion is to export HOME="/home/user/" so the server can locate the correct file. Bye. Maurix Zac Jensen wrote: > -----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 justinjohnson at fastmail.fm Tue Jun 17 09:08:45 2003 From: justinjohnson at fastmail.fm (Justin Johnson) Date: Tue, 17 Jun 2003 07:08:45 -0600 Subject: popen2.Popen3 on Windows In-Reply-To: <87he6pgnkk.fsf@emit.demon.co.uk> References: <3064b51d.0306151228.22c595e0@posting.google.com> <3eecfae8$0$49103$e4fe514c@news.xs4all.nl> <3EEDFE6D.4BE473A5@engcorp.com> <87he6pgnkk.fsf@emit.demon.co.uk> Message-ID: <20030617130845.CD9C42DFAB@www.fastmail.fm> Thank you so much. This looks like what I needed. On Tue, 17 Jun 2003 08:39:23 +0100, "Ian McConnell" said: > Peter Hansen writes: > > > Justin Johnson wrote: > >> > >> I need a way to run an external command, grab its output (stdout,stderr) > >> and get a return status for the command. It seems like popen2.Popen3 > >> (Note the upper case "P") is the way to do this, but it only works on > >> unix. Is there a way to get this info on Windows? > > > > You might get more or better replies if you create your posting as > > a new one, rather than replying to an existing one and changing the > > subject. Many news and mail readers will do "threading" which means > > your article will show up as part of the discussion to which you > > replied, and many people will have killed that thread (and thus > > never see your question) by now. > > Have a look at the process package on > http://starship.python.net/~tmick/ > > > > process.py is a (rather large) Python module to make process control > easier > and more consistent on Windows and Linux. The current mechanisms > (os.popen*, > os.system, os.exec*, os.spawn*) all have limitations. > > A quick list of some reasons to use process.py: > > * You don't have to handle quoting the arguments of your command > line. > You can pass in a command string or an argv. > > * You can specify the current working directory (cwd) and the > environment (env) for the started process. > > * On Windows you can spawn a process without a console window > opening. > > * You can wait for process termination or kill the running process > without having to worry about weird platform issues. (Killing on > Windows should first give the process a chance to shutdown cleanly. > Killing on Linux will not work from a different thread than the > process that created it.) > > * ProcessProxy allows you to interact in a pseudo-event-based way > with > the spawned process. I.e., you can pass in file-like object for any > of > stdin, stdout, or stderr to handle interaction with the process. > > > > -- > "Thinks: I can't think of a thinks. End of thinks routine": Blue Bottle > > ** Aunty Spam says: Remove the trailing x from the To: field to reply ** > -- > http://mail.python.org/mailman/listinfo/python-list > From andrewgould at yahoo.com Mon Jun 9 10:11:40 2003 From: andrewgould at yahoo.com (Andrew Gould) Date: Mon, 9 Jun 2003 07:11:40 -0700 (PDT) Subject: parsing emails and saving attached application files Message-ID: <20030609141140.1373.qmail@web13406.mail.yahoo.com> As a learning exercise I'm trying to parse my email messages. (The next step will be to save the components in a database.) How do I save attached application files separately from the email? In the script below, the email message contains some text and 2 excel files. Variable payload1a will give me the contents of of Book1.xls as a string. How do I save the contents as an Excel file (rather than a text file with unreadable content)? # begin script import email msgfile = open('a:/testmsg','r') msg = email.message_from_file(msgfile) payload1 = msg.get_payload(i=1,decode=0) payload1a = payload1.get_payload(i=None,decode=0) # end script Any help would be greatly appreciated. Thanks, Andrew From martin_chilvers at gmx.net Fri Jun 20 22:35:45 2003 From: martin_chilvers at gmx.net (Martin Chilvers) Date: Fri, 20 Jun 2003 21:35:45 -0500 Subject: Classic vs New-style classes... Message-ID: First of all, I should have asked a better question ;^) Second, I think I've answered it myself! > I've searched the archives and docs for an answer to this one, but I'm > still stuck... > > >>> class Foo(object) > ... pass > ... > >>> Foo.__dict__['bar'] = lambda self, x: x * 2 > Traceback (most recent call last): > File "", line 1, in ? > TypeError: object does not support item assignment > >>> type(Foo.__dict__) > What I really wanted was this:- def addToClass(klass, name, value): exec('klass.%s = value' % name) With classic classes, it can be written as:- def addToClass(klass, name, value): klass.__dict__[name] = value So now my question is... is this the cleanest way with new-style classes? Thanks for the previous responses, Martin Chilvers martin at enthought.com From krier115 at student.liu.se Mon Jun 16 17:53:31 2003 From: krier115 at student.liu.se (Kristoffer Erlandsson) Date: Mon, 16 Jun 2003 21:53:31 +0000 (UTC) Subject: Getting the CPU usage in a generic way across OSes References: Message-ID: On Mon, 16 Jun 2003 at 21:35 GMT, Fernando Perez wrote: > Kristoffer Erlandsson wrote: > >> Hello, >> >> I am writing an application that, among other things, should monitor the >> CPU usage. However, this seems impossible to do in a platform >> independant way. I have browsed the source from some C-programs which do >> this and they all seem to depend on very different ways depending on >> what OS the program is running on. Many of the ways use system specific >> system calls (which I can't find Python functions for). The only >> solution I have come up with so far is to extend python with some C-code >> which get the CPU usage for me. But this is of course more tedious than >> I'd like it to be. So I'm wondering if a module implementing this >> allready exists? I've had a date with google for this one, but no luck. >> If it doesn't exist, do anyone have a better idea than to write/rip the >> C-code implementing this for different OS:es? I'm only interested in >> doing it for *nix OS:es. >> >> I'm very grateful for any help on this. >> >> Regards, >> Kristoffer Erlandsson > > As long as you are using *nix, why not use resource.getrusage? > > http://www.python.org/doc/current/lib/node275.html I'm sorry, I maybe was a bit unclear in my first post. I want to monitor the _system wide_ cpu usage, as found for example in /proc/stat on some systems. resource.getrusage doesn't seem to help me do that. Thank you for your reply, and sorry for my unclearness. Regards, Kristoffer Erlandsson From martin at v.loewis.de Thu Jun 5 12:48:00 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 05 Jun 2003 18:48:00 +0200 Subject: 64 bit python References: <701f25e6.0306040749.d649f7f@posting.google.com> Message-ID: "E. McKay Hyde" writes: > SIZEOF_LONG=4, as defined in pyconfig.h That is the core of the problem; this setting is incorrect. > ; this value appears to be set > by the autoconf macro AC_CHECK_SIZEOF(long,4). Does this mean that > the configure script expects a size of 4 bytes? No. The second argument to AC_CHECK_SIZEOF is not used anymore; in earlier autoconf versions, it provided a default in case of cross compilation. Today, there is a tricky algorithm to detect the size of long even if cross-compiling (i.e. where you can't run the program you have compiled). > Or perhaps the macro is using a different compiler in determining > the size? It uses $CC. > I guess I will try to understand how AC_CHECK_SIZEOF works to see if > it is using the correct compiler and compiler flags. If you are not cross-compiling, it compiles and runs the program attached below, with the command $ac_link. The exact command used for compilation can be found in config.log, but it should be $CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5 HTH, Martin #include "confdefs.h" $ac_includes_default long longval () { return (long) (sizeof (long)); } unsigned long ulongval () { return (long) (sizeof (long)); } #include #include #ifdef F77_DUMMY_MAIN # ifdef __cplusplus extern "C" # endif int F77_DUMMY_MAIN() { return 1; } #endif int main () { FILE *f = fopen ("conftest.val", "w"); if (! f) exit (1); if (((long) (sizeof (long))) < 0) { long i = longval (); if (i != ((long) (sizeof (long)))) exit (1); fprintf (f, "%ld\n", i); } else { unsigned long i = ulongval (); if (i != ((long) (sizeof (long)))) exit (1); fprintf (f, "%lu\n", i); } exit (ferror (f) || fclose (f) != 0); ; return 0; } From peter at engcorp.com Fri Jun 6 22:13:41 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 06 Jun 2003 22:13:41 -0400 Subject: Postfix/Prefix Operators (++,--) References: <3EE05E36.40DF739F@engcorp.com> <3EE0B4D5.736EE894@engcorp.com> <3EE0D19C.7D7FFCA0@engcorp.com> Message-ID: <3EE14A55.AD00B185@engcorp.com> Joshua Marshall wrote: > List comprehensions let you rebind a variable in an expression, so > there is some precedent for this: > > >>> c = 1 > >>> a = [c - 1 for c in [c + 1]][0] > >>> a > 1 > >>> c > 2 > > but I'm not fond of list comprehensions either. 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. Personally, I'd much prefer to see that usage deprecated ASAP and eliminated in the near future, but I guess it's a wart we can (and must?) live with. -Peter From aleax at aleax.it Tue Jun 17 12:15:26 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 17 Jun 2003 16:15:26 GMT Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> <3EECED65.ACF1A6B7@engcorp.com> Message-ID: Terry Reedy wrote: ... >> E.g., indexing blah[bloh] with an >> invalid index value computed in variable bloh (invalid with respect >> to the set of indices that container blah can accept) is, alas, far >> from rare; but it's not a type-checking issue, > > Depends on what you call a type. A 'count' or a 'residue_class' is as > much a mathematical 'type' as an 'int' (or a 'rat'). A 'type' that is checkable at compile-time is (at the very least) a set whose membership needs to be fixed and known at compile-time. (There may be other requirements, but this one is crucial;-). "The set of acceptable keys/indices into 'blah' at this moment (which depends on how big 'blah' is right now, etc etc)" is not ``a type'' in this sense. So, if 'blah' is a std::vector<...> in C++, a Vector in Java, a Python list, or basically any sort of usable array/vector whose capacity can be determined at runtime, then compile-time type checking just cannot substitute for runtime checking of indices. Alex From ebolonev at rol.ru Mon Jun 30 06:43:23 2003 From: ebolonev at rol.ru (Egor Bolonev) Date: Mon, 30 Jun 2003 21:43:23 +1100 Subject: console mp3->wav decoder for $indows or GUI one which supports console References: Message-ID: "Egor Bolonev" wrote in message news:bdnvc9$ktc$1 at news.rol.ru... > Hi All! > > I'm seeking a subj. > > -- > Egor [ru eo en] > > From kodambal at imec.be Wed Jun 11 21:31:00 2003 From: kodambal at imec.be (K C Shashidhar) Date: Thu, 12 Jun 2003 03:31:00 +0200 Subject: re module In-Reply-To: References: Message-ID: <1055381461.291238@dmz2.imec.be> Mathieu Malaterre wrote: > > patt = re.compile('(?P.*?)\\\\helpref{?(?P.*?)}{?(?P.*?)}(?P.*?)', > re.DOTALL) remove the last '?'. it will work. Shashi From other at cazabon.com Tue Jun 17 23:07:05 2003 From: other at cazabon.com (Kevin) Date: Wed, 18 Jun 2003 03:07:05 GMT Subject: passing a C struct to Python and back References: Message-ID: Thanks Alex... I guess I gave up too easily. I got it working "as-is" with a better cast: theProcs = *((KPDCProcs *) (PyCObject_AsVoidPtr(pyTheProcs))); Kevin. "Alex Martelli" wrote in message news:KazHa.100629$pR3.2188842 at news1.tin.it... > > > 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 mwilson at the-wire.com Sat Jun 28 11:12:26 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Sat, 28 Jun 2003 11:12:26 -0400 Subject: XML (fwd) References: Message-ID: In article , Lulu of the Lotus-Eaters wrote: >mwilson at the-wire.com (Mel Wilson) wrote previously: >| And there isn't much to XML. There's a first line of >|version information... Then there's >|the [ ... ] > >Add entity escaping >Add namespace declarations >Add namespace modified tags >Add namespace modified attributes [ ... ] >... and then you're almost there. > >What could be easier? Thanks. I'm making a study list for my next run through _XML in a Nutshell_. DTD validation I know and handwaved away, the rest is on. Namespaces particularly. The people I was seeing coming to Usenet to be peeved at XML were dwelling on the issues I did cover. xml.sax seems to have handled a lot without bothering me. Regards. Mel. From bignose-hates-spam at and-zip-does-too.com.au Sun Jun 22 05:14:49 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Sun, 22 Jun 2003 09:14:49 GMT Subject: License Question References: <3EF54BDF.46423D0A@easystreet.com> Message-ID: On Sat, 21 Jun 2003 23:25:35 -0700, achrist at easystreet.com wrote: > I really do hate to discuss or argue about licenses. Honest. They can be pretty stressful. They are important, though, which is why people put so much energy into them. > "3. In the event Licensee prepares a derivative work that is based on > or incorporates Python 2.2.3 or any part thereof, [...] > Licensee hereby agrees to include in any such work a brief summary of > the changes made to Python 2.2.3." > > I interpret this to mean that a distributed version of a python > script I write, created with Py2exe or the McMillan installer, > since it includes Python is covered by this provision. "Derivative work" here is a copyright term (this is a copyright license) referring to a work that incorporates, in whole or in part, the work with this license attached. So, something that includes the whole of Python is a derivative work, by my reading. > So, I've got to put a copy of the news.txt file or something like it > somewhere in my distribution? No, you only have to include "[...] the changes made to Python 2.2.3." If you're including the whole thing, but not actually making changes to it, then your "brief summary of the changes" is zero length. > I don't have to make any other mention of Python, but I've got to tell > about changes in the current release, which is why? Only changes that *you*, the Licensee of Python 2.2.3, have made to the original in your derivative work. Seems like if you're not actually changing Python 2.2.3, you need do nothing to satisfy this clause. As for "make any other mention of Python", you'll need to read the rest of the license to confirm that; I'm pretty sure you'll need to include the Python 2.2.3 license text when you distribute it. IANAL, TINLA. -- \ "I wish I had a dollar for every time I spent a dollar, because | `\ then, yahoo!, I'd have all my money back." -- Jack Handey | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From alanmk at hotmail.com Fri Jun 20 10:39:38 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 20 Jun 2003 15:39:38 +0100 Subject: cgi getlist() problem (my first python program) References: <3EF1CFC0.2010803@yahoo.com> <3EF1DA5E.AC6C4F68@hotmail.com> <3EF216A2.8040508@yahoo.com> Message-ID: <3EF31CAA.B5DB5FCD@hotmail.com> Alan Kennedy wrote: >> One way to approach the problem is by numbering the fields in your >> HTML form Gobo Borz wrote: > I didn't want to use this approach because I thought I would have to use > eval() or something like that on the server side to build the field name > during iteration. You don't need to use eval. You could just extract the numeric part and turn that into an integer, for example using regular expressions: import re s = "name123" pattern = re.compile("name([0-9]+)") # Pedants go bother someone else ;-) match = re.search(pattern, s) if match: print "Your number is %d" % int(match.group(1)) > Maybe there's an easier way in Python to iterate > through a list of names like this, Yes, there is. Max M wrote it in another message (and a nice solution it is too, Max). That's probably the way to go. Best of luck. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From point14 at magma.ca Tue Jun 3 23:07:15 2003 From: point14 at magma.ca (Martin d'Anjou) Date: Wed, 04 Jun 2003 03:07:15 GMT Subject: Extension without sub-classing? References: <3EDB61A1.3050203@magma.ca> Message-ID: <3EDCBED5.20501@magma.ca> Thank you all for the answers. Martin From fredrik at pythonware.com Sun Jun 8 17:34:52 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 8 Jun 2003 23:34:52 +0200 Subject: Python Tkinter question References: <2747f65c.0306081302.4ccac40@posting.google.com> Message-ID: "Thyme" wrote: > I've hit a bump learning to use Tkinter. Nothing I've found on line > has helped me nail down the problem. Any insights would be welcome. > > This is something very easy, actually - I'm trying to use the feature > a label is assigned a variable so that it can be automatically > updated. I followed the syntax I found in a Tkinter PDF on line and > another online doc I found. > > Here is some code: > > # File: testx.py > from Tkinter import * > > con1 = StringVar("Quick Question!") >>> import Tkinter >>> help(Tkinter.StringVar) Help on class StringVar in module Tkinter: class StringVar(Variable) | Value holder for strings variables. | | Methods defined here: | | __init__(self, master=None) | Construct a string variable. | | MASTER can be given as master widget. | | get(self) | Return value of variable as string. | | ---------------------------------------------------------------------- | Methods inherited from Variable: | | __del__(self) | Unset the variable in Tcl. | | __str__(self) | Return the name of the variable in Tcl. | | set(self, value) | Set the variable to VALUE. in other words, the StringVar constructor takes an optional master (parent) widget argument, and you must use the "set" method to change the value: con1 = StringVar() con1.set("Quick Question!") From eyakubovich at cccglobal.com Mon Jun 9 15:39:15 2003 From: eyakubovich at cccglobal.com (Eugene Yakubovich) Date: Mon, 9 Jun 2003 14:39:15 -0500 Subject: regex question Message-ID: <003901c32ebe$cf30c650$9c01090a@4test> Hello, I have a question about regular expression matching. Consider the following: Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> import re >>> re.match(r'((a)5)*(abc)', 'abc').groups() (None, 'a', 'abc') >>> I would think that I would get (None, None, 'abc') since ((a)5)* would not match even once. Can anyone explain how regular expression engine matches this expression? Thank you, Eugene eyakubovich at cccglobal.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From davidcfox at post.harvard.edu Fri Jun 27 17:04:35 2003 From: davidcfox at post.harvard.edu (David Fox) Date: Fri, 27 Jun 2003 21:04:35 GMT Subject: Will bsddb changes in 2.3 affect shelve files? Message-ID: I have a question about the upcoming changes to bsddb in Python 2.3, as described in the release notes. I have an application which uses the shelve module to store selected attributes of a particular object and restore them the next time the application starts. I've noticed that, under Python 2.2.2 for Windows, shelve appears to use bsddb for its underlying database. Given that the bsddb files will need to be converted in format to work with Python 2.3, does that mean that my shelve files will have to be converted as well? Can I (and the users of my application) use the same db2pickle/pickle2db utilities to convert files created/read by shelve? Is the file format planned to remain stable after this transition to Python 2.3? I've currently putting substantial effort into ensuring that I can add to the set of stored attributes, when necessary, without preventing my application from reading files created by earlier versions and without any loss of information. However, all of that effort will be useless if the underlying database format used by shelve isn't stable. Thanks in advance, David Fox From guettler at thomas-guettler.de Tue Jun 24 04:56:40 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Tue, 24 Jun 2003 10:56:40 +0200 Subject: Persist Python objects to a MySQL database? References: Message-ID: Robert Oschler wrote: > I did a Google search (+persist +python +MySQL) and saw a few references > to persisting a Python object (class instance) to a MySQL database, but > nothing > extensive. Is there anything new that does this, hopefully in a > relatively transparent manner? Why not use ZODB? thomas From adalke at mindspring.com Sun Jun 8 02:56:30 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 8 Jun 2003 00:56:30 -0600 Subject: OT: dav/webdav uri scheme? Message-ID: Off-topic, I know, but I am using Python on the back-end ;) I'm developing a web-based app for job submission on a queue. The progression is simple: login -> main page -> start job -> view progress -> view results I want to provide some way for users to manage the results, eg, to delete old jobs. I did not want to develop a web-based GUI for what is basically manipulating directory names. I figured the easiest solution is to use WebDAV and leverage the existing webdav clients, which are designed to manipulate file-like resources. So I want my user's main page (after login) to have a link to "manage jobs" which points the webdav client to http://server/userhome/jobs As far as I can tell, this is impossible. There is a 'dav:' uri scheme but it isn't supported in IE nor in Safari. (That is, "dav:server/userhome/jobs" and "webdav:server/ ... " both give be a "not supported" error.) Does anyone here know a way to tell the web browser to use the webdav client to connect to a server's resource? Otherwise, I may punt and have written instructions which say "open your client and paste in this url". Which is silly. Andrew dalke at dalkescientific.com From max at cNOvSisiPonAtecMh.com Tue Jun 3 14:14:54 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Tue, 03 Jun 2003 18:14:54 GMT Subject: PIL + bump map References: Message-ID: maybe pythonMagic (py wrapper to the image magic lib) is your ticket? -- ======================================== 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] "Nagy L?szl? Zsolt" wrote in message news:mailman.1054650486.31645.python-list at python.org... > I'm a newbie to Python Imaging Library. I searched for something like > Bump Map in Gimp but I could not find a solution. > It would be the best to have the same filter in PIL but I can live with > something similar that gives me 'elevation' feeling on > a smooth gradient image. My task is to split several 6000x4800 pixel > image into many smaller regions and apply differents > effects on them. So I cannot use Gimp because there are thousands of > images. Please give me a point to start with. > Many thanks. > > Laci 1.0 > > > From max at alcyone.com Tue Jun 3 05:37:32 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 03 Jun 2003 02:37:32 -0700 Subject: a = b = 1 just syntactic sugar? References: <3EDC6A13.5020409@nospam.com> Message-ID: <3EDC6C5C.9B8E6020@alcyone.com> Kendear wrote: > so you mean in Python, = is just > like if, for, while... ? If by "just like" you mean "is a statement as opposed to an expression," then yes. Same thing with print and exec, for example. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Bring me men / Bring me men to match my mountains \__/ Lamya From news at manuelmgarcia.com Thu Jun 12 20:28:11 2003 From: news at manuelmgarcia.com (Manuel Garcia) Date: Fri, 13 Jun 2003 00:28:11 GMT Subject: why 'lambda' and 'reduce'? References: <84fc4588.0306112339.10a4012b@posting.google.com> Message-ID: On Thu, 12 Jun 2003 17:09:37 -0600, Steven Taschuk wrote: >(It prints the first 5000 digits of pi, by the way. At least, it >seems to. The first thirty digits are right, at least, and the >algorithm is based on a sound plan. The only question is whether >the arithmetic error and hardcoded recurrence-iteration limits >affect more than ten digits (which is what the code allows for). I shouldn't feed a troll, but this reply is just too delicious. The author claims the code is unobfuscated, but the nature of how all 5000 digits are kept accurate are obfuscated from him. >Determining *that* would require someone who actually knows >something about numerical analysis, which I do not.) Now you're saying something! ;-) Manuel From news at exultants.org Thu Jun 19 10:56:18 2003 From: news at exultants.org (Van Gale) Date: Thu, 19 Jun 2003 14:56:18 GMT Subject: ANNOUNCE: JOTWeb 1.11, preview of new web application system. In-Reply-To: References: <20030617162210.GB5896@tummy.com> <1055884182.1169.11.camel@emilio> <20030619102215.GC23876@tummy.com> Message-ID: Dave Cole wrote: >>>>>>"Sean" == Sean Reifschneider writes: > > 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. Then of course, as the project grows, you start adding more flexibility at the request of a developer who likes your method but needs to change one bit. Next thing you know people are starting new "simple" projects because yours is now too "complex" :) Van From gh at ghaering.de Sun Jun 1 10:21:12 2003 From: gh at ghaering.de (Gerhard Haering) Date: Sun, 1 Jun 2003 16:21:12 +0200 Subject: SV: CGI question: safe passwords possible? In-Reply-To: References: <3ED88344.8000803@ghaering.de> Message-ID: <20030601142112.GB416@mephisto.ghaering.de> * Carsten Gehling [2003-06-01 11:11 +0200]: > > Fra: python-list-admin at python.org > > [mailto:python-list-admin at python.org]Pa vegne af Gerhard Haring > > Sendt: 31. maj 2003 12:26 > > > That's why I recommended to use digest authentication. > > > > See http://httpd.apache.org/docs/mod/mod_auth_digest.html > > > > It implements a similar algorithm that your proposed JavaScript gimmick > > did. Only that it works with all modern browsers, JavaScript enabled or > > not and that it's a standard. > > From http://httpd.apache.org/docs/mod/mod_auth_digest.html : > > "Note: MD5 authentication provides a more secure password system than Basic > authentication, but only works with supporting browsers. As of this writing > (October 2001), the only major browsers which support digest authentication > are Opera 4.0, MS Internet Explorer 5.0 and Amaya. [...] October 2001 is long gone. Mozilla (Netscape [1], ...): yes Konqueror (possible Safari): yes w3m: yes lynx: no links: no Gerhard [1] *Not* Netscape 4.x obviously. But I'm very happy to desupport this beast :-P -- http://ghaering.de/ From glenfant at NOSPAM.bigfoot.com Fri Jun 20 08:41:14 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Fri, 20 Jun 2003 14:41:14 +0200 Subject: shebang strange thing... References: Message-ID: "Steve McAllister" a ?crit dans le message de news: bcus6i$1rl$1 at alto.univ-mlv.fr... > > $ ./myscript.py > > error : interpreter not found. (!!!) > > Ensure your very first line _is_ exactly the one you _see_ , i.e. > `#!/usr/bin/python\n', without any additional invisible character; > trailing `\x00\n', for instance, would make you believe your script > runs fine but does nothing. > > I bet bash nerves shall be soothed if you delete then quietly rewrite > this line. > Many thanks to all This script is a copy from a FAT32 (windows) partition. Emacs carried on saving silently this file with DOS like end of lines. A "dos2unix" fixed this. --Gilles From aahz at pythoncraft.com Wed Jun 18 15:28:58 2003 From: aahz at pythoncraft.com (Aahz) Date: 18 Jun 2003 15:28:58 -0400 Subject: [OT] (was: does lack of type declarations make Python unsafe?) References: <3064b51d.0306151228.22c595e0@posting.google.com> <3EEFD22C.93B58AE3@alcyone.com> Message-ID: In article , Nick Vargish